369 lines
18 KiB
Python
369 lines
18 KiB
Python
"""A composition answered on request: how a period's units split across the categories of their latest valid fact.
|
|
|
|
The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring:
|
|
composition` and gives the category rule (`categoria`): which column is the category, what makes a fact valid
|
|
(a template like a metric's `filter`), the dates the event and knowledge cut-offs apply to, and the order that picks
|
|
each unit's latest fact. Which fact is a unit's latest depends on the question (its period and cut-offs), so it's
|
|
computed in the answer, with `ROW_NUMBER()`, not stored in the model. The rest (the question, the history, strata
|
|
by age at the period's start) is `webapi.metrics`'.
|
|
"""
|
|
|
|
import dataclasses
|
|
import hashlib
|
|
import json
|
|
from collections.abc import Iterable
|
|
from datetime import 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, select, table, text
|
|
|
|
from webapi.metrics import (
|
|
AGGREGATION_VERSION,
|
|
HISTORY_ENTRY,
|
|
EVENT_CUTOFF,
|
|
KNOWLEDGE_CUTOFF,
|
|
POPULATION_SYSTEM,
|
|
MeasureQueries,
|
|
Population,
|
|
Question,
|
|
StatusAtEnd,
|
|
Stratum,
|
|
_population,
|
|
_semantic_model_of,
|
|
key_of,
|
|
rule_values,
|
|
)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class FollowUp:
|
|
"""A fact that follows the chosen one (a biopsy of the chosen sample): the category comes from the first of
|
|
them by `order`, among those that exist and were dated and known by the cut-offs; `none` if there's none."""
|
|
|
|
exists: str
|
|
dated_at: tuple[str, ...]
|
|
known_at: tuple[str, ...]
|
|
order: tuple[str, ...]
|
|
none: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Category:
|
|
value: str
|
|
no_data: str
|
|
valid_sql: str
|
|
dated_at: tuple[str, ...]
|
|
known_at: tuple[str, ...]
|
|
order: tuple[str, ...]
|
|
admits_sql: str | None = None # which units count, judged on their chosen fact
|
|
follow_up: FollowUp | None = None
|
|
# A number's band instead of the value itself: (band, rule of its upper bound), in order; the last has no bound.
|
|
bands: tuple[tuple[str, str | None], ...] = ()
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class CompositionDefinition:
|
|
"""A composition, shaped so `MeasureQueries` can build its period, cut-offs and strata."""
|
|
|
|
url: str
|
|
version: str
|
|
metric: str
|
|
relation: str
|
|
model_checksum: str
|
|
time_dimension: str
|
|
dimensions: dict[str, str]
|
|
units: Population
|
|
category: Category
|
|
group: str
|
|
basis: str
|
|
rules: dict[str, str]
|
|
strata: tuple[Stratum, ...]
|
|
population: StatusAtEnd | 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]
|
|
|
|
@property
|
|
def numerator(self) -> Population:
|
|
return self.units
|
|
|
|
@property
|
|
def denominator(self) -> Population:
|
|
return self.units
|
|
|
|
improvement_notation = None
|
|
|
|
|
|
class InvalidCategoryGroups(ValueError):
|
|
"""A composition's category groups (`categoria.grupos` and each label's `grupo`) don't hold together."""
|
|
|
|
|
|
def category_groups(url: str, rule: dict) -> dict[str, str]:
|
|
"""The groups of a composition's categories (`categoria.grupos`: code -> caption), checked against the labels that
|
|
name them (`categoria.etiquetas.<code>.grupo`). Optional: without either, there are none.
|
|
|
|
A label may name no group (a category kept apart, like «Sin biopsia aún»); every group named is declared, every
|
|
declared group has a category, and the no-data category, if grouped, is alone in the group of its own code, as the
|
|
indicator page reads it.
|
|
"""
|
|
grupos = rule.get("grupos")
|
|
labels = rule.get("etiquetas", {})
|
|
named = {code: spec["grupo"] for code, spec in labels.items() if isinstance(spec, dict) and "grupo" in spec}
|
|
if grupos is None:
|
|
if named:
|
|
raise InvalidCategoryGroups(f"{url}: categories name groups ({', '.join(sorted(named))}) but `grupos` is missing")
|
|
return {}
|
|
if not isinstance(grupos, dict) or not grupos or not all(
|
|
isinstance(code, str) and code and isinstance(caption, str) and caption.strip() for code, caption in grupos.items()):
|
|
raise InvalidCategoryGroups(f"{url}: `grupos` maps each group's code to a non-empty caption")
|
|
if unknown := sorted({g for g in named.values() if g not in grupos}):
|
|
raise InvalidCategoryGroups(f"{url}: undeclared groups {unknown}")
|
|
if unused := sorted(set(grupos) - set(named.values())):
|
|
raise InvalidCategoryGroups(f"{url}: groups without categories {unused}")
|
|
no_data = rule.get("sin_dato")
|
|
if no_data in named and (named[no_data] != no_data or [c for c, g in named.items() if g == no_data and c != no_data]):
|
|
raise InvalidCategoryGroups(f"{url}: the no-data category {no_data!r} goes alone in the group {no_data!r}")
|
|
if no_data in grupos and named.get(no_data) != no_data:
|
|
raise InvalidCategoryGroups(f"{url}: the group {no_data!r} is the no-data category's own")
|
|
return dict(grupos)
|
|
|
|
|
|
def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
|
|
"""The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`."""
|
|
m = json.loads(manifest.read_text(encoding="utf-8"))
|
|
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 m["metrics"].values():
|
|
meta = metric["config"].get("meta", {})
|
|
if metric["type"] != "simple" or meta.get("scoring") != "composition":
|
|
continue
|
|
model = _semantic_model_of(metric, semantic)
|
|
node = models[model["depends_on"]["nodes"][0]]
|
|
rule = meta["categoria"]
|
|
category_groups(meta["measure_url"], rule) # fails the manifest's load if the groups don't hold together
|
|
definitions[meta["measure_url"]] = CompositionDefinition(
|
|
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"]}},
|
|
units=_population(metric, model),
|
|
category=Category(rule["valor"], rule["sin_dato"], rule["valido"], tuple(rule.get("fechada_en", ())),
|
|
tuple(rule.get("conocida_en", ())), tuple(rule["orden"]), rule.get("admite"),
|
|
_follow_up(rule.get("seguimiento")),
|
|
tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))),
|
|
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()),
|
|
population=StatusAtEnd.of(meta.get("poblacion")), meta=meta,
|
|
)
|
|
return definitions
|
|
|
|
|
|
def _follow_up(rule: dict | None) -> FollowUp | None:
|
|
if rule is None:
|
|
return None
|
|
return FollowUp(rule["existe"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())),
|
|
tuple(rule["orden"]), rule["sin_seguimiento"])
|
|
|
|
|
|
class CompositionQueries(MeasureQueries):
|
|
"""Each unit's category in the period, from the latest of its facts, valid ones first."""
|
|
|
|
def __init__(self, definition: CompositionDefinition, question: Question, rule_values: dict, period_table):
|
|
super().__init__(definition, question, rule_values, period_table)
|
|
c, f = definition.category, definition.category.follow_up
|
|
names = [c.value, *c.order, *c.dated_at, *c.known_at,
|
|
*((f.exists, *f.order, *f.dated_at, *f.known_at) if f else ()),
|
|
*(s.spec["valor"] for s in definition.strata if s.kind == "del_elegido")]
|
|
known = {definition.dimensions[n] for n in (*c.known_at, *(f.known_at if f else ()))}
|
|
for name in {definition.dimensions[n] for n in names} - set(self.events.c.keys()):
|
|
self.events.append_column(column(name, FechaHoraUTC) if name in known else column(name))
|
|
|
|
def _template(self, sql: str):
|
|
"""A `meta` condition, rendered like a metric's `filter`, with the rules it names bound (a list as `in`)."""
|
|
rendered = Environment().from_string(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]
|
|
return text(f"({rendered})").bindparams(*(
|
|
bindparam(n, self.values[n], expanding=isinstance(self.values[n], (list, tuple))) for n in names))
|
|
|
|
def _value(self):
|
|
"""The category's value: the column's, or the band its number falls in, by the question's rules."""
|
|
c = self.d.category
|
|
if not c.bands:
|
|
return self._column(c.value)
|
|
number = self._column(c.value)
|
|
*bounded, (last, _) = c.bands
|
|
return case(*((number < self.values[rule], literal(band)) for band, rule in bounded), else_=literal(last))
|
|
|
|
def _counted(self):
|
|
"""The follow-up fact of this row exists and was dated and known by the cut-offs."""
|
|
f = self.d.category.follow_up
|
|
conditions = [self._column(f.exists).is_not(None)]
|
|
if self.q.event_cutoff is not None:
|
|
conditions += [self._column(n) <= self.q.event_cutoff.isoformat() for n in f.dated_at]
|
|
if self.q.knowledge_cutoff is not None:
|
|
conditions += [self._column(n) <= self.q.knowledge_cutoff for n in f.known_at]
|
|
return and_(*conditions)
|
|
|
|
def _valid(self):
|
|
c = self.d.category
|
|
conditions = [self._template(c.valid_sql)]
|
|
for name in c.dated_at:
|
|
conditions.append(self._column(name).is_not(None))
|
|
if self.q.event_cutoff is not None:
|
|
conditions.append(self._column(name) <= self.q.event_cutoff.isoformat())
|
|
if self.q.knowledge_cutoff is not None:
|
|
conditions += [self._column(name) <= self.q.knowledge_cutoff for name in c.known_at]
|
|
return and_(*conditions)
|
|
|
|
def latest(self, *, with_strata: bool = False):
|
|
"""One row per unit: its category (`categoria`) and, with strata, its value of each (`estrato_<name>`)."""
|
|
unit = self.events.c[self.d.units.measure_expr]
|
|
c, f = self.d.category, self.d.category.follow_up
|
|
valid = self._valid()
|
|
order = [desc(case((valid, 1), else_=0)), *(desc(self._column(n)) for n in c.order)]
|
|
value = self._value()
|
|
category = case((valid, value))
|
|
if f is not None:
|
|
counted = self._counted()
|
|
order += [desc(case((counted, 1), else_=0)), *(desc(self._column(n)) for n in f.order)]
|
|
category = case((valid & ~counted, literal(f.none)), (valid, value))
|
|
admitted = valid if c.admits_sql is None else and_(valid, self._template(c.admits_sql))
|
|
where = self._in_question()
|
|
units = self._filter(self.d.units)
|
|
if units is not None:
|
|
where = and_(where, units)
|
|
strata = [self.stratum_value(s).label(f"estrato_{s.name}") for s in self.d.strata] if with_strata else []
|
|
ranked = (select(unit.label("unidad"), category.label("categoria"), case((admitted, 1), else_=0).label("admitida"),
|
|
*strata, func.row_number().over(partition_by=unit, order_by=order).label("lugar"))
|
|
.select_from(self._from(with_strata=with_strata)).where(where).subquery("por_unidad"))
|
|
chosen = [ranked.c.lugar == 1] + ([ranked.c.admitida == 1] if c.admits_sql is not None else [])
|
|
return (select(ranked.c.unidad, func.coalesce(ranked.c.categoria, c.no_data).label("categoria"),
|
|
*(ranked.c[f"estrato_{s.name}"] for s in self.d.strata if with_strata))
|
|
.where(*chosen).subquery("ultima"))
|
|
|
|
def category_counts(self) -> Select:
|
|
latest = self.latest()
|
|
return (select(latest.c.categoria, func.count(distinct(latest.c.unidad)))
|
|
.group_by(latest.c.categoria).order_by(latest.c.categoria))
|
|
|
|
def counts_by_stratum(self, stratum: Stratum) -> Select:
|
|
latest = self.latest(with_strata=True)
|
|
value = latest.c[f"estrato_{stratum.name}"]
|
|
return (select(value, latest.c.categoria, func.count(distinct(latest.c.unidad)))
|
|
.group_by(value, latest.c.categoria))
|
|
|
|
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
|
|
latest = self.latest(with_strata=True)
|
|
(code,) = self.d.units.codes
|
|
yield unit_model, select(
|
|
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
|
|
cast(latest.c.unidad, String(64)).label("unidad_id"),
|
|
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
|
|
(latest.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"),
|
|
latest.c.categoria.label("valor_id"),
|
|
)
|
|
for stratum in self.d.strata:
|
|
yield stratum_model, select(
|
|
literal(report_id).label("report_id"), cast(latest.c.unidad, String(64)).label("unidad_id"),
|
|
literal(stratum.name).label("estrato_id"), latest.c[f"estrato_{stratum.name}"].label("estrato_valor"),
|
|
)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class CompositionAnswer:
|
|
report_id: int
|
|
categories: dict[str, int]
|
|
strata: dict[str, dict[str, dict[str, int]]]
|
|
stored_before: bool
|
|
|
|
@property
|
|
def total(self) -> int:
|
|
return sum(self.categories.values())
|
|
|
|
|
|
def answer_composition(project: str, definition: CompositionDefinition, question: Question, *, parameters, periods,
|
|
history, queries, allow_undecided: bool = False,
|
|
now: datetime | None = None) -> CompositionAnswer:
|
|
"""The stored answer, or a new one: the database ranks each unit's facts, counts and writes the units."""
|
|
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(stored, history.counts(stored))
|
|
|
|
period = periods.get(question.period_id)
|
|
if period is None:
|
|
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
|
|
sql = CompositionQueries(definition, question, values, periods.model.__table__)
|
|
_, rows = queries.rows(sql.category_counts())
|
|
categories = {category: n for category, n in rows}
|
|
strata = {}
|
|
for stratum in definition.strata:
|
|
_, cells = queries.rows(sql.counts_by_stratum(stratum))
|
|
for value, category, n in cells:
|
|
strata.setdefault(stratum.name, {}).setdefault(value, {})[category] = n
|
|
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, sorted(categories.items()), sorted(
|
|
(s, v, c, n) for s, by in strata.items() for v, cs in by.items() for c, n in cs.items())]).encode()
|
|
).hexdigest(),
|
|
)
|
|
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
|
|
models.MeasureReportUnidadEstrato))
|
|
return CompositionAnswer(report_id, categories, strata, stored_before=False)
|
|
|
|
|
|
def _from_counts(report_id: int, counts: dict) -> CompositionAnswer:
|
|
categories, strata = {}, {}
|
|
for (stratum, value, _, category), n in counts.items():
|
|
if stratum == "total":
|
|
categories[category] = n
|
|
else:
|
|
strata.setdefault(stratum, {}).setdefault(value, {})[category] = n
|
|
return CompositionAnswer(report_id, categories, strata, stored_before=True)
|
|
|
|
|
|
def composition_report(definition: CompositionDefinition, question: Question, result: CompositionAnswer, period,
|
|
generated_at: datetime) -> dict:
|
|
"""The answer as a FHIR R4 `MeasureReport`: the units counted, and a stratifier by category (and by each stratum)."""
|
|
(code,) = definition.units.codes
|
|
|
|
def stratum(value: str, n: int) -> dict:
|
|
return {"value": {"text": value}, "population": [
|
|
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": n}]}
|
|
|
|
stratifiers = [{"code": [{"text": definition.category.value}],
|
|
"stratum": [stratum(c, n) for c, n in sorted(result.categories.items())]}]
|
|
for name, by_value in result.strata.items():
|
|
stratifiers.append({"code": [{"text": name}],
|
|
"stratum": [stratum(v, sum(cs.values())) for v, cs in sorted(by_value.items())]})
|
|
group = {"id": definition.group, "population": [
|
|
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.total},
|
|
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": code}]}, "count": result.total},
|
|
], "stratifier": stratifiers}
|
|
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()})
|
|
return {
|
|
"resourceType": "MeasureReport", "status": "complete", "type": "summary",
|
|
"measure": f"{definition.url}|{definition.version}", "date": generated_at.isoformat(),
|
|
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
|
"extension": extensions, "group": [group],
|
|
}
|