e2ecaa027c
webapi/fhir/risk.py builds a patient's RiskAssessment for CaCu and CaMa; GET /cama/modelo/curvas serves the production version's survival curves; the cycle's estimator is generic by scenario; silver persona carries the date of death for CaMa; the import schema accepts it; the CaMa risk batches can be confirmed and voided.
61 lines
3.3 KiB
Python
61 lines
3.3 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).
|
|
|
|
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 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"
|
|
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
|
|
|
|
|
|
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],
|
|
}
|
|
return tagged(resource, simulated)
|