f002e24811
The registered model's scenario (`[estimand]` of its `model.toml`) goes in the extension `estimando`, one `valueString` per key, and its quantity as `method.text`. A model whose scenario can't be read has neither.
83 lines
4.4 KiB
Python
83 lines
4.4 KiB
Python
"""A patient's individual risk in FHIR R4: one `RiskAssessment` per batch and patient, built from `PatientRisk`
|
|
(`CohortRepository.current_risk`: the newest batch with a confirmed evaluation).
|
|
|
|
id `<lote_id>-<pac_id>`
|
|
status the batch's state (`final`)
|
|
subject `Patient/<pac_id>`: the platform's key (TEA keeps a pseudonym until its patients get
|
|
their own identity)
|
|
occurrenceDateTime when the batch was evaluated
|
|
method the registered model and its version (MLflow)
|
|
prediction[] one per horizon: `outcome` (the batch's outcome), `probabilityDecimal`, and `whenPeriod`
|
|
from the risk's index date (the model's decision point) to that date plus the horizon;
|
|
the immediate risk (horizon 0) is a period of one day. A confidence interval, when the
|
|
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
|
|
|
|
|
|
def _utc(moment: datetime) -> str:
|
|
moment = moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
|
|
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def _until(start: date, years: float) -> date:
|
|
return start + timedelta(days=round(years * DAYS_PER_YEAR))
|
|
|
|
|
|
def _prediction(horizon, outcome: dict, start: date | None) -> dict:
|
|
item = {"outcome": outcome, "probabilityDecimal": horizon.probabilidad}
|
|
if start is not None:
|
|
item["whenPeriod"] = {"start": start.isoformat(), "end": _until(start, horizon.horizonte_anios).isoformat()}
|
|
if horizon.ic_bajo is not None and horizon.ic_alto is not None:
|
|
item["extension"] = [{"url": INTERVAL, "valueRange": {"low": {"value": horizon.ic_bajo},
|
|
"high": {"value": horizon.ic_alto}}}]
|
|
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."""
|
|
desenlace = risk.desenlace or default_outcome
|
|
outcome = concept(OUTCOME, desenlace, outcomes.get(desenlace))
|
|
resource = {
|
|
"resourceType": "RiskAssessment", "id": f"{risk.lote_id}-{pac_id}", "status": risk.estado_lote,
|
|
"subject": {"reference": f"Patient/{pac_id}"}, "occurrenceDateTime": _utc(risk.evaluado_en),
|
|
"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)
|