FHIR: one RiskAssessment per outcome, and one with no prediction for a model that didn't score her
The patient's Bundle holds the current batch of each outcome (`CohortRepository.current_risks`), so a CIN2+ and a cancer model are both shown. For a patient with some risk, each current model of another outcome that didn't score her (`current_batches`) gives a RiskAssessment with no prediction and the extension `sin-estimacion` (its outcome and why it may be so), so the record can tell "no model" from "not estimated for her".
This commit is contained in:
@@ -107,3 +107,55 @@ def test_the_capability_statement_declares_the_search(client):
|
|||||||
|
|
||||||
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
|
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
|
||||||
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
|
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
|
||||||
|
|||||||
+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.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.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.fhir.terminology import code_systems, metric_value_set
|
||||||
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
|
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
|
||||||
from webapi.metrics import Question, UndecidedRule
|
from webapi.metrics import Question, UndecidedRule
|
||||||
@@ -198,8 +199,15 @@ def _risk_routes(blueprint: Blueprint, repositories, project: str) -> None:
|
|||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
return outcome(400, "invalid", str(error))
|
return outcome(400, "invalid", str(error))
|
||||||
pac_id = int(reference)
|
pac_id = int(reference)
|
||||||
risk = repositories.cohort_repository.current_risk(pac_id)
|
# one RiskAssessment per outcome: the current batch of each (a CIN2+ and a cancer model, say), and, for a
|
||||||
found = [] if risk is None else [domain.risk_assessment(pac_id, risk, simulated_data())]
|
# 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))
|
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+18
-1
@@ -14,9 +14,12 @@
|
|||||||
decimal or a range, not both).
|
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`:
|
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
|
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.
|
`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
|
Not yet: `basis` (the observations the model used) and `mitigation`. Each domain gives its outcomes' codes and labels
|
||||||
(`webapi.fhir.cacu`, `webapi.fhir.cama`).
|
(`webapi.fhir.cacu`, `webapi.fhir.cama`).
|
||||||
"""
|
"""
|
||||||
@@ -30,6 +33,9 @@ OUTCOME = f"{CODE_SYSTEM}/desenlace"
|
|||||||
MODEL = f"{CODE_SYSTEM}/modelo"
|
MODEL = f"{CODE_SYSTEM}/modelo"
|
||||||
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
|
INTERVAL = f"{STRUCTURE}/intervalo-confianza"
|
||||||
ESTIMAND = f"{STRUCTURE}/estimando"
|
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
|
DAYS_PER_YEAR = 365.25
|
||||||
|
|
||||||
|
|
||||||
@@ -75,8 +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)}]},
|
"method": {"coding": [{**coding(MODEL, risk.modelo_nombre), "version": str(risk.modelo_version)}]},
|
||||||
"prediction": [_prediction(h, outcome, risk.fecha_indice) for h in risk.horizontes],
|
"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):
|
if found := estimand(risk.modelo_nombre):
|
||||||
resource["method"]["text"] = found.get("quantity", "")
|
resource["method"]["text"] = found.get("quantity", "")
|
||||||
resource["extension"] = [{"url": ESTIMAND, "extension": [{"url": k, "valueString": v}
|
resource["extension"] = [{"url": ESTIMAND, "extension": [{"url": k, "valueString": v}
|
||||||
for k, v in found.items()]}]
|
for k, v in found.items()]}]
|
||||||
return tagged(resource, simulated)
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user