TEA: an answer as of a knowledge cut-off reads each child's version known then, and the measures waiting for a validation stay hidden outside FHIR too

This commit is contained in:
2026-11-12 19:47:19 -06:00
parent a0407e41d6
commit 0f9433949f
6 changed files with 93 additions and 26 deletions
+1 -7
View File
@@ -39,13 +39,7 @@ def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients:
def definitions() -> dict:
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
every = {fhir_id(d): d for d in definitions_of(project, manifest).values()}
if project == "tea":
from webapi.fhir.tea import alterations_validated
if not alterations_validated():
every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")}
return every
return {fhir_id(d): d for d in definitions_of(project, manifest).values()}
def definition_of(measure_id: str):
return definitions().get(measure_id.replace("_", "-"))
+19 -4
View File
@@ -10,6 +10,7 @@ durations (`webapi.durations`; without `corte_evento`, the day of the last load)
import json
from collections.abc import Callable
from datetime import date, datetime, timezone
from functools import lru_cache
from pathlib import Path
from core.indicadores.tipos import FechaHoraUTC
@@ -24,28 +25,42 @@ LOADS = table("carga", column("inicio", FechaHoraUTC))
def definitions_of(project: str, manifest: Path) -> dict:
"""Every measure the manifest defines for the domain, by its id (the end of its url)."""
"""Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for
a validation (`meta.requiere_validacion`) is left out until it's given."""
return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)}
@lru_cache
def _defined(project: str, manifest: Path) -> dict:
every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)}
return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")}
def _awaits_validation(definition) -> bool:
"""TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them."""
if not definition.meta.get("requiere_validacion"):
return False
from webapi.fhir.tea import alterations_validated
return not alterations_validated()
def kpis_blueprint(project: str, repositories, manifest: Path, *,
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
"""The blueprint of a domain, to register with `url_prefix="/<domain>"`. `repositories` is the domain's
`persistance.<domain>` module."""
blueprint = Blueprint(f"{project}_kpis", __name__)
definitions = definitions_of(project, manifest)
@blueprint.get("/indicadores")
def list_kpis():
"""The measures answered on request: id, url, version and scoring."""
return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)}
for i, d in sorted(definitions.items())])
for i, d in sorted(definitions_of(project, manifest).items())])
@blueprint.get("/indicadores/<measure_id>")
def get_kpi(measure_id: str):
"""A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history."""
definition = definitions.get(measure_id)
definition = definitions_of(project, manifest).get(measure_id)
if definition is None:
return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404
try:
+20
View File
@@ -49,6 +49,7 @@ TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo"
OF_THE_CHOSEN = "del_elegido"
COLUMN = "columna"
STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo"
KNOWN_VERSION = "version_conocida"
class UndecidedRule(ValueError):
@@ -283,10 +284,15 @@ class MeasureQueries:
if self.status is not None:
names |= {definition.dimensions[n] for n in self.status.columns()}
known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n}
version = (getattr(definition, "meta", None) or {}).get(KNOWN_VERSION)
if version is not None:
known.add(definition.dimensions[version])
self.events = table(definition.relation, *(
column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names)
if name.isidentifier()))
self.periods = period_table
if version is not None:
self.events = self._known_version(definition.dimensions[version])
if self.status is not None:
self.events = self._status_rows()
self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento")
@@ -329,6 +335,20 @@ class MeasureQueries:
conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff]
return and_(*conditions)
def _known_version(self, version: str):
"""Each unit's rows as they were known at the knowledge cut-off, for a model with one set of rows per unit
and knowledge version (`meta.version_conocida`, the column that dates each version): the unit's latest
version by the cut-off, or its latest of all without one. A subquery with the model's name, read as the
model is."""
base = self.events
latest = func.rank().over(partition_by=base.c[self.d.numerator.measure_expr], order_by=desc(base.c[version]))
versions = select(*base.c, latest.label("lugar_de_version"))
if self.q.knowledge_cutoff is not None:
versions = versions.where(base.c[version] <= self.q.knowledge_cutoff)
versions = versions.subquery("versiones")
return (select(*(c for c in versions.c if c.name != "lugar_de_version"))
.where(versions.c.lugar_de_version == 1).subquery(self.d.relation))
def _status_rows(self):
"""Each unit the period counts, with its row of highest order: a subquery with the model's name, so the
rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds.