From 5a4baeb33edef322a71b2a8e68bbef10aee904fe Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:56:07 -0600 Subject: [PATCH 01/23] 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 -- 2.53.0 From 7a84cb19c937c907fbc24c96df1119b566ba6d33 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:56:07 -0600 Subject: [PATCH 02/23] 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")} -- 2.53.0 From ca0f02aa0ce691e70df554cee7784d2a0150cd5f Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:56:07 -0600 Subject: [PATCH 03/23] 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 -- 2.53.0 From 028f774400fbb597abf1698c5533019f7e495263 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 20:46:09 -0600 Subject: [PATCH 04/23] 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)} -- 2.53.0 From 8130f86f3aca93a4daab650ce987c58bce45a17f Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 20 Nov 2026 18:46:40 -0600 Subject: [PATCH 05/23] 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, } -- 2.53.0 From 7d06f9db9d5100e519752c4305c4b48e4db527c3 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 20:18:00 -0600 Subject: [PATCH 06/23] 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 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- docker-entrypoint.sh | 2 +- tests/test_orquestacion_ciclo.py | 19 ++++++++---- tests/test_orquestacion_pasos.py | 18 ++++++++--- webapi/blueprints/governance.py | 4 +-- webapi/orchestration/cycle.py | 50 ++++++++++-------------------- webapi/orchestration/estimators.py | 44 +++++++++++++------------- webapi/orchestration/project.py | 12 +++---- webapi/orchestration/runner.py | 13 ++++---- 8 files changed, 83 insertions(+), 79 deletions(-) diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index c882adb..ebd9e06 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -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 diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index 480e5cc..f89e3dc 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -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() diff --git a/tests/test_orquestacion_pasos.py b/tests/test_orquestacion_pasos.py index df737f4..13d3b93 100644 --- a/tests/test_orquestacion_pasos.py +++ b/tests/test_orquestacion_pasos.py @@ -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")) diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index e0decb0..68f91d7 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -8,7 +8,7 @@ either run elsewhere and register its result through `POST /model-versions` `cohorte_armado_id`), or be triggered in place through `POST /model-versions///train`, for a deployment with no command-line access to run the `entrenar` compose profile by hand. -Notebooks (`models.pipelines.experiment`) run in the background on the build's +Notebooks (`models.reports.experiment`) run in the background on the build's file alone and are kept as MLflow runs. """ import contextlib @@ -28,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 diff --git a/webapi/orchestration/cycle.py b/webapi/orchestration/cycle.py index 2559bf5..e1b8d77 100644 --- a/webapi/orchestration/cycle.py +++ b/webapi/orchestration/cycle.py @@ -37,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__) @@ -188,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 @@ -220,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]) diff --git a/webapi/orchestration/estimators.py b/webapi/orchestration/estimators.py index f8965cf..31a762c 100644 --- a/webapi/orchestration/estimators.py +++ b/webapi/orchestration/estimators.py @@ -3,9 +3,9 @@ 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, read from the build's exported file (the same export `python -m models cohorts export` writes), so an -estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership, -the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go +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. """ @@ -37,28 +37,29 @@ class Cin2LogisticEstimator: self._provenance: Provenance | None = None def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]: - import mlflow.pyfunc - from persistance.settings import settings + import json - from models.cacu.cin2_logistic.model import SETTINGS + 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 cohorts_root, read_cohort - from models.pipelines.export_cohort import export_kit_build + from models.io.storage import KitBuild from models.steps.risks import risk_rows repos = import_module(f"persistance.{self.domain}") - url = SETTINGS["cohort"] - build_id = repos.cohort_repository.latest_build(url) - resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version) - root = cohorts_root(getattr(settings, f"{self.domain}_database_url")) - path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id) - risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path)) - window = SETTINGS["outcome_window_months"] - self.desenlace = f"cin2_{window}m" + 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, SETTINGS["scenario"]), modelo_version=resolved.version, + 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(risks, window / 12)] + return [tuple(row) for row in risk_rows(estimate_frame(frame, probabilities, horizons))] def procedencia(self) -> Provenance: if self._provenance is None: @@ -71,11 +72,12 @@ def live_estimators(domain: str) -> dict[str, Any]: none is in production yet, the same as no estimator being configured: `estimate` then does nothing.""" if domain != "cacu": return {} - from models.cacu.cin2_logistic.model import SETTINGS + from models.dags.training import Scenario from models.io.registry import registry + scenario = Scenario.load(domain, "cin2_logistic") try: - registry.resolve(domain, SETTINGS["scenario"]) + registry.resolve(domain, scenario.scenario) except LookupError: return {} - return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)} + return {scenario.cohort: Cin2LogisticEstimator(domain)} diff --git a/webapi/orchestration/project.py b/webapi/orchestration/project.py index 07c9e67..d4c8c52 100644 --- a/webapi/orchestration/project.py +++ b/webapi/orchestration/project.py @@ -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//*.toml`): today only CaCu's surveillance cohort. - Those in `/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//cohorts/`, + `meta.cohort` of their population query). dbt is their only definition. None without a manifest.""" + return _cohort_urls(manifest, proyecto) if manifest else [] diff --git a/webapi/orchestration/runner.py b/webapi/orchestration/runner.py index fd3c19c..776b87b 100644 --- a/webapi/orchestration/runner.py +++ b/webapi/orchestration/runner.py @@ -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}) -- 2.53.0 From 0c1b383da24b15f4d400df61e585820d9f8c9a93 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 23:02:46 -0600 Subject: [PATCH 07/23] CaCu's individual risk as a FHIR RiskAssessment, and each risk's index date GET /cacu/fhir/RiskAssessment?subject=Patient/ (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//riesgo adds riesgo.fecha_indice. Tests and the risk-band fixture carry the index date. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- tests/fixtures/casos_riesgo_banda.toml | 26 ++++-- tests/test_fhir_cacu_risk.py | 109 +++++++++++++++++++++++++ tests/test_orquestacion_riesgos.py | 2 +- tests/test_patient_risk.py | 6 +- tests/test_risk_batches.py | 2 +- webapi/fhir/__init__.py | 30 ++++++- webapi/fhir/cacu.py | 62 ++++++++++++++ webapi/patient_risk.py | 4 +- 8 files changed, 227 insertions(+), 14 deletions(-) create mode 100644 tests/test_fhir_cacu_risk.py create mode 100644 webapi/fhir/cacu.py diff --git a/tests/fixtures/casos_riesgo_banda.toml b/tests/fixtures/casos_riesgo_banda.toml index bd715d3..3e63ec3 100644 --- a/tests/fixtures/casos_riesgo_banda.toml +++ b/tests/fixtures/casos_riesgo_banda.toml @@ -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 } diff --git a/tests/test_fhir_cacu_risk.py b/tests/test_fhir_cacu_risk.py new file mode 100644 index 0000000..fe4f379 --- /dev/null +++ b/tests/test_fhir_cacu_risk.py @@ -0,0 +1,109 @@ +"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/` (`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/`, 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/` 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"] diff --git a/tests/test_orquestacion_riesgos.py b/tests/test_orquestacion_riesgos.py index 9d3f8a3..a226f0d 100644 --- a/tests/test_orquestacion_riesgos.py +++ b/tests/test_orquestacion_riesgos.py @@ -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 diff --git a/tests/test_patient_risk.py b/tests/test_patient_risk.py index e6757ce..2293b49 100644 --- a/tests/test_patient_risk.py +++ b/tests/test_patient_risk.py @@ -12,7 +12,8 @@ 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"} +RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "fecha_indice", "evaluado_en", "estado_lote", "horizontes"} +MODEL_INDEX = date(2026, 6, 1) # the model's index date: not the member's (2025-03-01) HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"} @@ -49,7 +50,7 @@ def seeded(client): 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)], + "cin2_12m", [(scored, MODEL_INDEX, 3.0, 0.3, None, None), (scored, MODEL_INDEX, 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 @@ -67,6 +68,7 @@ def test_a_scored_member_has_the_contracts_shape(client, seeded): 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" + assert (body["riesgo"]["fecha_indice"], body["cohorte"]["fecha_indice"]) == ("2026-06-01", "2025-03-01") 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")] diff --git a/tests/test_risk_batches.py b/tests/test_risk_batches.py index fee812b..14b7e5a 100644 --- a/tests/test_risk_batches.py +++ b/tests/test_risk_batches.py @@ -41,7 +41,7 @@ def batches(client): def batch(version, risk, ahora): lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version}, - "cin2_12m", [(pac_id, 1.0, risk, None, None)], ahora=ahora) + "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)) diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index 2ef8efb..330c5d4 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -1,4 +1,5 @@ -"""A domain's FHIR R4 endpoint, `//fhir/`: its measures and, for TEA, its patients' screening. +"""A domain's FHIR R4 endpoint, `//fhir/`: its measures and, for TEA and CaCu, its patients' screening and +individual risk. GET metadata CapabilityStatement GET Measure, Measure/ the measures (dbt's definitions) @@ -8,6 +9,7 @@ GET CodeSystem, CodeSystem/, ValueSet/ the project's code systems GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only) GET Patient//$resumen-tea TEA's patient summary (DEV only) + GET RiskAssessment?subject=Patient/ 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/`: 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"): diff --git a/webapi/fhir/cacu.py b/webapi/fhir/cacu.py new file mode 100644 index 0000000..46e3765 --- /dev/null +++ b/webapi/fhir/cacu.py @@ -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 `-` + status the batch's state (`final`) + subject `Patient/`: 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) diff --git a/webapi/patient_risk.py b/webapi/patient_risk.py index c276b19..240c697 100644 --- a/webapi/patient_risk.py +++ b/webapi/patient_risk.py @@ -2,7 +2,7 @@ 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; +evaluation, with the index date the model scored her from (`riesgo.fecha_indice`). 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. """ @@ -43,6 +43,8 @@ def _risk(risk) -> dict | 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, + # the model's index date for the patient: the horizons count from it (not the cohort's) + "fecha_indice": risk.fecha_indice.isoformat() if risk.fecha_indice else None, "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, -- 2.53.0 From 26f2b3533874da3b587450014d922f37ff818833 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 23:15:55 -0600 Subject: [PATCH 08/23] Retire GET /cacu/pacientes//riesgo: the record reads the FHIR RiskAssessment The WebApp patient record now reads GET /cacu/fhir/RiskAssessment?subject=Patient/ (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 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- tests/test_patient_risk.py | 89 ------------------------------------- webapi/__init__.py | 6 +-- webapi/follow_up/listing.py | 2 +- webapi/patient_risk.py | 51 --------------------- webapi/risk_batches.py | 5 ++- 5 files changed, 6 insertions(+), 147 deletions(-) delete mode 100644 tests/test_patient_risk.py delete mode 100644 webapi/patient_risk.py diff --git a/tests/test_patient_risk.py b/tests/test_patient_risk.py deleted file mode 100644 index 2293b49..0000000 --- a/tests/test_patient_risk.py +++ /dev/null @@ -1,89 +0,0 @@ -"""What this module covers: `GET /cacu/pacientes//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", "fecha_indice", "evaluado_en", "estado_lote", "horizontes"} -MODEL_INDEX = date(2026, 6, 1) # the model's index date: not the member's (2025-03-01) -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, MODEL_INDEX, 3.0, 0.3, None, None), (scored, MODEL_INDEX, 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" - assert (body["riesgo"]["fecha_indice"], body["cohorte"]["fecha_indice"]) == ("2026-06-01", "2025-03-01") - 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 diff --git a/webapi/__init__.py b/webapi/__init__.py index 7dfc3b9..fd5a899 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -92,18 +92,16 @@ 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, 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(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(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu") app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu") return app diff --git a/webapi/follow_up/listing.py b/webapi/follow_up/listing.py index 34503a1..580ff2c 100644 --- a/webapi/follow_up/listing.py +++ b/webapi/follow_up/listing.py @@ -9,7 +9,7 @@ de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula. **Es dato por paciente.** Toda respuesta lleva `simulado: true`; quién puede verla lo decide una regla de acceso. Cada fila identifica a su paciente por `pac_id`, la llave de la plataforma (como texto decimal), la -misma que usan los lotes de riesgo y `GET /cacu/pacientes//riesgo`; `id_seudonimo` repite ese valor +misma que usan los lotes de riesgo y `GET /cacu/fhir/RiskAssessment?subject=Patient/`; `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` diff --git a/webapi/patient_risk.py b/webapi/patient_risk.py deleted file mode 100644 index 240c697..0000000 --- a/webapi/patient_risk.py +++ /dev/null @@ -1,51 +0,0 @@ -"""A CaCu patient's individual risk: `GET /cacu/pacientes//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, with the index date the model scored her from (`riesgo.fecha_indice`). 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//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, - # the model's index date for the patient: the horizons count from it (not the cohort's) - "fecha_indice": risk.fecha_indice.isoformat() if risk.fecha_indice else None, - "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]} diff --git a/webapi/risk_batches.py b/webapi/risk_batches.py index c92217d..3319d6c 100644 --- a/webapi/risk_batches.py +++ b/webapi/risk_batches.py @@ -1,7 +1,8 @@ """Risk batches waiting for a clinical decision (ADR-MD-008): list the ones no one has confirmed or voided yet, -confirm one (`preliminary` -> `final`, visible on `/cacu/pacientes//riesgo`) or void it (`entered-in-error`). +confirm one (`preliminary` -> `final`, then served as the patient's FHIR `RiskAssessment`, +`/cacu/fhir/RiskAssessment?subject=Patient/`) or void it (`entered-in-error`). `GET/POST //riesgos/lotes...`. The route is always registered; who may act on it is an access rule still -to be defined, as `patient_risk.py` notes for reads. +to be defined. """ from flask import Blueprint, jsonify, request -- 2.53.0 From d1e06798c9548d8ccec2fbf81a0572bfd678aaf0 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Fri, 20 Nov 2026 23:28:33 -0600 Subject: [PATCH 09/23] 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 -- 2.53.0 From 9b617db9d022dfa168ded37af535c8c9920f3a26 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 01:55:04 -0600 Subject: [PATCH 10/23] 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") -- 2.53.0 From e2ecaa027cc44238d391d4c60aeab452e384934e Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 02:07:34 -0600 Subject: [PATCH 11/23] CaMa: individual risk and population curves served, and the cycle estimates with any scenario in production webapi/fhir/risk.py builds a patient's RiskAssessment for CaCu and CaMa; GET /cama/modelo/curvas serves the production version's survival curves; the cycle's estimator is generic by scenario; silver persona carries the date of death for CaMa; the import schema accepts it; the CaMa risk batches can be confirmed and voided. --- pyproject.toml | 2 +- tests/test_fhir_cama_risk.py | 109 ++++++++++++++++++++++++ tests/test_model_analysis.py | 64 ++++++++++++++ tests/test_orquestacion_ciclo.py | 10 ++- tests/test_pathology_report_wording.py | 52 +++++++++++ uv.lock | 40 ++++++++- webapi/__init__.py | 4 + webapi/fhir/__init__.py | 17 ++-- webapi/fhir/cacu.py | 62 ++------------ webapi/fhir/cama.py | 11 +++ webapi/fhir/risk.py | 60 +++++++++++++ webapi/imports/schemas/cama/paciente.py | 3 + webapi/model_analysis.py | 35 ++++++++ webapi/orchestration/estimators.py | 45 ++++++++-- webapi/orchestration/silver/persons.py | 6 ++ webapi/orchestration/tables/cama.py | 4 +- webapi/risk_batches.py | 7 +- 17 files changed, 446 insertions(+), 85 deletions(-) create mode 100644 tests/test_fhir_cama_risk.py create mode 100644 tests/test_model_analysis.py create mode 100644 tests/test_pathology_report_wording.py create mode 100644 webapi/fhir/cama.py create mode 100644 webapi/fhir/risk.py create mode 100644 webapi/model_analysis.py diff --git a/pyproject.toml b/pyproject.toml index 6e8bec8..c336e85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.12" dependencies = [ "flask>=3.0", "persistance", - "models[notebooks]", + "models[notebooks,survival-curves]", "extraction", "apache-hamilton>=1.90", "pandas>=2.0", diff --git a/tests/test_fhir_cama_risk.py b/tests/test_fhir_cama_risk.py new file mode 100644 index 0000000..6d0b149 --- /dev/null +++ b/tests/test_fhir_cama_risk.py @@ -0,0 +1,109 @@ +"""What this module covers: `GET /cama/fhir/RiskAssessment?subject=Patient/` (`webapi.fhir.cama`, built by +`webapi.fhir.risk` as CaCu's is): a patient's current mortality risk as a FHIR R4 `RiskAssessment` in a `searchset` +Bundle: its shape (status, subject, method, one prediction per horizon from the model's own index date, the interval +extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the +`CapabilityStatement` entry. The reads behind it are Persistance's, tested there. + +Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaMa demonstration +database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a total-cohort build with two of its patients, one +with a confirmed batch whose risks, at 0.5 and 1.5 years, have the model's index date. +""" + +import os +from datetime import date, datetime, timezone + +import pytest +from conftest import cliente_de + +MODEL_INDEX = date(2026, 6, 1) + + +@pytest.fixture(scope="module") +def client(tmp_path_factory): + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") + with pytest.MonkeyPatch.context() as mp: + mp.setenv("DEV_REVISION", "pruebas") + yield from cliente_de("cama", tmp_path_factory) + + +@pytest.fixture(scope="module") +def seeded(client): + """Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0.5 and 1.5 years, the + 1.5-year one with an interval. Returns (scored patient, member without risks).""" + from core.cama.indicadores.models import CohorteArmado, CohorteMiembro + from persistance import cama + from persistance.db import get_cama_session + + scored, unscored = [p.pac_id for p in cama.persona_repository.list(limit=2)] + with get_cama_session() as session: + build = CohorteArmado(url="cama/cohorte_total", version="0.1.0", definicion_sha="d", reglas_sha="r", + parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk-cama", marco_sha="m", + n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)) + session.add(build) + session.flush() + session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1), + indice_fuente_tabla="biopsiamama", indice_fuente_id=str(p)) + for p in (scored, unscored)]) + session.commit() + build_id = build.armado_id + batch, _ = cama.cohort_repository.save_batch( + build_id, {"modelo_nombre": "cama-survival", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"}, + "muerte", [(scored, MODEL_INDEX, 1.5, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.5, 0.08, None, None)], + ahora=datetime(2026, 10, 1, tzinfo=timezone.utc)) + cama.cohort_repository.change_state(batch, "final", "revisado") + return scored, unscored, batch + + +def test_a_scored_patient_gets_her_risk_assessment(client, seeded): + """Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/`, evaluated + when the batch was, by the registered model and version, with one prediction per horizon whose period starts at + the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension; + tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere.""" + scored, _, batch = seeded + + response = client.get(f"/cama/fhir/RiskAssessment?subject=Patient/{scored}") + + assert response.status_code == 200 and response.mimetype == "application/fhir+json" + bundle = response.get_json() + assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1) + risk = bundle["entry"][0]["resource"] + assert bundle["entry"][0]["fullUrl"].endswith(f"/cama/fhir/RiskAssessment/{batch}-{scored}") + assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"}) + assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z" + assert risk["method"]["coding"][0]["code"] == "cama-survival" and risk["method"]["coding"][0]["version"] == "3" + assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["muerte", "muerte"] + assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [ + (0.08, {"start": "2026-06-01", "end": "2026-12-01"}), (0.21, {"start": "2026-06-01", "end": "2027-12-01"})] + assert "extension" not in risk["prediction"][0] + assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}} + assert any(t["code"] == "simulado" for t in risk["meta"]["tag"]) + + +def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded): + """Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error. + Fails if a missing risk becomes a 404 or a resource with no predictions.""" + _, unscored, _ = seeded + + for subject in (f"Patient/{unscored}", "Patient/987654321"): + bundle = client.get(f"/cama/fhir/RiskAssessment?subject={subject}").get_json() + assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry` + + +@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"]) +def test_the_risk_is_searched_by_patient(client, query): + """Pins down: without `subject=Patient/` the answer is a 400 `OperationOutcome`. Fails if the route lists + every patient's risk.""" + response = client.get(f"/cama/fhir/RiskAssessment{query}") + + assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome" + + +def test_the_capability_statement_declares_the_search(client): + """Pins down: CaMa's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient + resources stay TEA's. Fails if the route exists without being declared, or the other way round.""" + resources = client.get("/cama/fhir/metadata").get_json()["rest"][0]["resource"] + risk = [r for r in resources if r["type"] == "RiskAssessment"] + + assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}] + assert not [r for r in resources if r["type"] == "EpisodeOfCare"] diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py new file mode 100644 index 0000000..2001b6e --- /dev/null +++ b/tests/test_model_analysis.py @@ -0,0 +1,64 @@ +"""What this module covers: `GET /cama/modelo/curvas` (`webapi.model_analysis`): it serves the production version's +population record with the version it comes from, and answers 404 while there is no version in production or the +version has no such record. + +Fixtures: `client`, the app with the registry's `resolve` and `artifact` replaced by what the test says a production +version holds, so no MLflow is needed; the CaMa survival record is a small stand-in for what a run publishes. +""" + +import json +from types import SimpleNamespace + +import pytest + +RECORD = {"horizons_months": [6, 12, 18], "points": {"COMB": {"S": [0.9, 0.8, 0.7], "low": [0.8, 0.7, 0.6], "high": [0.95, 0.9, 0.8]}}} + + +@pytest.fixture +def client(monkeypatch): + from flask import Flask + + from models.io import registry as registry_module + from webapi.model_analysis import model_analysis_blueprint + + app = Flask(__name__) + app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama") + monkeypatch.setenv("DEV_REVISION", "pruebas") + holder = SimpleNamespace(files={"analisis/curvas.json": json.dumps(RECORD).encode()}, production="3") + + def resolve(domain, scenario, version=None): + if holder.production is None: + raise LookupError("no hay una versión en producción") + return SimpleNamespace(version=holder.production, run_id="run-1") + + def artifact(domain, scenario, version, path): + if path not in holder.files: + raise LookupError(f"la corrida no tiene el artefacto {path!r}") + return path.rsplit("/", 1)[-1], holder.files[path] + + monkeypatch.setattr(registry_module.registry, "resolve", resolve) + monkeypatch.setattr(registry_module.registry, "artifact", artifact) + with app.test_client() as test_client: + test_client.holder = holder + yield test_client + + +def test_it_serves_the_production_versions_record_and_names_the_version(client): + """Pins down: the answer carries the record unchanged, the model and version it comes from and the simulated-data + flag. Fails if the record is altered on the way or the answer stops saying which version it is.""" + body = client.get("/cama/modelo/curvas").get_json() + + assert body["curvas"] == RECORD and body["simulado"] is True + assert body["modelo"] == {"nombre": "cama-survival", "version": "3", "mlflow_run_id": "run-1"} + + +def test_without_a_version_in_production_or_a_record_it_is_a_404(client): + """Pins down: no production version, and a version whose run published no `analisis/curvas.json`, are both a 404 + with the reason, never an empty record. Fails if either becomes a 200 or a 500.""" + client.holder.files.clear() + missing_record = client.get("/cama/modelo/curvas") + client.holder.production = None + no_version = client.get("/cama/modelo/curvas") + + assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"] + assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"] diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index f89e3dc..e0bf2dc 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -68,14 +68,16 @@ def test_volver_a_correr_no_agrega_reportes(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.""" + as many members as it counts. TEA has no dbt cohorts, so no cohort step; CaCu's include the surveillance cohort + and CaMa's the total cohort. 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": + if proyecto == "tea": assert "cohorts" not in [p.name for p in pasos] return armados = [p.summary for p in pasos if p.name == "cohorts"][0] - assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados + principal = {"cacu": "cacu/cohorte_vigilancia", "cama": "cama/cohorte_total"}[proyecto] + assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and principal in armados with motor.connect() as con: assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados) for armado_id, _ in armados.values(): diff --git a/tests/test_pathology_report_wording.py b/tests/test_pathology_report_wording.py new file mode 100644 index 0000000..0828fa6 --- /dev/null +++ b/tests/test_pathology_report_wording.py @@ -0,0 +1,52 @@ +"""What this module covers: how silver reads the wording of a breast pathology report's text layer, as the hospital's +reports (and dev-data's synthetic ones) print it: the grade after a histological type that says "no especial", the +HER2 caption with its method in parentheses, and Ki-67 under its long caption. Each case is one report fragment. + +Fixtures: none; the extractor is `silver.cama.DEL_REPORTE_DE_PATOLOGIA`, fed text through `lineas_de_texto`. +""" + +import pytest + +from webapi.orchestration.silver.cama import DEL_REPORTE_DE_PATOLOGIA +from webapi.orchestration.silver.extracted import lineas_de_texto + +DIAGNOSTICO = ( + "BIOPSIA: CARCINOMA DUCTAL INFILTRANTE (CARCINOMA INVASOR DE TIPO NO ESPECIAL) (8500/3), GRADO HISTOLÓGICO {g} " + "DE NOTTINGHAM (PUNTAJE 6/9). INVASIÓN LINFOVASCULAR: NO IDENTIFICADA." +) + + +def _leer(texto: str) -> dict: + extractor = DEL_REPORTE_DE_PATOLOGIA._extraer # the cached reader of text, as `leer` calls it + return extractor(texto) + + +@pytest.mark.parametrize("grado, codigo", [(1, "G1"), (2, "G2"), (3, "G3")]) +def test_the_grade_after_a_type_that_says_no_especial_is_read(grado, codigo): + """Pins down: "TIPO NO ESPECIAL" names a histological type, it does not deny what follows, so the Nottingham grade + later in the same line is still read. Fails if "no especial" stops being a pseudo-trigger of the negation context.""" + assert _leer(DIAGNOSTICO.format(g=grado))["biopsia.grado_nottingham"][0] == codigo + + +@pytest.mark.parametrize("texto, codigo", [ + ("HER2/neu (IHQ): NEGATIVO (0)", "H0"), ("HER2/neu (IHQ): NEGATIVO (1+)", "H1"), + ("HER2/neu (IHQ): EQUÍVOCO (2+)", "H2"), ("HER2/neu (IHQ): POSITIVO (3+)", "H3"), +]) +def test_her2_is_read_with_its_method_in_the_caption(texto, codigo): + """Pins down: a caption "HER2/neu (IHQ):" gives the score that follows it, not the "(IHQ):" of its own method. + Fails if the longer captions leave the catalog's `etiquetas_fuente` for HER2.""" + assert _leer(texto)["biopsia.her2"][0] == codigo + + +def test_ki67_is_read_under_its_long_caption_and_not_from_the_name(): + """Pins down: "Índice de proliferación Ki-67: 25 %" gives 25, not the 67 of the marker's name. Fails if the long + caption leaves the catalog's `etiquetas_fuente` for Ki-67.""" + assert float(_leer("Índice de proliferación Ki-67: 25 %")["biopsia.ki67_pct"][0]) == 25.0 + + +@pytest.mark.parametrize("tipo", ["CARCINOMA MUCINOSO", "CARCINOMA TUBULAR", + "CARCINOMA DUCTAL Y LOBULILLAR INFILTRANTE (MIXTO)"]) +def test_the_rarer_invasive_types_are_read_as_other(tipo): + """Pins down: a mucinous, tubular or mixed carcinoma is read as `OTRO` rather than left unresolved or taken as + ductal or lobular. Fails if their aliases leave the catalog.""" + assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == "OTRO" diff --git a/uv.lock b/uv.lock index 36bfe76..451ff3f 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -2068,32 +2068,64 @@ notebooks = [ { name = "nbclient" }, { name = "nbconvert" }, ] +survival-curves = [ + { name = "mpmath" }, + { name = "scipy" }, +] [package.metadata] requires-dist = [ { name = "apache-hamilton", specifier = ">=1.90" }, + { name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" }, { name = "extraction", editable = "../Extraction" }, { name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" }, + { name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" }, { name = "mlflow", specifier = ">=2.9" }, + { name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" }, + { name = "mpmath", marker = "extra == 'survival-curves'", specifier = ">=1.3" }, { name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" }, { name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" }, + { name = "networkx", marker = "extra == 'seer-survival'", specifier = ">=3.0" }, { name = "pandas", specifier = ">=2.0" }, { name = "pandera", specifier = ">=0.20" }, { name = "persistance", editable = "../Persistance" }, + { name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" }, { name = "pyarrow", specifier = ">=15" }, { name = "scikit-learn", specifier = ">=1.4" }, + { name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" }, + { name = "scipy", marker = "extra == 'survival-curves'", specifier = ">=1.11" }, + { name = "statsmodels", marker = "extra == 'seer-survival'", specifier = ">=0.14" }, { name = "tea", editable = "../models/libs/tea" }, { name = "tea", extras = ["s3"], marker = "extra == 'eeg-reference'", editable = "../models/libs/tea" }, ] -provides-extras = ["eeg-reference", "notebooks"] +provides-extras = ["eeg-reference", "notebooks", "seer-survival", "survival-curves", "seer-survival-dca"] [package.metadata.requires-dev] dev = [ { name = "ipykernel", specifier = ">=6.29" }, + { name = "matplotlib", specifier = ">=3.8" }, + { name = "mpmath", specifier = ">=1.3" }, { name = "nbclient", specifier = ">=0.10" }, { name = "nbconvert", specifier = ">=7.16" }, + { name = "networkx", specifier = ">=3.0" }, + { name = "pgmpy", specifier = ">=1.0" }, { name = "pytest", specifier = ">=8.0.0" }, { name = "reportlab", specifier = ">=4.0" }, + { name = "scipy", specifier = ">=1.11" }, + { name = "statsmodels", specifier = ">=0.14" }, +] +notebooks = [ + { name = "graphviz", specifier = ">=0.20" }, + { name = "ipykernel", specifier = ">=6.29" }, +] + +[[package]] +name = "mpmath" +version = "1.4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c5/b0/6de8e78014ff1842a90cc9a56da6ccfb598a5390ed0257fcdb7d9680c18b/mpmath-1.4.1.tar.gz", hash = "sha256:efd6d1b75f09d69524a67609949812668b28e81ecbfe0ab449ced8c13e92642e", size = 2093211, upload-time = "2026-03-15T01:17:38.245Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/13/f2/abeec3db71d221ccd3cd89d206be1fabf5a3ee7178862f5fba23a59607e0/mpmath-1.4.1-py3-none-any.whl", hash = "sha256:dc4f0ea2304480d4a9a48a94c1020571558ade522b44a6912efac63a586e140f", size = 567787, upload-time = "2026-03-15T01:17:36.392Z" }, ] [[package]] @@ -4503,7 +4535,7 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "models", extra = ["notebooks"] }, + { name = "models", extra = ["notebooks", "survival-curves"] }, { name = "openpyxl" }, { name = "pandas" }, { name = "pdfplumber" }, @@ -4539,7 +4571,7 @@ requires-dist = [ { name = "flask", specifier = ">=3.0" }, { name = "flask-cors", specifier = ">=4.0" }, { name = "gunicorn", specifier = ">=23.0" }, - { name = "models", extras = ["notebooks"], editable = "../models" }, + { name = "models", extras = ["notebooks", "survival-curves"], editable = "../models" }, { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2.0" }, { name = "pdfplumber", specifier = ">=0.11" }, diff --git a/webapi/__init__.py b/webapi/__init__.py index fd5a899..3a8323f 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -95,13 +95,17 @@ def create_app() -> Flask: # Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's # `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined. from persistance import cacu as cacu_repositories + from persistance import cama as cama_repositories from persistance.db import get_cacu_session, get_cama_session + from webapi.model_analysis import model_analysis_blueprint from webapi.risk_batches import risk_batches_blueprint app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama") app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis") app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu") + app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama") + app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama") return app diff --git a/webapi/fhir/__init__.py b/webapi/fhir/__init__.py index 330c5d4..0cab556 100644 --- a/webapi/fhir/__init__.py +++ b/webapi/fhir/__init__.py @@ -9,7 +9,7 @@ individual risk. GET CodeSystem, CodeSystem/, ValueSet/ the project's code systems GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only) GET Patient//$resumen-tea TEA's patient summary (DEV only) - GET RiskAssessment?subject=Patient/ CaCu's individual risk, the current batch (DEV only) + GET RiskAssessment?subject=Patient/ CaCu's and CaMa's individual risk, the current batch (DEV only) Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are `OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`. @@ -28,6 +28,7 @@ from webapi.fhir.terminology import code_systems, metric_value_set from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of from webapi.metrics import Question, UndecidedRule +RISK_DOMAINS = ("cacu", "cama") # the domains whose patients' individual risk is served as a RiskAssessment TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion") @@ -38,7 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: blueprint = Blueprint(f"{project}_fhir", __name__) titles = labels(manifest) patients = with_patients and project == "tea" - risks = with_patients and project == "cacu" + risks = with_patients and project in RISK_DOMAINS def definitions() -> dict: """The domain's measures by their FHIR id; `definition()` also takes the dbt id.""" @@ -176,13 +177,15 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: if patients: _patient_routes(blueprint, repositories, now) if risks: - _risk_routes(blueprint, repositories) + _risk_routes(blueprint, repositories, project) return blueprint -def _risk_routes(blueprint: Blueprint, repositories) -> None: - """CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data).""" - from webapi.fhir import cacu +def _risk_routes(blueprint: Blueprint, repositories, project: str) -> None: + """A patient's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data).""" + from importlib import import_module + + domain = import_module(f"webapi.fhir.{project}") @blueprint.get("/RiskAssessment") def risk_assessments(): @@ -196,7 +199,7 @@ def _risk_routes(blueprint: Blueprint, repositories) -> None: 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())] + found = [] if risk is None else [domain.risk_assessment(pac_id, risk, simulated_data())] return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset)) diff --git a/webapi/fhir/cacu.py b/webapi/fhir/cacu.py index 46e3765..7d96a75 100644 --- a/webapi/fhir/cacu.py +++ b/webapi/fhir/cacu.py @@ -1,62 +1,12 @@ -"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data). +"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by +`webapi.fhir.risk` with CaCu's outcomes.""" -The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed -evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient: +from webapi.fhir import risk +from webapi.fhir.risk import DAYS_PER_YEAR, INTERVAL, MODEL, OUTCOME # noqa: F401 (kept for readers of this module) - id `-` - status the batch's state (`final`) - subject `Patient/`: 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: +def risk_assessment(pac_id: int, patient_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) + return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "cin2_mas") diff --git a/webapi/fhir/cama.py b/webapi/fhir/cama.py new file mode 100644 index 0000000..54e51cd --- /dev/null +++ b/webapi/fhir/cama.py @@ -0,0 +1,11 @@ +"""CaMa's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by +`webapi.fhir.risk` with CaMa's outcomes: the mortality at each horizon from the model's index date.""" + +from webapi.fhir import risk + +OUTCOMES = {"muerte": "Muerte por cualquier causa"} + + +def risk_assessment(pac_id: int, patient_risk, simulated: bool) -> dict: + """The patient's current risk (`PatientRisk`) as a `RiskAssessment`.""" + return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "muerte") diff --git a/webapi/fhir/risk.py b/webapi/fhir/risk.py new file mode 100644 index 0000000..84bf7b6 --- /dev/null +++ b/webapi/fhir/risk.py @@ -0,0 +1,60 @@ +"""A patient's individual risk in FHIR R4: one `RiskAssessment` per batch and patient, built from `PatientRisk` +(`CohortRepository.current_risk`: the newest batch with a confirmed evaluation). + + id `-` + status the batch's state (`final`) + subject `Patient/`: the platform's key (TEA keeps a pseudonym until its patients get + their own identity) + occurrenceDateTime when the batch was evaluated + method the registered model and its version (MLflow) + prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod` + from the risk's index date (the model's decision point) to that date plus the horizon; + the immediate risk (horizon 0) is a period of one day. A confidence interval, when the + model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a + decimal or a range, not both). + +Not yet: `basis` (the observations the model used) and `mitigation`. Each domain gives its outcomes' codes and labels +(`webapi.fhir.cacu`, `webapi.fhir.cama`). +""" + +from datetime import date, datetime, timedelta, timezone + +from 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" +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, outcomes: dict[str, str], default_outcome: str) -> dict: + """The patient's current risk (`PatientRisk`) as a `RiskAssessment`; `outcomes` maps the domain's outcome codes to + their labels, and `default_outcome` stands for a batch that doesn't name one.""" + desenlace = risk.desenlace or default_outcome + outcome = concept(OUTCOME, desenlace, outcomes.get(desenlace)) + resource = { + "resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote, + "subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en), + "method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]}, + "prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes], + } + return tagged(resource, simulated) diff --git a/webapi/imports/schemas/cama/paciente.py b/webapi/imports/schemas/cama/paciente.py index 563d434..5bdf32c 100644 --- a/webapi/imports/schemas/cama/paciente.py +++ b/webapi/imports/schemas/cama/paciente.py @@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema from webapi.imports.schemas.coercion import ( Catalog, CatalogValue, + FlexDate, PostalCode, RequiredDate, RequiredHospitalId, @@ -25,6 +26,8 @@ class PacienteImportSchema(ImportSchema): pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None # IND-01: required, since age at each event of interest is derived from it. pac_fecha_nacimiento: RequiredDate + # Survival's outcome; empty while she is alive or the date is unknown. + pac_fecha_defuncion: FlexDate = None pac_codigo_postal: PostalCode = None pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py new file mode 100644 index 0000000..95f9359 --- /dev/null +++ b/webapi/model_analysis.py @@ -0,0 +1,35 @@ +"""What a model's production version found about its cohort: `GET //modelo/curvas`. + +The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's +survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the +cohort, not any patient. The answer names the version they come from, and carries `simulado: true` in DEV, where the +data are simulated. 404 while the scenario has no version in production, or its version has no such record. +""" + +import json + +from flask import Blueprint, jsonify + +from webapi.fhir.common import simulated_data + + +def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: + """The blueprint of one scenario, to register with `url_prefix="/"`.""" + blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__) + + @blueprint.get("/modelo/curvas") + def curves(): + """The curves and points of the scenario's production version.""" + from models.io.registry import registry + + try: + resolved = registry.resolve(domain, scenario) + _, content = registry.artifact(domain, scenario, resolved.version, "analisis/curvas.json") + except LookupError as error: + return jsonify({"error": f"sin curvas: {error}"}), 404 + return jsonify({"simulado": simulated_data(), + "modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version), + "mlflow_run_id": resolved.run_id}, + "curvas": json.loads(content)}) + + return blueprint diff --git a/webapi/orchestration/estimators.py b/webapi/orchestration/estimators.py index 31a762c..709d219 100644 --- a/webapi/orchestration/estimators.py +++ b/webapi/orchestration/estimators.py @@ -25,15 +25,16 @@ class Provenance: return {key: value for key, value in self.__dict__.items() if value} -class Cin2LogisticEstimator: - """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to - test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has - something to report when `estimate` calls it.""" +class ScenarioEstimator: + """Scores a domain's cohort with the version of one scenario that is in production (or `version`, to test a + candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has something to + report when `estimate` calls it.""" - def __init__(self, domain: str = "cacu", version: str | None = None): + def __init__(self, domain: str, scenario: str, version: str | None = None): self.domain = domain + self.scenario = scenario self.version = version - self.desenlace = "cin2_mas" + self.desenlace = "" self._provenance: Provenance | None = None def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]: @@ -49,7 +50,7 @@ class Cin2LogisticEstimator: from models.steps.risks import risk_rows repos = import_module(f"persistance.{self.domain}") - scenario = Scenario.load(self.domain, "cin2_logistic") + scenario = Scenario.load(self.domain, self.scenario) build_id = repos.cohort_repository.latest_build(scenario.cohort) resolved = registry.resolve(self.domain, scenario.scenario, self.version) frame = KitBuild(self.domain, build_id).frame() @@ -67,11 +68,39 @@ class Cin2LogisticEstimator: return self._provenance +class Cin2LogisticEstimator(ScenarioEstimator): + """Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`).""" + + def __init__(self, domain: str = "cacu", version: str | None = None): + super().__init__(domain, "cin2_logistic", version) + self.desenlace = "cin2_mas" + + +# The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production +# scores the cohort it names. +LIVE_SCENARIOS = {"cama": ("survival",)} + + +def _scenario_estimators(domain: str) -> dict[str, Any]: + from models.dags.training import Scenario + from models.io.registry import registry + + found = {} + for name in LIVE_SCENARIOS.get(domain, ()): + scenario = Scenario.load(domain, name) + try: + registry.resolve(domain, name) + except LookupError: + continue + found[scenario.cohort] = ScenarioEstimator(domain, name) + return found + + 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 {} + return _scenario_estimators(domain) from models.dags.training import Scenario from models.io.registry import registry diff --git a/webapi/orchestration/silver/persons.py b/webapi/orchestration/silver/persons.py index 613c760..ae7f31e 100644 --- a/webapi/orchestration/silver/persons.py +++ b/webapi/orchestration/silver/persons.py @@ -25,6 +25,12 @@ def de_derechohabiente(paciente) -> dict: } +def con_defuncion(paciente) -> dict: + """Lo de `de_derechohabiente` y la fecha de defunción, el desenlace de la supervivencia: nula mientras vive o si se + desconoce.""" + return {**de_derechohabiente(paciente), "fecha_defuncion": paciente.pac_fecha_defuncion} + + def con_sexo(paciente) -> dict: """Lo que la persona de TEA agrega: el sexo, como código.""" return {"sexo": codigo(paciente.pac_sexo)} diff --git a/webapi/orchestration/tables/cama.py b/webapi/orchestration/tables/cama.py index c1a7b5f..da4c23b 100644 --- a/webapi/orchestration/tables/cama.py +++ b/webapi/orchestration/tables/cama.py @@ -34,7 +34,7 @@ from core.cama.indicadores.models import ( Persona, ) -from webapi.orchestration.silver.persons import de_derechohabiente +from webapi.orchestration.silver.persons import con_defuncion from core.indicadores.cohortes import TablasCohorte from webapi.orchestration.tables import TablasKit @@ -63,7 +63,7 @@ TABLAS = TablasKit( CatMeasureEstrato=CatMeasureEstrato, MeasureReportUnidad=MeasureReportUnidad, MeasureReportUnidadEstrato=MeasureReportUnidadEstrato, - persona_propias=de_derechohabiente, + persona_propias=con_defuncion, ) # Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003; MD-12). diff --git a/webapi/risk_batches.py b/webapi/risk_batches.py index 3319d6c..8e739fe 100644 --- a/webapi/risk_batches.py +++ b/webapi/risk_batches.py @@ -9,9 +9,10 @@ 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__) +def risk_batches_blueprint(repositories, name: str = "risk_batches") -> Blueprint: + """The blueprint, to register with `url_prefix="/"`. `repositories` is `persistance.`; `name` is + unique per domain registered.""" + blueprint = Blueprint(name, __name__) @blueprint.get("/riesgos/lotes") def list_pending_batches(): -- 2.53.0 From 2ee95576a811625ab04c34ec89ec7dbdae7855d6 Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 21 Nov 2026 02:14:26 -0600 Subject: [PATCH 12/23] Tests: the cycle builds every dbt cohort of each project, CaMa's survival cohort included Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- tests/test_orquestacion_ciclo.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/test_orquestacion_ciclo.py b/tests/test_orquestacion_ciclo.py index f89e3dc..016126d 100644 --- a/tests/test_orquestacion_ciclo.py +++ b/tests/test_orquestacion_ciclo.py @@ -66,16 +66,18 @@ def test_volver_a_correr_no_agrega_reportes(bases): assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes -def test_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases): +def test_arma_cada_cohorte_de_dbt_una_vez(bases): """Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores - as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from - anywhere else than dbt, or a build's count and members disagree.""" + as many members as it counts (CaCu's, CaMa's survival cohort); a project without dbt cohorts (TEA) has no cohort + step. Fails if a cohort comes from anywhere else than dbt, or a build's count and members disagree.""" proyecto, ctx, motor, _, pasos = bases - if proyecto != "cacu": + urls = set(cohort_urls(proyecto, ctx.dbt_manifest)) + if not urls: assert "cohorts" not in [p.name for p in pasos] return armados = [p.summary for p in pasos if p.name == "cohorts"][0] - assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados + assert set(armados) == urls + assert {"cacu": "cacu/cohorte_vigilancia", "cama": "cama/cohorte_supervivencia"}[proyecto] in armados with motor.connect() as con: assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados) for armado_id, _ in armados.values(): -- 2.53.0 From fae6b2232f3d3bf30c52a72bf2dcb7eff6f15db2 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 02:57:36 -0600 Subject: [PATCH 13/23] The CaCu timeline fixture knows the biopsy order, and the rare-type wording test uses the ICD-O-3 codes --- tests/test_orquestacion_timeline.py | 2 +- tests/test_pathology_report_wording.py | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_orquestacion_timeline.py b/tests/test_orquestacion_timeline.py index eda31fa..acfda7a 100644 --- a/tests/test_orquestacion_timeline.py +++ b/tests/test_orquestacion_timeline.py @@ -15,7 +15,7 @@ from pathlib import Path import pytest CORTE = date(2025, 12, 31) -INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"} +INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente", "orden_biopsia"} KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json" diff --git a/tests/test_pathology_report_wording.py b/tests/test_pathology_report_wording.py index 0828fa6..b73594d 100644 --- a/tests/test_pathology_report_wording.py +++ b/tests/test_pathology_report_wording.py @@ -44,9 +44,9 @@ def test_ki67_is_read_under_its_long_caption_and_not_from_the_name(): assert float(_leer("Índice de proliferación Ki-67: 25 %")["biopsia.ki67_pct"][0]) == 25.0 -@pytest.mark.parametrize("tipo", ["CARCINOMA MUCINOSO", "CARCINOMA TUBULAR", - "CARCINOMA DUCTAL Y LOBULILLAR INFILTRANTE (MIXTO)"]) -def test_the_rarer_invasive_types_are_read_as_other(tipo): - """Pins down: a mucinous, tubular or mixed carcinoma is read as `OTRO` rather than left unresolved or taken as - ductal or lobular. Fails if their aliases leave the catalog.""" - assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == "OTRO" +@pytest.mark.parametrize("tipo, codigo", [("CARCINOMA MUCINOSO", "8480/3"), ("CARCINOMA TUBULAR", "8211/3"), + ("CARCINOMA DUCTAL Y LOBULILLAR INFILTRANTE (MIXTO)", "8522/3")]) +def test_the_rarer_invasive_types_are_read_as_their_code(tipo, codigo): + """Pins down: a mucinous, tubular or mixed ductal and lobular carcinoma is read as its ICD-O-3 code rather than left + unresolved or taken as ductal or lobular. Fails if their names leave the catalog's aliases.""" + assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == codigo -- 2.53.0 From 2d71fe1103b62373fa2f86bb063bbcf92ccf2bc2 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 03:28:13 -0600 Subject: [PATCH 14/23] Lesion size extracted from pathology reports; development record route; scenario catalog and background training jobs in governance --- pyproject.toml | 2 +- tests/test_extracted_results.py | 4 +- tests/test_model_analysis.py | 17 ++- tests/test_pathology_report_wording.py | 11 ++ tests/test_training_jobs.py | 103 ++++++++++++++ uv.lock | 163 ++++++++++++++++++++++- webapi/blueprints/governance.py | 44 ++++++ webapi/model_analysis.py | 17 ++- webapi/orchestration/silver/cama.py | 2 +- webapi/orchestration/silver/extracted.py | 15 ++- webapi/training_jobs.py | 120 +++++++++++++++++ 11 files changed, 489 insertions(+), 9 deletions(-) create mode 100644 tests/test_training_jobs.py create mode 100644 webapi/training_jobs.py diff --git a/pyproject.toml b/pyproject.toml index c336e85..f1ce319 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ requires-python = ">=3.12" dependencies = [ "flask>=3.0", "persistance", - "models[notebooks,survival-curves]", + "models[notebooks,survival-curves,seer-survival]", "extraction", "apache-hamilton>=1.90", "pandas>=2.0", diff --git a/tests/test_extracted_results.py b/tests/test_extracted_results.py index 440f42e..69a3479 100644 --- a/tests/test_extracted_results.py +++ b/tests/test_extracted_results.py @@ -121,14 +121,14 @@ def test_a_stage_is_found_in_a_note_without_a_caption(): def test_a_pathology_pdf_s_text_layer_gives_its_results(): - """Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop + """Pins down: a PDF's text layer is read without OCR and every result on it comes out (the size, which the fixture report does not state, as nothing). Fails if bytes stop going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor.""" leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1]))) assert {r: v for r, (v, _) in leido.items()} == { "biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2", "biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0, "biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0, - "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, + "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, "biopsia.tamano_tumor_mm": None, } diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 2001b6e..6538a51 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -1,4 +1,4 @@ -"""What this module covers: `GET /cama/modelo/curvas` (`webapi.model_analysis`): it serves the production version's +"""What this module covers: `GET /cama/modelo/curvas` and `GET /cama/modelo/desarrollo` (`webapi.model_analysis`): they serve the production version's population record with the version it comes from, and answers 404 while there is no version in production or the version has no such record. @@ -62,3 +62,18 @@ def test_without_a_version_in_production_or_a_record_it_is_a_404(client): assert missing_record.status_code == 404 and "curvas.json" in missing_record.get_json()["error"] assert no_version.status_code == 404 and "producción" in no_version.get_json()["error"] + + +def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none(client): + """Pins down: `GET /cama/modelo/desarrollo` returns `analisis/desarrollo.json` with the version it comes from, and a + version trained before that record existed is a 404, not an empty page. Fails if the route reads another file or + answers 200 without a record.""" + record = {"tablas": {"or_lr_balanceada": [{"variable": "Grado"}]}, "figuras": {}} + client.holder.files["analisis/desarrollo.json"] = json.dumps(record).encode() + found = client.get("/cama/modelo/desarrollo") + del client.holder.files["analisis/desarrollo.json"] + missing = client.get("/cama/modelo/desarrollo") + + assert found.status_code == 200 and found.get_json()["desarrollo"] == record + assert found.get_json()["modelo"]["version"] == "3" + assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"] diff --git a/tests/test_pathology_report_wording.py b/tests/test_pathology_report_wording.py index b73594d..919b8cb 100644 --- a/tests/test_pathology_report_wording.py +++ b/tests/test_pathology_report_wording.py @@ -50,3 +50,14 @@ def test_the_rarer_invasive_types_are_read_as_their_code(tipo, codigo): """Pins down: a mucinous, tubular or mixed ductal and lobular carcinoma is read as its ICD-O-3 code rather than left unresolved or taken as ductal or lobular. Fails if their names leave the catalog's aliases.""" assert _leer(f"Diagnóstico: BIOPSIA: {tipo} (8480/3).")["biopsia.tipo_histologico"][0] == codigo + + +@pytest.mark.parametrize("texto", [ + "GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO DE LA LESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.", + "GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO DE LA\nLESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.", + "GRADO HISTOLÓGICO 2 DE NOTTINGHAM (PUNTAJE 6/9). TAMAÑO\nDE LA LESIÓN: 25 MM. INVASIÓN LINFOVASCULAR: NO.", +]) +def test_the_lesion_size_is_read_even_when_the_page_wraps_its_caption(texto): + """Pins down: "TAMAÑO DE LA LESIÓN: 25 MM" gives 25 whether it is on one line or the page wraps it between words, + because the extractor also sees each pair of adjacent lines joined. Fails if the joined lines stop being offered.""" + assert float(_leer(texto)["biopsia.tamano_tumor_mm"][0]) == 25.0 diff --git a/tests/test_training_jobs.py b/tests/test_training_jobs.py new file mode 100644 index 0000000..50728ba --- /dev/null +++ b/tests/test_training_jobs.py @@ -0,0 +1,103 @@ +"""What this module covers: the scenarios governance can train and the background training jobs (`webapi.training_jobs` +and their routes in `webapi.blueprints.governance`): the catalog, a job's states (running, completed, failed, trained but +not promoted, interrupted), and the refusal to start a second job of a scenario that is running. + +Fixtures: `app_client`, the governance blueprint on a bare Flask app with `INDICADORES_DIR` in a temporary folder and the +job's command replaced by a Python one-liner the test chooses, so no model is trained. `esperar` waits for a job to leave +`en_curso`. +""" + +import sys +import time + +import pytest +from flask import Flask + +from webapi import training_jobs +from webapi.blueprints.governance import governance_bp + + +@pytest.fixture +def app_client(tmp_path, monkeypatch): + monkeypatch.setenv("INDICADORES_DIR", str(tmp_path)) + monkeypatch.setenv("DBT_MANIFEST", str(tmp_path / "manifest.json")) + app = Flask(__name__) + app.register_blueprint(governance_bp, url_prefix="/governance") + with app.test_client() as client: + yield client + + +def _command_that(code: str): + return lambda domain, scenario: [sys.executable, "-c", code] + + +def esperar(client, job_id, timeout=20): + deadline = time.time() + timeout + while time.time() < deadline: + job = client.get(f"/governance/training-jobs/{job_id}").get_json()["job"] + if job["estado"] != "en_curso": + return job + time.sleep(0.1) + raise AssertionError("the job did not finish") + + +def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings(): + """Pins down: every scenario with its own `model.toml` and a cohort is listed (CaCu, CaMa), TEA's EEG is listed as + trained on its reference, and the SEER pipeline's settings file is not a scenario. Fails if a scenario stops being + discoverable or a settings file starts showing as one.""" + entries = {(s["domain"], s["scenario"]): s for s in training_jobs.catalog()} + + assert ("cama", "survival") in entries and ("cacu", "cin2_logistic") in entries + assert entries[("tea", "eeg")]["kind"] == "referencia" and entries[("cama", "survival")]["kind"] == "cohorte" + assert ("cama", "seer_survival") not in entries + + +@pytest.mark.parametrize("code,estado", [ + ("print('trained: version 4')", "completado"), + ("import sys; print('boom', file=sys.stderr); sys.exit(1)", "fallido"), + ("import sys; print('version 4 not promoted, missing MLD-01', file=sys.stderr); sys.exit(1)", "entrenado_sin_promover"), +]) +def test_a_job_ends_as_completed_failed_or_trained_without_promotion(app_client, monkeypatch, code, estado): + """Pins down: the job's state comes from its exit code and its error output, and carries both outputs. Fails if a + failure is shown as done, or a version that only lacks its reports is shown as failed.""" + monkeypatch.setattr(training_jobs, "_command", _command_that(code)) + + started = app_client.post("/governance/model-versions/cama/survival/train-jobs") + job = esperar(app_client, started.get_json()["job"]["id"]) + + assert started.status_code == 202 and job["estado"] == estado + assert ("trained" in job["salida"]) or ("boom" in job["error"]) or ("not promoted" in job["error"]) + + +def test_a_second_job_of_a_running_scenario_is_refused_with_the_running_one(app_client, monkeypatch): + """Pins down: while a scenario's job runs, starting another answers 409 with that job, and another scenario still + starts. Fails if two trainings of one model can run at once, which would register the same version twice.""" + monkeypatch.setattr(training_jobs, "_command", _command_that("import time; time.sleep(3)")) + first = app_client.post("/governance/model-versions/cama/survival/train-jobs") + again = app_client.post("/governance/model-versions/cama/survival/train-jobs") + other = app_client.post("/governance/model-versions/cacu/cin2_logistic/train-jobs") + + assert first.status_code == 202 and again.status_code == 409 + assert again.get_json()["job"]["id"] == first.get_json()["job"]["id"] + assert other.status_code == 202 + + +def test_a_job_whose_process_is_gone_without_an_exit_code_is_interrupted(app_client, tmp_path): + """Pins down: a job file with no exit file and a dead process reads `interrumpido`, not `en_curso` forever. Fails if + a killed worker leaves its job running in the list.""" + folder = tmp_path / "entrenamientos" / "20260101T000000-aaaaaa" + folder.mkdir(parents=True) + (folder / "job.json").write_text('{"id": "20260101T000000-aaaaaa", "domain": "cama", "scenario": "survival", ' + '"pid": 2147483646, "iniciado": "2026-01-01T00:00:00+00:00"}') + + assert app_client.get("/governance/training-jobs/20260101T000000-aaaaaa").get_json()["job"]["estado"] == "interrumpido" + assert [j["id"] for j in app_client.get("/governance/training-jobs").get_json()["jobs"]] == ["20260101T000000-aaaaaa"] + + +def test_an_unknown_scenario_or_job_is_a_404_and_no_manifest_is_a_503(app_client, monkeypatch): + """Pins down: starting an unknown scenario, or reading an unknown job, is a 404; a cohort scenario with no dbt + manifest configured is a 503 and starts nothing. Fails if either becomes a 500 or starts a process.""" + assert app_client.post("/governance/model-versions/cama/nope/train-jobs").status_code == 404 + assert app_client.get("/governance/training-jobs/nada").status_code == 404 + monkeypatch.delenv("DBT_MANIFEST") + assert app_client.post("/governance/model-versions/cama/survival/train-jobs").status_code == 503 diff --git a/uv.lock b/uv.lock index 451ff3f..729b021 100644 --- a/uv.lock +++ b/uv.lock @@ -992,6 +992,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/86/32914542064b8aee77ac48142f8a1955df78da4eb905dd41697d26941d21/fhir_resources-8.3.0-py2.py3-none-any.whl", hash = "sha256:151e6c9b4336e36383cc2aaf2067a6f112a420fce1c7bd289182e55dd950871b", size = 2288069, upload-time = "2026-07-03T15:23:51.97Z" }, ] +[[package]] +name = "filelock" +version = "4.2.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/aa/8ccff8da9a27e089727fcffd3c5b61708383217e47eb1e1b8af37b1dd166/filelock-4.2.12.tar.gz", hash = "sha256:7e7da24d3ac39268b0f156e56870001de44886318f092f9d851e692f7114d6dd", size = 680837, upload-time = "2026-11-18T01:20:03.951Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/c9/eb6b6528c7edb958d4c24ac47a8b94113d9de36e4cfc6eecd599b1a4f349/filelock-4.2.12-py3-none-any.whl", hash = "sha256:21decfec02f116ed4c954433cdb31f28c3b346b784543177b6d7059da2702ee9", size = 222442, upload-time = "2026-11-18T01:20:02.439Z" }, +] + [[package]] name = "flask" version = "3.1.3" @@ -1354,6 +1363,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" }, + { url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" }, + { url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" }, + { url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" }, + { url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" }, + { url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" }, + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "httpcore2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" }, +] + +[[package]] +name = "httpx2" +version = "2.16.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" }, + { name = "idna" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, +] + [[package]] name = "huey" version = "3.4.0" @@ -1363,6 +1435,26 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/57/31/cee585bd4d1e39947a426a6736f4e17d22b454952370fb9cf48eb3103085/huey-3.4.0-py3-none-any.whl", hash = "sha256:d0580762397744026f83baae5f2b97a62474a62b8565ac75bbafefe72f9c784f", size = 136493, upload-time = "2026-09-04T02:04:32.848Z" }, ] +[[package]] +name = "huggingface-hub" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "httpx2" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" }, +] + [[package]] name = "idna" version = "3.20" @@ -2068,6 +2160,14 @@ notebooks = [ { name = "nbclient" }, { name = "nbconvert" }, ] +seer-survival = [ + { name = "matplotlib" }, + { name = "mpmath" }, + { name = "networkx" }, + { name = "pgmpy" }, + { name = "scipy" }, + { name = "statsmodels" }, +] survival-curves = [ { name = "mpmath" }, { name = "scipy" }, @@ -2425,6 +2525,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/09/ed/559d2915dce85794bc0c36064043da170da50cd98746dcbddd85d5932017/nest_asyncio2-1.7.4-py3-none-any.whl", hash = "sha256:86e77b52c3d1496b294af3c944b44213b9b82a12a5ee590c0acc4ca4692ef6c7", size = 8543, upload-time = "2026-10-07T22:31:49.245Z" }, ] +[[package]] +name = "networkx" +version = "3.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" }, +] + [[package]] name = "numba" version = "0.68.1" @@ -2596,6 +2705,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" }, ] +[[package]] +name = "opt-einsum" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004, upload-time = "2024-09-26T14:33:24.483Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932, upload-time = "2024-09-26T14:33:23.039Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -2795,6 +2913,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" }, ] +[[package]] +name = "pgmpy" +version = "1.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, + { name = "joblib" }, + { name = "networkx" }, + { name = "numpy" }, + { name = "opt-einsum" }, + { name = "pandas" }, + { name = "pyparsing" }, + { name = "scikit-base" }, + { name = "scikit-learn" }, + { name = "scipy" }, + { name = "statsmodels" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/9a/b94ccd1d6cbf2982937c26e54e887b47ee10f848ad53c4427965578a358d/pgmpy-1.1.2.tar.gz", hash = "sha256:a62a89352f139a5d459839e54e6bfa202a7d8749e6dc6d7ceec088a71529af45", size = 2183113, upload-time = "2026-04-30T11:34:49.538Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c6/5d/d03634ed296986abad834a69b0df21510cc9b6c40fb8afaed5df1c4b6074/pgmpy-1.1.2-py3-none-any.whl", hash = "sha256:e55c78763a4a45dd644a13b250cea86af0c7e08590cf35de489624f34a4d9a0b", size = 2446383, upload-time = "2026-04-30T11:34:47.189Z" }, +] + [[package]] name = "pillow" version = "12.3.0" @@ -3858,6 +3999,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" }, ] +[[package]] +name = "scikit-base" +version = "1.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/e9/287707e71be93558076d873f92444fa788c1a11c259982a1967ad2071b0e/scikit_base-1.2.1.tar.gz", hash = "sha256:6cccfab1cf51e36141b731fe3248bd3c1a55361e965ddc7457be75ad8a9803eb", size = 136836, upload-time = "2026-11-08T20:24:26.859Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/b4/21adac81fbb522bdbb74c4809c7ea06fbde847a24c54b68dfed1519ff3dc/scikit_base-1.2.1-py3-none-any.whl", hash = "sha256:8695538dcf61c5439752b56baeca9d4ce52de012ddc4cee50ee67c910a9b5fb9", size = 163886, upload-time = "2026-11-08T20:24:25.324Z" }, +] + [[package]] name = "scikit-learn" version = "1.9.1" @@ -4356,6 +4506,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "typeguard" version = "4.6.0" @@ -4535,7 +4694,7 @@ dependencies = [ { name = "flask" }, { name = "flask-cors" }, { name = "gunicorn" }, - { name = "models", extra = ["notebooks", "survival-curves"] }, + { name = "models", extra = ["notebooks", "seer-survival", "survival-curves"] }, { name = "openpyxl" }, { name = "pandas" }, { name = "pdfplumber" }, @@ -4571,7 +4730,7 @@ requires-dist = [ { name = "flask", specifier = ">=3.0" }, { name = "flask-cors", specifier = ">=4.0" }, { name = "gunicorn", specifier = ">=23.0" }, - { name = "models", extras = ["notebooks", "survival-curves"], editable = "../models" }, + { name = "models", extras = ["notebooks", "survival-curves", "seer-survival"], editable = "../models" }, { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2.0" }, { name = "pdfplumber", specifier = ">=0.11" }, diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index 68f91d7..dd7c11d 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -117,6 +117,50 @@ def train_model_version(domain: str, scenario: str): return jsonify({"error": error or "No se pudo entrenar el modelo.", "output": output}), status +@governance_bp.get("/scenarios") +def trainable_scenarios(): + """The scenarios that can be trained from here, each with its production version if it has one.""" + from webapi import training_jobs + + result = [] + for entry in training_jobs.catalog(): + try: + production = str(registry.resolve(entry["domain"], entry["scenario"]).version) + except LookupError: + production = None + result.append({**entry, "produccion": production}) + return jsonify({"scenarios": result}) + + +@governance_bp.post("/model-versions///train-jobs") +def start_training_job(domain: str, scenario: str): + """Starts the scenario's training in the background and answers 202 with the job; a job of that scenario that is + still running is answered 409 with it. 404 for a scenario that cannot be trained, 503 with no dbt manifest.""" + from webapi import training_jobs + + if training_jobs.running(domain, scenario) is not None: + return jsonify({"error": "Ya hay un entrenamiento en curso para este modelo.", + "job": training_jobs.running(domain, scenario)}), 409 + try: + return jsonify({"job": training_jobs.start(domain, scenario)}), 202 + except RuntimeError as error: + return jsonify({"error": str(error)}), 503 + + +@governance_bp.get("/training-jobs") +def list_training_jobs(): + from webapi import training_jobs + + return jsonify({"jobs": training_jobs.jobs()}) + + +@governance_bp.get("/training-jobs/") +def training_job(job_id: str): + from webapi import training_jobs + + return jsonify({"job": training_jobs.get(job_id)}) + + @governance_bp.patch("/model-versions////reports") def attach_reports(domain: str, scenario: str, version: str): """MLD-01/01b/03 documents, usually written after training.""" diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 95f9359..697eb6c 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -1,4 +1,4 @@ -"""What a model's production version found about its cohort: `GET //modelo/curvas`. +"""What a model's production version found about its cohort: `GET //modelo/curvas` and `GET //modelo/desarrollo`. The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the @@ -32,4 +32,19 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: "mlflow_run_id": resolved.run_id}, "curvas": json.loads(content)}) + @blueprint.get("/modelo/desarrollo") + def development(): + """The development stages' tables and figures of the scenario's production version.""" + from models.io.registry import registry + + try: + resolved = registry.resolve(domain, scenario) + _, content = registry.artifact(domain, scenario, resolved.version, "analisis/desarrollo.json") + except LookupError as error: + return jsonify({"error": f"sin desarrollo: {error}"}), 404 + return jsonify({"simulado": simulated_data(), + "modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version), + "mlflow_run_id": resolved.run_id}, + "desarrollo": json.loads(content)}) + return blueprint diff --git a/webapi/orchestration/silver/cama.py b/webapi/orchestration/silver/cama.py index 4716e56..9332bb4 100644 --- a/webapi/orchestration/silver/cama.py +++ b/webapi/orchestration/silver/cama.py @@ -33,7 +33,7 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto( "cama", ("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno", "biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct", - "biopsia.her2", "biopsia.ki67_pct"), + "biopsia.her2", "biopsia.ki67_pct", "biopsia.tamano_tumor_mm"), texto=lambda f: f.bx_pdf_blob, ) DE_LA_NOTA = DesdeTexto( diff --git a/webapi/orchestration/silver/extracted.py b/webapi/orchestration/silver/extracted.py index dee3604..7ac8666 100644 --- a/webapi/orchestration/silver/extracted.py +++ b/webapi/orchestration/silver/extracted.py @@ -42,6 +42,19 @@ def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]: return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)] +def con_renglones_unidos(lineas: list[SegmentLine]) -> list[SegmentLine]: + """The lines and, after them, each pair of consecutive lines of a page joined: a caption that the page wraps ("TAMAÑO + DE LA" / "LESIÓN: 25 MM") is whole in one of them. A value found in both counts as found twice, which doesn't change + which one wins.""" + unidas = [] + for a, b in zip(lineas, lineas[1:]): + if a.page_number != b.page_number or a.document != b.document: + continue + caja = BBox(min(a.line.bbox.x0, b.line.bbox.x0), a.line.bbox.y0, max(a.line.bbox.x1, b.line.bbox.x1), b.line.bbox.y1) + unidas.append(SegmentLine(a.document, a.page_number, Line(f"{a.line.text} {b.line.text}", caja), a.ocr or b.ocr)) + return [*lineas, *unidas] + + def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]: """The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines.""" try: @@ -74,7 +87,7 @@ class DesdeTexto: @lru_cache(maxsize=256) def extraer(contenido: str | bytes) -> dict[str, tuple]: - lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido) + lineas = con_renglones_unidos(lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido)) leidos = extractor.extract(lineas) return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos} diff --git a/webapi/training_jobs.py b/webapi/training_jobs.py new file mode 100644 index 0000000..46a654a --- /dev/null +++ b/webapi/training_jobs.py @@ -0,0 +1,120 @@ +"""Model training started from governance: the scenarios that can be trained and the jobs that train them. + +A job is the same pipeline the `entrenar` compose profile runs (`models run --export --source dbt +--environment prod --train --promote`), in a detached process that the request does not wait for. Its state lives in files +under `INDICADORES_DIR/entrenamientos//` (`job.json`, `stdout.log`, `stderr.log` and `exit` once it ends), so any +worker of the server answers for any job and a restart does not lose them. A job whose process is gone without an exit +code is `interrumpido`. +""" + +import json +import os +import subprocess +import sys +import tomllib +import uuid +from datetime import datetime, timezone +from pathlib import Path + +TAIL_CHARS = 4000 +# A domain whose scenarios train on a reference cohort and not on a dbt cohort build. +OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (requiere el clúster o --reference-dir)."} + + +def _models_root() -> Path: + import models + + return Path(models.__file__).parent + + +def catalog() -> list[dict]: + """The scenarios that have a `model.toml` of their own, with the cohort each trains on.""" + found = [] + for path in sorted(_models_root().glob("*/*/model.toml")): + spec = tomllib.loads(path.read_text(encoding="utf-8")) + domain = spec.get("domain") + if domain is None: + continue + own = domain in OWN_STEPS + if not own and "scenario" not in spec: + continue + found.append({ + "domain": domain, "scenario": spec.get("scenario", path.parent.name), "cohort": spec.get("cohort"), + "outcome": spec.get("outcome"), "description": " ".join(str(spec.get("description", OWN_STEPS.get(domain, ""))).split()), + "kind": "referencia" if own else "cohorte", + }) + return found + + +def _base() -> Path: + return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos" + + +def _command(domain: str, scenario: str) -> list[str]: + argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"] + if domain not in OWN_STEPS: + argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]] + return argv + + +def _alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +def _tail(path: Path) -> str: + return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else "" + + +def _state(folder: Path) -> dict: + job = json.loads((folder / "job.json").read_text(encoding="utf-8")) + out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log") + exit_file = folder / "exit" + if exit_file.exists(): + code = int(exit_file.read_text().strip() or 1) + state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido") + elif _alive(job["pid"]): + code, state = None, "en_curso" + else: + code, state = None, "interrumpido" + return {**job, "estado": state, "codigo": code, "salida": out, "error": err} + + +def running(domain: str, scenario: str) -> dict | None: + return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None) + + +def start(domain: str, scenario: str) -> dict: + """Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest.""" + if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}: + raise LookupError(f"no such model: {domain}/{scenario}") + if domain not in OWN_STEPS and not os.environ.get("DBT_MANIFEST"): + raise RuntimeError("No hay un manifest de dbt configurado.") + job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}" + folder = _base() / job_id + folder.mkdir(parents=True) + shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }' + process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True, + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid, + "iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")} + (folder / "job.json").write_text(json.dumps(job), encoding="utf-8") + return _state(folder) + + +def get(job_id: str) -> dict: + folder = _base() / job_id + if "/" in job_id or not (folder / "job.json").exists(): + raise LookupError(f"no such training job: {job_id}") + return _state(folder) + + +def jobs(limit: int = 50) -> list[dict]: + """The latest jobs, newest first.""" + folders = sorted((p for p in _base().glob("*") if (p / "job.json").exists()), reverse=True) if _base().exists() else [] + return [_state(p) for p in folders[:limit]] -- 2.53.0 From e33eaafb08695bbb873137c2db04cae5f949cb31 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 03:33:44 -0600 Subject: [PATCH 15/23] Live estimators test says what it checks for CaMa --- tests/test_live_estimators.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_live_estimators.py b/tests/test_live_estimators.py index 4b1e669..99a12ef 100644 --- a/tests/test_live_estimators.py +++ b/tests/test_live_estimators.py @@ -14,8 +14,8 @@ 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.""" + """With no version in the registry, CaMa's cycle estimates nothing, and TEA never has a live estimator. Fails if a + domain without a production model gets an estimator that would then fail resolving a version.""" assert estimators.live_estimators("cama") == {} assert estimators.live_estimators("tea") == {} -- 2.53.0 From 8b379db28b614266394a4747874e8cf17e49b9b1 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 04:48:43 -0600 Subject: [PATCH 16/23] Governance trains TEA's EEG on a local reference folder when one is configured --- tests/test_training_jobs.py | 14 ++++++++++++++ webapi/training_jobs.py | 9 ++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/tests/test_training_jobs.py b/tests/test_training_jobs.py index 50728ba..1a7f22d 100644 --- a/tests/test_training_jobs.py +++ b/tests/test_training_jobs.py @@ -101,3 +101,17 @@ def test_an_unknown_scenario_or_job_is_a_404_and_no_manifest_is_a_503(app_client assert app_client.get("/governance/training-jobs/nada").status_code == 404 monkeypatch.delenv("DBT_MANIFEST") assert app_client.post("/governance/model-versions/cama/survival/train-jobs").status_code == 503 + + +def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypatch): + """Pins down: with `TEA_REFERENCE_DIR` (and its ages table) set, TEA's job passes them to `models run`, and CaMa's job + never does. Fails if the folder is ignored, which would send the training to storage the machine cannot reach.""" + monkeypatch.setenv("DBT_MANIFEST", "m.json") + monkeypatch.setenv("TEA_REFERENCE_DIR", "/referencia") + monkeypatch.setenv("TEA_REFERENCE_AGES", "/referencia/edades.csv") + + tea = training_jobs._command("tea", "eeg") + cama = training_jobs._command("cama", "survival") + + assert tea[tea.index("--reference-dir") + 1] == "/referencia" and tea[tea.index("--reference-ages") + 1] == "/referencia/edades.csv" + assert "--manifest" not in tea and "--reference-dir" not in cama diff --git a/webapi/training_jobs.py b/webapi/training_jobs.py index 46a654a..4ce244a 100644 --- a/webapi/training_jobs.py +++ b/webapi/training_jobs.py @@ -18,7 +18,7 @@ from pathlib import Path TAIL_CHARS = 4000 # A domain whose scenarios train on a reference cohort and not on a dbt cohort build. -OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (requiere el clúster o --reference-dir)."} +OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."} def _models_root() -> Path: @@ -54,6 +54,13 @@ def _command(domain: str, scenario: str) -> list[str]: argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"] if domain not in OWN_STEPS: argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]] + elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"): + # A reference cohort on this machine's disk, instead of the configured one in the cluster's storage. + argv += ["--reference-dir", os.environ["TEA_REFERENCE_DIR"]] + if os.environ.get("TEA_REFERENCE_AGES"): + argv += ["--reference-ages", os.environ["TEA_REFERENCE_AGES"]] + if os.environ.get("TEA_REFERENCE_LINE_HZ"): + argv += ["--line-hz", os.environ["TEA_REFERENCE_LINE_HZ"]] return argv -- 2.53.0 From eeb4c1fbd5cac480079baba19978d208a00c1452 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 12:07:21 -0600 Subject: [PATCH 17/23] CaMa survival: live options and selection routes over the production model --- tests/test_model_analysis.py | 57 ++++++++++++++++++++++++++ webapi/model_analysis.py | 78 +++++++++++++++++++++++++++++++++++- 2 files changed, 133 insertions(+), 2 deletions(-) diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 6538a51..6efc4e4 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -77,3 +77,60 @@ def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none assert found.status_code == 200 and found.get_json()["desarrollo"] == record assert found.get_json()["modelo"]["version"] == "3" assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"] + + +@pytest.fixture +def live_client(client, monkeypatch): + """`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, so the routes run + without MLflow or a cohort build; `live.curves` answers from `holder.answer` or raises what the test sets.""" + from models.cama.survival import live + from webapi import model_analysis + + holder = SimpleNamespace(calls=0, error=None) + + def context(domain, scenario): + return "spec", "model", "labelled", "3" + + def curves(spec, model, labelled, query): + holder.calls += 1 + if holder.error: + raise live.QueryError(holder.error) + return {"n": 100, "seleccion": query} + + monkeypatch.setattr(model_analysis, "_live_context", context) + monkeypatch.setattr(live, "curves", curves) + monkeypatch.setattr(live, "options", lambda labelled, pac_id=None: {"n": 100, "paciente": {"grade": "G2"} if pac_id == 7 else None}) + model_analysis._ANSWERS.clear() + client.holder = holder + return client + + +def test_the_live_figure_is_asked_with_a_selection_and_the_answer_is_kept(live_client): + """Pins down: `POST /cama/modelo/curvas/consulta` returns the record for the selection with the version that scored it, + and the same selection a second time is answered without computing again. Fails if the answer lacks the version, or every + request recomputes (the figure would take seconds each time a reader goes back to a selection).""" + body = {"filtros": {"grade": ["G3"]}} + first = live_client.post("/cama/modelo/curvas/consulta", json=body) + second = live_client.post("/cama/modelo/curvas/consulta", json=body) + + assert first.status_code == 200 and first.get_json()["modelo"]["version"] == "3" + assert first.get_json()["curvas"]["seleccion"] == body and second.get_json() == first.get_json() + assert live_client.holder.calls == 1 + + +def test_a_selection_that_cannot_be_answered_is_a_422_with_the_reason(live_client): + """Pins down: a selection too small or invalid is a 422 with the message, not a 500 or an empty record. Fails if the + reader sees a server error instead of why the selection says nothing.""" + live_client.holder.error = "La selección tiene 3 pacientes" + answer = live_client.post("/cama/modelo/curvas/consulta", json={"filtros": {"er": ["NEGATIVO"]}}) + + assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"] + + +def test_the_options_carry_the_patients_own_values_when_one_is_named(live_client): + """Pins down: `GET /cama/modelo/curvas/opciones?paciente=7` carries patient 7's values, and without it none. Fails if the + patient parameter is ignored, which would leave the dashboard unable to offer her subgroup.""" + named = live_client.get("/cama/modelo/curvas/opciones?paciente=7").get_json() + plain = live_client.get("/cama/modelo/curvas/opciones").get_json() + + assert named["opciones"]["paciente"] == {"grade": "G2"} and plain["opciones"]["paciente"] is None diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 697eb6c..adb7e1e 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -1,4 +1,4 @@ -"""What a model's production version found about its cohort: `GET //modelo/curvas` and `GET //modelo/desarrollo`. +"""What a model's production version found about its cohort: `GET //modelo/curvas`, `GET //modelo/desarrollo` and, over the data ingested so far, `GET //modelo/curvas/opciones` and `POST //modelo/curvas/consulta`. The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the @@ -7,12 +7,47 @@ data are simulated. 404 while the scenario has no version in production, or its """ import json +from collections import OrderedDict +from threading import Lock -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, request from webapi.fhir.common import simulated_data +_LIVE: dict = {} +_ANSWERS: OrderedDict = OrderedDict() +_LOCK = Lock() +MAX_ANSWERS = 64 + + +def _live_context(domain: str, scenario: str): + """`(scenario, fitted model, labelled members, version)`: the production version and the cohort build the cycle made last, + kept until either changes. `LookupError` while there is no version or no build.""" + import importlib + + import mlflow.sklearn + + from models.cama.survival import live + from models.dags.training import Scenario + from models.io.registry import registry + from models.io.storage import KitBuild + + resolved = registry.resolve(domain, scenario) + spec = Scenario.load(domain, scenario) + build_id = importlib.import_module(f"persistance.{domain}").cohort_repository.latest_build(spec.cohort) + if build_id is None: + raise LookupError(f"({domain}, {scenario}) has no cohort build yet") + key = (resolved.version, build_id) + with _LOCK: + if _LIVE.get("key") != key: + build = KitBuild(domain, build_id) + model = mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1] + _LIVE.update(key=key, value=(spec, model, live.members(spec, build.frame(), build.lineage()), resolved.version)) + _ANSWERS.clear() + return _LIVE["value"] + + def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: """The blueprint of one scenario, to register with `url_prefix="/"`.""" blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__) @@ -47,4 +82,43 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: "mlflow_run_id": resolved.run_id}, "desarrollo": json.loads(content)}) + @blueprint.get("/modelo/curvas/opciones") + def live_options(): + """What can be selected for the live figure: each covariate's values, the period, the limits and, given + `?paciente=`, that patient's own values.""" + from models.cama.survival import live + + try: + _, _, labelled, version = _live_context(domain, scenario) + except LookupError as error: + return jsonify({"error": f"sin curvas: {error}"}), 404 + paciente = request.args.get("paciente") + found = live.options(labelled, int(paciente) if paciente and paciente.isdigit() else None) + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "opciones": found}) + + @blueprint.post("/modelo/curvas/consulta") + def live_curves(): + """The figure's record for the selection in the body (`{filtros, periodo}`), scored with the production version over + the data ingested so far. 422 with the reason when the selection is too small or invalid.""" + from models.cama.survival import live + + query = request.get_json(silent=True) or {} + try: + spec, model, labelled, version = _live_context(domain, scenario) + except LookupError as error: + return jsonify({"error": f"sin curvas: {error}"}), 404 + key = json.dumps({"v": version, "q": query}, sort_keys=True, default=str) + with _LOCK: + record = _ANSWERS.get(key) + if record is None: + try: + record = live.curves(spec, model, labelled, query) + except live.QueryError as error: + return jsonify({"error": str(error)}), 422 + with _LOCK: + _ANSWERS[key] = record + while len(_ANSWERS) > MAX_ANSWERS: + _ANSWERS.popitem(last=False) + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record}) + return blueprint -- 2.53.0 From 57947d4131bd92799f4e2552b1c8cf937ecf57ab Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 12:15:22 -0600 Subject: [PATCH 18/23] Live survival: score with the rehydrated production model --- webapi/model_analysis.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index adb7e1e..d159afa 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -42,7 +42,7 @@ def _live_context(domain: str, scenario: str): with _LOCK: if _LIVE.get("key") != key: build = KitBuild(domain, build_id) - model = mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1] + model = live.rehydrate(mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1]) _LIVE.update(key=key, value=(spec, model, live.members(spec, build.frame(), build.lineage()), resolved.version)) _ANSWERS.clear() return _LIVE["value"] -- 2.53.0 From 3b192207fd71dd60ebf06465c9d821e395834ec4 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:03:19 -0600 Subject: [PATCH 19/23] Live survival: no options route --- tests/test_model_analysis.py | 10 ---------- webapi/model_analysis.py | 16 +--------------- 2 files changed, 1 insertion(+), 25 deletions(-) diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 6efc4e4..58ce5d7 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -99,7 +99,6 @@ def live_client(client, monkeypatch): monkeypatch.setattr(model_analysis, "_live_context", context) monkeypatch.setattr(live, "curves", curves) - monkeypatch.setattr(live, "options", lambda labelled, pac_id=None: {"n": 100, "paciente": {"grade": "G2"} if pac_id == 7 else None}) model_analysis._ANSWERS.clear() client.holder = holder return client @@ -125,12 +124,3 @@ def test_a_selection_that_cannot_be_answered_is_a_422_with_the_reason(live_clien answer = live_client.post("/cama/modelo/curvas/consulta", json={"filtros": {"er": ["NEGATIVO"]}}) assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"] - - -def test_the_options_carry_the_patients_own_values_when_one_is_named(live_client): - """Pins down: `GET /cama/modelo/curvas/opciones?paciente=7` carries patient 7's values, and without it none. Fails if the - patient parameter is ignored, which would leave the dashboard unable to offer her subgroup.""" - named = live_client.get("/cama/modelo/curvas/opciones?paciente=7").get_json() - plain = live_client.get("/cama/modelo/curvas/opciones").get_json() - - assert named["opciones"]["paciente"] == {"grade": "G2"} and plain["opciones"]["paciente"] is None diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index d159afa..7e474b8 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -1,4 +1,4 @@ -"""What a model's production version found about its cohort: `GET //modelo/curvas`, `GET //modelo/desarrollo` and, over the data ingested so far, `GET //modelo/curvas/opciones` and `POST //modelo/curvas/consulta`. +"""What a model's production version found about its cohort: `GET //modelo/curvas`, `GET //modelo/desarrollo` and, over the data ingested so far, `POST //modelo/curvas/consulta`. The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the @@ -82,20 +82,6 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: "mlflow_run_id": resolved.run_id}, "desarrollo": json.loads(content)}) - @blueprint.get("/modelo/curvas/opciones") - def live_options(): - """What can be selected for the live figure: each covariate's values, the period, the limits and, given - `?paciente=`, that patient's own values.""" - from models.cama.survival import live - - try: - _, _, labelled, version = _live_context(domain, scenario) - except LookupError as error: - return jsonify({"error": f"sin curvas: {error}"}), 404 - paciente = request.args.get("paciente") - found = live.options(labelled, int(paciente) if paciente and paciente.isdigit() else None) - return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "opciones": found}) - @blueprint.post("/modelo/curvas/consulta") def live_curves(): """The figure's record for the selection in the body (`{filtros, periodo}`), scored with the production version over -- 2.53.0 From a53179aa2ededf58517b27febcfee0b3b4d8984a Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:14:06 -0600 Subject: [PATCH 20/23] Live survival: the scenarios of a patient and the figure of one scenario --- tests/test_model_analysis.py | 47 ++++++++++++++++++++++++------------ webapi/model_analysis.py | 35 +++++++++++++++++++++------ 2 files changed, 58 insertions(+), 24 deletions(-) diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 58ce5d7..cdb7630 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -82,7 +82,7 @@ def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none @pytest.fixture def live_client(client, monkeypatch): """`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, so the routes run - without MLflow or a cohort build; `live.curves` answers from `holder.answer` or raises what the test sets.""" + without MLflow or a cohort build; `live.curves` answers from the stand-in or raises what the test sets.""" from models.cama.survival import live from webapi import model_analysis @@ -91,36 +91,51 @@ def live_client(client, monkeypatch): def context(domain, scenario): return "spec", "model", "labelled", "3" - def curves(spec, model, labelled, query): + def curves(spec, model, labelled, name): holder.calls += 1 if holder.error: raise live.QueryError(holder.error) - return {"n": 100, "seleccion": query} + return {"n": 100, "escenario": name or "Toda la cohorte"} + + def patient_scenarios(labelled, pac_id): + if pac_id == 404: + raise live.QueryError("La paciente no está en la cohorte del modelo.") + return ["< 45 años"] if pac_id == 7 else ["Toda la cohorte"] monkeypatch.setattr(model_analysis, "_live_context", context) monkeypatch.setattr(live, "curves", curves) + monkeypatch.setattr(live, "patient_scenarios", patient_scenarios) model_analysis._ANSWERS.clear() client.holder = holder return client -def test_the_live_figure_is_asked_with_a_selection_and_the_answer_is_kept(live_client): - """Pins down: `POST /cama/modelo/curvas/consulta` returns the record for the selection with the version that scored it, - and the same selection a second time is answered without computing again. Fails if the answer lacks the version, or every - request recomputes (the figure would take seconds each time a reader goes back to a selection).""" - body = {"filtros": {"grade": ["G3"]}} - first = live_client.post("/cama/modelo/curvas/consulta", json=body) - second = live_client.post("/cama/modelo/curvas/consulta", json=body) +def test_a_scenarios_figure_is_asked_by_name_and_the_answer_is_kept(live_client): + """Pins down: `POST /cama/modelo/curvas/consulta` returns the record of the named scenario with the version that scored it, + and the same scenario a second time is answered without computing again. Fails if the answer lacks the version, or every + request recomputes (the figure takes seconds each time a patient's record opens).""" + first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}) + second = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}) assert first.status_code == 200 and first.get_json()["modelo"]["version"] == "3" - assert first.get_json()["curvas"]["seleccion"] == body and second.get_json() == first.get_json() + assert first.get_json()["curvas"]["escenario"] == "< 45 años" and second.get_json() == first.get_json() assert live_client.holder.calls == 1 -def test_a_selection_that_cannot_be_answered_is_a_422_with_the_reason(live_client): - """Pins down: a selection too small or invalid is a 422 with the message, not a 500 or an empty record. Fails if the - reader sees a server error instead of why the selection says nothing.""" - live_client.holder.error = "La selección tiene 3 pacientes" - answer = live_client.post("/cama/modelo/curvas/consulta", json={"filtros": {"er": ["NEGATIVO"]}}) +def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client): + """Pins down: an unknown scenario or one too small is a 422 with the message, not a 500 or an empty record. Fails if the + reader sees a server error instead of why the scenario says nothing.""" + live_client.holder.error = "El escenario tiene 3 pacientes" + answer = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Estadio IV"}) assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"] + + +def test_the_scenarios_of_a_patient_are_listed_and_a_stranger_is_refused(live_client): + """Pins down: `GET /cama/modelo/escenarios?paciente=7` lists her scenarios, one in none gets the whole cohort, and a patient + outside the cohort or no patient is a 422. Fails if the patient parameter is ignored, which would draw the same figure for + every patient.""" + assert live_client.get("/cama/modelo/escenarios?paciente=7").get_json()["escenarios"] == ["< 45 años"] + assert live_client.get("/cama/modelo/escenarios?paciente=8").get_json()["escenarios"] == ["Toda la cohorte"] + assert live_client.get("/cama/modelo/escenarios?paciente=404").status_code == 422 + assert live_client.get("/cama/modelo/escenarios").status_code == 422 diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 7e474b8..4941954 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -1,4 +1,4 @@ -"""What a model's production version found about its cohort: `GET //modelo/curvas`, `GET //modelo/desarrollo` and, over the data ingested so far, `POST //modelo/curvas/consulta`. +"""What a model's production version found about its cohort: `GET //modelo/curvas`, `GET //modelo/desarrollo` and, over the data ingested so far, `GET //modelo/escenarios` and `POST //modelo/curvas/consulta`. The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the @@ -82,23 +82,42 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: "mlflow_run_id": resolved.run_id}, "desarrollo": json.loads(content)}) - @blueprint.post("/modelo/curvas/consulta") - def live_curves(): - """The figure's record for the selection in the body (`{filtros, periodo}`), scored with the production version over - the data ingested so far. 422 with the reason when the selection is too small or invalid.""" + @blueprint.get("/modelo/escenarios") + def patient_scenarios(): + """The clinical scenarios `?paciente=` belongs to (the whole cohort when she is in none), over the data + ingested so far. 404 while there is no version in production; 422 with the reason for a patient outside the cohort.""" from models.cama.survival import live - query = request.get_json(silent=True) or {} + try: + _, _, labelled, version = _live_context(domain, scenario) + except LookupError as error: + return jsonify({"error": f"sin curvas: {error}"}), 404 + paciente = request.args.get("paciente", "") + if not paciente.isdigit(): + return jsonify({"error": "Falta la paciente."}), 422 + try: + found = live.patient_scenarios(labelled, int(paciente)) + except live.QueryError as error: + return jsonify({"error": str(error)}), 422 + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": found}) + + @blueprint.post("/modelo/curvas/consulta") + def live_curves(): + """The figure's record for the clinical scenario in the body (`{escenario}`, none for the whole cohort), scored with the + production version over the data ingested so far. 422 with the reason for an unknown scenario or one too small.""" + from models.cama.survival import live + + name = (request.get_json(silent=True) or {}).get("escenario") try: spec, model, labelled, version = _live_context(domain, scenario) except LookupError as error: return jsonify({"error": f"sin curvas: {error}"}), 404 - key = json.dumps({"v": version, "q": query}, sort_keys=True, default=str) + key = json.dumps({"v": version, "e": name}, default=str) with _LOCK: record = _ANSWERS.get(key) if record is None: try: - record = live.curves(spec, model, labelled, query) + record = live.curves(spec, model, labelled, name) except live.QueryError as error: return jsonify({"error": str(error)}), 422 with _LOCK: -- 2.53.0 From 2c4bfa569171547ceb13745a1409a8ce7864c17d Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:34:56 -0600 Subject: [PATCH 21/23] Recurrence figures for a patient; governance trains scenarios with external data; lifelines in the lock --- tests/test_model_analysis.py | 53 ++++++++++++++++++++++++++++++++++++ tests/test_training_jobs.py | 15 ++++++++++ uv.lock | 42 ++++++++++++++++++++++++++++ webapi/__init__.py | 3 +- webapi/model_analysis.py | 34 +++++++++++++++++++++++ webapi/training_jobs.py | 12 ++++---- 6 files changed, 153 insertions(+), 6 deletions(-) diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index cdb7630..0f443b9 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -139,3 +139,56 @@ def test_the_scenarios_of_a_patient_are_listed_and_a_stranger_is_refused(live_cl assert live_client.get("/cama/modelo/escenarios?paciente=8").get_json()["escenarios"] == ["Toda la cohorte"] assert live_client.get("/cama/modelo/escenarios?paciente=404").status_code == 422 assert live_client.get("/cama/modelo/escenarios").status_code == 422 + + +@pytest.fixture +def recurrence_client(monkeypatch): + """The recurrence route on a bare app, with the registry's production version, its recurrence record and the labelled members + replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor.""" + import pandas as pd + from flask import Flask + + from models.io import registry as registry_module + from webapi import model_analysis + + record = {"horizons_months": [12, 36, 60], "escenarios": [ + {"cohorte": "metabric", "escenario": "< 45 años", "condiciones": {"Edad": ["<45"]}, "n": 100}, + {"cohorte": "metabric", "escenario": "RE− · grado 3", "condiciones": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, "n": 300}, + {"cohorte": "metabric", "escenario": "Ganglios 4+", "condiciones": {"Ganglios_positivos": ["4+"]}, "n": 80}, + {"cohorte": "scanb", "escenario": "Grado 3", "condiciones": {"Grado_histologico": ["3"]}, "n": 900}]} + labelled = pd.DataFrame({"pac_id": [7], "age_years": [40.0], "size_mm": [None], "grade": ["G3"], "er": ["NEGATIVO"], "pr": ["NEGATIVO"], "her2": ["H2"]}) + holder = SimpleNamespace(production="2") + + def resolve(domain, scenario, version=None): + if holder.production is None: + raise LookupError("no hay una versión en producción") + return SimpleNamespace(version=holder.production, run_id="run-2") + + monkeypatch.setattr(registry_module.registry, "resolve", resolve) + monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: ("recurrencia.json", json.dumps(record).encode())) + monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3")) + app = Flask(__name__) + app.register_blueprint(model_analysis.recurrence_blueprint(), url_prefix="/cama") + with app.test_client() as client: + client.holder = holder + yield client + + +def test_a_patient_gets_the_recurrence_scenarios_her_covariates_meet(recurrence_client): + """Pins down: `GET /cama/modelo/recurrencia?paciente=7` returns the scenarios whose every condition her age, grade and + receptors meet (one that needs the nodes, which the hospital does not report, is left out), the larger first within a + cohort, with the version that published them. Fails if a scenario she does not meet is returned, a missing covariate counts + as met, or the version is not named.""" + body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json() + + assert [(s["cohorte"], s["escenario"]) for s in body["escenarios"]] == [("metabric", "RE− · grado 3"), ("metabric", "< 45 años"), ("scanb", "Grado 3")] + assert body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60] + + +def test_without_a_recurrence_version_or_for_a_stranger_it_says_so(recurrence_client): + """Pins down: no recurrence version in production is a 404, a patient outside the cohort or no patient is a 422 with a reason. + Fails if either becomes a 200 with nothing or a 500.""" + assert recurrence_client.get("/cama/modelo/recurrencia?paciente=99").status_code == 422 + assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 422 + recurrence_client.holder.production = None + assert recurrence_client.get("/cama/modelo/recurrencia?paciente=7").status_code == 404 diff --git a/tests/test_training_jobs.py b/tests/test_training_jobs.py index 1a7f22d..5c9f827 100644 --- a/tests/test_training_jobs.py +++ b/tests/test_training_jobs.py @@ -50,6 +50,7 @@ def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings assert ("cama", "survival") in entries and ("cacu", "cin2_logistic") in entries assert entries[("tea", "eeg")]["kind"] == "referencia" and entries[("cama", "survival")]["kind"] == "cohorte" assert ("cama", "seer_survival") not in entries + assert entries[("cama", "recurrence")]["kind"] == "referencia" # trained on its external files, not on a dbt cohort @pytest.mark.parametrize("code,estado", [ @@ -115,3 +116,17 @@ def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypat assert tea[tea.index("--reference-dir") + 1] == "/referencia" and tea[tea.index("--reference-ages") + 1] == "/referencia/edades.csv" assert "--manifest" not in tea and "--reference-dir" not in cama + + +def test_a_scenario_with_external_data_trains_without_a_dbt_export_or_manifest(monkeypatch): + """Pins down: CaMa's recurrence scenario, whose training data are files, is started with no `--export`, `--manifest` or dbt + manifest, while CaMa's survival scenario still is. Fails if an external scenario is refused for want of a manifest or run + through the cohort export, which would train it on the wrong data.""" + monkeypatch.delenv("DBT_MANIFEST", raising=False) + + recurrence = training_jobs._command("cama", "recurrence") + monkeypatch.setenv("DBT_MANIFEST", "m.json") + survival = training_jobs._command("cama", "survival") + + assert "--export" not in recurrence and "--manifest" not in recurrence + assert "--export" in survival and survival[survival.index("--manifest") + 1] == "m.json" diff --git a/uv.lock b/uv.lock index 729b021..ce6d0b9 100644 --- a/uv.lock +++ b/uv.lock @@ -299,6 +299,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "autograd" +version = "1.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/ac/4a8b58364ba865ab545251edbe475e5a35326814a5d274a2211d33ed8a5d/autograd-1.9.1.tar.gz", hash = "sha256:7818c5c69ddf9efb7da74097bd741a4c7920133f41966f68537223a15ef798bc", size = 2566975, upload-time = "2026-07-02T07:43:58.255Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6e/ce/8c98e6604bb1ec9d03c8493c328185b69bb7533fe08f3640f0f3641bd9d1/autograd-1.9.1-py3-none-any.whl", hash = "sha256:b788bae3fa010cbffb4cfb7b8ba2a3f0daa6072a8506da6164c779fe9cf3e05a", size = 54387, upload-time = "2026-07-02T07:43:56.502Z" }, +] + +[[package]] +name = "autograd-gamma" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "autograd" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/85/ae/7f2031ea76140444b2453fa139041e5afd4a09fc5300cfefeb1103291f80/autograd-gamma-0.5.0.tar.gz", hash = "sha256:f27abb7b8bb9cffc8badcbf59f3fe44a9db39e124ecacf1992b6d952934ac9c4", size = 3952, upload-time = "2020-10-15T16:51:06.785Z" } + [[package]] name = "beautifulsoup4" version = "4.15.0" @@ -1783,6 +1805,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/23/93/4e45e37f26c820216704b36b8e67cc55c490a7abd287a78a26a2c0e21386/lazy_loader-0.6-py3-none-any.whl", hash = "sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056", size = 8791, upload-time = "2026-09-21T21:31:31.632Z" }, ] +[[package]] +name = "lifelines" +version = "0.30.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "autograd" }, + { name = "autograd-gamma" }, + { name = "formulaic" }, + { name = "matplotlib" }, + { name = "numpy" }, + { name = "pandas" }, + { name = "scipy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ea/4f/f0b363278d40baf7d7a03217bee839cb880946c62109f243391c8754bb09/lifelines-0.30.0.tar.gz", hash = "sha256:f7f6f6275fcb167fe0f5b1ef98f868993f9c074cb74b1dd6e92736efa854be18", size = 383221, upload-time = "2024-10-29T12:00:43.513Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/f7/379e185a75ac8166ac70756d0ba68d9a2b02b555c7fde4983246752396bd/lifelines-0.30.0-py3-none-any.whl", hash = "sha256:ac7c602c8aceced9770d3977817c9d99c250ed8cd86f2567fa0d23e4e8014bf9", size = 349319, upload-time = "2024-10-29T12:00:41.749Z" }, +] + [[package]] name = "lightgbm" version = "4.7.0" @@ -2161,6 +2201,7 @@ notebooks = [ { name = "nbconvert" }, ] seer-survival = [ + { name = "lifelines" }, { name = "matplotlib" }, { name = "mpmath" }, { name = "networkx" }, @@ -2179,6 +2220,7 @@ requires-dist = [ { name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" }, { name = "extraction", editable = "../Extraction" }, { name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" }, + { name = "lifelines", marker = "extra == 'seer-survival'", specifier = ">=0.28" }, { name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" }, { name = "mlflow", specifier = ">=2.9" }, { name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" }, diff --git a/webapi/__init__.py b/webapi/__init__.py index 3a8323f..82e564e 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -98,7 +98,7 @@ def create_app() -> Flask: from persistance import cama as cama_repositories from persistance.db import get_cacu_session, get_cama_session - from webapi.model_analysis import model_analysis_blueprint + from webapi.model_analysis import model_analysis_blueprint, recurrence_blueprint from webapi.risk_batches import risk_batches_blueprint app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") @@ -107,5 +107,6 @@ def create_app() -> Flask: app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu") app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama") app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama") + app.register_blueprint(recurrence_blueprint(), url_prefix="/cama") return app diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 4941954..6e6a1ab 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -127,3 +127,37 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record}) return blueprint + + +def recurrence_blueprint() -> Blueprint: + """CaMa's recurrence figures for a patient, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia?paciente=` + answers the figures (METABRIC's and SCAN-B's) of the clinical scenarios her covariates meet, from the recurrence version in + production. The scenarios are the external cohorts' analyses; she is placed in them by her own age, tumor size, grade and + receptors, from the data ingested so far.""" + blueprint = Blueprint("model_analysis_cama_recurrence", __name__) + + @blueprint.get("/modelo/recurrencia") + def recurrence(): + import pandas as pd + + from models.cama.recurrence import patient + from models.io.registry import registry + + paciente = request.args.get("paciente", "") + if not paciente.isdigit(): + return jsonify({"error": "Falta la paciente."}), 422 + try: + resolved = registry.resolve("cama", "recurrence") + _, content = registry.artifact("cama", "recurrence", resolved.version, "analisis/recurrencia.json") + _, _, labelled, _ = _live_context("cama", "survival") + except LookupError as error: + return jsonify({"error": f"sin recurrencia: {error}"}), 404 + rows = labelled[labelled["pac_id"] == int(paciente)] + if rows.empty: + return jsonify({"error": "La paciente no está en la cohorte del modelo."}), 422 + record = json.loads(content) + found = patient.matching(record["escenarios"], patient.covariates_of(rows.iloc[0])) + return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"], + "escenarios": found}) + + return blueprint diff --git a/webapi/training_jobs.py b/webapi/training_jobs.py index 4ce244a..6b5feea 100644 --- a/webapi/training_jobs.py +++ b/webapi/training_jobs.py @@ -17,7 +17,8 @@ from datetime import datetime, timezone from pathlib import Path TAIL_CHARS = 4000 -# A domain whose scenarios train on a reference cohort and not on a dbt cohort build. +# A domain whose scenarios train on a reference cohort and not on a dbt cohort build; a scenario that says `external` in its +# `model.toml` does too, whatever its domain. OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (el clúster, o la carpeta de `TEA_REFERENCE_DIR`)."} @@ -35,13 +36,13 @@ def catalog() -> list[dict]: domain = spec.get("domain") if domain is None: continue - own = domain in OWN_STEPS + own = domain in OWN_STEPS or bool(spec.get("external")) if not own and "scenario" not in spec: continue found.append({ "domain": domain, "scenario": spec.get("scenario", path.parent.name), "cohort": spec.get("cohort"), "outcome": spec.get("outcome"), "description": " ".join(str(spec.get("description", OWN_STEPS.get(domain, ""))).split()), - "kind": "referencia" if own else "cohorte", + "kind": "referencia" if own else "cohorte", "external": own, }) return found @@ -52,7 +53,8 @@ def _base() -> Path: def _command(domain: str, scenario: str) -> list[str]: argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"] - if domain not in OWN_STEPS: + external = any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) + if not external: argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]] elif domain == "tea" and os.environ.get("TEA_REFERENCE_DIR"): # A reference cohort on this machine's disk, instead of the configured one in the cluster's storage. @@ -100,7 +102,7 @@ def start(domain: str, scenario: str) -> dict: """Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest.""" if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}: raise LookupError(f"no such model: {domain}/{scenario}") - if domain not in OWN_STEPS and not os.environ.get("DBT_MANIFEST"): + if not any(e["external"] for e in catalog() if (e["domain"], e["scenario"]) == (domain, scenario)) and not os.environ.get("DBT_MANIFEST"): raise RuntimeError("No hay un manifest de dbt configurado.") job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}" folder = _base() / job_id -- 2.53.0 From 0edac6d0e22826d5c7fc0cdf1f571a255f41afb6 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:35:23 -0600 Subject: [PATCH 22/23] Lock: lifelines in the models dev group --- uv.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/uv.lock b/uv.lock index ce6d0b9..def2cb1 100644 --- a/uv.lock +++ b/uv.lock @@ -2245,6 +2245,7 @@ provides-extras = ["eeg-reference", "notebooks", "seer-survival", "survival-curv [package.metadata.requires-dev] dev = [ { name = "ipykernel", specifier = ">=6.29" }, + { name = "lifelines", specifier = ">=0.28" }, { name = "matplotlib", specifier = ">=3.8" }, { name = "mpmath", specifier = ">=1.3" }, { name = "nbclient", specifier = ">=0.10" }, -- 2.53.0 From 4cc2ce83ac7af2518d77aaa96f0f72ca18fcb726 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 14:43:46 -0600 Subject: [PATCH 23/23] CaMa: scenario menus and risk-factor rows for the survival and recurrence analyses --- tests/test_model_analysis.py | 118 +++++++++++++++++++---------------- webapi/model_analysis.py | 81 +++++++++++++++--------- 2 files changed, 117 insertions(+), 82 deletions(-) diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 0f443b9..6267750 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -79,47 +79,63 @@ def test_it_serves_the_development_record_and_is_a_404_when_the_version_has_none assert missing.status_code == 404 and "desarrollo.json" in missing.get_json()["error"] +SUMMARY = {"columnas": ["escenario", "riesgo_definitorios", "incluye_factor_riesgo"], + "filas": [{"escenario": "< 45 años", "riesgo_definitorios": "Grado=G3 (robusto, 97%)", "incluye_factor_riesgo": True}, + {"escenario": "Estadio IV", "riesgo_definitorios": "", "incluye_factor_riesgo": False}]} + + @pytest.fixture def live_client(client, monkeypatch): - """`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, so the routes run - without MLflow or a cohort build; `live.curves` answers from the stand-in or raises what the test sets.""" + """`client` with the live context replaced by stand-ins: a scenario, a model and the labelled members, and the version's summary + of two scenarios (one with a risk factor, one without) in its development record, so the routes run without MLflow or a + cohort build; `live.curves` answers from the stand-in or raises what the test sets; the masks put patients 1-100 in + `< 45 años`, 1-3 in a tiny scenario with no summary row, and nobody in `Estadio IV`.""" + import numpy as np + import pandas as pd from models.cama.survival import live from webapi import model_analysis - holder = SimpleNamespace(calls=0, error=None) + holder = client.holder + holder.calls, holder.error = 0, None + labelled = pd.DataFrame({"pac_id": range(1, 201), "event": [True] * 40 + [False] * 160}) + masks = {"< 45 años": np.arange(200) < 100, "Diminuto": np.arange(200) < 3, "Estadio IV": np.zeros(200, bool)} + holder.files["analisis/desarrollo.json"] = json.dumps({"tablas": {"escenarios_resumen": SUMMARY}}).encode() - def context(domain, scenario): - return "spec", "model", "labelled", "3" - - def curves(spec, model, labelled, name): + def curves(spec, model, labelled_members, name): holder.calls += 1 if holder.error: raise live.QueryError(holder.error) return {"n": 100, "escenario": name or "Toda la cohorte"} - def patient_scenarios(labelled, pac_id): - if pac_id == 404: - raise live.QueryError("La paciente no está en la cohorte del modelo.") - return ["< 45 años"] if pac_id == 7 else ["Toda la cohorte"] - - monkeypatch.setattr(model_analysis, "_live_context", context) + monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3")) + monkeypatch.setattr(live, "scenario_masks", lambda frame: masks) monkeypatch.setattr(live, "curves", curves) - monkeypatch.setattr(live, "patient_scenarios", patient_scenarios) model_analysis._ANSWERS.clear() - client.holder = holder return client -def test_a_scenarios_figure_is_asked_by_name_and_the_answer_is_kept(live_client): - """Pins down: `POST /cama/modelo/curvas/consulta` returns the record of the named scenario with the version that scored it, - and the same scenario a second time is answered without computing again. Fails if the answer lacks the version, or every - request recomputes (the figure takes seconds each time a patient's record opens).""" - first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}) - second = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}) +def test_the_menu_offers_the_scenarios_with_a_summary_row_and_enough_patients(live_client): + """Pins down: `GET /cama/modelo/escenarios` offers only the scenarios that have a row in the version's summary and enough patients + to draw (not the one with no row, not the one with nobody), with their patients, in the pipeline's order, and names the one a + patient belongs to as the default. Fails if a scenario with nothing to say reaches the menu, or the default ignores the patient.""" + menu = live_client.get("/cama/modelo/escenarios?paciente=7").get_json() - assert first.status_code == 200 and first.get_json()["modelo"]["version"] == "3" - assert first.get_json()["curvas"]["escenario"] == "< 45 años" and second.get_json() == first.get_json() - assert live_client.holder.calls == 1 + assert menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}] and menu["predeterminado"] == "< 45 años" + assert menu["modelo"]["version"] == "3" + assert live_client.get("/cama/modelo/escenarios?paciente=500").status_code == 422 + + +def test_a_scenarios_figure_comes_with_its_risk_factors_and_the_answer_is_kept(live_client): + """Pins down: `POST /cama/modelo/curvas/consulta` returns the figure of the named scenario with its summary row (the risk-factor + label) and the version that scored it, and the same scenario a second time is answered without computing again; a scenario with + no row has no factors. Fails if curve and label can come from different scenarios, or every request recomputes.""" + first = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}).get_json() + again = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "< 45 años"}).get_json() + other = live_client.post("/cama/modelo/curvas/consulta", json={"escenario": "Diminuto"}).get_json() + + assert first["curvas"]["escenario"] == "< 45 años" and first["factores"]["riesgo_definitorios"] == "Grado=G3 (robusto, 97%)" + assert again == first and live_client.holder.calls == 2 and other["factores"] is None + assert first["modelo"]["version"] == "3" def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client): @@ -131,31 +147,24 @@ def test_a_scenario_that_cannot_be_answered_is_a_422_with_the_reason(live_client assert answer.status_code == 422 and "3 pacientes" in answer.get_json()["error"] -def test_the_scenarios_of_a_patient_are_listed_and_a_stranger_is_refused(live_client): - """Pins down: `GET /cama/modelo/escenarios?paciente=7` lists her scenarios, one in none gets the whole cohort, and a patient - outside the cohort or no patient is a 422. Fails if the patient parameter is ignored, which would draw the same figure for - every patient.""" - assert live_client.get("/cama/modelo/escenarios?paciente=7").get_json()["escenarios"] == ["< 45 años"] - assert live_client.get("/cama/modelo/escenarios?paciente=8").get_json()["escenarios"] == ["Toda la cohorte"] - assert live_client.get("/cama/modelo/escenarios?paciente=404").status_code == 422 - assert live_client.get("/cama/modelo/escenarios").status_code == 422 - - @pytest.fixture def recurrence_client(monkeypatch): - """The recurrence route on a bare app, with the registry's production version, its recurrence record and the labelled members - replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor.""" + """The recurrence route on a bare app, with the registry's production version, its recurrence record, its summary and the + labelled members replaced by stand-ins: one patient aged 40 with grade 3 and an estrogen-negative tumor.""" import pandas as pd from flask import Flask from models.io import registry as registry_module from webapi import model_analysis + figure = lambda cohorte, name, cond, n: {"cohorte": cohorte, "escenario": name, "condiciones": cond, "n": n} record = {"horizons_months": [12, 36, 60], "escenarios": [ - {"cohorte": "metabric", "escenario": "< 45 años", "condiciones": {"Edad": ["<45"]}, "n": 100}, - {"cohorte": "metabric", "escenario": "RE− · grado 3", "condiciones": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, "n": 300}, - {"cohorte": "metabric", "escenario": "Ganglios 4+", "condiciones": {"Ganglios_positivos": ["4+"]}, "n": 80}, - {"cohorte": "scanb", "escenario": "Grado 3", "condiciones": {"Grado_histologico": ["3"]}, "n": 900}]} + figure("metabric", "< 45 años", {"Edad": ["<45"]}, 100), figure("metabric", "RE− · grado 3", {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]}, 300), + figure("metabric", "Ganglios 4+", {"Ganglios_positivos": ["4+"]}, 80), figure("scanb", "Grado 3", {"Grado_histologico": ["3"]}, 900), + figure("scanb", "Sin fila", {"Edad": ["<45"]}, 50)]} + summary = {"tablas": {"escenarios_resumen": {"filas": [ + {"cohorte": "metabric", "escenario": "< 45 años", "horizonte_meses": 60}, {"cohorte": "metabric", "escenario": "RE− · grado 3", "horizonte_meses": 60}, + {"cohorte": "metabric", "escenario": "Ganglios 4+", "horizonte_meses": 60}, {"cohorte": "scanb", "escenario": "Grado 3", "horizonte_meses": 60}]}}} labelled = pd.DataFrame({"pac_id": [7], "age_years": [40.0], "size_mm": [None], "grade": ["G3"], "er": ["NEGATIVO"], "pr": ["NEGATIVO"], "her2": ["H2"]}) holder = SimpleNamespace(production="2") @@ -164,8 +173,9 @@ def recurrence_client(monkeypatch): raise LookupError("no hay una versión en producción") return SimpleNamespace(version=holder.production, run_id="run-2") + files = {"analisis/recurrencia.json": json.dumps(record).encode(), "analisis/recurrencia_desarrollo.json": json.dumps(summary).encode()} monkeypatch.setattr(registry_module.registry, "resolve", resolve) - monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: ("recurrencia.json", json.dumps(record).encode())) + monkeypatch.setattr(registry_module.registry, "artifact", lambda d, s, v, p: (p, files[p])) monkeypatch.setattr(model_analysis, "_live_context", lambda d, s: ("spec", "model", labelled, "3")) app = Flask(__name__) app.register_blueprint(model_analysis.recurrence_blueprint(), url_prefix="/cama") @@ -174,21 +184,21 @@ def recurrence_client(monkeypatch): yield client -def test_a_patient_gets_the_recurrence_scenarios_her_covariates_meet(recurrence_client): - """Pins down: `GET /cama/modelo/recurrencia?paciente=7` returns the scenarios whose every condition her age, grade and - receptors meet (one that needs the nodes, which the hospital does not report, is left out), the larger first within a - cohort, with the version that published them. Fails if a scenario she does not meet is returned, a missing covariate counts - as met, or the version is not named.""" +def test_the_recurrence_menu_has_the_scenarios_with_a_summary_row_and_the_patients_default(recurrence_client): + """Pins down: `GET /cama/modelo/recurrencia` returns the figures of the scenarios that have a row in the version's summary (not + the one without), the summary rows, the version, and, for patient 7, the larger scenario her age, grade and receptors meet as the + default (one that needs the nodes, which the hospital does not report, is never it). Fails if a scenario with no row is offered, + the rows are not returned, or the default is not one she meets.""" body = recurrence_client.get("/cama/modelo/recurrencia?paciente=7").get_json() - assert [(s["cohorte"], s["escenario"]) for s in body["escenarios"]] == [("metabric", "RE− · grado 3"), ("metabric", "< 45 años"), ("scanb", "Grado 3")] - assert body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60] + assert [(f["cohorte"], f["escenario"]) for f in body["escenarios"]] == [("metabric", "< 45 años"), ("metabric", "RE− · grado 3"), ("metabric", "Ganglios 4+"), ("scanb", "Grado 3")] + assert len(body["resumen"]) == 4 and body["modelo"] == {"nombre": "cama-recurrence", "version": "2"} and body["horizontes"] == [12, 36, 60] + assert body["predeterminado"] == {"cohorte": "metabric", "escenario": "RE− · grado 3"} + assert recurrence_client.get("/cama/modelo/recurrencia").get_json()["predeterminado"] is None -def test_without_a_recurrence_version_or_for_a_stranger_it_says_so(recurrence_client): - """Pins down: no recurrence version in production is a 404, a patient outside the cohort or no patient is a 422 with a reason. - Fails if either becomes a 200 with nothing or a 500.""" - assert recurrence_client.get("/cama/modelo/recurrencia?paciente=99").status_code == 422 - assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 422 +def test_without_a_recurrence_version_it_is_a_404(recurrence_client): + """Pins down: no recurrence version in production is a 404 with the reason. Fails if it becomes a 200 with nothing or a 500.""" recurrence_client.holder.production = None - assert recurrence_client.get("/cama/modelo/recurrencia?paciente=7").status_code == 404 + + assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 404 diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index 6e6a1ab..814717d 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -48,6 +48,20 @@ def _live_context(domain: str, scenario: str): return _LIVE["value"] +def _summary(domain: str, scenario: str, version: str, artifact: str = "analisis/desarrollo.json", table: str = "escenarios_resumen") -> list[dict]: + """The rows of the scenario summary a version published (`escenarios_resumen`): one per scenario, and for recurrence one per + cohort, scenario and horizon. `[]` for a version that published none (trained before the summary existed).""" + from models.io.registry import registry + + try: + _, content = registry.artifact(domain, scenario, version, artifact) + except LookupError: + return [] + record = json.loads(content) + rows = (record.get("tablas") or record.get("desarrollo", {}).get("tablas") or {}).get(table) or {} + return rows.get("filas", []) if isinstance(rows, dict) else rows + + def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: """The blueprint of one scenario, to register with `url_prefix="/"`.""" blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__) @@ -83,28 +97,34 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: "desarrollo": json.loads(content)}) @blueprint.get("/modelo/escenarios") - def patient_scenarios(): - """The clinical scenarios `?paciente=` belongs to (the whole cohort when she is in none), over the data - ingested so far. 404 while there is no version in production; 422 with the reason for a patient outside the cohort.""" + def scenarios_menu(): + """The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data + ingested so far to draw, in the pipeline's order, with their patients; `?paciente=` also names the one she + belongs to first as the default. 404 while there is no version in production.""" from models.cama.survival import live try: _, _, labelled, version = _live_context(domain, scenario) except LookupError as error: return jsonify({"error": f"sin curvas: {error}"}), 404 + in_summary = {row["escenario"] for row in _summary(domain, scenario, version)} + masks = live.scenario_masks(labelled) + menu = [{"nombre": name, "n": int(mask.sum())} for name, mask in masks.items() if name in in_summary and live.answerable(labelled, mask)] + default = menu[0]["nombre"] if menu else None paciente = request.args.get("paciente", "") - if not paciente.isdigit(): - return jsonify({"error": "Falta la paciente."}), 422 - try: - found = live.patient_scenarios(labelled, int(paciente)) - except live.QueryError as error: - return jsonify({"error": str(error)}), 422 - return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": found}) + if paciente.isdigit(): + try: + mine = live.patient_scenarios(labelled, int(paciente)) + except live.QueryError as error: + return jsonify({"error": str(error)}), 422 + default = next((m["nombre"] for m in menu if m["nombre"] in mine), default) + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu, "predeterminado": default}) @blueprint.post("/modelo/curvas/consulta") def live_curves(): - """The figure's record for the clinical scenario in the body (`{escenario}`, none for the whole cohort), scored with the - production version over the data ingested so far. 422 with the reason for an unknown scenario or one too small.""" + """The figure's record of the clinical scenario in the body (`{escenario}`), scored with the production version over the data + ingested so far, and the scenario's risk factors (its summary row, `null` when it has none). 422 with the reason for an + unknown scenario or one too small.""" from models.cama.survival import live name = (request.get_json(silent=True) or {}).get("escenario") @@ -124,40 +144,45 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint: _ANSWERS[key] = record while len(_ANSWERS) > MAX_ANSWERS: _ANSWERS.popitem(last=False) - return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record}) + row = next((r for r in _summary(domain, scenario, version) if r["escenario"] == name), None) + return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "curvas": record, "factores": row}) return blueprint def recurrence_blueprint() -> Blueprint: - """CaMa's recurrence figures for a patient, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia?paciente=` - answers the figures (METABRIC's and SCAN-B's) of the clinical scenarios her covariates meet, from the recurrence version in - production. The scenarios are the external cohorts' analyses; she is placed in them by her own age, tumor size, grade and - receptors, from the data ingested so far.""" + """CaMa's recurrence analysis, to register with `url_prefix="/cama"`: `GET /modelo/recurrencia` answers the figures of every clinical + scenario of both external cohorts (METABRIC and SCAN-B) that has a row in the summary the production version published, those rows + (one per cohort, scenario and horizon) for the risk-factor label, and, given `?paciente=`, the scenario her own age, tumor + size, grade and receptors place her in first as the default. The figures describe the cohorts' patients, not her.""" blueprint = Blueprint("model_analysis_cama_recurrence", __name__) @blueprint.get("/modelo/recurrencia") def recurrence(): - import pandas as pd - from models.cama.recurrence import patient from models.io.registry import registry - paciente = request.args.get("paciente", "") - if not paciente.isdigit(): - return jsonify({"error": "Falta la paciente."}), 422 try: resolved = registry.resolve("cama", "recurrence") _, content = registry.artifact("cama", "recurrence", resolved.version, "analisis/recurrencia.json") - _, _, labelled, _ = _live_context("cama", "survival") except LookupError as error: return jsonify({"error": f"sin recurrencia: {error}"}), 404 - rows = labelled[labelled["pac_id"] == int(paciente)] - if rows.empty: - return jsonify({"error": "La paciente no está en la cohorte del modelo."}), 422 record = json.loads(content) - found = patient.matching(record["escenarios"], patient.covariates_of(rows.iloc[0])) + summary = _summary("cama", "recurrence", resolved.version, "analisis/recurrencia_desarrollo.json") + present = {(r["cohorte"], r["escenario"]) for r in summary} + figures = [f for f in record["escenarios"] if (f["cohorte"], f["escenario"]) in present] + default = None + paciente = request.args.get("paciente", "") + if paciente.isdigit(): + try: + _, _, labelled, _ = _live_context("cama", "survival") + except LookupError: + labelled = None + rows = labelled[labelled["pac_id"] == int(paciente)] if labelled is not None else None + if rows is not None and not rows.empty: + mine = patient.matching(figures, patient.covariates_of(rows.iloc[0])) + default = {"cohorte": mine[0]["cohorte"], "escenario": mine[0]["escenario"]} if mine else None return jsonify({"modelo": {"nombre": "cama-recurrence", "version": str(resolved.version)}, "horizontes": record["horizons_months"], - "escenarios": found}) + "escenarios": figures, "resumen": summary, "predeterminado": default}) return blueprint -- 2.53.0