1d52da79e4
The code systems, value sets and the extensions (cut-offs, report id, interval, quartiles) each wrote the domain by hand. They now derive from webapi.fhir_base, a leaf module so metrics and durations can use it without a cycle. The default is unchanged; the WebApp still reads the same URLs by exact match, so changing the domain goes to both. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
301 lines
15 KiB
Python
301 lines
15 KiB
Python
"""A duration answered on request: the days each unit takes from one fact to the next, summarized by quartiles.
|
|
|
|
The definition is a simple metric of dbt's semantic layer (the units counted) whose `meta` says `scoring:
|
|
continuous-variable` and gives the observation rule (`observacion`): the column with each unit's days, the dates the
|
|
cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't passed by the event cut-off isn't
|
|
measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in
|
|
dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`).
|
|
|
|
The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. With a population at
|
|
the period's end (`webapi.metrics.StatusAtEnd`), a unit's interval has a value only if it ended by the period's end.
|
|
"""
|
|
|
|
import dataclasses
|
|
import hashlib
|
|
import json
|
|
from collections.abc import Iterable
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import Integer, Select, String, and_, case, cast, column, func, literal, not_, null, select, table, true
|
|
|
|
from webapi.fhir_base import STRUCTURE
|
|
from webapi.metrics import (
|
|
AGGREGATION_VERSION,
|
|
EVENT_CUTOFF,
|
|
HISTORY_ENTRY,
|
|
KNOWLEDGE_CUTOFF,
|
|
POPULATION_SYSTEM,
|
|
MeasureQueries,
|
|
Population,
|
|
Question,
|
|
StatusAtEnd,
|
|
_population,
|
|
_semantic_model_of,
|
|
key_of,
|
|
rule_values,
|
|
)
|
|
|
|
OBSERVATION = "measure-observation"
|
|
LOADS = table("carga", column("inicio"), column("fin"))
|
|
DAYS = table("dim_fecha", column("fecha"), column("dia_num"))
|
|
|
|
|
|
def inclusive_quartiles(values) -> Select:
|
|
"""(n, q1, median, q3) of a subquery's `numero`, by the inclusive method in ANSI SQL.
|
|
|
|
The quartile `q` is at position `(n - 1) q` of the sorted values (from 0), interpolating between its two
|
|
neighbors, as `statistics.quantiles(method="inclusive")`; with one value, the three are it. Window functions,
|
|
`CAST` and `CASE` only: the same SQL on every engine.
|
|
"""
|
|
ranked = select(values.c.numero,
|
|
(func.row_number().over(order_by=values.c.numero) - 1).label("i"),
|
|
func.count().over().label("n")).subquery("ordenados")
|
|
cells = []
|
|
for name, q in (("q1", 0.25), ("mediana", 0.5), ("q3", 0.75)):
|
|
position = (ranked.c.n - 1) * q
|
|
floor = cast(position, Integer)
|
|
fraction = position - floor
|
|
cells.append((func.sum(case((ranked.c.i == floor, ranked.c.numero * (1 - fraction)), else_=0.0))
|
|
+ func.sum(case((ranked.c.i == floor + 1, ranked.c.numero * fraction), else_=0.0))).label(name))
|
|
return select(func.count(ranked.c.numero).label("n"), *cells)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Observation:
|
|
value: str
|
|
dated_at: tuple[str, ...]
|
|
known_at: tuple[str, ...]
|
|
horizon_rule: str | None
|
|
start_day: str
|
|
horizon_days: int | None = None # a fixed horizon, when the model used the same one to find the next fact
|
|
|
|
def horizon(self, values: dict) -> int:
|
|
return self.horizon_days if self.horizon_rule is None else values[self.horizon_rule]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class DurationDefinition:
|
|
"""A duration, shaped so `MeasureQueries` can build its period and cut-offs."""
|
|
|
|
url: str
|
|
version: str
|
|
metric: str
|
|
relation: str
|
|
model_checksum: str
|
|
time_dimension: str
|
|
dimensions: dict[str, str]
|
|
units: Population
|
|
observation: Observation
|
|
group: str
|
|
basis: str
|
|
rules: dict[str, str]
|
|
improvement_notation: str | None = None
|
|
strata: tuple = ()
|
|
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
|
|
|
|
|
|
def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]:
|
|
"""The simple metrics of the manifest whose `meta` declares a duration, 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") != "continuous-variable":
|
|
continue
|
|
model = _semantic_model_of(metric, semantic)
|
|
node = models[model["depends_on"]["nodes"][0]]
|
|
rule = meta["observacion"]
|
|
definitions[meta["measure_url"]] = DurationDefinition(
|
|
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),
|
|
observation=Observation(rule["valor"], tuple(rule.get("fechada_en", ())), tuple(rule.get("conocida_en", ())),
|
|
rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"],
|
|
int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None),
|
|
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
|
improvement_notation=meta.get("improvement_notation"), population=StatusAtEnd.of(meta.get("poblacion")),
|
|
meta=meta,
|
|
)
|
|
return definitions
|
|
|
|
|
|
class DurationQueries(MeasureQueries):
|
|
"""Each unit of the period: measured or not yet, and its days if it has them."""
|
|
|
|
def __init__(self, definition: DurationDefinition, question: Question, rule_values: dict, period_table):
|
|
super().__init__(definition, question, rule_values, period_table)
|
|
o = definition.observation
|
|
for name in {definition.dimensions[n] for n in (o.value, o.start_day, *o.dated_at)} - set(self.events.c.keys()):
|
|
self.events.append_column(column(name))
|
|
|
|
def _has_value(self):
|
|
o, q = self.d.observation, self.q
|
|
conditions = [self._column(o.value).is_not(None)]
|
|
conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at]
|
|
if self.status is not None:
|
|
# Counted at the period's end: the interval has to have ended by then.
|
|
conditions += [self._column(n) < self.events.c.periodo_fin for n in o.dated_at]
|
|
if q.knowledge_cutoff is not None:
|
|
conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at]
|
|
return and_(*conditions)
|
|
|
|
def per_unit(self):
|
|
"""One row per unit in the period: `unidad`, `numero` (its days, or null) and whether it's still `pendiente`."""
|
|
o = self.d.observation
|
|
cutoff_day = select(DAYS.c.dia_num).where(DAYS.c.fecha == self.q.event_cutoff.isoformat()).scalar_subquery()
|
|
has_value = self._has_value()
|
|
pending = and_(not_(has_value),
|
|
cutoff_day - self._column(o.start_day) < o.horizon(self.values))
|
|
where = self._in_question()
|
|
units = self._filter(self.d.units)
|
|
if units is not None:
|
|
where = and_(where, units)
|
|
unit = self.events.c[self.d.units.measure_expr]
|
|
return (select(unit.label("unidad"), case((has_value, self._column(o.value)), else_=null()).label("numero"),
|
|
case((pending, 1), else_=0).label("pendiente"))
|
|
.select_from(self._from(with_strata=False)).where(where).distinct().subquery("por_unidad"))
|
|
|
|
def summary(self) -> Select:
|
|
units = self.per_unit()
|
|
measured = select(units.c.numero).where(units.c.numero.is_not(None)).subquery("medidos")
|
|
quartiles = inclusive_quartiles(measured).subquery("cuartiles")
|
|
initial = select(func.count(units.c.unidad).label("inicial")).where(units.c.pendiente == 0).subquery("inicial")
|
|
# Two one-row subqueries side by side.
|
|
return (select(initial.c.inicial, quartiles.c.n, quartiles.c.q1, quartiles.c.mediana, quartiles.c.q3)
|
|
.select_from(initial.join(quartiles, true())))
|
|
|
|
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
|
|
units = self.per_unit()
|
|
(initial,) = self.d.units.codes
|
|
for code, where, number in ((initial, units.c.pendiente == 0, null()),
|
|
(OBSERVATION, units.c.numero.is_not(None), units.c.numero)):
|
|
yield unit_model, select(
|
|
literal(report_id).label("report_id"), literal(self.d.group).label("grupo"),
|
|
cast(units.c.unidad, String(64)).label("unidad_id"),
|
|
literal(f"{self.d.measure_id}.{code}").label("resultado_id"),
|
|
(units.c.unidad if self.d.basis == "paciente" else literal(None)).label("pac_id"),
|
|
cast(number, unit_model.__table__.c.numero.type).label("numero"),
|
|
).where(where)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class DurationAnswer:
|
|
report_id: int
|
|
initial: int
|
|
n: int
|
|
q1: float | None
|
|
median: float | None
|
|
q3: float | None
|
|
stored_before: bool
|
|
event_cutoff: date | None = None # the one it was computed at: the question's, or the last load's day
|
|
|
|
@property
|
|
def excluded(self) -> int:
|
|
return self.initial - self.n
|
|
|
|
|
|
def last_load_day(queries) -> date | None:
|
|
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish."""
|
|
_, ((last,),) = queries.rows(select(func.max(func.coalesce(LOADS.c.fin, LOADS.c.inicio))))
|
|
return None if last is None else date.fromisoformat(str(last)[:10])
|
|
|
|
|
|
def answer_duration(project: str, definition: DurationDefinition, question: Question, *, parameters, periods,
|
|
history, queries, allow_undecided: bool = False, now: datetime | None = None) -> DurationAnswer:
|
|
"""The stored answer, or a new one: the database decides each unit, counts, takes the quartiles and stores."""
|
|
if question.event_cutoff is None:
|
|
question = dataclasses.replace(question, event_cutoff=last_load_day(queries))
|
|
values = rule_values(parameters, definition, allow_undecided)
|
|
if definition.observation.horizon_rule is None:
|
|
values["horizonte_dias"] = definition.observation.horizon_days
|
|
key, key_sha = key_of(definition, question, values)
|
|
models = import_module(f"core.{project}.indicadores.models")
|
|
stored = history.find(definition.url, key_sha)
|
|
if stored is not None:
|
|
return dataclasses.replace(_from_stored(definition, stored, queries, models.MeasureReportUnidad),
|
|
event_cutoff=question.event_cutoff)
|
|
|
|
period = periods.get(question.period_id)
|
|
if period is None:
|
|
raise LookupError(f"dim_periodo has no period {question.period_id!r}")
|
|
sql = DurationQueries(definition, question, values, periods.model.__table__)
|
|
_, ((initial, n, q1, median, q3),) = queries.rows(sql.summary())
|
|
(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, initial, n, q1, median, q3]).encode()).hexdigest(),
|
|
)
|
|
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
|
|
models.MeasureReportUnidadEstrato))
|
|
return DurationAnswer(report_id, initial, n, *_numbers(n, q1, median, q3), stored_before=False,
|
|
event_cutoff=question.event_cutoff)
|
|
|
|
|
|
def _numbers(n, q1, median, q3):
|
|
return (None, None, None) if not n else (float(q1), float(median), float(q3))
|
|
|
|
|
|
def _from_stored(definition: DurationDefinition, report_id: int, queries, unit_model) -> DurationAnswer:
|
|
"""A stored duration read back from its units: the initial ones counted, the quartiles of their days."""
|
|
u = unit_model.__table__.c
|
|
initial = f"{definition.measure_id}.{definition.units.codes[0]}"
|
|
observed = select(u.numero).where(u.report_id == report_id, u.resultado_id == f"{definition.measure_id}.{OBSERVATION}")
|
|
_, ((n, q1, median, q3),) = queries.rows(inclusive_quartiles(observed.subquery("medidos")))
|
|
_, ((count,),) = queries.rows(select(func.count()).where(u.report_id == report_id, u.resultado_id == initial))
|
|
return DurationAnswer(report_id, count, n, *_numbers(n, q1, median, q3), stored_before=True)
|
|
|
|
|
|
def duration_report(definition: DurationDefinition, question: Question, result: DurationAnswer, period,
|
|
generated_at: datetime) -> dict:
|
|
"""The answer as a FHIR R4 `MeasureReport`: the units measurable and measured, the median as the score, and the
|
|
quartiles as its components."""
|
|
group = {"id": definition.group, "population": [
|
|
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": "initial-population"}]}, "count": result.initial},
|
|
{"code": {"coding": [{"system": POPULATION_SYSTEM, "code": OBSERVATION}]}, "count": result.n},
|
|
]}
|
|
if result.median is not None:
|
|
group["measureScore"] = {"value": result.median, "unit": "d",
|
|
"extension": [{"url": f"{STRUCTURE}/q1",
|
|
"valueDecimal": result.q1},
|
|
{"url": f"{STRUCTURE}/q3",
|
|
"valueDecimal": result.q3}]}
|
|
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id},
|
|
{"url": EVENT_CUTOFF, "valueDate": (result.event_cutoff or 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(),
|
|
"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
|