Files
ISSSTELEON/Core/core/measures.py
T
Roberto Treviño 2fe5301fd1
ci / python (push) Successful in 51m44s
ci / web (push) Successful in 16m59s
CaCu: procedures with their cytology and histology, seven measures, the cytology form's fields
2026-11-30 23:32:01 -06:00

557 lines
24 KiB
Python

"""The measure engine: what a domain's measure counts, evaluated per period over the rows gold
gives (pure, no IO), and the FHIR R4B MeasureReport each evaluation is served as. Each domain
declares its measures in `core.<domain>.measures` (`MEASURES`).
Three kinds, as FHIR scores them:
- proportion: patients in the denominator and, of them, in the numerator; with a Wilson
95% interval;
- composition: patients split by the category of their latest valid fact in the period;
- continuous variable: days per unit, summarized by the median and inclusive quartiles. A
unit still within its horizon without an end isn't measured yet, so it is left out.
Rows are known from `known_at`; an evaluation `as_of` a moment uses only rows known by then
(all of them by default). Durations count to the event cut-off, `as_of`'s day by default.
"""
import functools
import math
import statistics
from collections import defaultdict
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from datetime import UTC, date, datetime
from typing import ClassVar
from fhir.resources.R4B.measurereport import MeasureReport
from core.fhir import EXTENSION, measure_url, stratifier_code
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
IMPROVEMENT = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
Z = 1.959963984540054
NO_DATA = "no_data"
NO_BIOPSY = "no_biopsy"
@dataclass(frozen=True)
class Period:
start: date
end: date # exclusive
@classmethod
def parse(cls, text: str) -> "Period":
"""A semester (`2025-S1`) or a month (`2025-03`)."""
year, part = text.split("-")
if part.startswith("S"):
first = 1 if part == "S1" else 7
return cls(
date(int(year), first, 1),
date(int(year), 7, 1) if first == 1 else date(int(year) + 1, 1, 1),
)
month = int(part)
return cls(date(int(year), month, 1),
date(int(year) + month // 12, month % 12 + 1, 1)) # fmt: skip
@functools.cached_property
def _iso(self) -> tuple[str, str]:
return self.start.isoformat(), self.end.isoformat()
def __contains__(self, day) -> bool:
if isinstance(day, str): # ISO days sort as the days they name
start, end = self._iso
return start <= day[:10] < end
return day is not None and self.start <= as_day(day) < self.end
def as_day(value) -> date | None:
"""A day, from a date, a datetime or ISO text."""
if value is None or isinstance(value, date) and not isinstance(value, datetime):
return value
if isinstance(value, datetime):
return value.date()
return _iso_day(str(value)[:10])
@functools.lru_cache(maxsize=65536)
def _iso_day(text: str) -> date:
"""Parsed once per day: every period scans every row."""
return date.fromisoformat(text)
def _moment(value) -> datetime | None:
"""A moment; one stored without an offset is UTC (how the platform stores them)."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return found if found.tzinfo else found.replace(tzinfo=UTC)
def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
"""`low-high` of the group her age at `at` falls in, or below/above them all."""
birth = as_day(birth)
if birth is None:
return NO_DATA
age = at.year - birth.year - ((at.month, at.day) < (birth.month, birth.day))
for low, high in groups:
if low <= age <= high:
return f"{low}-{high}"
lowest, highest = groups[0][0], groups[-1][1]
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
# A stratum: its name and the value a row takes in a period; a list when it takes several (its
# groups overlap) or none.
Stratum = tuple[str, Callable[[dict, "Period"], "str | list[str]"]]
def groups(value: "str | list[str]") -> list[str]:
return [value] if isinstance(value, str) else value
@dataclass(frozen=True)
class Result:
populations: dict[str, int]
score: float | None = None
score_extensions: dict[str, float] = field(default_factory=dict)
unit: str | None = None
strata: dict[str, dict[str, dict[str, int]]] = field(default_factory=dict)
# A stratum crossed with the category: (its name, "category") -> (value, category) ->
# counts (a composition by clinical scenario and result, say).
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
default_factory=dict
)
# A stratum value's own score: (stratum, value) -> score, its extensions and unit.
scores: dict[tuple[str, str], tuple[float, dict[str, float], str]] = field(default_factory=dict)
def wilson(k: int, n: int) -> tuple[float, float]:
p = k / n
centre, half = p + Z * Z / (2 * n), Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n))
low, high = (centre - half) / (1 + Z * Z / n), (centre + half) / (1 + Z * Z / n)
return round(max(low, 0.0), 12), round(min(high, 1.0), 12)
@dataclass(frozen=True)
class Proportion:
"""Units with a row dated in the period that meets `denominator` and, of them, those
with such a row that also meets `numerator`; with a Wilson 95% interval. With `order`, a
unit counts with one row only, the one it ranks highest. `levels` are other numerators
over the same denominator: the stratifier `level`."""
numerator: Callable[[dict], bool]
strata: tuple[Stratum, ...] = ()
denominator: Callable[[dict], bool] = lambda row: True
order: Callable[[dict], tuple] | None = None
levels: tuple[tuple[str, Callable[[dict], bool]], ...] = ()
unit: str = "person_id"
date: str = "sample_date"
kind: str = "proportion"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
mine = [r for r in rows if r[self.date] in period and self.denominator(r)]
if self.order:
mine = list({r[self.unit]: r for r in sorted(mine, key=self.order)}.values())
den = {r[self.unit]: r for r in mine}
num = {r[self.unit] for r in mine if self.numerator(r)}
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
strata = {}
for name, stratum in self.strata:
values: dict[str, dict[str, int]] = {}
for unit, row in den.items():
for value in groups(stratum(row, period)):
cell = values.setdefault(
value, {"initial-population": 0, "denominator": 0, "numerator": 0}
)
cell["initial-population"] += 1
cell["denominator"] += 1
cell["numerator"] += unit in num
strata[name] = values
if self.levels and den:
strata["level"] = {
level: {**found, "numerator": len({r[self.unit] for r in mine if meets(r)})}
for level, meets in self.levels
}
if not den:
return Result(found, strata=strata)
low, high = wilson(len(num), len(den))
return Result(found, len(num) / len(den), {"ic-bajo": low, "ic-alto": high}, strata=strata)
def desc(value) -> tuple:
"""A sort key on which a value ranks above a missing one."""
return (value is not None, value)
@dataclass(frozen=True)
class Composition:
"""Units by the category of one row each: of a unit's rows dated in the period (that meet
`where`), the one `order` ranks highest. Only units whose chosen row is `admit`ted count.
The chosen row's `category` is the first stratifier; `strata` add others."""
order: Callable[[dict], tuple]
category: Callable[[dict], str]
admit: Callable[[dict], bool] = lambda row: True
where: Callable[[dict], bool] = lambda row: True
strata: tuple[Stratum, ...] = ()
unit: str = "person_id"
date: str = "sample_date"
kind: str = "composition"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
chosen: dict[str, dict] = {}
for row in rows:
if row[self.date] in period and self.where(row):
unit = row[self.unit]
if unit not in chosen or self.order(row) > self.order(chosen[unit]):
chosen[unit] = row
chosen = {u: r for u, r in chosen.items() if self.admit(r)}
strata: dict[str, dict[str, dict[str, int]]] = {}
for name, stratum in (("category", lambda row, p: self.category(row)), *self.strata):
values: dict[str, dict[str, int]] = {}
for row in chosen.values():
for value in groups(stratum(row, period)):
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
strata[name] = values
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {}
for name, stratum in self.strata: # each also by category
pairs: dict[tuple[str, str], dict[str, int]] = {}
for row in chosen.values():
for value in groups(stratum(row, period)):
key = (value, self.category(row))
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
crossed[(name, "category")] = pairs
n = len(chosen)
return Result({"initial-population": n, "measure-observation": n}, strata=strata,
crossed=crossed) # fmt: skip
def quartiles(values: list[float]) -> tuple[float, dict[str, float]]:
"""The median, and the quartiles as score extensions."""
if len(values) == 1:
return values[0], {"q1": values[0], "q3": values[0]}
q1, median, q3 = statistics.quantiles(values, n=4, method="inclusive")
return median, {"q1": q1, "q3": q3}
@dataclass(frozen=True)
class Duration:
"""Days from `start` to `end` per unit (`value`), within `horizon` days. A unit whose
interval `ended` (default: has an `end`) without a value, like a sample reported
unsatisfactory, is in the initial population but not measured."""
value: str
end: str
start: str
horizon: int
units: Callable[[dict], bool] = lambda row: True
ended: str | None = None
strata: tuple[Stratum, ...] = ()
unit: str = "sample_id"
date: str = "sample_date"
kind: str = "continuous-variable"
# Keeps each unit's last row, then reads only those dated in the period.
dated_only: ClassVar[bool] = True
one_per_unit: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
measured, initial = [], 0
grouped: dict[str, dict[str, list[float]]] = {name: {} for name, _ in self.strata}
for row in {r[self.unit]: r for r in rows}.values():
if row[self.date] not in period or not self.units(row):
continue
end = as_day(row.get(self.end))
has = row.get(self.value) is not None and end is not None and end <= cutoff
if has:
measured.append(float(row[self.value]))
for name, stratum in self.strata:
for value in groups(stratum(row, period)):
grouped[name].setdefault(value, []).append(measured[-1])
stop = as_day(row.get(self.ended)) if self.ended else None
done = has or (stop is not None and stop <= cutoff)
pending = not done and (cutoff - as_day(row[self.start])).days < self.horizon
initial += not pending
found = {"initial-population": initial, "measure-observation": len(measured)}
if not measured:
return Result(found)
median, spread = quartiles(measured)
return Result(
found, median, spread, unit="d",
strata={name: {v: {"measure-observation": len(days)} for v, days in values.items()}
for name, values in grouped.items()},
scores={(name, v): (*quartiles(days), "d")
for name, values in grouped.items() for v, days in values.items()},
) # fmt: skip
@dataclass(frozen=True)
class RiskBand:
"""Patients indexed in the period, by the band their risk falls in (NO_DATA unscored):
`bands` are (name, upper cut), the last one's cut None."""
bands: tuple[tuple[str, float | None], ...]
kind: str = "composition"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
bands: dict[str, dict[str, int]] = {}
mine = [r for r in rows if r["index_date"] in period]
for row in mine:
band = NO_DATA
if (p := row.get("probability")) is not None:
band = next(name for name, cut in self.bands if cut is None or p < cut)
bands.setdefault(band, {"initial-population": 0})["initial-population"] += 1
n = len(mine)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": bands}) # fmt: skip
@dataclass(frozen=True)
class AtEnd:
"""The units on the books at a period's end: entered (`entry`) before it ended and not
gone (`exit`) before it began. Each is in the latest of `states` (name, date column, in
order) it reached before the end."""
entry: str
exit: str
states: tuple[tuple[str, str], ...]
unit: str = "person_id"
def units(self, rows: list[dict], period: Period) -> dict[str, tuple[dict, str]]:
found = {}
for row in rows:
entry, gone = as_day(row.get(self.entry)), as_day(row.get(self.exit))
if entry is None or entry >= period.end or (gone is not None and gone < period.start):
continue
reached = [n for n, c in self.states
if (d := as_day(row.get(c))) is not None and d < period.end] # fmt: skip
if reached:
found[row[self.unit]] = (row, reached[-1])
return found
def reached(row: dict, column: str, period: Period) -> bool:
"""A date reached by the period's end."""
day = as_day(row.get(column))
return day is not None and day < period.end
@dataclass(frozen=True)
class StatusProportion:
"""Of the units on the books at the end (`population`) that meet `denominator`, those
that meet `numerator`; both see the unit's row, its state and the period. Strata count
every unit on the books, so a stratum with none in the denominator still shows."""
population: AtEnd
denominator: Callable[[dict, str, Period], bool]
numerator: Callable[[dict, str, Period], bool]
strata: tuple[Stratum, ...] = ()
kind: str = "proportion"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = self.population.units(rows, period)
den = {u for u, (r, s) in units.items() if self.denominator(r, s, period)}
num = {u for u in den if self.numerator(*units[u], period)}
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
strata = {}
for name, stratum in self.strata:
values: dict[str, dict[str, int]] = {}
for unit, (row, _) in units.items():
cell = values.setdefault(stratum(row, period), {
"initial-population": 0, "denominator": 0, "numerator": 0}) # fmt: skip
cell["initial-population"] += unit in den
cell["denominator"] += unit in den
cell["numerator"] += unit in num
strata[name] = values
if not den:
return Result(found, strata=strata)
low, high = wilson(len(num), len(den))
return Result(found, len(num) / len(den), {"ic-bajo": low, "ic-alto": high}, strata=strata)
@dataclass(frozen=True)
class StatusComposition:
"""The units on the books at the end, by their state; only `admit`ted states count."""
population: AtEnd
admit: Callable[[str], bool] = lambda state: True
kind: str = "composition"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
states = [s for _, s in self.population.units(rows, period).values() if self.admit(s)]
categories: dict[str, dict[str, int]] = {}
for state in states:
categories.setdefault(state, {"initial-population": 0})["initial-population"] += 1
n = len(states)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": categories}) # fmt: skip
@dataclass(frozen=True)
class StatusDuration:
"""Days (`value`) per unit on the books at the end, for those whose interval ended
(`end`) before the period's end and by the cut-off; every unit on the books is in the
initial population."""
population: AtEnd
value: str
end: str
kind: str = "continuous-variable"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = self.population.units(rows, period)
measured = [float(r[self.value]) for r, _ in units.values()
if r.get(self.value) is not None and reached(r, self.end, period)
and as_day(r[self.end]) <= cutoff] # fmt: skip
found = {"initial-population": len(units), "measure-observation": len(measured)}
if not measured:
return Result(found)
if len(measured) == 1:
q1 = median = q3 = measured[0]
else:
q1, median, q3 = statistics.quantiles(measured, n=4, method="inclusive")
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
Rule = (Proportion | Composition | Duration | RiskBand | StatusProportion | StatusComposition
| StatusDuration) # fmt: skip
@dataclass(frozen=True)
class Measure:
id: str
title: str
rows: str # which gold rows it reads (see persistance.measures)
rule: Rule
improvement: str | None = None
version: str = "1.0.0"
periods: tuple[str, ...] = ("semester", "month")
group: str = "TOTAL"
params: dict = field(default_factory=dict) # bound into the read of its rows
known: str = "known_at" # when a row's unit became known: before then it isn't counted
# Facts a row carries that became known apart from the row itself: their `known_at`
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
# The same by the event cutoff: a date column -> the columns it dates.
dated: dict[str, tuple[str, ...]] = field(default_factory=dict)
description: str | None = None
def evaluate(
measure: Measure,
rows: Iterable[dict],
period: Period,
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> Result:
"""The measure over the rows known `as_of` (all by default) for one period; durations
count to `event_cutoff` (default: `as_of`'s day, or today)."""
as_of = _moment(as_of)
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
if measure.dated:
rows = [{**row, **dict.fromkeys(c for day, cols in measure.dated.items()
if (as_day(row.get(day)) or cutoff) > cutoff
for c in (day, *cols))} for row in rows] # fmt: skip
if as_of is None: # every row and fact is known
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
def known(column: str, row: dict) -> bool:
return as_of is None or (_moment(row.get(column)) or as_of) <= as_of
found = []
for row in rows:
if known(measure.known, row):
unknown = [c for k, cols in measure.facts.items() if not known(k, row) for c in cols]
found.append({**row, **dict.fromkeys(unknown)} if unknown else row)
return measure.rule.evaluate(found, period, cutoff)
def evaluate_periods(
measure: Measure,
rows: Iterable[dict],
periods: list[Period],
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> list[Result]:
"""`evaluate` for each period. A rule that reads only the rows dated in the period gets
just those, in their order: the rows are indexed by month once (periods are whole
months), not scanned once per period. One that keeps a row per unit first gets them
already kept."""
rule = measure.rule
rows = rows if isinstance(rows, list) else list(rows)
if as_of is not None or not getattr(rule, "dated_only", False):
return [evaluate(measure, rows, p, as_of, event_cutoff) for p in periods]
if getattr(rule, "one_per_unit", False): # the same for every period: done once
rows = list({row[rule.unit]: row for row in rows}.values())
months: dict[tuple[int, int], list[int]] = defaultdict(list)
for i, row in enumerate(rows):
if (day := as_day(row[rule.date])) is not None:
months[day.year, day.month].append(i)
found = []
for period in periods:
mine = sorted(i for (y, m), ids in months.items() if date(y, m, 1) in period for i in ids)
found.append(evaluate(measure, [rows[i] for i in mine], period, None, event_cutoff))
return found
def _population(code: str, count: int) -> dict:
return {"code": {"coding": [{"system": POPULATION, "code": code}]}, "count": count}
def _score(value: float, extensions: dict[str, float], unit: str | None) -> dict:
return {
"value": value,
**({"unit": unit} if unit else {}),
"extension": [{"url": EXTENSION + k, "valueDecimal": v} for k, v in extensions.items()],
}
def report(
measure: Measure, period: Period, result: Result, as_of: datetime | None
) -> MeasureReport:
"""The evaluation as a FHIR R4B MeasureReport (validated when built)."""
group: dict = {
"id": measure.group,
"population": [_population(c, n) for c, n in result.populations.items()],
}
if result.score is not None:
group["measureScore"] = _score(result.score, result.score_extensions, result.unit)
elif measure.rule.kind == "composition": # a cohort scores its count
group["measureScore"] = {"value": result.populations["initial-population"]}
if result.strata:
group["stratifier"] = [
{"id": name, "code": [stratifier_code(name)],
"stratum": [{"value": {"text": value},
"population": [_population(c, n) for c, n in cells.items()],
**({"measureScore": _score(*result.scores[name, value])}
if (name, value) in result.scores else {})}
for value, cells in sorted(values.items())]}
for name, values in result.strata.items()
] + [
{"id": f"{a}-{b}", "code": [stratifier_code(a), stratifier_code(b)],
"stratum": [{"component": [{"code": stratifier_code(a), "value": {"text": va}},
{"code": stratifier_code(b), "value": {"text": vb}}],
"population": [_population(c, n) for c, n in cells.items()]}
for (va, vb), cells in sorted(values.items())]}
for (a, b), values in result.crossed.items()
] # fmt: skip
found = {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary", # with no score when nothing in the period could be measured
"measure": f"{measure_url(measure.id)}|{measure.version}",
"period": {"start": period.start.isoformat(),
"end": date.fromordinal(period.end.toordinal() - 1).isoformat()},
"date": datetime.now().astimezone().isoformat(),
"group": [group],
} # fmt: skip
if as_of is not None:
found["extension"] = [{"url": EXTENSION + "corte-conocimiento",
"valueDateTime": _moment(as_of).isoformat()}] # fmt: skip
if measure.improvement:
found["improvementNotation"] = {"coding": [{"system": IMPROVEMENT,
"code": measure.improvement}]} # fmt: skip
return MeasureReport.model_validate(found)