CaCu indicators: times along the screening route, proportion intervals and survival notebooks #16

Merged
edgar merged 5 commits from integration/cacu-indicadores into dev 2026-11-22 01:01:08 -06:00
12 changed files with 255 additions and 35 deletions
+5 -1
View File
@@ -70,12 +70,16 @@ def groups(measure: dict) -> dict[str, str]:
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
"""Pins down: the two distributions offer the donut and the bars and the two durations their box plot; the C1
"""Pins down: the two distributions offer the donut and the bars and the nine durations their box plot; the C1
proportions and the risk bands none, because no figure is approved for them yet. Fails if a figure is declared
that the page has no builder for, or one is dropped."""
assert {i: figures(m) for i, m in measures.items()} == {
"CACU-EU7": ["fig_c2_donas", "fig_c2_barras"], "CACU-CONFIRMACION-CITOLOGIA": ["fig_c2_donas", "fig_c2_barras"],
"CACU-EU-TIEMPO-REPORTE": ["fig_c3r_caja"], "CACU-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-DIAS-TOMA-TRATAMIENTO": ["fig_c3r_caja"], "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO": ["fig_c3r_caja"],
"CACU-DIAS-TOMA-COLPOSCOPIA": ["fig_c3r_caja"], "CACU-DIAS-TOMA-BIOPSIA": ["fig_c3r_caja"],
"CACU-DIAS-RESULTADO-COLPOSCOPIA": ["fig_c3r_caja"], "CACU-DIAS-COLPOSCOPIA-BIOPSIA": ["fig_c3r_caja"],
"CACU-DIAS-BIOPSIA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-EU13": [], "IND1": [], "CACU-RIESGO-BANDA": []}
+1 -1
View File
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
domain, client = domain_client
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
assert measures["total"] == {"cacu": 7, "cama": 11}[domain]
assert measures["total"] == {"cacu": 14, "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()
+47
View File
@@ -448,3 +448,50 @@ def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
refused before anything runs. Fails if `/experiments` stops checking any of them."""
response = _run(client, notebook or _notebook("1"), **fields)
assert response.status_code in (400, 404)
def _run_template(client, template, *, scenario):
form = {"template": template, "domain": "cacu", "scenario": scenario, "url": "cacu/cohorte_vigilancia",
"source": "dbt", "build": "4"}
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
def test_the_notebooks_kept_in_the_code_are_listed_with_their_scenarios(client, notebooks):
"""Fails if `/notebook-templates` stops listing the notebooks under `models/<domain>/<scenario>/notebooks/` or the
scenarios each can run for."""
found = {t["id"]: t for t in client.get("/governance/notebook-templates", query_string={"domain": "cacu"})
.get_json()["templates"]}
assert "cin2_pim_post_colposcopy" in found["cacu/cin2_pim/reporte_subgrupos"]["scenarios"]
assert found["cacu/survival/reporte_subgrupos"]["scenarios"] == ["survival"]
def test_a_template_runs_like_an_upload_with_the_notebook_read_from_the_code(client, notebooks, monkeypatch):
"""Pins down: a template answers 202 with a run whose notebook is the template's, read from the code (the run
itself is left queued here). Fails if the request's notebook could stand in for the template or the run loses its
name."""
from models.reports.rendering import notebook_sha256
from models.reports.templates import template_notebook
from webapi.blueprints import governance
monkeypatch.setattr(governance, "submit", lambda job, *args: None)
started = _run_template(client, "cacu/cin2_pim/reporte_subgrupos", scenario="cin2_pim_post_colposcopy")
assert started.status_code == 202, started.get_json()
run = started.get_json()
assert run["notebook"] == "reporte_subgrupos" and run["scenario"] == "cin2_pim_post_colposcopy"
assert run["notebook_sha256"] == notebook_sha256(template_notebook("cacu/cin2_pim/reporte_subgrupos")[1])
@pytest.mark.parametrize("template, scenario, status", [
("cacu/survival/reporte_subgrupos", "cin2_pim", 400), # not a scenario it serves
("cacu/../../etc/passwd", "cin2_pim", 400), # not a template id
("cacu/cin2_pim/no_existe", "cin2_pim", 404), # no such template
])
def test_a_template_that_does_not_serve_the_run_is_refused(client, notebooks, template, scenario, status):
"""Fails if a template runs for a scenario it doesn't serve, or an id reaches a file outside the templates."""
assert _run_template(client, template, scenario=scenario).status_code == status
def test_a_file_and_a_template_together_are_refused(client, notebooks):
"""Fails if a request with both a file and a template runs either."""
response = _run(client, _notebook("1"), template="cacu/survival/reporte_subgrupos", scenario="survival")
assert response.status_code == 400
+4 -2
View File
@@ -80,8 +80,10 @@ def test_the_list_names_what_is_answered_on_request(client):
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA",
"CACU_RIESGO_BANDA"}
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
"CACU_DIAS_TOMA_COLPOSCOPIA", "CACU_DIAS_TOMA_BIOPSIA", "CACU_DIAS_RESULTADO_COLPOSCOPIA",
"CACU_DIAS_COLPOSCOPIA_BIOPSIA", "CACU_DIAS_BIOPSIA_DIAGNOSTICO",
"CACU_CONFIRMACION_CITOLOGIA", "CACU_RIESGO_BANDA"}
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
+117 -5
View File
@@ -19,9 +19,9 @@ from sqlalchemy import text
from sqlmodel import Session, select
from conftest import base_de
from core.cacu.models import BiopsiaCervical, CitologiaCervical
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, Paciente
from webapi.compositions import answer_composition, composition_definitions, composition_report
from webapi.metrics import Question, answer, measure_definitions, measure_report
from webapi.metrics import INTERVAL_HIGH, INTERVAL_LOW, Counts, Question, answer, measure_definitions, measure_report
from webapi.orchestration import run
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
@@ -47,6 +47,61 @@ def base(tmp_path, sin_supresion, manifest):
base.motor.dispose()
def _con_tratamiento(sesion: Session) -> None:
"""The fixture data and, for H-004, her colposcopy (August 20) and her treatment (August 28), after the
valuation visit of August 10: the timeline then holds a treatment to end an interval at."""
from staging.cacu import COLPOSCOPIA, FAMILIAR, insertar
insertar(sesion)
paciente = sesion.exec(select(Paciente).where(Paciente.pac_id_hospital == "H-004")).one()
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-004", nm_id_hospital=f"NM-9{n}", nm_fecha=fecha,
nm_cie_codigo=cie, nm_especialidad=especialidad)
for n, (fecha, cie, especialidad) in enumerate(
[(date(2025, 8, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 28), "D06.9", FAMILIAR)], start=1))
sesion.commit()
def _con_ruta(sesion: Session) -> None:
"""The fixture data and H-007, who goes the whole route in order: a cytology on July 5 with its result on July 15,
a valuation note on July 20, her colposcopy and the request of her biopsy on August 5, the biopsy report on
August 25 and a diagnosis after it on September 10."""
from staging.cacu import COLPOSCOPIA, ONCOLOGIA, SATISFACTORIO, insertar
insertar(sesion)
paciente = Paciente(pac_id_hospital="H-007", pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1))
sesion.add(paciente)
sesion.flush()
citologia = CitologiaCervical(pac_id=paciente.pac_id, pac_id_hospital="H-007", cit_fecha_toma=date(2025, 7, 5),
cit_calidad_especimen=SATISFACTORIO, cit_fecha_reporte=date(2025, 7, 15),
cit_celulas_escamosas="ASC-US", cit_vph_resultado="POSITIVO")
sesion.add(citologia)
sesion.flush()
sesion.add(BiopsiaCervical(pac_id=paciente.pac_id, pac_id_hospital="H-007", cit_id=citologia.cit_id,
bx_fecha_solicitud=date(2025, 8, 5), bx_fecha_reporte=date(2025, 8, 25), bx_cin_grado="CIN2"))
sesion.add_all(NotaMedica(pac_id=paciente.pac_id, pac_id_hospital="H-007", nm_id_hospital=f"NM-8{n}", nm_fecha=fecha,
nm_cie_codigo=cie, nm_especialidad=especialidad)
for n, (fecha, cie, especialidad) in enumerate(
[(date(2025, 7, 20), "R87.6", COLPOSCOPIA), (date(2025, 8, 5), "R87.6", COLPOSCOPIA),
(date(2025, 9, 10), "D06.9", ONCOLOGIA)], start=1))
sesion.commit()
@pytest.fixture
def base_con_ruta(tmp_path, sin_supresion, manifest):
base = base_de("cacu", tmp_path, datos=_con_ruta)
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
base.motor.dispose()
@pytest.fixture
def base_con_tratamiento(tmp_path, sin_supresion, manifest):
base = base_de("cacu", tmp_path, datos=_con_tratamiento)
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
base.motor.dispose()
@pytest.fixture
def kit():
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
@@ -254,8 +309,9 @@ def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base,
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's
categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer."""
inclusive period end, each population's count, the score with its interval, strata as a `stratifier`, and a
composition's categories as one more. Fails if a population, the score, a stratum or a category stops matching
the answer."""
period = base.dominio.dim_periodo_repository.get("2025-S1")
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
@@ -265,7 +321,7 @@ def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
"initial-population": 4, "denominator": 4, "numerator": 1}
assert group["measureScore"] == {"value": 0.25}
assert group["measureScore"]["value"] == 0.25
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
@@ -281,6 +337,18 @@ def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
def test_a_proportion_is_scored_with_its_wilson_interval():
"""Pins down: `Counts.score` carries the proportion and its 95 % Wilson interval as proportions, in the
`ic-bajo` and `ic-alto` extensions (1 of 4 is 0.25 within 0.0456 and 0.6994), and publishes no score when the
denominator is zero. Fails if an interval is dropped, comes out as a percentage, or a zero denominator is scored."""
score = Counts(1, 4).score
bounds = {e["url"]: e["valueDecimal"] for e in score["extension"]}
assert score["value"] == 0.25
assert bounds[INTERVAL_LOW] == pytest.approx(0.0456, abs=1e-4)
assert bounds[INTERVAL_HIGH] == pytest.approx(0.6994, abs=1e-4)
assert Counts(0, 0).score is None
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
@@ -454,6 +522,50 @@ def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_y
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
DIAS_TOMA_TRATAMIENTO = "cacu/CACU_DIAS_TOMA_TRATAMIENTO"
DIAS_DIAGNOSTICO_TRATAMIENTO = "cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (4, 1, 58.0, 3)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
def test_the_times_to_treatment_are_counted_from_their_start_to_the_first_treatment(base_con_tratamiento, manifest, url, expected):
"""Pins down the two times to treatment on the fixture with H-004's colposcopy and treatment, 2025-S2 cut at the
end of the year, with a 60-day horizon. From the sample: H-004's July sample reaches her treatment of August 28 in
58 days; the other three samples of the semester have no treatment and their horizon has passed, so they are in
the initial population and not measured. From the diagnosis: only that sample has one in the period, and its
diagnosis of August 10 reaches the treatment in 18 days. Fails if the end event, the start (sample or diagnosis),
the horizon rule or the split between not measured yet and without event changes."""
from webapi.durations import answer_duration, duration_definitions
definition = duration_definitions(manifest)[url]
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)),
**repositories(base_con_tratamiento))
assert (result.initial, result.n, result.median, result.excluded) == expected
RUTA = { # url -> (población inicial, n, mediana, excluidas) en 2025-S2, con corte a fin de año
"cacu/CACU_DIAS_TOMA_COLPOSCOPIA": (5, 1, 31.0, 4),
"cacu/CACU_DIAS_TOMA_BIOPSIA": (5, 2, 41.0, 3),
"cacu/CACU_DIAS_RESULTADO_COLPOSCOPIA": (3, 1, 21.0, 2),
"cacu/CACU_DIAS_COLPOSCOPIA_BIOPSIA": (1, 1, 20.0, 0),
"cacu/CACU_DIAS_BIOPSIA_DIAGNOSTICO": (2, 2, 12.5, 0),
}
@pytest.mark.parametrize("url", sorted(RUTA))
def test_the_times_along_the_screening_route_count_between_consecutive_events(base_con_ruta, manifest, url):
"""Pins down the five times of the screening route on the fixture with H-007, 2025-S2 cut at the end of the year.
From the sample: H-007's colposcopy (31 days) and the biopsy reports of H-004 (31) and H-007 (51); the other
samples have none and their 60-day horizon has passed, so they are in the initial population and not measured.
Between events: the colposcopy from the cytology result (21 days), the biopsy report from the colposcopy (20) and
the diagnosis from the biopsy report (9 and 16 days). Fails if an event, its start, its horizon or the population
each measure counts over changes."""
from webapi.durations import answer_duration, duration_definitions
definition = duration_definitions(manifest)[url]
result = answer_duration("cacu", definition, Question(url, "2025-S2", date(2025, 12, 31)), **repositories(base_con_ruta))
assert (result.initial, result.n, result.median, result.excluded) == RUTA[url]
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
+3 -3
View File
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: the BI-RADS stratum of the histopathological result and its
# CaCu: three strata and its fourteen 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]
assert resumen["definitions"] == {"cacu": 17, "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": 11, "tea": 10}[base.proyecto]
assert base.dominio.cat_measure_repository.count() == {"cacu": 14, "cama": 11, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0
+8 -6
View File
@@ -15,7 +15,9 @@ from pathlib import Path
import pytest
CORTE = date(2025, 12, 31)
INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente", "orden_biopsia"}
# What dbt adds to the kit's timeline: the procedures it infers and the patient's birth and death, from `persona`.
ADDED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente", "orden_biopsia",
"nacimiento", "defuncion"}
KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json"
@@ -38,18 +40,18 @@ def kit_rows():
def as_kit(rows) -> list[dict]:
"""Rows as the snapshot keeps them: text values, no load time, without the inferred procedures."""
"""Rows as the snapshot keeps them: text values, no load time, without the rows dbt adds."""
return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"}
for row in rows if row["tipo"] not in INFERRED]
for row in rows if row["tipo"] not in ADDED]
def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows):
"""Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its
order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or
the view stops giving one of the kit's rows."""
order and with a date as `fecha`, plus the inferred procedures and the patient's birth and death. Fails if the
orchestration binds another query, or the view stops giving one of the kit's rows."""
rows = loaded.ctx.repos.silver.timeline.read(until=CORTE)
assert as_kit(rows) == kit_rows
assert {row["tipo"] for row in rows} & INFERRED
assert {row["tipo"] for row in rows} & ADDED
assert all(isinstance(row["fecha"], date) for row in rows)
+3 -1
View File
@@ -108,7 +108,9 @@ def test_indicators_recompute_from_imported_rows(client):
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
"CACU_DIAS_TOMA_COLPOSCOPIA", "CACU_DIAS_TOMA_BIOPSIA", "CACU_DIAS_RESULTADO_COLPOSCOPIA",
"CACU_DIAS_COLPOSCOPIA_BIOPSIA", "CACU_DIAS_BIOPSIA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
Generated
+19 -3
View File
@@ -1414,8 +1414,8 @@ name = "httpcore2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h11" },
{ name = "truststore" },
{ name = "h11", marker = "sys_platform != 'emscripten'" },
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
]
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 = [
@@ -2211,6 +2211,7 @@ seer-survival = [
]
survival-curves = [
{ name = "mpmath" },
{ name = "plotly" },
{ name = "scipy" },
]
@@ -2232,6 +2233,7 @@ requires-dist = [
{ name = "pandera", specifier = ">=0.20" },
{ name = "persistance", editable = "../Persistance" },
{ name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" },
{ name = "plotly", marker = "extra == 'survival-curves'", specifier = ">=5.18" },
{ name = "pyarrow", specifier = ">=15" },
{ name = "scikit-learn", specifier = ">=1.4" },
{ name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" },
@@ -2252,6 +2254,7 @@ dev = [
{ name = "nbconvert", specifier = ">=7.16" },
{ name = "networkx", specifier = ">=3.0" },
{ name = "pgmpy", specifier = ">=1.0" },
{ name = "plotly", specifier = ">=5.18" },
{ name = "pytest", specifier = ">=8.0.0" },
{ name = "reportlab", specifier = ">=4.0" },
{ name = "scipy", specifier = ">=1.11" },
@@ -2949,7 +2952,7 @@ name = "pexpect"
version = "4.9.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "ptyprocess" },
{ name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }
wheels = [
@@ -3059,6 +3062,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" },
]
[[package]]
name = "plotly"
version = "7.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "narwhals" },
{ name = "packaging" },
]
sdist = { url = "https://files.pythonhosted.org/packages/49/c3/72b369f5ed7701b04ab0ea3dcf83e9bbce71c0b3bc6f07f87568550d09ea/plotly-7.1.0.tar.gz", hash = "sha256:f860166a4a3d78c69cb1f4a15f28a5c8283eade98a282a698f3bb853a449ace5", size = 6689315, upload-time = "2026-09-15T19:21:21.75Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl", hash = "sha256:dbb7fa18afce40d0a8e80d1bf162eceb3faa0ce5a77fe741ad09a74cf78f53f3", size = 9692368, upload-time = "2026-09-15T19:21:18.331Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
+31 -9
View File
@@ -228,6 +228,15 @@ def list_cohort_files():
return jsonify({"builds": exported_builds(_cohorts_root(domain), domain)})
@governance_bp.get("/notebook-templates")
def list_notebook_templates():
"""`?domain=`: the notebooks kept in the code (`models/<domain>/<scenario>/notebooks/`), with the scenarios each can
run for; `POST /experiments` runs one by its `id` as `template`."""
from models.reports.templates import notebook_templates
return jsonify({"templates": notebook_templates(request.args.get("domain") or None)})
@governance_bp.get("/experiments")
def list_experiments():
"""Notebook runs, newest first; `?domain=` and `?domain=&scenario=` narrow them."""
@@ -237,13 +246,18 @@ def list_experiments():
@governance_bp.post("/experiments")
def run_experiment():
"""Multipart `file` (a .ipynb), `domain`, `scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`:
runs the notebook on that build's file in the background and answers 202 with the run, still `en_curso`."""
"""Multipart `file` (a .ipynb) or `template` (the id of a notebook kept in the code, `/notebook-templates`), `domain`,
`scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`: runs the notebook on that build's file in
the background and answers 202 with the run, still `en_curso`. A template is read from the code, never from the
request, and must be of the domain and serve the scenario."""
upload = request.files.get("file")
form = request.form
template = form.get("template") or None
missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)]
if upload is None or missing:
return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 400
if (upload is None and template is None) or missing:
return jsonify({"error": f"faltan campos: {(['file o template'] if upload is None and template is None else []) + missing}"}), 400
if upload is not None and template is not None:
return jsonify({"error": "elige un archivo o una plantilla, no ambos"}), 400
domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None
url = form["url"]
if url.split("/", 1)[0] != domain:
@@ -251,13 +265,21 @@ def run_experiment():
if not form["build"].isdigit():
return jsonify({"error": "build debe ser un número"}), 400
path = build_file(_cohorts_root(domain), url, form["source"], int(form["build"]))
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
if template is not None:
from models.reports.templates import notebook_templates, template_notebook
name, notebook = template_notebook(template)
found = {t["id"]: t for t in notebook_templates(domain)}.get(template)
if found is None or scenario not in found["scenarios"]:
return jsonify({"error": f"la plantilla {template!r} no corre para {domain}/{scenario}"}), 400
else:
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
name = experiment.notebook_name(upload.filename or "notebook")
if version:
registry.get(domain, scenario, version)
name = experiment.notebook_name(upload.filename or "notebook")
run_id = experiment.start(notebook, name, path, domain, scenario, version)
submit(experiment.execute, run_id, notebook, name, path, domain, scenario, version)
return jsonify(experiment.describe(run_id)), 202
+2 -2
View File
@@ -122,8 +122,8 @@ def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
if excluded is not None and getattr(definition, "exclusion", None):
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
if counts.proportion is not None:
cells["measureScore"] = {"value": counts.proportion}
if counts.score:
cells["measureScore"] = counts.score
return cells
+15 -2
View File
@@ -41,6 +41,8 @@ from sqlalchemy import (
true,
)
from webapi.cama_analysis.stats import wilson
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
TOTAL = "total"
NO_DATA = "sin_dato"
@@ -545,6 +547,15 @@ class Counts:
def proportion(self) -> float | None:
return self.numerator / self.denominator if self.denominator else None
@property
def score(self) -> dict | None:
"""The FHIR `measureScore`: the proportion and its 95 % Wilson interval, all as proportions in [0, 1]."""
if not self.denominator:
return None
low, high = wilson(self.numerator, self.denominator)
return {"value": self.proportion, "extension": [
{"url": INTERVAL_LOW, "valueDecimal": low}, {"url": INTERVAL_HIGH, "valueDecimal": high}]}
@dataclasses.dataclass(frozen=True)
class Answer:
@@ -657,6 +668,8 @@ POPULATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-population"
EVENT_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-evento"
KNOWLEDGE_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento"
HISTORY_ENTRY = "https://isssteleon.org/fhir/StructureDefinition/reporte-id"
INTERVAL_LOW = "https://isssteleon.org/fhir/StructureDefinition/ic-bajo"
INTERVAL_HIGH = "https://isssteleon.org/fhir/StructureDefinition/ic-alto"
def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
@@ -667,8 +680,8 @@ def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
def _scored(entry: dict, counts: Counts) -> dict:
if counts.proportion is not None:
entry["measureScore"] = {"value": counts.proportion}
if counts.score:
entry["measureScore"] = counts.score
return entry