Add TIR bar/threshold lines, Dagoverzicht charts, and hypo/hyper Level-1 charts to PDF export

Closes gitea #14 (PDF part), #15 (PDF part), #16, #17, #18.
This commit is contained in:
2026-08-01 22:33:45 +02:00
parent 00fb81b283
commit 441bb84212
2 changed files with 197 additions and 4 deletions
+145 -3
View File
@@ -21,8 +21,13 @@ from fpdf import FPDF
from fpdf.enums import XPos, YPos
from reporting import (
HIGH,
LOW,
VERY_HIGH,
VERY_LOW,
agp_percentile_bands,
completeness_warning,
detect_events,
gmi_percent,
percent_cv,
sensor_active_percent,
@@ -31,12 +36,46 @@ from reporting import (
SECTION_SUMMARY = "Samenvatting"
SECTION_AGP = "AGP profiel"
SECTION_DAGOVERZICHT = "Dagoverzicht"
SECTION_EVENTS = "Hypo-/hyperevents"
AVAILABLE_SECTIONS = [SECTION_SUMMARY, SECTION_AGP, SECTION_EVENTS]
AVAILABLE_SECTIONS = [SECTION_SUMMARY, SECTION_AGP, SECTION_DAGOVERZICHT, SECTION_EVENTS]
_LINE_KWARGS = {"new_x": XPos.LMARGIN, "new_y": YPos.NEXT}
# Zelfde kleuren als het PALETTE["light"] in ui_common.py — bewust hier
# gedupliceerd (5 hex-waarden) in plaats van ui_common.py te importeren, want
# dat zou een streamlit-dependency in deze module trekken die verder bewust
# vrij van UI-framework-imports is (los te unit-testen, zie moduledocstring).
_MUTED = "#898781"
_TIR_BAND_ORDER = ["very_low", "low", "in_range", "high", "very_high"]
_TIR_BAND_LABELS = {
"very_low": "Zeer laag",
"low": "Laag",
"in_range": "In bereik",
"high": "Hoog",
"very_high": "Zeer hoog",
}
_TIR_COLORS = {
"very_low": "#8b1a1a",
"low": "#d03b3b",
"in_range": "#0ca30c",
"high": "#fab219",
"very_high": "#c76f0a",
}
_THRESHOLD_LINES = [VERY_LOW, LOW, HIGH, VERY_HIGH]
DAGOVERZICHT_MAX_DAYS = 14
def _add_threshold_lines(ax) -> None:
"""Teken de 4 klinische drempellijnen (3.0/3.9/10.0/13.9 mmol/L) op een matplotlib-as.
PDF-tegenhanger van ui_common.add_threshold_lines() voor de Plotly-versie
op de dashboardpagina's (gitea #15) — zelfde 4 waarden, zelfde grijstint.
"""
for value in _THRESHOLD_LINES:
ax.axhline(value, color=_MUTED, linewidth=0.7, linestyle=":")
def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
bands = agp_percentile_bands(glucose)
@@ -45,6 +84,7 @@ def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
ax.fill_between(hours, bands["p5"], bands["p95"], alpha=0.15, color="#2a78d6", label="5e-95e pct")
ax.fill_between(hours, bands["p25"], bands["p75"], alpha=0.3, color="#2a78d6", label="25e-75e pct")
ax.plot(hours, bands["p50"], color="#2a78d6", linewidth=2, label="Mediaan")
_add_threshold_lines(ax)
ax.set_xlabel("Uur van de dag")
ax.set_ylabel("mmol/L")
ax.set_xlim(0, 24)
@@ -58,6 +98,69 @@ def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
return buf.getvalue()
def _tir_bar_figure_png(tir: dict) -> bytes:
"""Gestapelde staafgrafiek van de 5 TIR-banden — PDF-tegenhanger van
ui_common.build_tir_stacked_bar_figure() (gitea #14)."""
fig, ax = plt.subplots(figsize=(7, 1.1))
left = 0.0
for band in _TIR_BAND_ORDER:
value = tir[band]
ax.barh(0, value, left=left, color=_TIR_COLORS[band], label=_TIR_BAND_LABELS[band])
left += value
ax.set_xlim(0, 100)
ax.set_yticks([])
ax.set_xlabel("%")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.75), ncol=5, fontsize=7, frameon=False)
buf = io.BytesIO()
# bbox_inches="tight" i.p.v. fig.tight_layout(): de legend zit buiten de
# axes (bbox_to_anchor met negatieve y), waar tight_layout() niet voor
# kan compenseren — savefig's eigen bbox-berekening kan dat wel.
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def _daily_figure_png(day_df: pd.DataFrame, day_label: str) -> bytes:
"""Eén dag als kleine lijngrafiek — PDF-tegenhanger van de Dagoverzicht-pagina (gitea #16)."""
hours = day_df["timestamp"].dt.hour + day_df["timestamp"].dt.minute / 60
fig, ax = plt.subplots(figsize=(7, 1.4))
ax.plot(hours, day_df["mmol"], color="#2a78d6", linewidth=1.2)
_add_threshold_lines(ax)
ax.set_xlim(0, 24)
ax.set_xticks(range(0, 25, 4))
ax.set_ylabel("mmol/L", fontsize=8)
ax.set_title(day_label, fontsize=9, loc="left")
ax.tick_params(labelsize=7)
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def _event_hour_histogram_png(events: pd.DataFrame, color: str) -> bytes:
"""Aantal events per uur-van-de-dag — PDF-tegenhanger van render_event_level()'s
histogram op de Hypo/Hyper Events-pagina's (gitea #17, #18)."""
hour_counts = events["start"].dt.hour.value_counts().reindex(range(24), fill_value=0).sort_index()
fig, ax = plt.subplots(figsize=(7, 2))
ax.bar(hour_counts.index, hour_counts.to_numpy(), color=color)
ax.set_xlabel("Uur van de dag")
ax.set_ylabel("Aantal events")
ax.set_xlim(-0.5, 23.5)
ax.set_xticks(range(0, 24, 2))
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
mean_mmol = glucose["mmol"].mean()
tir = tir_breakdown_5band(glucose)
@@ -83,6 +186,9 @@ def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
pdf.cell(0, 6, f"In bereik (3.9-10.0 mmol/L): {tir['in_range']:.0f}%", **_LINE_KWARGS)
pdf.cell(0, 6, f"Hoog (10.0-13.9 mmol/L): {tir['high']:.0f}%", **_LINE_KWARGS)
pdf.cell(0, 6, f"Zeer hoog (>13.9 mmol/L): {tir['very_high']:.0f}%", **_LINE_KWARGS)
pdf.ln(2)
png_bytes = _tir_bar_figure_png(tir)
pdf.image(io.BytesIO(png_bytes), w=160)
pdf.ln(4)
@@ -94,7 +200,29 @@ def _add_agp_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
pdf.ln(4)
def _add_events_section(pdf: FPDF, events_summary: dict[str, dict]) -> None:
def _add_dagoverzicht_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
"""Eén dagelijkse mini-grafiek per kalenderdag (gitea #16), max. de meest
recente DAGOVERZICHT_MAX_DAYS dagen — voor langere periodes zou de PDF
anders onwerkbaar lang worden."""
pdf.set_font("Helvetica", "B", 13)
pdf.cell(0, 8, "Dagoverzicht", **_LINE_KWARGS)
df = glucose.copy()
df["date"] = df["timestamp"].dt.date
dates = sorted(df["date"].unique())
if len(dates) > DAGOVERZICHT_MAX_DAYS:
dates = dates[-DAGOVERZICHT_MAX_DAYS:]
pdf.set_font("Helvetica", "I", 9)
pdf.cell(0, 5, f"Beperkt tot de meest recente {DAGOVERZICHT_MAX_DAYS} dagen.", **_LINE_KWARGS)
for day in dates:
day_df = df[df["date"] == day]
png_bytes = _daily_figure_png(day_df, day.strftime("%A %d-%m-%Y"))
pdf.image(io.BytesIO(png_bytes), w=180)
pdf.ln(4)
def _add_events_section(pdf: FPDF, glucose: pd.DataFrame, events_summary: dict[str, dict]) -> None:
pdf.set_font("Helvetica", "B", 13)
pdf.cell(0, 8, "Hypo-/hyperevents", **_LINE_KWARGS)
pdf.set_font("Helvetica", "", 11)
@@ -106,6 +234,18 @@ def _add_events_section(pdf: FPDF, events_summary: dict[str, dict]) -> None:
f"{summary['events_per_week']:.1f}/week",
**_LINE_KWARGS,
)
pdf.ln(2)
# Alleen Level 1 krijgt een grafiek in het PDF-rapport (gitea #17, #18) —
# geen tabel met losse events, de samenvattende cijfers staan al hierboven.
if not glucose.empty:
hypo_events = detect_events(glucose, LOW, "below")
if not hypo_events.empty:
pdf.image(io.BytesIO(_event_hour_histogram_png(hypo_events, _TIR_COLORS["low"])), w=180)
hyper_events = detect_events(glucose, HIGH, "above")
if not hyper_events.empty:
pdf.image(io.BytesIO(_event_hour_histogram_png(hyper_events, _TIR_COLORS["high"])), w=180)
pdf.ln(4)
@@ -135,8 +275,10 @@ def build_report_pdf(
_add_summary_section(pdf, glucose, start, end)
if SECTION_AGP in sections:
_add_agp_section(pdf, glucose)
if SECTION_DAGOVERZICHT in sections:
_add_dagoverzicht_section(pdf, glucose)
if SECTION_EVENTS in sections and events_summary:
_add_events_section(pdf, events_summary)
_add_events_section(pdf, glucose, events_summary)
return bytes(pdf.output())