From d5413b7e7a9e700ff8b457544cca8a5a37c5bfda Mon Sep 17 00:00:00 2001 From: edgar Date: Mon, 16 Nov 2026 22:57:47 -0600 Subject: [PATCH] FHIR Measures carry each metric's technical sheet; the live estimator uses the scenario dataflow and the cohort check --- tests/test_fhir_measures.py | 24 +++++++++++++++ webapi/fhir/measures.py | 21 +++++++++++-- webapi/orchestration/estimators.py | 48 ++++++++++++++++-------------- 3 files changed, 69 insertions(+), 24 deletions(-) diff --git a/tests/test_fhir_measures.py b/tests/test_fhir_measures.py index c601cb6..f39058e 100644 --- a/tests/test_fhir_measures.py +++ b/tests/test_fhir_measures.py @@ -58,3 +58,27 @@ def test_the_patient_routes_are_tea_s_only(domain_client): domain, client = domain_client response = client.get(f"/{domain}/fhir/EpisodeOfCare") assert response.status_code == 404 and valid(response.get_json())["resourceType"] == "OperationOutcome" + + +def test_a_measure_carries_its_technical_sheet(domain_client): + """Pins down: what a metric's `meta` writes for the technical sheet reaches its Measure: `ficha` and + `figuras_detalle` as extensions, `referencias` as `relatedArtifact` and `descripcion_poblaciones` as the + populations' descriptions. Fails if `measure_resource` stops reading one of them, or CACU_EU7's or + CAMA_BIOPSIAS' `meta` loses it.""" + domain, client = domain_client + measure_id = {"cacu": "CACU-EU7", "cama": "CAMA-BIOPSIAS"}[domain] + measure = client.get(f"/{domain}/fhir/Measure/{measure_id}").get_json() + by_name = {} + for extension in measure["extension"]: + by_name.setdefault(extension["url"].rsplit("/", 1)[-1], []).append(extension) + sheet = {e["url"]: e["valueString"] for e in by_name["ficha"][0]["extension"]} + assert sheet["para"] == "Médico" and sheet["pregunta"].startswith("¿Cómo se distribuyen") + if domain == "cacu": + assert measure["relatedArtifact"] == [{ + "type": "citation", "display": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)", + "citation": "indicador 7"}] + texts = {e["extension"][0]["valueString"]: e["extension"][1:] for e in by_name["figura-detalle"]} + assert set(texts) == {"fig_c2_barras", "fig_c2_donas"} + assert [e["url"] for e in texts["fig_c2_donas"]][:2] == ["descripcion", "como-leer"] + population = measure["group"][0]["population"][0] + assert population["description"].startswith("Pacientes con al menos una citología tomada en el periodo.") diff --git a/webapi/fhir/measures.py b/webapi/fhir/measures.py index 2981340..4cb4654 100644 --- a/webapi/fhir/measures.py +++ b/webapi/fhir/measures.py @@ -2,7 +2,8 @@ The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as -extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier +extensions) and its technical sheet: `meta.ficha` and `meta.figuras_detalle` as extensions, `meta.referencias` as +`relatedArtifact` and `meta.descripcion_poblaciones` as each population's description. A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds its category as a `component`. A duration reports the units without a value as their own population. """ @@ -26,6 +27,9 @@ PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo" CATEGORY_LABEL = f"{STRUCTURE}/categoria" CONTRACT = f"{STRUCTURE}/contrato" REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion" +SHEET = f"{STRUCTURE}/ficha" +FIGURE_TEXT = f"{STRUCTURE}/figura-detalle" +SHEET_FIELDS = ("codigo", "para", "unidad", "pregunta", "definicion", "nota") POPULATION_LABELS = { "initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador", "denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor", @@ -68,7 +72,8 @@ def _populations(definition) -> list[dict]: codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION, EXCLUDED] metrics = {c: definition.metric for c in codes} - return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c), + texts = (getattr(definition, "meta", None) or {}).get("descripcion_poblaciones", {}) + return [{"code": concept(POPULATION_SYSTEM, c), "description": texts.get(c) or POPULATION_LABELS.get(c, c), "criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()] @@ -92,12 +97,24 @@ def measure_resource(definition, title: str, description: str) -> dict: {"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()] if meta.get("requiere_validacion"): extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]}) + sheet = meta.get("ficha", {}) + if sheet: + extensions.append({"url": SHEET, "extension": [{"url": f, "valueString": sheet[f]} + for f in SHEET_FIELDS if sheet.get(f)]}) + extensions += [{"url": FIGURE_TEXT, "extension": [ + {"url": "figura", "valueString": figure}, {"url": "descripcion", "valueString": text["descripcion"]}, + *({"url": "como-leer", "valueString": line} for line in text.get("como_leer", ()))]} + for figure, text in meta.get("figuras_detalle", {}).items()] resource = { "resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition), "version": definition.version, "name": definition.metric, "title": title, "status": "active", "description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)], "scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups, } + if meta.get("referencias"): + resource["relatedArtifact"] = [ + {"type": r.get("tipo", "citation"), "display": r["etiqueta"], **({"citation": r["ref"]} if r.get("ref") else {})} + for r in meta["referencias"]] if definition.basis: resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis) if definition.improvement_notation: diff --git a/webapi/orchestration/estimators.py b/webapi/orchestration/estimators.py index f8965cf..502d90a 100644 --- a/webapi/orchestration/estimators.py +++ b/webapi/orchestration/estimators.py @@ -3,16 +3,19 @@ its domain has in production. `estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`, `desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger -set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an -estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership, -the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go -unused by design. +set, so an estimator here ignores the wide frame and reads the model's own input, the build's long frame, from the +database (`models.io.storage.KitBuild`: the cycle's latest build for membership, the domain's timeline for the +events), then scores it with the production version in MLflow: one risk per member and horizon of that version. +A build with no rows or with a member, a date or an event missing is refused (`models.io.storage.model_frame`). +`estimar`'s arguments go unused by design. """ from dataclasses import dataclass from importlib import import_module from typing import Any +SCENARIO = "cin2_logistic" + @dataclass(frozen=True) class Provenance: @@ -37,28 +40,28 @@ class Cin2LogisticEstimator: self._provenance: Provenance | None = None def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]: - import mlflow.pyfunc - from persistance.settings import settings + import json - from models.cacu.cin2_logistic.model import SETTINGS + import mlflow.pyfunc + import numpy as np + + from models.dags.estimation import estimate_frame + from models.dags.training import Scenario from models.io.registry import registered_name, registry - from models.io.storage import cohorts_root, read_cohort - from models.pipelines.export_cohort import export_kit_build + from models.io.storage import KitBuild, model_frame from models.steps.risks import risk_rows + scenario = Scenario.load(self.domain, SCENARIO) repos = import_module(f"persistance.{self.domain}") - url = SETTINGS["cohort"] - build_id = repos.cohort_repository.latest_build(url) - resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version) - root = cohorts_root(getattr(settings, f"{self.domain}_database_url")) - path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id) - risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path)) - window = SETTINGS["outcome_window_months"] - self.desenlace = f"cin2_{window}m" + resolved = registry.resolve(self.domain, scenario.scenario, self.version) + cohort = model_frame(KitBuild(self.domain, repos.cohort_repository.latest_build(scenario.cohort))) + horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"]) + probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort)) + self.desenlace = scenario.outcome self._provenance = Provenance( - modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version, + modelo_nombre=registered_name(self.domain, scenario.scenario), modelo_version=resolved.version, mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha) - return [tuple(row) for row in risk_rows(risks, window / 12)] + return risk_rows(estimate_frame(cohort, probabilities, horizons)) def procedencia(self) -> Provenance: if self._provenance is None: @@ -71,11 +74,12 @@ def live_estimators(domain: str) -> dict[str, Any]: none is in production yet, the same as no estimator being configured: `estimate` then does nothing.""" if domain != "cacu": return {} - from models.cacu.cin2_logistic.model import SETTINGS + from models.dags.training import Scenario from models.io.registry import registry + scenario = Scenario.load(domain, SCENARIO) try: - registry.resolve(domain, SETTINGS["scenario"]) + registry.resolve(domain, scenario.scenario) except LookupError: return {} - return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)} + return {scenario.cohort: Cin2LogisticEstimator(domain)}