f183e495fb
How: `linea_de_tiempo_al_corte` is `linea_de_tiempo_al_inicio_del_periodo` with what the timeline held by the question's event cut-off (all of it without one) instead of before the period's start. FHIR's `_label` reads a timeline stratum's labels from its `valores` entries and `resto_etiqueta`. Tests cover CaMa's tumour stratifiers: the facts dbt derives, the surrogate subtype's rules, CAMA_BIRADS_CANCER_INVASOR broken down by them, and the cut-off. Implications: a patient's characteristic learned after the fact that put her in the period (a cancer's stage or subtype, written after its biopsy) can stratify a measure, and stays reproducible through the cut-offs. CaMa publishes eight measures and five strata.
201 lines
12 KiB
Python
201 lines
12 KiB
Python
"""A domain's measures as FHIR R4 `Measure` resources, and their answers as `MeasureReport`s.
|
|
|
|
The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from
|
|
each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as
|
|
extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier
|
|
has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds
|
|
its category as a `component`. A duration reports the units without a value as their own population.
|
|
"""
|
|
|
|
import json
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
|
|
from webapi.compositions import CompositionAnswer, CompositionDefinition
|
|
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
|
|
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
|
|
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
|
|
|
|
SCORING_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-scoring"
|
|
IMPROVEMENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
|
|
GROUP_SYSTEM = f"{CODE_SYSTEM}/grupo-medida"
|
|
STRATIFIER_SYSTEM = f"{CODE_SYSTEM}/estratificador"
|
|
EXCLUDED = "measure-population-exclusion"
|
|
FIGURES = f"{STRUCTURE}/figuras"
|
|
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
|
|
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
|
|
CONTRACT = f"{STRUCTURE}/contrato"
|
|
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
|
|
POPULATION_LABELS = {
|
|
"initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador",
|
|
"denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor",
|
|
EXCLUDED: "Unidades sin valor",
|
|
}
|
|
|
|
|
|
def scoring(definition) -> str:
|
|
"""The FHIR scoring: a composition is a `cohort` (its categories are a stratifier)."""
|
|
if isinstance(definition, CompositionDefinition):
|
|
return "cohort"
|
|
return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion"
|
|
|
|
|
|
def labels(manifest: Path) -> dict[str, tuple[str, str]]:
|
|
"""Each metric's (title, description) in the manifest: `meta.titulo` when the label had to differ."""
|
|
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
|
return {m["name"]: (m["config"].get("meta", {}).get("titulo") or m["label"], (m.get("description") or "").strip())
|
|
for m in metrics}
|
|
|
|
|
|
def fhir_id(definition) -> str:
|
|
"""The measure's id as FHIR allows one (letters, digits, `-` and `.`): `M21_diagnosticados_con_eeg` ->
|
|
`M21-diagnosticados-con-eeg`."""
|
|
return definition.measure_id.replace("_", "-")
|
|
|
|
|
|
def measure_url(definition) -> str:
|
|
return canonical(f"Measure/{fhir_id(definition)}")
|
|
|
|
|
|
def _populations(definition) -> list[dict]:
|
|
"""Each population with the dbt metric that counts it as its criteria."""
|
|
if scoring(definition) == "proportion":
|
|
metrics = {**{c: definition.denominator.metric for c in definition.denominator.codes},
|
|
**{c: definition.numerator.metric for c in definition.numerator.codes},
|
|
**({c: definition.exclusion.metric for c in definition.exclusion.codes}
|
|
if getattr(definition, "exclusion", None) else {})}
|
|
else:
|
|
codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION,
|
|
EXCLUDED]
|
|
metrics = {c: definition.metric for c in codes}
|
|
return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c),
|
|
"criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()]
|
|
|
|
|
|
def measure_resource(definition, title: str, description: str) -> dict:
|
|
"""The `Measure` of a definition: one group per group it publishes, each with its populations and strata."""
|
|
meta = getattr(definition, "meta", {}) or {}
|
|
strata = [{"code": concept(STRATIFIER_SYSTEM, s.name, text=s.spec.get("etiqueta", s.name))}
|
|
for s in definition.strata]
|
|
if isinstance(definition, CompositionDefinition):
|
|
strata.insert(0, {"code": concept(STRATIFIER_SYSTEM, definition.category.value)})
|
|
groups = [{"code": concept(GROUP_SYSTEM, definition.group), "population": _populations(definition),
|
|
**({"stratifier": strata} if strata else {})}]
|
|
groups += [{"code": concept(GROUP_SYSTEM, g.name, g.label), "population": _populations(definition)}
|
|
for g in getattr(definition, "groups", ())]
|
|
extensions = [{"url": CONTRACT, "valueCode": meta.get("contrato", "")},
|
|
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
|
|
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
|
|
category = meta.get("categoria", {})
|
|
extensions += [{"url": CATEGORY_LABEL, "extension": [
|
|
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
|
|
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
|
|
if meta.get("requiere_validacion"):
|
|
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
|
|
resource = {
|
|
"resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition),
|
|
"version": definition.version, "name": definition.metric, "title": title, "status": "active",
|
|
"description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)],
|
|
"scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups,
|
|
}
|
|
if definition.basis:
|
|
resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis)
|
|
if definition.improvement_notation:
|
|
resource["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
|
return resource
|
|
|
|
|
|
def _count(code: str, n: int) -> dict:
|
|
return {"code": concept(POPULATION_SYSTEM, code), "count": n}
|
|
|
|
|
|
def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -> dict:
|
|
cells = {"population": [*(_count(c, counts.denominator) for c in definition.denominator.codes),
|
|
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
|
|
if excluded is not None and getattr(definition, "exclusion", None):
|
|
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
|
|
if counts.proportion is not None:
|
|
cells["measureScore"] = {"value": counts.proportion}
|
|
return cells
|
|
|
|
|
|
def _label(spec: dict, value: str) -> str | None:
|
|
"""A stratum value's label: from `valores` as a map of values to labels, or as a list of entries with `etiqueta`
|
|
(a timeline stratum's), or `resto_etiqueta` for its `resto`."""
|
|
labels_of = spec.get("valores")
|
|
if isinstance(labels_of, dict):
|
|
return labels_of.get(value)
|
|
if isinstance(labels_of, list):
|
|
found = [v.get("etiqueta") for v in labels_of if isinstance(v, dict) and v.get("valor") == value]
|
|
return found[0] if found else (spec.get("resto_etiqueta") if value == spec.get("resto") else None)
|
|
return None
|
|
|
|
|
|
def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict:
|
|
return concept(f"{CODE_SYSTEM}/{stratifier.replace('_', '-')}", value, display)
|
|
|
|
|
|
def _groups(definition, result) -> list[dict]:
|
|
if isinstance(result, CompositionAnswer):
|
|
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [_count("initial-population",
|
|
result.total)]}
|
|
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
|
|
category = definition.category.value
|
|
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
|
|
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
|
|
for c, n in sorted(result.categories.items())]}]
|
|
for name, by_value in result.strata.items():
|
|
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
|
|
"stratum": [{"component": [
|
|
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
|
|
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
|
|
], "population": [_count("initial-population", n)]}
|
|
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
|
|
group["stratifier"] = stratifiers
|
|
return [group]
|
|
if isinstance(result, DurationAnswer):
|
|
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [
|
|
_count("initial-population", result.initial), _count(OBSERVATION, result.n),
|
|
_count(EXCLUDED, result.excluded)]}
|
|
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}]}
|
|
return [group]
|
|
assert isinstance(result, Answer)
|
|
spec_of = {s.name: s.spec for s in definition.strata}
|
|
group = {"code": concept(GROUP_SYSTEM, definition.group), **_proportion_cells(definition, result.total,
|
|
result.excluded)}
|
|
if result.strata:
|
|
group["stratifier"] = [{"code": [concept(STRATIFIER_SYSTEM, name, text=spec_of[name].get("etiqueta"))],
|
|
"stratum": [{"value": _stratum_value(name, value, _label(spec_of[name], value)),
|
|
**_proportion_cells(definition, c)}
|
|
for value, c in sorted(values.items())]}
|
|
for name, values in result.strata.items()]
|
|
groups = [group]
|
|
labels_of = {g.name: g.label for g in getattr(definition, "groups", ())}
|
|
groups += [{"code": concept(GROUP_SYSTEM, name, labels_of.get(name)), **_proportion_cells(definition, counts)}
|
|
for name, counts in result.groups.items()]
|
|
return groups
|
|
|
|
|
|
def measure_report(definition, question, result, period, generated_at: datetime) -> dict:
|
|
"""An answer as a FHIR R4 `MeasureReport` (summary), naming its measure by its absolute canonical."""
|
|
cutoff = getattr(result, "event_cutoff", None) or question.event_cutoff
|
|
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
|
|
if cutoff is not None:
|
|
extensions.append({"url": EVENT_CUTOFF, "valueDate": cutoff.isoformat()})
|
|
if question.knowledge_cutoff is not None:
|
|
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
|
report = {
|
|
"resourceType": "MeasureReport", "id": f"{fhir_id(definition)}-{result.report_id}", "status": "complete",
|
|
"type": "summary", "measure": f"{measure_url(definition)}|{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": _groups(definition, result),
|
|
}
|
|
if definition.improvement_notation:
|
|
report["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
|
return report
|