CaCu: windows to diagnosis and treatment, FHIR base URL, the patient's risks per outcome #17
+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/
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -89,7 +89,7 @@ def test_the_list_names_what_is_answered_on_request(client):
|
||||
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"]
|
||||
@@ -97,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(
|
||||
|
||||
@@ -354,7 +354,14 @@ 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
|
||||
@@ -526,14 +533,15 @@ DIAS_TOMA_TRATAMIENTO = "cacu/CACU_DIAS_TOMA_TRATAMIENTO"
|
||||
DIAS_DIAGNOSTICO_TRATAMIENTO = "cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, expected", [(DIAS_TOMA_TRATAMIENTO, (4, 1, 58.0, 3)), (DIAS_DIAGNOSTICO_TRATAMIENTO, (1, 1, 18.0, 0))])
|
||||
@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, with a 60-day horizon. From the sample: H-004's July sample reaches her treatment of August 28 in
|
||||
58 days; the other three samples of the semester have no treatment and their horizon has passed, so they are in
|
||||
the initial population and not measured. From the diagnosis: only that sample has one in the period, and its
|
||||
diagnosis of August 10 reaches the treatment in 18 days. Fails if the end event, the start (sample or diagnosis),
|
||||
the horizon rule or the split between not measured yet and without event changes."""
|
||||
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]
|
||||
|
||||
@@ -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
|
||||
|
||||
+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
|
||||
|
||||
@@ -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"
|
||||
+6
-5
@@ -42,6 +42,7 @@ from sqlalchemy import (
|
||||
)
|
||||
|
||||
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"
|
||||
@@ -665,11 +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"
|
||||
INTERVAL_LOW = "https://isssteleon.org/fhir/StructureDefinition/ic-bajo"
|
||||
INTERVAL_HIGH = "https://isssteleon.org/fhir/StructureDefinition/ic-alto"
|
||||
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]:
|
||||
|
||||
@@ -38,12 +38,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 +49,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:
|
||||
|
||||
@@ -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