Tests: CaMa's stage and size measures of invasive cancers, and the measure counts

This commit is contained in:
rockdrigo
2026-11-18 19:56:07 -06:00
parent 7101913fff
commit 5a4baeb33e
4 changed files with 41 additions and 61 deletions
+2 -1
View File
@@ -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-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-EU38A": ["fig_c3r_caja"],
"CAMA-CONFIRMACION-BIRADS45": [], "CAMA-BIRADS-CANCER-INVASOR": [], "CAMA-CONFIRMACION-BIRADS45": [], "CAMA-BIRADS-CANCER-INVASOR": [],
"CAMA-DIAS-RESULTADO-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-TASA-DETECCION-HISTOPATOLOGICA": [], "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 assert {i: figures(m) for i, m in measures.items()} == expected
+34 -55
View File
@@ -1,11 +1,12 @@
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata. """What this module covers: CaMa's tumour characteristics, from the results read from reports to the measures of the
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as invasive cancers. dbt's `cama_estratificadores` (stage group, early or advanced stage, T by size) as timeline facts;
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the `CAMA_ESTADIO_CANCER_INVASOR` and `CAMA_TAMANO_CANCER_INVASOR`, whose category is that characteristic as known by the
labels a timeline stratum's values carry into FHIR. 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 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 (`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 import os
@@ -20,7 +21,7 @@ from webapi.compositions import answer_composition, composition_definitions
from webapi.fhir.measures import _label from webapi.fhir.measures import _label
from webapi.metrics import Question 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") UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
@@ -40,10 +41,10 @@ def base(tmp_path, sin_supresion, manifest):
base.motor.dispose() 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 d = base.dominio
definition = composition_definitions(manifest)[URL] definition = composition_definitions(manifest)[url]
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff), return answer_composition("cama", definition, Question(url, period, event_cutoff=event_cutoff),
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository, parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True) 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): 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 """Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads
`vars.cama.estratos` or a timeline `tipo` it reads changes.""" changes, or a subtype comes back."""
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"} assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "tamano_t1"}
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest): 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 the BI-RADS of the mammogram that led to """Pins down: H-003 counts in S2, the period of her biopsy report, under her stage (II, from the note) and her T
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the (T1, from the mammogram), each broken down by age; S1 has no invasive cancer. Fails if the characteristics model,
category or a stratum's values drift.""" a category rule or the age stratum drifts."""
assert answered(base, manifest, "2025-S1").categories == {} assert answered(base, manifest, ESTADIO, "2025-S1").categories == {}
result = answered(base, manifest, "2025-S2") estadio = answered(base, manifest, ESTADIO, "2025-S2")
assert result.categories == {"B4A": 1} assert (estadio.categories, estadio.strata) == ({"II": 1}, {"grupo_edad": {"50-59": {"II": 1}}})
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}}, tamano = answered(base, manifest, TAMANO, "2025-S2")
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}}, assert (tamano.categories, tamano.strata) == ({"T1": 1}, {"grupo_edad": {"50-59": {"T1": 1}}})
"tamano": {"T1": {"B4A": 1}}}
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest): def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest):
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype """Pins down: the BI-RADS of the mammogram before an invasive cancer isn't broken down by the tumour's
(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 characteristics, which describe the cancer and not that mammogram. Fails if tumour strata come back."""
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage).""" result = answered(base, manifest, BIRADS, "2025-S2")
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata assert (result.categories, result.strata) == ({"B4A": 1}, {})
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
SUBTIPOS = [ def test_a_characteristic_is_read_as_known_by_the_cut_off(base, manifest):
({"her2": "H3"}, "subtipo_her2"), """Pins down: a characteristic counts only if it was dated by the event cut-off: on 2025-08-01 the size (from the
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"), mammogram before the biopsy) is known and the stage (note of 08-04) isn't, so H-003 still counts, without data.
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"), Fails if a fact after the cut-off is read, or a patient without a fact by then drops out."""
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"), assert answered(base, manifest, TAMANO, "2025-S2", event_cutoff=date(2025, 8, 1)).categories == {"T1": 1}
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"), assert answered(base, manifest, ESTADIO, "2025-S2", event_cutoff=date(2025, 8, 1)).categories == {"SIN_DATO": 1}
({"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_timeline_stratum_s_values_carry_their_labels(): def test_a_timeline_stratum_s_values_carry_their_labels():
+1 -1
View File
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape.""" with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
domain, client = domain_client domain, client = domain_client
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json()) 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"]: for item in measures["entry"]:
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1") 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() assert response.status_code in (200, 409), response.get_json()
+4 -4
View File
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"] 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; # CaCu: three strata and its seven measures; CaMa: the age group of its invasive cancers, the BI-RADS stratum of
# TEA: the age group and its ten measures. # the histopathological result and its thirteen measures; TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto] 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. # 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 assert base.run("definitions")["definitions"]["borradas"] == 0