b1bbbc25b4
Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
711 lines
36 KiB
Python
711 lines
36 KiB
Python
"""A measure answered on request: the question carries the period and both cut-offs, the definition is dbt's.
|
|
|
|
The definition lives in dbt's semantic layer (`manifest.json`): a semantic model over an event-grain model (one row
|
|
per fact, with its date and when it became known), simple metrics for each population and a `ratio` metric whose
|
|
`meta` holds the rest of the measure, its strata included. dbt validates it; nothing here runs MetricFlow, which
|
|
doesn't support the project's engines. What runs instead is the small part of it these measures use:
|
|
`count_distinct` measures with a categorical filter, over a period of `dim_periodo`, broken down by strata, as
|
|
SQLAlchemy Core so every engine gets its own SQL.
|
|
|
|
A question is a measure, a period, an event cut-off (facts dated after it don't count) and a knowledge cut-off (facts
|
|
known after it don't count). Its answer is stored once (`MeasureHistoryRepository`); asking again reads it. The
|
|
database counts and writes the units and their strata; only the counts reach Python.
|
|
"""
|
|
|
|
import dataclasses
|
|
import hashlib
|
|
import json
|
|
from collections.abc import Callable, Iterable
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
from core.indicadores.tipos import FechaHoraUTC
|
|
from jinja2 import Environment
|
|
from sqlalchemy import (
|
|
Select,
|
|
String,
|
|
and_,
|
|
bindparam,
|
|
case,
|
|
cast,
|
|
column,
|
|
desc,
|
|
distinct,
|
|
func,
|
|
literal,
|
|
or_,
|
|
select,
|
|
table,
|
|
text,
|
|
true,
|
|
)
|
|
|
|
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
|
|
TOTAL = "total"
|
|
NO_DATA = "sin_dato"
|
|
AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo"
|
|
TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo"
|
|
TIMELINE_BY_CUTOFF = "linea_de_tiempo_al_corte"
|
|
OF_THE_CHOSEN = "del_elegido"
|
|
COLUMN = "columna"
|
|
STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo"
|
|
KNOWN_VERSION = "version_conocida"
|
|
|
|
|
|
class UndecidedRule(ValueError):
|
|
"""A rule a measure needs is still `sin_definir`."""
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
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. `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
|
|
measure_expr: str
|
|
filter_sql: str | None
|
|
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)
|
|
class Stratum:
|
|
"""A breakdown of the measure, as its `meta.estratos` entry declares it. `kind` says how its value is computed:
|
|
|
|
- `edad_al_inicio_del_periodo`: the age group at the period's start, from the model's `nacimiento` column;
|
|
- `linea_de_tiempo_al_inicio_del_periodo`: what the patient's timeline (`linea`, a model with `pac_id`, `tipo`,
|
|
`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;
|
|
- `linea_de_tiempo_al_corte`: the same, with what the timeline held by the question's event cut-off (all of it
|
|
without one) instead of before the period's start: a patient's characteristic learned after the fact that
|
|
put her in the period, such as the stage of a cancer whose biopsy the period counts;
|
|
- `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
|
|
kind: str
|
|
spec: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
|
|
|
@property
|
|
def birth(self) -> str:
|
|
return self.spec["nacimiento"]
|
|
|
|
@classmethod
|
|
def of(cls, name: str, spec: dict) -> "Stratum":
|
|
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, TIMELINE_BY_CUTOFF, OF_THE_CHOSEN, COLUMN):
|
|
raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered")
|
|
return cls(name, spec["tipo"], spec)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class MeasureDefinition:
|
|
"""A `ratio` metric with its numerator and denominator, the event model they count over, and its `meta`."""
|
|
|
|
url: str
|
|
version: str
|
|
metric: str
|
|
relation: str
|
|
model_checksum: str
|
|
time_dimension: str
|
|
dimensions: dict[str, str]
|
|
numerator: Population
|
|
denominator: Population
|
|
group: str
|
|
basis: str
|
|
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."""
|
|
m = json.loads(manifest.read_text(encoding="utf-8"))
|
|
metrics = {node["name"]: node for node in m["metrics"].values()}
|
|
semantic = {node["name"]: node for node in m["semantic_models"].values()}
|
|
models = {node["unique_id"]: node for node in m["nodes"].values()}
|
|
definitions = {}
|
|
for metric in metrics.values():
|
|
meta = metric["config"].get("meta", {})
|
|
if metric["type"] != "ratio" or "measure_url" not in meta:
|
|
continue
|
|
params = metric["type_params"]
|
|
numerator, denominator = metrics[params["numerator"]["name"]], metrics[params["denominator"]["name"]]
|
|
model = _semantic_model_of(numerator, semantic)
|
|
node = models[model["depends_on"]["nodes"][0]]
|
|
definitions[meta["measure_url"]] = MeasureDefinition(
|
|
url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"],
|
|
relation=node["alias"], model_checksum=node["checksum"]["checksum"],
|
|
time_dimension=model["defaults"]["agg_time_dimension"],
|
|
dimensions={**{e["name"]: e["expr"] or e["name"] for e in model["entities"]},
|
|
**{d["name"]: d["expr"] or d["name"] for d in model["dimensions"]}},
|
|
numerator=_population(numerator, model), denominator=_population(denominator, model),
|
|
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():
|
|
if any(m["name"] == measure for m in model["measures"]):
|
|
return model
|
|
raise LookupError(f"no semantic model has the measure {measure!r} of {metric['name']}")
|
|
|
|
|
|
def _population(metric: dict, model: dict) -> Population:
|
|
measure_name = metric["type_params"]["measure"]["name"]
|
|
(measure,) = [m for m in model["measures"] if m["name"] == measure_name]
|
|
if measure["agg"] != "count_distinct":
|
|
raise NotImplementedError(f"{metric['name']}: only count_distinct measures are answered, not {measure['agg']}")
|
|
filters = (metric.get("filter") or {}).get("where_filters", [])
|
|
meta = metric["config"].get("meta", {})
|
|
return Population(
|
|
metric=metric["name"], measure_expr=measure["expr"] or measure["name"],
|
|
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", ())),
|
|
)
|
|
|
|
|
|
# --- the question and its SQL ----------------------------------------------------------------------------------------
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Question:
|
|
"""What is asked: a measure in a period, with what was dated and known up to the cut-offs."""
|
|
|
|
measure_url: str
|
|
period_id: str
|
|
event_cutoff: date | None = None
|
|
knowledge_cutoff: datetime | None = None
|
|
|
|
|
|
DIM_FECHA = ("fecha", "anio", "mes", "dia")
|
|
DIM_GRUPO_EDAD = ("etiqueta", "edad_min", "edad_max")
|
|
|
|
|
|
class MeasureQueries:
|
|
"""The SQL of one definition for one question: counts per population and stratum, and the rows to store."""
|
|
|
|
def __init__(self, definition: MeasureDefinition, question: Question, rule_values: dict, period_table):
|
|
self.d, self.q, self.values = definition, question, rule_values
|
|
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 ())}
|
|
# The follow-up fact of a composition (the biopsy of the chosen sample) is compared with the knowledge cut-off too:
|
|
# its column has to be read as a datetime, or a text compare against the cut-off would be wrong.
|
|
follow_up = getattr(getattr(definition, "category", None), "follow_up", None)
|
|
known |= {definition.dimensions[n] for n in (follow_up.known_at if follow_up 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}
|
|
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")
|
|
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))
|
|
self._timelines: dict[str, object] = {}
|
|
|
|
def _column(self, dimension: str):
|
|
return self.events.c[self.d.dimensions[dimension]]
|
|
|
|
def _filter(self, population: Population):
|
|
conditions = []
|
|
if population.filter_sql:
|
|
rendered = Environment().from_string(population.filter_sql).render(
|
|
Dimension=lambda ref: f"{self.d.relation}.{self.d.dimensions[ref.split('__')[-1]]}")
|
|
names = [n for n in self.values if f":{n}" in rendered]
|
|
conditions.append(text(rendered).bindparams(*(
|
|
bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names)))
|
|
if self.q.event_cutoff is not None:
|
|
conditions += [self._column(name) <= self.q.event_cutoff.isoformat() for name in population.dated_at]
|
|
conditions += [self._column(name).is_not(None) for name in population.dated_at]
|
|
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 _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.
|
|
|
|
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:
|
|
conditions.append(when <= self.q.event_cutoff.isoformat())
|
|
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 in (OF_THE_CHOSEN, COLUMN):
|
|
continue
|
|
if stratum.kind == AGE_AT_PERIOD_START:
|
|
joined = (joined
|
|
.join(self.start_day, self.start_day.c.fecha == p.inicio)
|
|
.outerjoin(self.birth_day, self.birth_day.c.fecha == self._column(stratum.birth))
|
|
.outerjoin(self.age_groups, and_(self._age() >= self.age_groups.c.edad_min,
|
|
self._age() <= self.age_groups.c.edad_max)))
|
|
else:
|
|
had = self._timeline(stratum)
|
|
joined = joined.outerjoin(had, had.c.pac_id == self._column("paciente"))
|
|
return joined
|
|
|
|
def _timeline(self, stratum: Stratum):
|
|
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start
|
|
(or, for `linea_de_tiempo_al_corte`, by the event cut-off).
|
|
|
|
Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped
|
|
by on every engine.
|
|
"""
|
|
if stratum.name in self._timelines:
|
|
return self._timelines[stratum.name]
|
|
kinds = sorted({k for v in stratum.spec["valores"] for alternative in v["si"] for k in alternative})
|
|
line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"),
|
|
column("conocida_en", FechaHoraUTC))
|
|
period = self.periods.alias(f"periodo_{stratum.name}")
|
|
conditions = [line.c.tipo.in_(kinds)]
|
|
if stratum.kind == TIMELINE_AT_PERIOD_START:
|
|
conditions.append(line.c.fecha < period.c.inicio)
|
|
elif self.q.event_cutoff is not None:
|
|
conditions.append(line.c.fecha <= self.q.event_cutoff.isoformat())
|
|
if self.q.knowledge_cutoff is not None:
|
|
conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff)
|
|
had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds))
|
|
.select_from(line.join(period, period.c.periodo_id == self.q.period_id))
|
|
.where(*conditions).group_by(line.c.pac_id).subquery(f"linea_{stratum.name}"))
|
|
self._timelines[stratum.name] = had
|
|
return had
|
|
|
|
def _age(self):
|
|
"""Completed years at the period's start, from the parts of `dim_fecha`: no engine date functions."""
|
|
start, birth = self.start_day.c, self.birth_day.c
|
|
not_yet = or_(start.mes < birth.mes, and_(start.mes == birth.mes, start.dia < birth.dia))
|
|
return start.anio - birth.anio - case((not_yet, 1), else_=0)
|
|
|
|
def stratum_value(self, stratum: Stratum):
|
|
if stratum.kind == AGE_AT_PERIOD_START:
|
|
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):
|
|
return and_(*(func.coalesce(had[k], 0) == (1 if wanted else 0) for k, wanted in alternative.items()))
|
|
|
|
return case(*((or_(*map(holds, v["si"])), literal(v["valor"])) for v in stratum.spec["valores"]),
|
|
else_=literal(stratum.spec["resto"]))
|
|
|
|
def _cells(self):
|
|
unit = self.events.c[self.d.numerator.measure_expr]
|
|
for name, population in (("numerator", self.d.numerator), ("denominator", self.d.denominator)):
|
|
condition = self._filter(population)
|
|
counted = unit if condition is None else case((condition, unit))
|
|
yield func.count(distinct(counted)).label(name)
|
|
|
|
def counts(self) -> Select:
|
|
return select(*self._cells()).select_from(self._from(with_strata=False)).where(self._in_question())
|
|
|
|
def counts_by_stratum(self, stratum: Stratum) -> Select:
|
|
value = self.stratum_value(stratum).label("valor")
|
|
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, *((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)
|
|
for code in population.codes:
|
|
yield unit_model, (select(
|
|
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
|
|
cast(unit, String(64)).label("unidad_id"),
|
|
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
|
|
(unit if self.d.basis == "paciente" else literal(None)).label("pac_id"),
|
|
).select_from(self._from(with_strata=False)).where(where).distinct())
|
|
unit = self.events.c[self.d.denominator.measure_expr]
|
|
condition = self._filter(self.d.denominator)
|
|
where = self._in_question() if condition is None else and_(self._in_question(), condition)
|
|
for stratum in self.d.strata:
|
|
yield stratum_model, (select(
|
|
literal(report_id).label("report_id"), cast(unit, String(64)).label("unidad_id"),
|
|
literal(stratum.name).label("estrato_id"), self.stratum_value(stratum).label("estrato_valor"),
|
|
).select_from(self._from(with_strata=True)).where(where).distinct())
|
|
|
|
|
|
# --- answering ---------------------------------------------------------------------------------------------------------
|
|
|
|
|
|
def rule_values(parameters, definition: MeasureDefinition, allow_undecided: bool = False) -> dict:
|
|
values = {}
|
|
for name, rule in definition.rules.items():
|
|
row = parameters.get(rule)
|
|
if row is None:
|
|
raise KeyError(f"{definition.url}: there's no rule {rule!r} in def_parametro")
|
|
if row.estado == "sin_definir" and not allow_undecided:
|
|
raise UndecidedRule(f"{definition.url}: the rule {rule!r} is undecided ({row.fuente})")
|
|
values[name] = json.loads(row.valor)
|
|
return values
|
|
|
|
|
|
def key_of(definition: MeasureDefinition, question: Question, values: dict) -> tuple[str, str]:
|
|
"""The full key of a question, as JSON, and its hash."""
|
|
key = json.dumps({
|
|
"measure": definition.url, "version": definition.version, "metric": definition.metric,
|
|
"periodo": question.period_id,
|
|
"corte_evento": question.event_cutoff.isoformat() if question.event_cutoff else None,
|
|
"corte_conocimiento": question.knowledge_cutoff.isoformat() if question.knowledge_cutoff else None,
|
|
"sql": values, "estratos": {s.name: s.spec for s in definition.strata},
|
|
}, sort_keys=True, ensure_ascii=False)
|
|
return key, hashlib.sha256(key.encode("utf-8")).hexdigest()
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Counts:
|
|
numerator: int
|
|
denominator: int
|
|
|
|
@property
|
|
def proportion(self) -> float | None:
|
|
return self.numerator / self.denominator if self.denominator else None
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Answer:
|
|
report_id: int
|
|
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:
|
|
return self.total.numerator
|
|
|
|
@property
|
|
def denominator(self) -> int:
|
|
return self.total.denominator
|
|
|
|
@property
|
|
def proportion(self) -> float | None:
|
|
return self.total.proportion
|
|
|
|
|
|
def answer(project: str, definition: MeasureDefinition, question: Question, *, parameters, periods, history,
|
|
queries, allow_undecided: bool = False, now: datetime | None = None) -> Answer:
|
|
"""The stored answer to the question, or a new one computed by the database and stored.
|
|
|
|
`parameters`, `periods`, `history` and `queries` are the domain's repositories (`def_parametro`, `dim_periodo`,
|
|
`MeasureHistoryRepository`, `DbtQueryRepository`). A stored answer is read back from its units' counts.
|
|
"""
|
|
values = rule_values(parameters, definition, allow_undecided)
|
|
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),
|
|
history.group_counts(stored) if definition.groups else {})
|
|
|
|
period = periods.get(question.period_id)
|
|
if period is None:
|
|
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
|
|
sql = MeasureQueries(definition, question, values, periods.model.__table__)
|
|
_, ((numerator, denominator),) = queries.rows(sql.counts())
|
|
strata = {}
|
|
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(
|
|
measure_url=definition.url, measure_version=definition.version,
|
|
kit_version=f"metric:{definition.metric}:{definition.model_checksum[:12]}", toml_sha=any_rule.toml_sha,
|
|
parametros=key, parametros_sha=key_sha, fecha_corte=question.event_cutoff,
|
|
periodo_id=period.periodo_id, periodo_inicio=period.inicio, periodo_fin=period.fin,
|
|
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()),
|
|
excluded, sorted((g, c.numerator, c.denominator) for g, c in groups.items())]).encode()
|
|
).hexdigest(),
|
|
)
|
|
|
|
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, 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]] = {}
|
|
for (stratum, value, resultado, _), n in counts.items():
|
|
cell = cells.setdefault((stratum, value), [0, 0])
|
|
if resultado == numerator:
|
|
cell[0] = n
|
|
elif resultado == denominator:
|
|
cell[1] = n
|
|
strata: dict[str, dict[str, Counts]] = {}
|
|
for (stratum, value), (n, d) in cells.items():
|
|
if stratum != TOTAL:
|
|
strata.setdefault(stratum, {})[value] = Counts(n, d)
|
|
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 --------------------------------------------------------------------------------------------------
|
|
|
|
POPULATION_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-population"
|
|
EVENT_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-evento"
|
|
KNOWLEDGE_CUTOFF = "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento"
|
|
HISTORY_ENTRY = "https://isssteleon.org/fhir/StructureDefinition/reporte-id"
|
|
|
|
|
|
def _populations(definition: MeasureDefinition, counts: Counts) -> list[dict]:
|
|
by_code = {**{code: counts.denominator for code in definition.denominator.codes},
|
|
**{code: counts.numerator for code in definition.numerator.codes}}
|
|
return [{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": count}
|
|
for code, count in by_code.items()]
|
|
|
|
|
|
def _scored(entry: dict, counts: Counts) -> dict:
|
|
if counts.proportion is not None:
|
|
entry["measureScore"] = {"value": counts.proportion}
|
|
return entry
|
|
|
|
|
|
def measure_report(definition: MeasureDefinition, question: Question, result: Answer, period,
|
|
generated_at: datetime) -> dict:
|
|
"""The answer as a FHIR R4 `MeasureReport` (summary): one group, its populations, its score and its strata.
|
|
|
|
The cut-offs aren't FHIR elements: they go as extensions of the report, with the history entry it was read from.
|
|
"""
|
|
group = _scored({"id": definition.group, "population": _populations(definition, result.total)}, result.total)
|
|
if result.strata:
|
|
group["stratifier"] = [
|
|
{"code": [{"text": name}], "stratum": [
|
|
_scored({"value": {"text": value}, "population": _populations(definition, counts)}, counts)
|
|
for value, counts in sorted(values.items())]}
|
|
for name, values in result.strata.items()
|
|
]
|
|
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
|
|
if question.event_cutoff is not None:
|
|
extensions.append({"url": EVENT_CUTOFF, "valueDate": question.event_cutoff.isoformat()})
|
|
if question.knowledge_cutoff is not None:
|
|
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
|
report = {
|
|
"resourceType": "MeasureReport",
|
|
"status": "complete",
|
|
"type": "summary",
|
|
"measure": f"{definition.url}|{definition.version}",
|
|
"date": generated_at.isoformat(),
|
|
# FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`.
|
|
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
|
"extension": extensions,
|
|
"group": [group],
|
|
}
|
|
if definition.improvement_notation:
|
|
report["improvementNotation"] = {"coding": [{
|
|
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
|
"code": definition.improvement_notation}]}
|
|
return report
|
|
|