Merge pull request 'Add TIR bar/threshold lines, Dagoverzicht + hypo/hyper Level-1 charts to PDF (#14, #15, #16, #17, #18)' (#23) from dev into main
This commit was merged in pull request #23.
This commit is contained in:
+145
-3
@@ -21,8 +21,13 @@ from fpdf import FPDF
|
|||||||
from fpdf.enums import XPos, YPos
|
from fpdf.enums import XPos, YPos
|
||||||
|
|
||||||
from reporting import (
|
from reporting import (
|
||||||
|
HIGH,
|
||||||
|
LOW,
|
||||||
|
VERY_HIGH,
|
||||||
|
VERY_LOW,
|
||||||
agp_percentile_bands,
|
agp_percentile_bands,
|
||||||
completeness_warning,
|
completeness_warning,
|
||||||
|
detect_events,
|
||||||
gmi_percent,
|
gmi_percent,
|
||||||
percent_cv,
|
percent_cv,
|
||||||
sensor_active_percent,
|
sensor_active_percent,
|
||||||
@@ -31,12 +36,46 @@ from reporting import (
|
|||||||
|
|
||||||
SECTION_SUMMARY = "Samenvatting"
|
SECTION_SUMMARY = "Samenvatting"
|
||||||
SECTION_AGP = "AGP profiel"
|
SECTION_AGP = "AGP profiel"
|
||||||
|
SECTION_DAGOVERZICHT = "Dagoverzicht"
|
||||||
SECTION_EVENTS = "Hypo-/hyperevents"
|
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}
|
_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:
|
def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
|
||||||
bands = agp_percentile_bands(glucose)
|
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["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.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")
|
ax.plot(hours, bands["p50"], color="#2a78d6", linewidth=2, label="Mediaan")
|
||||||
|
_add_threshold_lines(ax)
|
||||||
ax.set_xlabel("Uur van de dag")
|
ax.set_xlabel("Uur van de dag")
|
||||||
ax.set_ylabel("mmol/L")
|
ax.set_ylabel("mmol/L")
|
||||||
ax.set_xlim(0, 24)
|
ax.set_xlim(0, 24)
|
||||||
@@ -58,6 +98,69 @@ def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
|
|||||||
return buf.getvalue()
|
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:
|
def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
|
||||||
mean_mmol = glucose["mmol"].mean()
|
mean_mmol = glucose["mmol"].mean()
|
||||||
tir = tir_breakdown_5band(glucose)
|
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"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"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.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)
|
pdf.ln(4)
|
||||||
|
|
||||||
|
|
||||||
@@ -94,7 +200,29 @@ def _add_agp_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
|
|||||||
pdf.ln(4)
|
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.set_font("Helvetica", "B", 13)
|
||||||
pdf.cell(0, 8, "Hypo-/hyperevents", **_LINE_KWARGS)
|
pdf.cell(0, 8, "Hypo-/hyperevents", **_LINE_KWARGS)
|
||||||
pdf.set_font("Helvetica", "", 11)
|
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",
|
f"{summary['events_per_week']:.1f}/week",
|
||||||
**_LINE_KWARGS,
|
**_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)
|
pdf.ln(4)
|
||||||
|
|
||||||
|
|
||||||
@@ -135,8 +275,10 @@ def build_report_pdf(
|
|||||||
_add_summary_section(pdf, glucose, start, end)
|
_add_summary_section(pdf, glucose, start, end)
|
||||||
if SECTION_AGP in sections:
|
if SECTION_AGP in sections:
|
||||||
_add_agp_section(pdf, glucose)
|
_add_agp_section(pdf, glucose)
|
||||||
|
if SECTION_DAGOVERZICHT in sections:
|
||||||
|
_add_dagoverzicht_section(pdf, glucose)
|
||||||
|
|
||||||
if SECTION_EVENTS in sections and events_summary:
|
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())
|
return bytes(pdf.output())
|
||||||
|
|||||||
@@ -2,7 +2,14 @@ from datetime import date
|
|||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from pdf_export import SECTION_AGP, SECTION_EVENTS, SECTION_SUMMARY, build_report_pdf
|
from pdf_export import (
|
||||||
|
DAGOVERZICHT_MAX_DAYS,
|
||||||
|
SECTION_AGP,
|
||||||
|
SECTION_DAGOVERZICHT,
|
||||||
|
SECTION_EVENTS,
|
||||||
|
SECTION_SUMMARY,
|
||||||
|
build_report_pdf,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _sample_glucose():
|
def _sample_glucose():
|
||||||
@@ -10,6 +17,15 @@ def _sample_glucose():
|
|||||||
return pd.DataFrame({"timestamp": timestamps, "mmol": [6.0 + (i % 5) for i in range(48)]})
|
return pd.DataFrame({"timestamp": timestamps, "mmol": [6.0 + (i % 5) for i in range(48)]})
|
||||||
|
|
||||||
|
|
||||||
|
def _glucose_with_hypo_and_hyper_events():
|
||||||
|
"""3 dagen data met een echte hypo- (<3.9, >=15 min) en hyperepisode (>10.0)."""
|
||||||
|
timestamps = pd.date_range("2026-01-01", periods=3 * 24 * 12, freq="5min")
|
||||||
|
values = [7.0] * len(timestamps)
|
||||||
|
values[10:15] = [3.0] * 5 # 25 min hypo
|
||||||
|
values[100:106] = [12.0] * 6 # 30 min hyper
|
||||||
|
return pd.DataFrame({"timestamp": timestamps, "mmol": values})
|
||||||
|
|
||||||
|
|
||||||
def test_build_report_pdf_produces_valid_pdf_bytes():
|
def test_build_report_pdf_produces_valid_pdf_bytes():
|
||||||
glucose = _sample_glucose()
|
glucose = _sample_glucose()
|
||||||
events_summary = {
|
events_summary = {
|
||||||
@@ -39,3 +55,38 @@ def test_build_report_pdf_handles_no_sections_selected():
|
|||||||
glucose = _sample_glucose()
|
glucose = _sample_glucose()
|
||||||
pdf_bytes = build_report_pdf([], glucose, {}, date(2026, 1, 1), date(2026, 1, 2))
|
pdf_bytes = build_report_pdf([], glucose, {}, date(2026, 1, 1), date(2026, 1, 2))
|
||||||
assert pdf_bytes.startswith(b"%PDF")
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_includes_dagoverzicht_section():
|
||||||
|
glucose = _sample_glucose()
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_DAGOVERZICHT], glucose, {}, date(2026, 1, 1), date(2026, 1, 2)
|
||||||
|
)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
assert len(pdf_bytes) > 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_caps_dagoverzicht_at_max_days():
|
||||||
|
timestamps = pd.date_range("2026-01-01", periods=(DAGOVERZICHT_MAX_DAYS + 10) * 24, freq="1h")
|
||||||
|
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [7.0] * len(timestamps)})
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_DAGOVERZICHT],
|
||||||
|
glucose,
|
||||||
|
{},
|
||||||
|
timestamps[0].date(),
|
||||||
|
timestamps[-1].date(),
|
||||||
|
)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_draws_hypo_and_hyper_charts_when_events_present():
|
||||||
|
glucose = _glucose_with_hypo_and_hyper_events()
|
||||||
|
events_summary = {
|
||||||
|
"Hypo Level 1": {"count": 1, "avg_duration_minutes": 25.0, "events_per_week": 2.3},
|
||||||
|
"Hyper Level 1": {"count": 1, "avg_duration_minutes": 30.0, "events_per_week": 2.3},
|
||||||
|
}
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_EVENTS], glucose, events_summary, date(2026, 1, 1), date(2026, 1, 4)
|
||||||
|
)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
assert len(pdf_bytes) > 500
|
||||||
|
|||||||
Reference in New Issue
Block a user