TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary

This commit is contained in:
2026-11-12 15:21:25 -06:00
committed by rockdrigo
parent 205bc214fa
commit e224b8b2aa
55 changed files with 2607 additions and 788 deletions
+187 -12
View File
@@ -30,6 +30,7 @@ from sqlalchemy import (
case,
cast,
column,
desc,
distinct,
func,
literal,
@@ -37,6 +38,7 @@ from sqlalchemy import (
select,
table,
text,
true,
)
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
@@ -45,6 +47,8 @@ NO_DATA = "sin_dato"
AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo"
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"
class UndecidedRule(ValueError):
@@ -56,7 +60,8 @@ class Population:
"""A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates.
`dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the
dates the knowledge cut-off applies to.
dates the knowledge cut-off applies to. `at_end`, with a status at the period's end: dates that must have (or must
not have) been reached by the period's end, each with when it became known.
"""
metric: str
@@ -65,6 +70,53 @@ class Population:
codes: tuple[str, ...]
dated_at: tuple[str, ...]
known_at: tuple[str, ...]
at_end: tuple["ReachedByEnd", ...] = ()
@dataclasses.dataclass(frozen=True)
class ReachedByEnd:
"""A date reached by the period's end (`reached`) or not: dated before the period's end and the event cut-off,
and known by the knowledge cut-off."""
date: str
known_at: str | None
reached: bool
@dataclasses.dataclass(frozen=True)
class StatusAtEnd:
"""Who a period counts and with which row: every unit that entered (`entry`) on or before the period's end and
hadn't left (`exit`, known at `exit_known`) before its start, whether or not it has a fact in the period. Each
unit is counted with its row of highest `order` dated on or before the period's end (its status then) and known
by the cut-offs (`known_at`). With no `order`, the model has one row per unit."""
entry: str
exit: str
exit_known: str | None
order: str | None
known_at: tuple[str, ...]
@classmethod
def of(cls, spec: dict | None) -> "StatusAtEnd | None":
if spec is None:
return None
if spec["tipo"] != STATUS_AT_PERIOD_END:
raise NotImplementedError(f"populations of kind {spec['tipo']!r} aren't answered")
return cls(spec["ingreso"], spec["salida"], spec.get("salida_conocida_en"), spec.get("orden"),
tuple(spec.get("conocida_en", ())))
def columns(self) -> set[str]:
return {self.entry, self.exit, *((self.exit_known,) if self.exit_known else ()),
*((self.order,) if self.order else ()), *self.known_at}
@dataclasses.dataclass(frozen=True)
class Group:
"""One of several groups of a measure: its numerator is the measure's own with this filter instead."""
name: str
label: str
filter_sql: str
@dataclasses.dataclass(frozen=True)
@@ -76,7 +128,8 @@ class Stratum:
`fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose
condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a
timeline `tipo` to whether there was one;
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category.
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category;
- `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null.
"""
name: str
@@ -89,7 +142,7 @@ class Stratum:
@classmethod
def of(cls, name: str, spec: dict) -> "Stratum":
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN):
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN, COLUMN):
raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered")
return cls(name, spec["tipo"], spec)
@@ -112,11 +165,26 @@ class MeasureDefinition:
rules: dict[str, str]
strata: tuple[Stratum, ...]
improvement_notation: str | None = None
population: StatusAtEnd | None = None
groups: tuple[Group, ...] = ()
exclusion: Population | None = None
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
@property
def measure_id(self) -> str:
return self.url.rsplit("/", 1)[-1]
def for_group(self, group: Group) -> "MeasureDefinition":
"""The definition as one of its groups: the denominator's units, filtered by the group."""
numerator = dataclasses.replace(self.denominator, metric=f"{self.numerator.metric}:{group.name}",
codes=self.numerator.codes, filter_sql=_both(self.denominator.filter_sql,
group.filter_sql))
return dataclasses.replace(self, numerator=numerator, group=group.name, groups=(), strata=(), exclusion=None)
def _both(first: str | None, second: str | None) -> str | None:
return " and ".join(f"({c})" for c in (first, second) if c) or None
def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]:
"""The ratio metrics of the manifest that declare a `measure_url`, by that url."""
@@ -143,10 +211,20 @@ def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]:
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()),
improvement_notation=meta.get("improvement_notation"),
population=StatusAtEnd.of(meta.get("poblacion")),
groups=tuple(Group(g["grupo"], g.get("etiqueta", g["grupo"]), _unraw(g["filtro"]))
for g in meta.get("grupos", ())),
exclusion=_population(metrics[meta["exclusion"]], model) if "exclusion" in meta else None,
meta=meta,
)
return definitions
def _unraw(template: str) -> str:
"""A `meta` template as written, without the `{% raw %}` that keeps dbt from rendering it."""
return template.replace("{% raw %}", "").replace("{% endraw %}", "")
def _semantic_model_of(metric: dict, semantic: dict) -> dict:
measure = metric["type_params"]["measure"]["name"]
for model in semantic.values():
@@ -167,6 +245,8 @@ def _population(metric: dict, model: dict) -> Population:
filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None,
codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())),
known_at=tuple(meta.get("conocida_en", ())),
at_end=tuple(ReachedByEnd(a["fecha"], a.get("conocida_en"), bool(a.get("alcanzada", True)))
for a in meta.get("al_fin", ())),
)
@@ -195,12 +275,20 @@ class MeasureQueries:
names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr}
# When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in.
known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at}
known |= {definition.dimensions[a.known_at] for p in (definition.numerator, definition.denominator)
for a in p.at_end if a.known_at}
for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)):
known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())}
self.status = getattr(definition, "population", None)
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}
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 self.status is not None:
self.events = self._status_rows()
self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento")
self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio")
self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD))
@@ -223,9 +311,56 @@ class MeasureQueries:
if self.q.knowledge_cutoff is not None:
conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at]
conditions += [self._column(name).is_not(None) for name in population.known_at]
for date in population.at_end:
reached = self._reached_by_end(date.date, date.known_at)
conditions.append(reached if date.reached else case((reached, 0), else_=1) == 1)
return and_(*conditions) if conditions else None
def _reached_by_end(self, date: str, known_at: str | None):
"""The date is reached by the period's end: dated before it and by the event cut-off, known by the
knowledge cut-off. Only with a status at the period's end, whose rows carry the period's bounds."""
if self.status is None:
raise ValueError(f"{self.d.url}: `al_fin` needs a population at the period's end")
value = self._column(date)
conditions = [value.is_not(None), value < self.events.c.periodo_fin]
if self.q.event_cutoff is not None:
conditions.append(value <= self.q.event_cutoff.isoformat())
if known_at is not None and self.q.knowledge_cutoff is not None:
conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff]
return and_(*conditions)
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.
A unit is in when it entered by the period's end and hadn't left before its start; a later exit, or one not
yet dated or known by the cut-offs, doesn't count. Its rows are those dated before the period's end and by
the event cut-off, and known by the knowledge cut-off.
"""
rule, base, p = self.status, self.events, self.periods.c
col = lambda name: base.c[self.d.dimensions[name]] # noqa: E731
when, unit = base.c[self.d.time_dimension], base.c[self.d.numerator.measure_expr]
conditions = [p.periodo_id == self.q.period_id, when.is_not(None), when < p.fin, col(rule.entry) < p.fin]
left = [col(rule.exit).is_not(None), col(rule.exit) < p.inicio]
if self.q.event_cutoff is not None:
conditions.append(when <= self.q.event_cutoff.isoformat())
left.append(col(rule.exit) <= self.q.event_cutoff.isoformat())
if self.q.knowledge_cutoff is not None:
conditions += [col(n) <= self.q.knowledge_cutoff for n in rule.known_at]
if rule.exit_known:
left += [col(rule.exit_known).is_not(None), col(rule.exit_known) <= self.q.knowledge_cutoff]
conditions.append(case((and_(*left), 1), else_=0) == 0)
order = [desc(col(rule.order))] if rule.order else [desc(when)]
ranked = (select(*base.c, p.periodo_id.label("periodo_id"), p.inicio.label("periodo_inicio"),
p.fin.label("periodo_fin"),
func.row_number().over(partition_by=unit, order_by=order).label("lugar_al_fin"))
.select_from(base.join(self.periods, true())).where(*conditions).subquery("al_fin_del_periodo"))
return (select(*(c for c in ranked.c if c.name != "lugar_al_fin")).where(ranked.c.lugar_al_fin == 1)
.subquery(self.d.relation))
def _in_question(self):
if self.status is not None:
return self.events.c.periodo_id == self.q.period_id
when, p = self.events.c[self.d.time_dimension], self.periods.c
conditions = [p.periodo_id == self.q.period_id]
if self.q.event_cutoff is not None:
@@ -233,12 +368,16 @@ class MeasureQueries:
return and_(*conditions)
def _from(self, *, with_strata: bool):
if self.status is not None:
if with_strata and any(s.kind not in (COLUMN, OF_THE_CHOSEN) for s in self.d.strata):
raise NotImplementedError(f"{self.d.url}: a status at the period's end takes column strata only")
return self.events
when, p = self.events.c[self.d.time_dimension], self.periods.c
joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin))
if not with_strata:
return joined
for stratum in self.d.strata:
if stratum.kind == OF_THE_CHOSEN:
if stratum.kind in (OF_THE_CHOSEN, COLUMN):
continue
if stratum.kind == AGE_AT_PERIOD_START:
joined = (joined
@@ -283,6 +422,8 @@ class MeasureQueries:
return func.coalesce(self.age_groups.c.etiqueta, NO_DATA)
if stratum.kind == OF_THE_CHOSEN:
return self._column(stratum.spec["valor"])
if stratum.kind == COLUMN:
return func.coalesce(self._column(stratum.spec["columna"]), NO_DATA)
had = self._timeline(stratum).c
def holds(alternative: dict):
@@ -306,9 +447,15 @@ class MeasureQueries:
return (select(value, *self._cells()).select_from(self._from(with_strata=True))
.where(self._in_question()).group_by(value))
def excluded(self) -> Select:
"""The units of the measure's exclusion (`meta.exclusion`): in the period, but out of its denominator."""
unit, condition = self.events.c[self.d.exclusion.measure_expr], self._filter(self.d.exclusion)
counted = unit if condition is None else case((condition, unit))
return select(func.count(distinct(counted))).select_from(self._from(with_strata=False)).where(self._in_question())
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
"""What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum."""
for population in (self.d.denominator, self.d.numerator):
for population in (self.d.denominator, self.d.numerator, *((self.d.exclusion,) if self.d.exclusion else ())):
unit = self.events.c[population.measure_expr]
condition = self._filter(population)
where = self._in_question() if condition is None else and_(self._in_question(), condition)
@@ -372,6 +519,8 @@ class Answer:
total: Counts
strata: dict[str, dict[str, Counts]]
stored_before: bool
groups: dict[str, Counts] = dataclasses.field(default_factory=dict) # by group, for a measure with several
excluded: int | None = None # the units of its exclusion, when it has one
@property
def numerator(self) -> int:
@@ -397,7 +546,8 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
key, key_sha = key_of(definition, question, values)
stored = history.find(definition.url, key_sha)
if stored is not None:
return _from_counts(definition, stored, history.counts(stored))
return _from_counts(definition, stored, history.counts(stored),
history.group_counts(stored) if definition.groups else {})
period = periods.get(question.period_id)
if period is None:
@@ -408,6 +558,13 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
for stratum in definition.strata:
_, cells = queries.rows(sql.counts_by_stratum(stratum))
strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells}
excluded = queries.rows(sql.excluded())[1][0][0] if definition.exclusion else None
group_sql, groups = [], {}
for group in definition.groups:
g = MeasureQueries(definition.for_group(group), question, values, periods.model.__table__)
_, ((n, d),) = queries.rows(g.counts())
groups[group.name] = Counts(n, d)
group_sql.append(g)
models = import_module(f"core.{project}.indicadores.models")
(any_rule,) = parameters.list(limit=1)
report = models.MeasureReport(
@@ -418,15 +575,21 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
agregacion_version=AGGREGATION_VERSION,
huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted(
(s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode()
(s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items()),
excluded, sorted((g, c.numerator, c.denominator) for g, c in groups.items())]).encode()
).hexdigest(),
)
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
models.MeasureReportUnidadEstrato))
return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False)
def rows(rid):
for queries_of in (sql, *group_sql):
yield from queries_of.rows(rid, models.MeasureReportUnidad, models.MeasureReportUnidadEstrato)
report_id = history.record(report, rows)
return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False, groups=groups,
excluded=excluded)
def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer:
def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by_group: dict | None = None) -> Answer:
numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0],
definition.denominator.codes[0]))
cells: dict[tuple[str, str], list[int]] = {}
@@ -440,7 +603,19 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) ->
for (stratum, value), (n, d) in cells.items():
if stratum != TOTAL:
strata.setdefault(stratum, {})[value] = Counts(n, d)
return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True)
excluded = None
if definition.exclusion is not None:
code = f"{definition.measure_id}.{definition.exclusion.codes[0]}"
excluded = sum(n for (stratum, _, resultado, _), n in counts.items() if stratum == TOTAL and resultado == code)
groups = {}
if definition.groups:
by_group = by_group or {}
groups = {g.name: Counts(by_group.get((g.name, numerator), 0), by_group.get((g.name, denominator), 0))
for g in definition.groups}
totals = Counts(by_group.get((definition.group, numerator), 0), by_group.get((definition.group, denominator), 0))
else:
totals = Counts(*cells.get((TOTAL, TOTAL), (0, 0)))
return Answer(report_id, totals, strata, stored_before=True, groups=groups, excluded=excluded)
# --- the contract --------------------------------------------------------------------------------------------------