diff --git a/tests/test_fhir_risk_estimand.py b/tests/test_fhir_risk_estimand.py new file mode 100644 index 0000000..d7737b1 --- /dev/null +++ b/tests/test_fhir_risk_estimand.py @@ -0,0 +1,35 @@ +"""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", [])) diff --git a/webapi/fhir/risk.py b/webapi/fhir/risk.py index 84bf7b6..2f20e02 100644 --- a/webapi/fhir/risk.py +++ b/webapi/fhir/risk.py @@ -13,17 +13,23 @@ 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`, `interval`), and its +`quantity` as `method.text`. A model whose scenario can't be read has neither. + 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" DAYS_PER_YEAR = 365.25 @@ -46,6 +52,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 (`-`), 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 +75,8 @@ 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 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)