Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fe4101982 | |||
| e0967d0175 | |||
| 377882edd0 | |||
| c51402510a | |||
| 7640486852 | |||
| 4a61bd8d33 | |||
| e2732f5e8a | |||
| b9795c02ca | |||
| b63a253b19 | |||
| f002e24811 | |||
| a04ceb6301 | |||
| 03be05fb17 | |||
| 0c69140d2e | |||
| 1d52da79e4 | |||
| 6d01742a85 | |||
| 8e5a7e3b81 | |||
| d156bf3c99 | |||
| 9461dfbd20 | |||
| 0a8e3577a1 | |||
| e44f0c84b3 | |||
| 4840bd3dc8 | |||
| b7ce3e7ddd |
+3
-2
@@ -19,9 +19,10 @@ RUN uv sync --group sqlite --group sqlserver --group postgres \
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary. Graphviz's `dot` draws each
|
||||
# trained version's dataflow (`diagramas/pipeline.svg`); without it only the `.dot` source is stored.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-spa \
|
||||
tesseract-ocr tesseract-ocr-spa graphviz \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
|
||||
@@ -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": []}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Every FHIR URL the API emits hangs from one base, which FHIR_BASE_URL sets (issue 199)."""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
from webapi import durations, fhir_base, metrics
|
||||
from webapi.fhir import common
|
||||
|
||||
POR_DEFECTO = "https://isssteleon.org/fhir"
|
||||
|
||||
|
||||
def test_todas_las_urls_cuelgan_de_la_misma_base():
|
||||
estructuras = [metrics.EVENT_CUTOFF, metrics.KNOWLEDGE_CUTOFF, metrics.HISTORY_ENTRY, metrics.INTERVAL_LOW, metrics.INTERVAL_HIGH]
|
||||
assert all(u.startswith(f"{common.STRUCTURE}/") for u in estructuras)
|
||||
assert common.STRUCTURE == f"{common.BASE}/StructureDefinition" == fhir_base.STRUCTURE
|
||||
assert common.CODE_SYSTEM.startswith(common.BASE) and common.VALUE_SET.startswith(common.BASE)
|
||||
|
||||
|
||||
def test_no_quedan_dominios_escritos_a_mano_fuera_de_la_base():
|
||||
import pathlib
|
||||
raiz = pathlib.Path(fhir_base.__file__).parent
|
||||
escritos = [p.name for p in raiz.rglob("*.py") if "isssteleon.org" in p.read_text() and p.name != "fhir_base.py"]
|
||||
assert escritos == []
|
||||
|
||||
|
||||
def test_la_base_se_puede_cambiar_por_ambiente(monkeypatch):
|
||||
monkeypatch.setenv("FHIR_BASE_URL", "https://fhir.ejemplo.test/base/")
|
||||
try:
|
||||
importlib.reload(fhir_base)
|
||||
assert fhir_base.BASE == "https://fhir.ejemplo.test/base"
|
||||
assert fhir_base.STRUCTURE == "https://fhir.ejemplo.test/base/StructureDefinition"
|
||||
finally:
|
||||
monkeypatch.delenv("FHIR_BASE_URL")
|
||||
importlib.reload(fhir_base)
|
||||
assert fhir_base.BASE == POR_DEFECTO
|
||||
|
||||
|
||||
def test_los_q1_y_q3_de_los_tiempos_usan_la_misma_base():
|
||||
assert durations.STRUCTURE == metrics.INTERVAL_LOW.rsplit("/", 1)[0]
|
||||
@@ -107,3 +107,55 @@ def test_the_capability_statement_declares_the_search(client):
|
||||
|
||||
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
|
||||
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
|
||||
|
||||
|
||||
def test_each_outcome_is_its_own_risk_assessment(client, seeded):
|
||||
"""Pins down: with a confirmed cancer batch next to the CIN2+ one, the patient's Bundle holds one RiskAssessment
|
||||
per outcome, the newest first, each with its own outcome code. Fails if the route goes back to one batch, which
|
||||
hides the other outcome's risk. Runs last: it adds a batch to the module's database."""
|
||||
from persistance import cacu
|
||||
|
||||
scored, _, batch = seeded
|
||||
cancer, _ = cacu.cohort_repository.save_batch(
|
||||
_build_of(batch),
|
||||
{"modelo_nombre": "cacu-cancer_pim", "modelo_version": "1", "mlflow_run_id": "r2", "modelo_sha": "s2"},
|
||||
"cancer", [(scored, MODEL_INDEX, 3.0, 0.02, 0.01, 0.04)], ahora=datetime(2026, 10, 2, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(cancer, "final", "revisado")
|
||||
|
||||
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()
|
||||
|
||||
found = [e["resource"] for e in bundle["entry"]]
|
||||
assert bundle["total"] == 2 and [r["id"] for r in found] == [f"{cancer}-{scored}", f"{batch}-{scored}"]
|
||||
assert [r["prediction"][0]["outcome"]["coding"][0]["code"] for r in found] == ["cancer", "cin2_mas"]
|
||||
|
||||
|
||||
def _build_of(batch: int) -> int:
|
||||
from core.cacu.indicadores.models import EvaluacionRiesgoLote
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
return session.get(EvaluacionRiesgoLote, batch).armado_id
|
||||
|
||||
|
||||
def test_a_current_model_that_did_not_score_her_says_so(client, seeded):
|
||||
"""Pins down: a confirmed batch of another outcome that scored only another patient gives the scored patient a
|
||||
RiskAssessment with no prediction and the `sin-estimacion` extension, while a patient with no risk at all still
|
||||
gets an empty Bundle. Fails if the record can't tell "no model" from "not estimated for her", or a patient with
|
||||
no risk gets one. Runs after the cancer test: it adds another batch to the module's database."""
|
||||
from persistance import cacu
|
||||
|
||||
from webapi.fhir.risk import NOT_SCORED
|
||||
|
||||
scored, unscored, batch = seeded
|
||||
other, _ = cacu.cohort_repository.save_batch(
|
||||
_build_of(batch), {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r3",
|
||||
"modelo_sha": "s3"},
|
||||
"muerte", [(unscored, MODEL_INDEX, 1.0, 0.1, None, None)], ahora=datetime(2026, 10, 3, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(other, "final", "revisado")
|
||||
|
||||
found = {e["resource"]["id"]: e["resource"] for e in
|
||||
client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()["entry"]}
|
||||
missing = found[f"{other}-{scored}"]
|
||||
marker = next(e for e in missing["extension"] if e["url"] == NOT_SCORED)
|
||||
assert "prediction" not in missing and {"url": "desenlace", "valueCode": "muerte"} in marker["extension"]
|
||||
assert len(found) == 3
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""What this module covers: `webapi.fhir.risk.risk_assessment` naming what the model's number is (`[estimand]` of its
|
||||
scenario's `model.toml`) in the extension `estimando` and `method.text`, and leaving both out for a model whose
|
||||
scenario can't be read.
|
||||
|
||||
Fixtures: none; the patient's risk is a stand-in with the fields `PatientRisk` has.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from webapi.fhir import risk
|
||||
|
||||
|
||||
def _risk(modelo_nombre):
|
||||
horizon = SimpleNamespace(horizonte_anios=1.0, probabilidad=0.1, ic_bajo=0.05, ic_alto=0.2)
|
||||
return SimpleNamespace(lote_id=1, estado_lote="final", evaluado_en=datetime(2026, 1, 1, tzinfo=timezone.utc),
|
||||
modelo_nombre=modelo_nombre, modelo_version="2", fecha_indice=date(2025, 1, 1),
|
||||
horizontes=[horizon], desenlace="cin2")
|
||||
|
||||
|
||||
def test_the_risk_says_what_its_number_is():
|
||||
"""Pins down: a PIM risk carries its scenario's quantity, outcome and horizons' unit. Fails if the extension's url
|
||||
or keys change, which the WebApp reads, or the scenario stops being found by the registered name."""
|
||||
found = risk.risk_assessment(7, _risk("cacu-cin2_pim"), True, {}, "cin2_mas")
|
||||
|
||||
extension = {e["url"]: e["valueString"] for e in found["extension"][0]["extension"]}
|
||||
assert found["extension"][0]["url"] == risk.ESTIMAND and found["method"]["text"] == "Riesgo acumulado"
|
||||
assert extension["horizons_unit"] == "años" and extension["outcome"].startswith("CIN2+")
|
||||
|
||||
|
||||
def test_a_model_without_a_scenario_has_no_estimand():
|
||||
"""Pins down: a registered name with no scenario behind it gives the resource without the extension. Fails if
|
||||
a missing scenario breaks the patient's risk."""
|
||||
found = risk.risk_assessment(7, _risk("cacu-no_existe"), True, {}, "cin2_mas")
|
||||
assert "text" not in found["method"] and not any(e.get("url") == risk.ESTIMAND for e in found.get("extension", []))
|
||||
|
||||
|
||||
def test_a_cacu_risk_names_the_results_of_its_index_cytology(monkeypatch):
|
||||
"""Pins down: CaCu's RiskAssessment carries the squamous, glandular and HPV results of the cytology sampled on the
|
||||
risk's index date (the most complete if there are several), which the record words its sentence with; a risk
|
||||
with none that day has no such extension. Fails if the extension's url or keys change, or another day's sample
|
||||
is read."""
|
||||
from persistance import cacu as repos
|
||||
|
||||
from webapi.fhir import cacu
|
||||
|
||||
asked = []
|
||||
|
||||
def rows(**filters):
|
||||
asked.append(filters)
|
||||
return [SimpleNamespace(cit_celulas_escamosas="LIEBG", cit_celulas_glandulares=None, cit_vph_resultado=None),
|
||||
SimpleNamespace(cit_celulas_escamosas="LIEBG", cit_celulas_glandulares=None,
|
||||
cit_vph_resultado="POSITIVO")]
|
||||
|
||||
monkeypatch.setattr(repos.citologia_cervical_repository, "list", rows)
|
||||
found = cacu.risk_assessment(7, _risk("cacu-cin2_pim"), True)
|
||||
|
||||
extension = next(e for e in found["extension"] if e["url"] == cacu.INDEX_RESULTS)
|
||||
assert {e["url"]: e["valueString"] for e in extension["extension"]} == {"escamosas": "LIEBG", "vph": "POSITIVO"}
|
||||
assert asked[0]["pac_id"] == 7 and asked[0]["cit_fecha_toma"] == date(2025, 1, 1)
|
||||
|
||||
monkeypatch.setattr(repos.citologia_cervical_repository, "list", lambda **filters: [])
|
||||
without = cacu.risk_assessment(7, _risk("cacu-cin2_pim"), True)["extension"]
|
||||
assert not any(e["url"] == cacu.INDEX_RESULTS for e in without)
|
||||
@@ -113,13 +113,13 @@ REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_vali
|
||||
|
||||
|
||||
def test_model_version_lifecycle_over_http(client):
|
||||
"""A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can,
|
||||
and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared
|
||||
over the API, or promotion stops retiring the previous version."""
|
||||
"""A version registered over HTTP carries no saved model, so it can't be promoted; trained ones can, and promoting
|
||||
the second retires the first. Fails if the ML-01b check starts trusting what's declared over the API, or promotion
|
||||
stops retiring the previous version."""
|
||||
declared = _register(client, "v0", scenario="lifecycle")
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json()
|
||||
assert checks["ready"] is False
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"]
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote")
|
||||
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -80,14 +80,16 @@ 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):
|
||||
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
|
||||
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
|
||||
by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its
|
||||
by default). 2025-S2's samples resolved in 40 and 161 days, and the 120-day horizon keeps only the first. Fails if a duration stops being served or its
|
||||
contract changes."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
|
||||
(entry,) = bundle["entry"]
|
||||
@@ -95,9 +97,9 @@ def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
||||
(group,) = report["group"]
|
||||
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "measure-observation": 2}
|
||||
assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d"
|
||||
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75]
|
||||
"initial-population": 4, "measure-observation": 1}
|
||||
assert group["measureScore"]["value"] == 40.0 and group["measureScore"]["unit"] == "d"
|
||||
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [40.0, 40.0]
|
||||
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
|
||||
|
||||
@@ -13,34 +13,38 @@ from webapi.recomputation import RecomputationQueue
|
||||
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
|
||||
|
||||
|
||||
def test_only_cacu_has_a_live_estimator():
|
||||
"""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."""
|
||||
def test_with_an_empty_registry_no_domain_has_a_live_estimator():
|
||||
"""With no version in the registry, neither CaMa's nor TEA's cycle estimates anything. 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") == {}
|
||||
|
||||
|
||||
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
|
||||
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
|
||||
Fails if `live_estimators` stops catching the registry's `LookupError`."""
|
||||
Fails if `live_estimators` offers a scenario the registry does not list as in production."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: [])
|
||||
assert estimators.live_estimators("cacu") == {}
|
||||
|
||||
|
||||
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
|
||||
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
|
||||
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
|
||||
def test_every_scenario_in_production_scores_its_cohort(monkeypatch):
|
||||
"""Each scenario the registry has in production gets an estimator on the cohort its `model.toml` names, so two
|
||||
scenarios on one cohort give that cohort two estimators; a registered name with no scenario in `models` is
|
||||
skipped. An estimator reports nothing until it has estimated. Fails if the scenarios go back to a fixed list,
|
||||
if one cohort keeps a single estimator, or if an unknown registered name breaks the cycle."""
|
||||
from models.dags.training import Scenario
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
|
||||
monkeypatch.setattr(registry, "in_production", lambda domain: ["cancer_pim", "cin2_pim", "no_such_model"])
|
||||
live = estimators.live_estimators("cacu")
|
||||
assert list(live) == [URL]
|
||||
estimator = live[URL]
|
||||
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
|
||||
cohort = Scenario.load("cacu", "cin2_pim").cohort
|
||||
assert Scenario.load("cacu", "cancer_pim").cohort == cohort
|
||||
assert list(live) == [cohort]
|
||||
assert [e.scenario for e in live[cohort]] == ["cancer_pim", "cin2_pim"]
|
||||
with pytest.raises(RuntimeError):
|
||||
estimator.procedencia()
|
||||
live[cohort][0].procedencia()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
@@ -48,7 +52,7 @@ def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monk
|
||||
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
|
||||
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
|
||||
as anything but `preliminary`."""
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: [EstimadorFijo()]})
|
||||
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
|
||||
assert result["estado"] == "ok", result
|
||||
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
|
||||
|
||||
@@ -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,12 +337,31 @@ 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"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO])
|
||||
# The oracle is the kit's output at the kit's 180-day horizon from the sample to the diagnosis; the project's is 120 (a
|
||||
# parameter it set on purpose), so a sample the kit measures at 161 days is no longer measured. The comparison fails
|
||||
# for that period until the oracle is regenerated from the kit with the project's horizon (strict: it then asks for
|
||||
# this mark to go).
|
||||
SIN_ORACULO_DE_120 = pytest.mark.xfail(strict=True, reason="the kit's oracle uses a 180-day horizon from the sample to the diagnosis; the project's is 120")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, pytest.param(DIAS_TOMA_DIAGNOSTICO, marks=SIN_ORACULO_DE_120)])
|
||||
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
|
||||
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
|
||||
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
|
||||
@@ -454,6 +529,51 @@ 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, (1, 1, 58.0, 0)), (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. From the sample (a 180-day horizon): H-004's July sample reaches her treatment of August 28 in 58
|
||||
days; the others of the semester (August 12, September 1 and October 2) have no treatment and their horizon is
|
||||
after the cut, so they are pending and not in the initial population. From the diagnosis (60 days): 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"
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ def cuenta(base, sql):
|
||||
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
estimador = EstimadorFijo()
|
||||
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: [estimador]})["estimate"][URL][0]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
@@ -68,16 +68,30 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
|
||||
|
||||
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
|
||||
assert cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0] == (primero, False)
|
||||
assert cacu.run("estimate")["estimate"] == {}
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_dos_modelos_de_una_cohorte_dejan_un_lote_cada_uno(cacu):
|
||||
"""Two estimators on one cohort (two scenarios in production on the same build) write one batch each. Fails if
|
||||
`estimate` keeps only one estimator per cohort or folds two models into one batch."""
|
||||
class OtroModelo(EstimadorFijo):
|
||||
def procedencia(self):
|
||||
return Procedencia(modelo_nombre="cacu-otro")
|
||||
|
||||
lotes = cacu.run("estimate", estimators={URL: [EstimadorFijo(), OtroModelo()]})["estimate"][URL]
|
||||
|
||||
assert [nuevo for _, nuevo in lotes] == [True, True] and lotes[0][0] != lotes[1][0]
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: [EstimadorFijo()]})["estimate"][URL][0]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -100,3 +100,17 @@ def test_an_unknown_batch_is_404(client):
|
||||
"""Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed
|
||||
nothing."""
|
||||
assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404
|
||||
|
||||
|
||||
def test_a_decision_that_collides_with_another_is_409(client, monkeypatch):
|
||||
"""Pins down: two decisions of one batch at the same moment (a double click reaching both workers) give the
|
||||
second a 409 instead of a server error. Fails if the unique version of an evaluation surfaces as a 500."""
|
||||
from persistance import cacu
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
def collide(*args, **kwargs):
|
||||
raise IntegrityError("INSERT", {}, Exception("UNIQUE constraint failed"))
|
||||
|
||||
monkeypatch.setattr(cacu.cohort_repository, "change_state", collide)
|
||||
|
||||
assert client.post("/cacu/riesgos/lotes/1/confirmar", json={"reason": "revisado"}).status_code == 409
|
||||
|
||||
@@ -43,6 +43,18 @@ def test_paciente_schema_coerces_date_from_datetime_object():
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_cacu_paciente_keeps_her_date_of_death():
|
||||
"""Pins down: a CaCu patient's `pac_fecha_defuncion` is imported (the survival scenario's outcome), and an alive
|
||||
patient has none. Fails if the schema drops the column again: every CaCu death would be lost on import and the
|
||||
survival model would train with no deaths."""
|
||||
from datetime import date
|
||||
|
||||
dead = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="1960-03-01", pac_fecha_defuncion="2025-07-09")
|
||||
alive = PacienteImportSchema(pac_id_hospital="H-2", pac_fecha_nacimiento="1960-03-01")
|
||||
|
||||
assert dead.pac_fecha_defuncion == date(2025, 7, 9) and alive.pac_fecha_defuncion is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_is_fully_optional():
|
||||
schema = PacientesImportSchema()
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
+124
-4
@@ -8,9 +8,10 @@ de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostr
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "horizontes_disponibles", "reglas",
|
||||
"paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
"dias_toma_diagnostico", "ultima_biopsia", "probabilidades", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -41,12 +42,13 @@ def test_el_pedido_se_respeta(client):
|
||||
|
||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA", "orden": "reciente", "horizonte": 5.0}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500",
|
||||
"?orden=edad", "?horizonte=cinco"],
|
||||
)
|
||||
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
|
||||
response = client.get(f"/cacu/seguimiento{query}")
|
||||
@@ -68,3 +70,121 @@ def test_in_dev_esta_obsoleta():
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
in_dev()
|
||||
|
||||
|
||||
def test_la_lista_se_ordena_por_la_probabilidad_de_lieag_al_horizonte_pedido(client):
|
||||
"""Fija: con un lote de CIN2+ confirmado, cada fila trae sus probabilidades por horizonte y `orden=lieag` pone
|
||||
primero a la de mayor probabilidad al `horizonte` pedido, y al final a quien el modelo no evalúa; un horizonte que
|
||||
los modelos no dan es 400. Falla si la lista deja de leer los lotes vigentes, o si ordena solo dentro de la página."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
baja, alta = int(filas[0]["pac_id"]), int(filas[1]["pac_id"])
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-orden",
|
||||
marco_sha="m", n_miembros=2, armado_en=datetime(2026, 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 (baja, alta)])
|
||||
session.commit()
|
||||
armado = build.armado_id
|
||||
indice = date(2025, 3, 1)
|
||||
lote, _ = cacu.cohort_repository.save_batch(
|
||||
armado, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "9", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2", [(baja, indice, 1.0, 0.02, 0.01, 0.04), (baja, indice, 5.0, 0.05, 0.03, 0.08),
|
||||
(alta, indice, 1.0, 0.10, 0.07, 0.14), (alta, indice, 5.0, 0.30, 0.22, 0.40)])
|
||||
cacu.cohort_repository.change_state(lote, "final", "revisado")
|
||||
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=lieag&horizonte=1").get_json()
|
||||
|
||||
assert cuerpo["horizontes_disponibles"] == [1.0, 5.0] and cuerpo["filtros"]["orden"] == "lieag"
|
||||
assert [i["pac_id"] for i in cuerpo["items"][:2]] == [str(alta), str(baja)]
|
||||
assert cuerpo["items"][0]["probabilidades"]["lieag"][1] == {"horizonte_anios": 5.0, "probabilidad": 0.30,
|
||||
"ic_bajo": 0.22, "ic_alto": 0.40}
|
||||
assert all(i["probabilidades"] is None for i in cuerpo["items"][2:])
|
||||
assert client.get("/cacu/seguimiento?corte=2025-12-31&orden=lieag&horizonte=3").status_code == 400
|
||||
|
||||
|
||||
def test_un_caso_tiene_su_estatus_y_su_probabilidad_de_supervivencia(client):
|
||||
"""Fija: una paciente con biopsia de carcinoma es CASO, gane lo que gane lo demás, y su probabilidad de supervivencia
|
||||
es 1 − la de morir del modelo de supervivencia, con el IC invertido, y 1 a los 0 años; la lista se ordena por ella.
|
||||
Falla si CASO
|
||||
deja de ganar o si la supervivencia se muestra como la probabilidad de morir."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
from webapi.follow_up.status import ESTATUS
|
||||
|
||||
assert ESTATUS[0] == "CASO"
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
paciente = int(filas[2]["pac_id"])
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_total", version="0.4.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella="seguimiento-caso",
|
||||
marco_sha="m", n_miembros=1, armado_en=datetime(2026, 1, 2, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=paciente, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="biopsiacervical", indice_fuente_id=str(paciente)))
|
||||
session.commit()
|
||||
armado = build.armado_id
|
||||
lote, _ = cacu.cohort_repository.save_batch(
|
||||
armado, {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"muerte", [(paciente, date(2025, 3, 1), 5.0, 0.30, 0.20, 0.45)])
|
||||
cacu.cohort_repository.change_state(lote, "final", "revisado")
|
||||
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&orden=supervivencia&horizonte=5"
|
||||
).get_json()
|
||||
|
||||
primera = cuerpo["items"][0]
|
||||
assert primera["pac_id"] == str(paciente)
|
||||
assert primera["probabilidades"]["supervivencia"] == [
|
||||
{"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0},
|
||||
{"horizonte_anios": 5.0, "probabilidad": 0.7, "ic_bajo": 0.55, "ic_alto": 0.8}]
|
||||
|
||||
|
||||
def test_una_biopsia_de_un_grado_de_caso_hace_caso_a_la_paciente(client, monkeypatch):
|
||||
"""Fija: quien tiene una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` al corte es CASO, gane lo
|
||||
que gane lo demás, y nadie sin una lo es; el filtro `estatus=CASO` las da. La base de demostración no tiene
|
||||
carcinomas, así que la regla se toma aquí como CIN2. Falla si la precedencia deja de poner CASO primero o el
|
||||
estatus deja de leer el grado de la biopsia de su regla."""
|
||||
from sqlalchemy import select
|
||||
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.follow_up import listing
|
||||
from webapi.follow_up.silver import biopsias
|
||||
|
||||
original = listing.valor_de
|
||||
monkeypatch.setattr(listing, "valor_de", lambda sesion, clave, **kw:
|
||||
["CIN2"] if clave == "cacu.seguimiento.caso.grados" else original(sesion, clave, **kw))
|
||||
b = biopsias()
|
||||
with get_cacu_session() as session:
|
||||
con_cin2 = {r.pac_id for r in session.execute(select(b.c.pac_id).where(b.c.grado == "CIN2"))}
|
||||
filas = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200").get_json()["items"]
|
||||
casos = {int(i["pac_id"]) for i in filas if i["estatus"]["codigo"] == "CASO"}
|
||||
|
||||
assert casos and casos == con_cin2 & {int(i["pac_id"]) for i in filas}
|
||||
solo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200&estatus=CASO").get_json()["items"]
|
||||
assert {int(i["pac_id"]) for i in solo} == casos
|
||||
|
||||
|
||||
def test_un_caso_es_un_carcinoma_invasor_o_in_situ():
|
||||
"""Fija: la regla de CASO toma CIS y carcinoma, como el índice del escenario de supervivencia, para que la tabla y
|
||||
la supervivencia hablen de las mismas pacientes. Falla si la regla deja fuera el in situ."""
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import webapi.orchestration.reference as referencia
|
||||
|
||||
parametros = tomllib.loads((Path(referencia.__file__).parent / "parametros.toml").read_text(encoding="utf-8"))
|
||||
assert parametros["cacu"]["seguimiento"]["caso"]["grados"]["valor"] == ["CIS", "CARCINOMA"]
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
+3
-2
@@ -20,6 +20,7 @@ from pathlib import Path
|
||||
|
||||
from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true
|
||||
|
||||
from webapi.fhir_base import STRUCTURE
|
||||
from webapi.metrics import (
|
||||
AGGREGATION_VERSION,
|
||||
EVENT_CUTOFF,
|
||||
@@ -278,9 +279,9 @@ def duration_report(definition: DurationDefinition, question: Question, result:
|
||||
]}
|
||||
if result.median is not None:
|
||||
group["measureScore"] = {"value": result.median, "unit": "d",
|
||||
"extension": [{"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
|
||||
"extension": [{"url": f"{STRUCTURE}/q1",
|
||||
"valueDecimal": result.q1},
|
||||
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
|
||||
{"url": f"{STRUCTURE}/q3",
|
||||
"valueDecimal": result.q3}]}
|
||||
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id},
|
||||
{"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or question.event_cutoff).isoformat()}]
|
||||
|
||||
+10
-2
@@ -24,6 +24,7 @@ from werkzeug.exceptions import HTTPException
|
||||
|
||||
from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data
|
||||
from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url
|
||||
from webapi.fhir.risk import not_scored
|
||||
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
|
||||
@@ -198,8 +199,15 @@ def _risk_routes(blueprint: Blueprint, repositories, project: str) -> None:
|
||||
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 [domain.risk_assessment(pac_id, risk, simulated_data())]
|
||||
# one RiskAssessment per outcome: the current batch of each (a CIN2+ and a cancer model, say), and, for a
|
||||
# patient with some risk, one with no prediction for each current model of another outcome that didn't
|
||||
# score her
|
||||
risks = repositories.cohort_repository.current_risks(pac_id)
|
||||
found = [domain.risk_assessment(pac_id, r, simulated_data()) for r in risks]
|
||||
if risks:
|
||||
scored = {r.desenlace for r in risks}
|
||||
found += [not_scored(domain.risk_assessment(pac_id, b, simulated_data()), b.desenlace)
|
||||
for b in repositories.cohort_repository.current_batches() if b.desenlace not in scored]
|
||||
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
|
||||
|
||||
|
||||
|
||||
+32
-4
@@ -1,12 +1,40 @@
|
||||
"""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."""
|
||||
`webapi.fhir.risk` with CaCu's outcomes.
|
||||
|
||||
The results the risk was computed from, the cytology sampled on its index date, go in the extension
|
||||
`resultados-indice`: one `valueString` per result it has (`escamosas`, `glandulares`, `vph`), as
|
||||
`citologiacervical` holds them. A risk with no cytology sampled that day has no such extension.
|
||||
"""
|
||||
|
||||
from webapi.fhir import risk
|
||||
from webapi.fhir.common import STRUCTURE
|
||||
from webapi.fhir.risk import DAYS_PER_YEAR, INTERVAL, MODEL, OUTCOME # noqa: F401 (kept for readers of this module)
|
||||
|
||||
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"}
|
||||
OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses", "cin2": "CIN2+ por biopsia",
|
||||
"cancer": "Cáncer cervicouterino por biopsia"}
|
||||
INDEX_RESULTS = f"{STRUCTURE}/resultados-indice"
|
||||
RESULT_COLUMNS = {"escamosas": "cit_celulas_escamosas", "glandulares": "cit_celulas_glandulares",
|
||||
"vph": "cit_vph_resultado"}
|
||||
|
||||
|
||||
def index_results(pac_id: int, fecha_indice) -> dict[str, str]:
|
||||
"""The results of the patient's cytology sampled on `fecha_indice` (the one with most of them), by name."""
|
||||
if fecha_indice is None:
|
||||
return {}
|
||||
from persistance import cacu
|
||||
|
||||
found = {}
|
||||
for row in cacu.citologia_cervical_repository.list(pac_id=pac_id, cit_fecha_toma=fecha_indice, limit=10):
|
||||
results = {name: str(v) for name, column in RESULT_COLUMNS.items() if (v := getattr(row, column, None))}
|
||||
if len(results) > len(found):
|
||||
found = results
|
||||
return found
|
||||
|
||||
|
||||
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, "cin2_mas")
|
||||
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`, with the index cytology's results."""
|
||||
resource = risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "cin2_mas")
|
||||
if results := index_results(pac_id, patient_risk.fecha_indice):
|
||||
resource.setdefault("extension", []).append(
|
||||
{"url": INDEX_RESULTS, "extension": [{"url": k, "valueString": v} for k, v in results.items()]})
|
||||
return resource
|
||||
|
||||
@@ -9,12 +9,14 @@ from urllib.parse import urlencode
|
||||
|
||||
from flask import Response, request
|
||||
|
||||
from webapi.fhir_base import BASE as _BASE, STRUCTURE as _STRUCTURE
|
||||
|
||||
FHIR_VERSION = "4.0.1"
|
||||
MEDIA_TYPE = "application/fhir+json"
|
||||
BASE = "https://isssteleon.org/fhir"
|
||||
BASE = _BASE
|
||||
CODE_SYSTEM = f"{BASE}/CodeSystem"
|
||||
VALUE_SET = f"{BASE}/ValueSet"
|
||||
STRUCTURE = f"{BASE}/StructureDefinition"
|
||||
STRUCTURE = _STRUCTURE
|
||||
SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"}
|
||||
MAX_COUNT = 200
|
||||
DEFAULT_COUNT = 50
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -13,17 +13,29 @@
|
||||
model gives one, goes in the extension `intervalo-confianza` (`probability[x]` holds a
|
||||
decimal or a range, not both).
|
||||
|
||||
What the number is, from the model's scenario (`[estimand]` of its `model.toml`), goes in the extension `estimando`:
|
||||
one `valueString` per key (`quantity`, `description`, `outcome`, `index_date`, `horizons_unit`), and its
|
||||
`quantity` as `method.text`. A model whose scenario can't be read has neither.
|
||||
|
||||
A current model of an outcome that didn't score the patient gives a `RiskAssessment` with no `prediction` and the
|
||||
extension `sin-estimacion` (`not_scored`), so her record can tell "no model" from "not estimated for her".
|
||||
|
||||
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 functools import lru_cache
|
||||
|
||||
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"
|
||||
ESTIMAND = f"{STRUCTURE}/estimando"
|
||||
NOT_SCORED = f"{STRUCTURE}/sin-estimacion"
|
||||
NOT_SCORED_TEXT = ("el modelo vigente de este desenlace no estima a la paciente: queda fuera de su población (su "
|
||||
"índice o sus reglas) o su combinación de resultados no estuvo en su entrenamiento")
|
||||
DAYS_PER_YEAR = 365.25
|
||||
|
||||
|
||||
@@ -46,6 +58,18 @@ def _prediction(horizon, outcome: dict, start: date | None) -> dict:
|
||||
return item
|
||||
|
||||
|
||||
@lru_cache(maxsize=32)
|
||||
def estimand(modelo_nombre: str) -> dict[str, str]:
|
||||
"""The `[estimand]` of the registered model's scenario (`<domain>-<scenario>`), empty if it can't be read."""
|
||||
domain, _, scenario = modelo_nombre.partition("-")
|
||||
try:
|
||||
from models.dags.training import Scenario
|
||||
|
||||
return {str(k): str(v) for k, v in Scenario.load(domain, scenario).estimand.items()}
|
||||
except (ImportError, LookupError, OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
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."""
|
||||
@@ -57,4 +81,19 @@ def risk_assessment(pac_id: int, risk, simulated: bool, outcomes: dict[str, str]
|
||||
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
|
||||
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
|
||||
}
|
||||
if not risk.horizontes: # a current model of the outcome that didn't score her (`not_scored`)
|
||||
del resource["prediction"]
|
||||
if found := estimand(risk.modelo_nombre):
|
||||
resource["method"]["text"] = found.get("quantity", "")
|
||||
resource["extension"] = [{"url": ESTIMAND, "extension": [{"url": k, "valueString": v}
|
||||
for k, v in found.items()]}]
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def not_scored(resource: dict, desenlace: str | None) -> dict:
|
||||
"""A `RiskAssessment` of a model that didn't score the patient (a batch with no horizons of hers), marked with
|
||||
the extension `sin-estimacion`: its outcome (`desenlace`, since there is no prediction to carry it) and why it
|
||||
may be so (`motivo`)."""
|
||||
resource.setdefault("extension", []).append({"url": NOT_SCORED, "extension": [
|
||||
{"url": "desenlace", "valueCode": desenlace or ""}, {"url": "motivo", "valueString": NOT_SCORED_TEXT}]})
|
||||
return resource
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"""The base of every FHIR URL this API emits: code systems, value sets and extensions.
|
||||
|
||||
It is a name we mint, not an address that has to resolve. `FHIR_BASE_URL` sets it. The WebApp reads these URLs by
|
||||
exact match (`fhir.ts` CODE_SYSTEM and `paciente-riesgo.validation.ts` INTERVAL), so a change of domain goes to both.
|
||||
|
||||
A module of its own, with no imports from the package, so `metrics` and `durations` can use it without a cycle.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
BASE = os.environ.get("FHIR_BASE_URL", "https://isssteleon.org/fhir").rstrip("/")
|
||||
STRUCTURE = f"{BASE}/StructureDefinition"
|
||||
@@ -27,6 +27,7 @@ etiqueta = "Estatus de seguimiento"
|
||||
expression = "cacu.seguimiento:estrato"
|
||||
unidad = "paciente"
|
||||
valores = [
|
||||
{ valor = "CASO", etiqueta = "Caso (cáncer)" },
|
||||
{ valor = "PRE_COLPOSCOPIA", etiqueta = "Pre colposcopia" },
|
||||
{ valor = "POST_COLPOSCOPIA", etiqueta = "Post colposcopia" },
|
||||
{ valor = "POST_TRATAMIENTO", etiqueta = "Post tratamiento" },
|
||||
@@ -37,6 +38,7 @@ valores = [
|
||||
seguimiento_marco = "cacu.seguimiento.marco"
|
||||
seguimiento_referencia = "cacu.seguimiento.referencia"
|
||||
seguimiento_precedencia = "cacu.seguimiento.precedencia"
|
||||
seguimiento_grados_caso = "cacu.seguimiento.caso.grados"
|
||||
seguimiento_evidencias = "cacu.seguimiento.colposcopia.evidencias"
|
||||
seguimiento_requisito = "cacu.seguimiento.colposcopia.requisito"
|
||||
seguimiento_biopsia_requisito = "cacu.seguimiento.colposcopia.biopsia_requisito"
|
||||
|
||||
@@ -5,7 +5,9 @@ vuelo sobre la plata, no un `measure_report`: no guarda nada. Entra cada pacient
|
||||
estudio (`cacu.seguimiento.estudios`) en la ventana de `meses` hasta el corte; por cada una, su
|
||||
grupo de edad al corte, su estatus al corte (`cacu.seguimiento.estatus_al`, la misma regla del
|
||||
estrato), su citología y su VPH de la ventana y los días de la toma a su valoración (con las reglas
|
||||
de CACU_DIAS_TOMA_DIAGNOSTICO). `prioridad` está reservada y va nula.
|
||||
de CACU_DIAS_TOMA_DIAGNOSTICO), su última biopsia reportada al corte y su probabilidad vigente de LIEAG+ y de
|
||||
cáncer en cada horizonte (los lotes confirmados que muestra su ficha). `orden` la ordena por la más reciente o por
|
||||
una de esas probabilidades a `horizonte`. `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
|
||||
@@ -26,7 +28,7 @@ from types import SimpleNamespace
|
||||
from sqlalchemy import func, select
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.follow_up.silver import citologias, notas
|
||||
from webapi.follow_up.silver import biopsias, citologias, notas
|
||||
from webapi.follow_up.status import ESTATUS, estatus_al, exigir_opcion, exigir_opciones, reglas_de
|
||||
from webapi.orchestration.tables.cacu import TABLAS
|
||||
from webapi.follow_up.view import P
|
||||
@@ -73,6 +75,12 @@ PARAMETROS_DE_LA_LISTA = {
|
||||
"horizonte_dias": "cacu.horizontes.toma_diagnostico_dias",
|
||||
}
|
||||
ESTRATO = "estatus_seguimiento"
|
||||
# How the list can be ordered: by its most recent study (the default), or by the probability, at `horizonte`, of
|
||||
# LIEAG+ (CIN2+, the models whose outcome starts with `cin2`), of cancer or of surviving (a case's), highest first.
|
||||
ORDENES = ("reciente", "lieag", "cancer", "supervivencia")
|
||||
HORIZONTE_POR_OMISION = 5.0
|
||||
# The outcomes other than CIN2+ the list shows, by their key in `probabilidades`.
|
||||
DESENLACES = {"cancer": "cancer", "muerte": "supervivencia"}
|
||||
|
||||
|
||||
class PedidoInvalido(ValueError):
|
||||
@@ -89,6 +97,8 @@ def seguimiento_de(
|
||||
corte: date | None = None,
|
||||
meses: int | None = None,
|
||||
estatus: str | None = None,
|
||||
orden: str = "reciente",
|
||||
horizonte: float | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
hoy: date | None = None,
|
||||
@@ -113,6 +123,8 @@ def seguimiento_de(
|
||||
raise PedidoInvalido(f"meses = {meses!r}: se admite {list(VENTANAS)}.")
|
||||
if estatus is not None and estatus not in ESTATUS:
|
||||
raise PedidoInvalido(f"estatus desconocido {estatus!r}; hay {list(ESTATUS)}.")
|
||||
if orden not in ORDENES:
|
||||
raise PedidoInvalido(f"orden desconocido {orden!r}; hay {list(ORDENES)}.")
|
||||
if page < 1 or not 1 <= page_size <= PAGINA_MAXIMA:
|
||||
raise PedidoInvalido(f"page empieza en 1 y page_size va de 1 a {PAGINA_MAXIMA}.")
|
||||
|
||||
@@ -122,6 +134,13 @@ def seguimiento_de(
|
||||
items = _items(sesion, corte, desde, lista, estatus_de, tablas)
|
||||
if estatus is not None:
|
||||
items = [i for i in items if i["estatus"]["codigo"] == estatus]
|
||||
horizontes = sorted({h["horizonte_anios"] for i in items for p in (i["probabilidades"] or {}).values() for h in p})
|
||||
horizonte = HORIZONTE_POR_OMISION if horizonte is None else float(horizonte)
|
||||
if horizontes and horizonte not in horizontes:
|
||||
raise PedidoInvalido(f"horizonte = {horizonte:g}: los modelos dan {[f'{h:g}' for h in horizontes]} años.")
|
||||
if orden != "reciente":
|
||||
# highest first, patients the model doesn't score last; the sort is stable, so ties stay most recent first
|
||||
items.sort(key=lambda i: (p := _probabilidad(i, orden, horizonte)) is None or -p)
|
||||
|
||||
total = len(items)
|
||||
paginas = -(-total // page_size)
|
||||
@@ -132,7 +151,8 @@ def seguimiento_de(
|
||||
"simulado": True,
|
||||
"corte": corte.isoformat(),
|
||||
"ventana": {"meses": meses, "desde": desde.isoformat(), "hasta": corte.isoformat()},
|
||||
"filtros": {"estatus": estatus},
|
||||
"filtros": {"estatus": estatus, "orden": orden, "horizonte": horizonte},
|
||||
"horizontes_disponibles": horizontes,
|
||||
"estatus_disponibles": [{"codigo": c, "etiqueta": e} for c, e in etiquetas.items()],
|
||||
"reglas": _reglas_usadas(sesion, [*PARAMETROS_DE_LA_LISTA.values(), *del_estatus.values()], tablas),
|
||||
"paginacion": {"page": page, "page_size": page_size, "total_items": total, "total_pages": paginas},
|
||||
@@ -176,6 +196,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
||||
if "vph" in lista["estudios"] and e["vph"] is not None:
|
||||
de_la_paciente["vph"].append(e)
|
||||
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
|
||||
biopsia_de = _ultima_biopsia(sesion, corte, tablas)
|
||||
riesgos = _probabilidades_por_paciente()
|
||||
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
|
||||
notas_de = _notas_por_paciente(sesion, corte)
|
||||
items = []
|
||||
@@ -199,6 +221,8 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
||||
"genotipo_16_18": None if vph["genotipo_16_18"] is None else bool(vph["genotipo_16_18"]),
|
||||
},
|
||||
"dias_toma_diagnostico": None if cito is None else _dias_a_la_valoracion(cito, notas_de, lista),
|
||||
"ultima_biopsia": biopsia_de.get(pac_id),
|
||||
"probabilidades": {k: v[pac_id] for k, v in riesgos.items() if pac_id in v} or None,
|
||||
"prioridad": None,
|
||||
"_orden": mas_reciente,
|
||||
})
|
||||
@@ -207,6 +231,54 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
|
||||
return items
|
||||
|
||||
|
||||
def _ultima_biopsia(sesion: Session, corte: date, tablas: TablasKit) -> dict[int, dict]:
|
||||
"""Each patient's latest biopsy reported by the cut-off: its report date and grade (`GradoCIN`)."""
|
||||
b = biopsias(tablas)
|
||||
filas = sesion.execute(select(b.c.pac_id, b.c.fecha_reporte, b.c.grado).where(b.c.fecha_reporte.is_not(None))).all()
|
||||
found: dict[int, dict] = {}
|
||||
for pac_id, fecha, grado in filas:
|
||||
fecha = _fecha(fecha)
|
||||
if fecha <= corte and (pac_id not in found or fecha > date.fromisoformat(found[pac_id]["fecha"])):
|
||||
found[pac_id] = {"fecha": fecha.isoformat(), "grado": grado}
|
||||
return found
|
||||
|
||||
|
||||
def _probabilidades_por_paciente() -> dict[str, dict[int, list[dict]]]:
|
||||
"""Each patient's current probability of LIEAG+ (`lieag`, the outcomes `cin2*`), of cancer (`cancer`) and of
|
||||
surviving (`supervivencia`, the complement of the survival model's death) at every horizon, with its interval: the
|
||||
confirmed batches the patient's record shows (`current_risks_by_patient`)."""
|
||||
from persistance import cacu
|
||||
|
||||
found: dict[str, dict[int, list[dict]]] = {}
|
||||
for desenlace, por_paciente in cacu.cohort_repository.current_risks_by_patient().items():
|
||||
clave = "lieag" if (desenlace or "").startswith("cin2") else DESENLACES.get(desenlace)
|
||||
if clave is None:
|
||||
continue
|
||||
destino = found.setdefault(clave, {})
|
||||
for pac_id, horizontes in por_paciente.items():
|
||||
filas = [_horizonte(h, complemento=clave == "supervivencia") for h in horizontes]
|
||||
if clave == "supervivencia" and filas and not any(f["horizonte_anios"] == 0 for f in filas):
|
||||
# at the index date every patient is alive
|
||||
filas.insert(0, {"horizonte_anios": 0.0, "probabilidad": 1.0, "ic_bajo": 1.0, "ic_alto": 1.0})
|
||||
destino.setdefault(pac_id, filas)
|
||||
return found
|
||||
|
||||
|
||||
def _horizonte(h, *, complemento: bool) -> dict:
|
||||
"""A horizon's probability and interval; with `complemento`, of not having the outcome (surviving a death)."""
|
||||
if not complemento:
|
||||
return {"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo,
|
||||
"ic_alto": h.ic_alto}
|
||||
return {"horizonte_anios": h.horizonte_anios, "probabilidad": 1 - h.probabilidad,
|
||||
"ic_bajo": None if h.ic_alto is None else 1 - h.ic_alto,
|
||||
"ic_alto": None if h.ic_bajo is None else 1 - h.ic_bajo}
|
||||
|
||||
|
||||
def _probabilidad(item: dict, clave: str, horizonte: float) -> float | None:
|
||||
return next((h["probabilidad"] for h in ((item["probabilidades"] or {}).get(clave) or [])
|
||||
if h["horizonte_anios"] == horizonte), None)
|
||||
|
||||
|
||||
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
|
||||
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
|
||||
c = citologias()
|
||||
|
||||
@@ -66,4 +66,11 @@ def _requested(args) -> dict:
|
||||
pedido[nombre] = int(texto)
|
||||
if estatus := args.get("estatus"):
|
||||
pedido["estatus"] = estatus
|
||||
if orden := args.get("orden"):
|
||||
pedido["orden"] = orden
|
||||
if (horizonte := args.get("horizonte")) not in (None, ""):
|
||||
try:
|
||||
pedido["horizonte"] = float(horizonte)
|
||||
except ValueError:
|
||||
raise ValueError(f"horizonte debe ser un número de años; llegó {horizonte!r}") from None
|
||||
return pedido
|
||||
|
||||
@@ -6,6 +6,8 @@ reporte), la lista de seguimiento (T-24d, al corte que pida el dashboard) y las
|
||||
fecha índice). Mira solo lo ocurrido antes de la referencia, así que el estatus de un periodo
|
||||
pasado no cambia cuando la paciente avanza.
|
||||
|
||||
CASO una biopsia reportada con un grado de `cacu.seguimiento.caso.grados` (CIS o carcinoma): la
|
||||
paciente ya tiene cáncer, y lo que se sigue es su supervivencia
|
||||
POST_TRATAMIENTO una nota con un CIE-10 de tratamiento, posterior a su primera colposcopia
|
||||
POST_COLPOSCOPIA alguna evidencia de colposcopia (`EVIDENCIAS`); una nota de colposcopia cuenta si
|
||||
es de «Clínica de la Mujer y Colposcopia» y, por regla, posterior a una cita de
|
||||
@@ -38,7 +40,7 @@ from webapi.follow_up.functions import dias_entre
|
||||
from webapi.follow_up.view import P, vista
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
ESTATUS = ("POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
|
||||
ESTATUS = ("CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA")
|
||||
RESTO = "INFO_INSUFICIENTE" # quien no cumple ninguno: el estrato es exhaustivo (§5.3)
|
||||
MARCOS = ("estatus", "ronda")
|
||||
REFERENCIAS = {"inicio_periodo": "periodo_inicio", "fecha_corte": "fecha_corte"} # opción -> parámetro del reporte
|
||||
@@ -81,7 +83,7 @@ def reglas_de(valores: Mapping) -> Reglas:
|
||||
precedencia = tuple(valores["seguimiento_precedencia"])
|
||||
if sorted(precedencia) != sorted(ESTATUS):
|
||||
raise ReglaDesconocida(
|
||||
f"cacu.seguimiento.precedencia debe ordenar los cuatro estatus, sin repetir: {ESTATUS}; "
|
||||
f"cacu.seguimiento.precedencia debe ordenar los {len(ESTATUS)} estatus, sin repetir: {ESTATUS}; "
|
||||
f"llegó {precedencia}."
|
||||
)
|
||||
exigir_opciones("cacu.seguimiento.colposcopia.evidencias", valores["seguimiento_evidencias"], EVIDENCIAS)
|
||||
@@ -186,6 +188,13 @@ def estatus_al(
|
||||
.group_by(evidencias.c.pac_id)
|
||||
.cte("seguimiento_colposcopia")
|
||||
)
|
||||
# Un caso: una biopsia reportada antes de la referencia con un grado de cáncer.
|
||||
caso = (
|
||||
select(reporte.c.pac_id)
|
||||
.distinct()
|
||||
.where(antes(reporte.c.fecha_reporte), reporte.c.grado.in_(P("seguimiento_grados_caso", lista=True)))
|
||||
.cte("seguimiento_caso")
|
||||
)
|
||||
tratamiento = (
|
||||
select(nota.c.pac_id)
|
||||
.distinct()
|
||||
@@ -210,6 +219,7 @@ def estatus_al(
|
||||
)
|
||||
persona = V_PERSONA
|
||||
cumple = {
|
||||
"CASO": caso.c.pac_id.is_not(None),
|
||||
"POST_TRATAMIENTO": tratamiento.c.pac_id.is_not(None),
|
||||
"POST_COLPOSCOPIA": colposcopia.c.pac_id.is_not(None),
|
||||
"INFO_INSUFICIENTE": _insuficiente(reglas.insuficiente),
|
||||
@@ -219,7 +229,8 @@ def estatus_al(
|
||||
return (
|
||||
select(persona.c.pac_id, estatus.label("estatus"))
|
||||
.select_from(
|
||||
persona.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
|
||||
persona.outerjoin(caso, caso.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(tratamiento, tratamiento.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(colposcopia, colposcopia.c.pac_id == persona.c.pac_id)
|
||||
.outerjoin(fuera_de_vigilancia, fuera_de_vigilancia.c.pac_id == persona.c.pac_id)
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
+19
-5
@@ -41,6 +41,9 @@ from sqlalchemy import (
|
||||
true,
|
||||
)
|
||||
|
||||
from webapi.cama_analysis.stats import wilson
|
||||
from webapi.fhir_base import STRUCTURE
|
||||
|
||||
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
|
||||
TOTAL = "total"
|
||||
NO_DATA = "sin_dato"
|
||||
@@ -545,6 +548,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:
|
||||
@@ -654,9 +666,11 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by
|
||||
# --- the contract --------------------------------------------------------------------------------------------------
|
||||
|
||||
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"
|
||||
EVENT_CUTOFF = f"{STRUCTURE}/corte-evento"
|
||||
KNOWLEDGE_CUTOFF = f"{STRUCTURE}/corte-conocimiento"
|
||||
HISTORY_ENTRY = f"{STRUCTURE}/reporte-id"
|
||||
INTERVAL_LOW = f"{STRUCTURE}/ic-bajo"
|
||||
INTERVAL_HIGH = f"{STRUCTURE}/ic-alto"
|
||||
|
||||
|
||||
def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
|
||||
@@ -667,8 +681,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
|
||||
|
||||
|
||||
|
||||
@@ -203,20 +203,20 @@ def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, list[tuple[int, bool]]]:
|
||||
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
|
||||
|
||||
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da al estimador
|
||||
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
|
||||
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
|
||||
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
|
||||
Lee el marco ancho del armado (`read_frame`) en una sesión de lectura, se lo da a cada estimador de la cohorte
|
||||
(`ctx.estimators[url]`, una lista: `estimar(columnas, filas)`, `procedencia()` y `desenlace`) y escribe los
|
||||
riesgos de cada uno como un lote `preliminary` (`CohortRepository.save_batch`). Estimar lo mismo otra vez no
|
||||
duplica. Devuelve, por cohorte, un (`lote_id`, si es nuevo) por estimador, en su orden. Confirmar o anular un lote es la orden
|
||||
`confirm-risks`, no este paso.
|
||||
"""
|
||||
tablas_cohorte = import_module(f"webapi.orchestration.tables.{ctx.project}").COHORTES
|
||||
lotes = {}
|
||||
for url in cohort_urls(ctx.project, _manifest(ctx)):
|
||||
estimador = ctx.estimators.get(url)
|
||||
if estimador is None:
|
||||
estimadores = ctx.estimators.get(url) or []
|
||||
if not estimadores:
|
||||
continue
|
||||
|
||||
def frame(sesion, url=url):
|
||||
@@ -226,8 +226,9 @@ def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tu
|
||||
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[url] = ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
lotes[url] = []
|
||||
for estimador in estimadores:
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[url].append(ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos))
|
||||
return lotes
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
|
||||
its domain has in production.
|
||||
"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with every model version
|
||||
of its domain in production, one batch per model.
|
||||
|
||||
`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
|
||||
@@ -11,7 +11,6 @@ unused by design.
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -38,12 +37,7 @@ class ScenarioEstimator:
|
||||
self._provenance: Provenance | None = None
|
||||
|
||||
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
|
||||
import json
|
||||
|
||||
import mlflow.pyfunc
|
||||
import numpy as np
|
||||
|
||||
from models.dags.estimation import estimate_frame
|
||||
from models.dags.estimation import scored_frame
|
||||
from models.dags.training import Scenario
|
||||
from models.io.registry import registered_name, registry
|
||||
from models.io.storage import KitBuild
|
||||
@@ -54,13 +48,11 @@ class ScenarioEstimator:
|
||||
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, 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(estimate_frame(frame, probabilities, horizons))]
|
||||
return [tuple(row) for row in risk_rows(scored_frame(resolved, frame))]
|
||||
|
||||
def procedencia(self) -> Provenance:
|
||||
if self._provenance is None:
|
||||
@@ -68,45 +60,19 @@ class ScenarioEstimator:
|
||||
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]:
|
||||
def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
|
||||
"""The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the
|
||||
registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario
|
||||
definition in `models` is skipped. Empty where none is in production, the same as no estimator being
|
||||
configured: `estimate` then does nothing."""
|
||||
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)
|
||||
found: dict[str, list[ScenarioEstimator]] = {}
|
||||
for name in registry.in_production(domain):
|
||||
try:
|
||||
registry.resolve(domain, name)
|
||||
scenario = Scenario.load(domain, name)
|
||||
except LookupError:
|
||||
continue
|
||||
found[scenario.cohort] = ScenarioEstimator(domain, name)
|
||||
found.setdefault(scenario.cohort, []).append(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 _scenario_estimators(domain)
|
||||
from models.dags.training import Scenario
|
||||
from models.io.registry import registry
|
||||
|
||||
scenario = Scenario.load(domain, "cin2_logistic")
|
||||
try:
|
||||
registry.resolve(domain, scenario.scenario)
|
||||
except LookupError:
|
||||
return {}
|
||||
return {scenario.cohort: Cin2LogisticEstimator(domain)}
|
||||
|
||||
@@ -203,13 +203,20 @@ estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme. Usuario, 2026-10-22: inicio del periodo"
|
||||
|
||||
[cacu.seguimiento.precedencia]
|
||||
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de
|
||||
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cuatro, sin repetir).
|
||||
# Qué estatus gana si aplican varios, del que más gana al que menos. Opciones: cualquier orden de "CASO",
|
||||
# "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE" y "PRE_COLPOSCOPIA" (los cinco, sin repetir).
|
||||
# Quien no cumple ninguno cae en "INFO_INSUFICIENTE" (el estrato es exhaustivo).
|
||||
valor = ["POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
|
||||
valor = ["CASO", "POST_TRATAMIENTO", "POST_COLPOSCOPIA", "INFO_INSUFICIENTE", "PRE_COLPOSCOPIA"]
|
||||
estado = "provisional"
|
||||
fuente = "Plan de seguimiento (ISSSTELEON-arquitectura/plan_seguimiento_ficha_filtros.md, §2bis), 2026-10-22; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.caso.grados]
|
||||
# Qué grados de biopsia hacen de la paciente un caso (ya tiene cáncer, invasor o in situ): su estatus es CASO, gane lo
|
||||
# que gane lo demás, y lo que se le sigue es la supervivencia. Opciones: grados de `GradoCIN`.
|
||||
valor = ["CIS", "CARCINOMA"]
|
||||
estado = "provisional"
|
||||
fuente = "Responsable del proyecto, 2026-11-22: un escenario para las pacientes que ya tienen cáncer, sobre el que se evalúa la supervivencia; falta que clínica la confirme"
|
||||
|
||||
[cacu.seguimiento.colposcopia.evidencias]
|
||||
# Qué cuenta como colposcopia antes de la referencia. Opciones (cualquier subconjunto):
|
||||
# "motivo" una nota de colposcopia cuyo motivo de consulta contiene uno de `colposcopia.motivos`
|
||||
|
||||
@@ -6,6 +6,7 @@ to be defined.
|
||||
"""
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from persistance.edges.gold import ERROR, FINAL
|
||||
|
||||
|
||||
@@ -34,7 +35,10 @@ def risk_batches_blueprint(repositories, name: str = "risk_batches") -> Blueprin
|
||||
reason = (request.get_json(silent=True) or {}).get("reason", "").strip()
|
||||
if not reason:
|
||||
return jsonify({"error": "se requiere un motivo"}), 400
|
||||
changed = repositories.cohort_repository.change_state(lote_id, estado, reason)
|
||||
try:
|
||||
changed = repositories.cohort_repository.change_state(lote_id, estado, reason)
|
||||
except IntegrityError: # another request decided the same batch at the same moment
|
||||
return jsonify({"error": f"el lote {lote_id} ya se está decidiendo en otra solicitud"}), 409
|
||||
if not changed:
|
||||
return jsonify({"error": f"el lote {lote_id} no existe o ya no tiene evaluaciones vigentes"}), 404
|
||||
return jsonify({"lote_id": lote_id, "evaluaciones_cambiadas": changed})
|
||||
|
||||
Reference in New Issue
Block a user