"""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 `-` status the batch's state (`final`) subject `Patient/`: 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`), 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 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 (`-`), 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 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