CaMa: individual risk and population curves served, and the cycle estimates with any scenario in production

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.
This commit is contained in:
rockdrigo
2026-11-21 02:07:34 -06:00
parent 26f2b35338
commit e2ecaa027c
17 changed files with 446 additions and 85 deletions
+4
View File
@@ -95,13 +95,17 @@ def create_app() -> Flask:
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
from persistance import cacu as cacu_repositories
from persistance import cama as cama_repositories
from persistance.db import get_cacu_session, get_cama_session
from webapi.model_analysis import model_analysis_blueprint
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
app.register_blueprint(risk_batches_blueprint(cama_repositories, "risk_batches_cama"), url_prefix="/cama")
app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama")
return app
+10 -7
View File
@@ -9,7 +9,7 @@ individual risk.
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's individual risk, the current batch (DEV only)
GET RiskAssessment?subject=Patient/<pac_id> CaCu's and CaMa's individual risk, the current batch (DEV only)
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
@@ -28,6 +28,7 @@ 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.metrics import Question, UndecidedRule
RISK_DOMAINS = ("cacu", "cama") # the domains whose patients' individual risk is served as a RiskAssessment
TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion")
@@ -38,7 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
blueprint = Blueprint(f"{project}_fhir", __name__)
titles = labels(manifest)
patients = with_patients and project == "tea"
risks = with_patients and project == "cacu"
risks = with_patients and project in RISK_DOMAINS
def definitions() -> dict:
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
@@ -176,13 +177,15 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
if patients:
_patient_routes(blueprint, repositories, now)
if risks:
_risk_routes(blueprint, repositories)
_risk_routes(blueprint, repositories, project)
return blueprint
def _risk_routes(blueprint: Blueprint, repositories) -> None:
"""CaCu's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from webapi.fhir import cacu
def _risk_routes(blueprint: Blueprint, repositories, project: str) -> None:
"""A patient's individual risk: `RiskAssessment` searched by `subject` (DEV only, simulated data)."""
from importlib import import_module
domain = import_module(f"webapi.fhir.{project}")
@blueprint.get("/RiskAssessment")
def risk_assessments():
@@ -196,7 +199,7 @@ def _risk_routes(blueprint: Blueprint, repositories) -> None:
return outcome(400, "invalid", str(error))
pac_id = int(reference)
risk = repositories.cohort_repository.current_risk(pac_id)
found = [] if risk is None else [cacu.risk_assessment(pac_id, risk, simulated_data())]
found = [] if risk is None else [domain.risk_assessment(pac_id, risk, simulated_data())]
return fhir(searchset([entry(r) for r in found[offset:offset + count]], len(found), count, offset))
+6 -56
View File
@@ -1,62 +1,12 @@
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data).
"""CaCu's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by
`webapi.fhir.risk` with CaCu's outcomes."""
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:
from webapi.fhir import risk
from webapi.fhir.risk import DAYS_PER_YEAR, INTERVAL, MODEL, OUTCOME # noqa: F401 (kept for readers of this module)
id `<lote_id>-<pac_id>`
status the batch's state (`final`)
subject `Patient/<pac_id>`: 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:
def risk_assessment(pac_id: int, patient_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)
return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "cin2_mas")
+11
View File
@@ -0,0 +1,11 @@
"""CaMa's patients in FHIR R4: a patient's individual risk as a `RiskAssessment` (DEV only, simulated data), built by
`webapi.fhir.risk` with CaMa's outcomes: the mortality at each horizon from the model's index date."""
from webapi.fhir import risk
OUTCOMES = {"muerte": "Muerte por cualquier causa"}
def risk_assessment(pac_id: int, patient_risk, simulated: bool) -> dict:
"""The patient's current risk (`PatientRisk`) as a `RiskAssessment`."""
return risk.risk_assessment(pac_id, patient_risk, simulated, OUTCOMES, "muerte")
+60
View File
@@ -0,0 +1,60 @@
"""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)
+3
View File
@@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import (
Catalog,
CatalogValue,
FlexDate,
PostalCode,
RequiredDate,
RequiredHospitalId,
@@ -25,6 +26,8 @@ class PacienteImportSchema(ImportSchema):
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
# IND-01: required, since age at each event of interest is derived from it.
pac_fecha_nacimiento: RequiredDate
# Survival's outcome; empty while she is alive or the date is unknown.
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
+35
View File
@@ -0,0 +1,35 @@
"""What a model's production version found about its cohort: `GET /<domain>/modelo/curvas`.
The population results a training run publishes (`analisis/curvas.json`, `models.cama.survival.population`): the cohort's
survival curves and the model's survival at each horizon with its intervals, for the dashboard to draw. They describe the
cohort, not any patient. The answer names the version they come from, and carries `simulado: true` in DEV, where the
data are simulated. 404 while the scenario has no version in production, or its version has no such record.
"""
import json
from flask import Blueprint, jsonify
from webapi.fhir.common import simulated_data
def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
"""The blueprint of one scenario, to register with `url_prefix="/<domain>"`."""
blueprint = Blueprint(f"model_analysis_{domain}_{scenario}", __name__)
@blueprint.get("/modelo/curvas")
def curves():
"""The curves and points of the scenario's production version."""
from models.io.registry import registry
try:
resolved = registry.resolve(domain, scenario)
_, content = registry.artifact(domain, scenario, resolved.version, "analisis/curvas.json")
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
return jsonify({"simulado": simulated_data(),
"modelo": {"nombre": f"{domain}-{scenario}", "version": str(resolved.version),
"mlflow_run_id": resolved.run_id},
"curvas": json.loads(content)})
return blueprint
+37 -8
View File
@@ -25,15 +25,16 @@ class Provenance:
return {key: value for key, value in self.__dict__.items() if value}
class Cin2LogisticEstimator:
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to
test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has
something to report when `estimate` calls it."""
class ScenarioEstimator:
"""Scores a domain's cohort with the version of one scenario that is in production (or `version`, to test a
candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has something to
report when `estimate` calls it."""
def __init__(self, domain: str = "cacu", version: str | None = None):
def __init__(self, domain: str, scenario: str, version: str | None = None):
self.domain = domain
self.scenario = scenario
self.version = version
self.desenlace = "cin2_mas"
self.desenlace = ""
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
@@ -49,7 +50,7 @@ class Cin2LogisticEstimator:
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
scenario = Scenario.load(self.domain, "cin2_logistic")
scenario = Scenario.load(self.domain, self.scenario)
build_id = repos.cohort_repository.latest_build(scenario.cohort)
resolved = registry.resolve(self.domain, scenario.scenario, self.version)
frame = KitBuild(self.domain, build_id).frame()
@@ -67,11 +68,39 @@ class Cin2LogisticEstimator:
return self._provenance
class Cin2LogisticEstimator(ScenarioEstimator):
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`)."""
def __init__(self, domain: str = "cacu", version: str | None = None):
super().__init__(domain, "cin2_logistic", version)
self.desenlace = "cin2_mas"
# The scenarios the cycle estimates with, per domain other than CaCu: each one that has a version in production
# scores the cohort it names.
LIVE_SCENARIOS = {"cama": ("survival",)}
def _scenario_estimators(domain: str) -> dict[str, Any]:
from models.dags.training import Scenario
from models.io.registry import registry
found = {}
for name in LIVE_SCENARIOS.get(domain, ()):
scenario = Scenario.load(domain, name)
try:
registry.resolve(domain, name)
except LookupError:
continue
found[scenario.cohort] = ScenarioEstimator(domain, name)
return found
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
return _scenario_estimators(domain)
from models.dags.training import Scenario
from models.io.registry import registry
+6
View File
@@ -25,6 +25,12 @@ def de_derechohabiente(paciente) -> dict:
}
def con_defuncion(paciente) -> dict:
"""Lo de `de_derechohabiente` y la fecha de defunción, el desenlace de la supervivencia: nula mientras vive o si se
desconoce."""
return {**de_derechohabiente(paciente), "fecha_defuncion": paciente.pac_fecha_defuncion}
def con_sexo(paciente) -> dict:
"""Lo que la persona de TEA agrega: el sexo, como código."""
return {"sexo": codigo(paciente.pac_sexo)}
+2 -2
View File
@@ -34,7 +34,7 @@ from core.cama.indicadores.models import (
Persona,
)
from webapi.orchestration.silver.persons import de_derechohabiente
from webapi.orchestration.silver.persons import con_defuncion
from core.indicadores.cohortes import TablasCohorte
from webapi.orchestration.tables import TablasKit
@@ -63,7 +63,7 @@ TABLAS = TablasKit(
CatMeasureEstrato=CatMeasureEstrato,
MeasureReportUnidad=MeasureReportUnidad,
MeasureReportUnidadEstrato=MeasureReportUnidadEstrato,
persona_propias=de_derechohabiente,
persona_propias=con_defuncion,
)
# Las cohortes para modelos y sus estimaciones de riesgo (oro restringido, ADR-MD-003; MD-12).
+4 -3
View File
@@ -9,9 +9,10 @@ from flask import Blueprint, jsonify, request
from persistance.edges.gold import ERROR, FINAL
def risk_batches_blueprint(repositories) -> Blueprint:
"""The blueprint, to register with `url_prefix="/cacu"`. `repositories` is `persistance.cacu`."""
blueprint = Blueprint("risk_batches", __name__)
def risk_batches_blueprint(repositories, name: str = "risk_batches") -> Blueprint:
"""The blueprint, to register with `url_prefix="/<domain>"`. `repositories` is `persistance.<domain>`; `name` is
unique per domain registered."""
blueprint = Blueprint(name, __name__)
@blueprint.get("/riesgos/lotes")
def list_pending_batches():