"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data). The risk is the patient's current batch (`CohortRepository.current_risk`): the newest batch with a confirmed evaluation, the same the patient record shows. One `RiskAssessment` per batch and patient: id `-` status the batch's state (`final`) subject `Patient/`: CaCu's follow-up list uses the platform's `pac_id` (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` (CaCu doesn't publish its cytology and HPV `Observation`s) and `mitigation` (ASCCP's clinical action thresholds are for CIN3+; the outcome here is CIN2+). """ 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" OUTCOMES = {"cin2_mas": "CIN2+ por biopsia", "cin2_12m": "CIN2+ por biopsia en 12 meses"} 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) -> dict: """The patient's current risk (`PatientRisk`) as a `RiskAssessment`.""" desenlace = risk.desenlace or "cin2_mas" 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)