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 @classmethod def parse(cls, text: str) -> "Period": 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)) @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): 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: 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: return date.fromisoformat(text) def _moment(value) -> datetime | None: 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: 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}+" Stratum = tuple[str, Callable[[dict, "Period"], str]] @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) crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = 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: numerator: Callable[[dict], bool] strata: tuple[Stratum, ...] = () denominator: Callable[[dict], bool] = lambda row: True unit: str = "person_id" date: str = "sample_date" kind: str = "proportion" 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)] 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(): cell = values.setdefault( stratum(row, period), {"initial-population": 0, "denominator": 0, "numerator": 0}, ) cell["initial-population"] += 1 cell["denominator"] += 1 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) def desc(value) -> tuple: return (value is not None, value) @dataclass(frozen=True) class Composition: 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" 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(): value = 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: pairs: dict[tuple[str, str], dict[str, int]] = {} for row in chosen.values(): key = (stratum(row, period), 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 ) @dataclass(frozen=True) class Duration: value: str end: str start: str horizon: int units: Callable[[dict], bool] = lambda row: True ended: str | None = None unit: str = "sample_id" date: str = "sample_date" kind: str = "continuous-variable" 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) 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])) 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) 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") @dataclass(frozen=True) class RiskBand: 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} ) @dataclass(frozen=True) class AtEnd: 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 ] if reached: found[row[self.unit]] = (row, reached[-1]) return found def reached(row: dict, column: str, period: Period) -> bool: day = as_day(row.get(column)) return day is not None and day < period.end @dataclass(frozen=True) class StatusProportion: 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}, ) 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: 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} ) @dataclass(frozen=True) class StatusDuration: 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) ] 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 ) @dataclass(frozen=True) class Measure: id: str title: str rows: str 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) known: str = "known_at" facts: dict[str, tuple[str, ...]] = field(default_factory=dict) def evaluate( measure: Measure, rows: Iterable[dict], period: Period, as_of: datetime | None = None, event_cutoff: date | None = None, ) -> Result: as_of = _moment(as_of) cutoff = event_cutoff or (as_of or datetime.now(UTC)).date() if as_of is None: 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]: 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): 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 report( measure: Measure, period: Period, result: Result, as_of: datetime | None ) -> MeasureReport: group: dict = { "id": measure.group, "population": [_population(c, n) for c, n in result.populations.items()], } if result.score is not None: group["measureScore"] = { "value": result.score, **({"unit": result.unit} if result.unit else {}), "extension": [ {"url": EXTENSION + k, "valueDecimal": v} for k, v in result.score_extensions.items() ], } elif measure.rule.kind == "composition": 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()], } 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() ] found = { "resourceType": "MeasureReport", "status": "complete", "type": "summary", "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], } if as_of is not None: found["extension"] = [ {"url": EXTENSION + "corte-conocimiento", "valueDateTime": as_of.isoformat()} ] if measure.improvement: found["improvementNotation"] = { "coding": [{"system": IMPROVEMENT, "code": measure.improvement}] } return MeasureReport.model_validate(found)