17 Commits
Author SHA1 Message Date
willemjan e08f269855 test jenkins
willemjan/glucose-dashboard/pipeline/head Something is wrong with the build of this commit
2026-08-10 23:19:27 +02:00
willemjan b8e01fa8c9 Show estimated HbA1c in mmol/mol (IFCC) alongside the % value
Dutch lab results conventionally report HbA1c in mmol/mol rather than
DCCT/NGSP %. Adds gmi_mmol_per_mol() using the standard IFCC conversion
(Hoelzel et al. 2004) and shows it next to the existing % value on the
Samenvatting page and in the PDF summary.

Closes gitea #25.
2026-08-01 23:12:43 +02:00
willemjan 374ead70e5 Replace monthly GMI bar chart with daily scatter + rolling avg + linear trend/CI
Adds daily_gmi() and gmi_trend(): per-day GMI as scatter points, a 7-day
rolling average line, and a linear regression trend line with a 95%
confidence band (normal approximation, no scipy dependency, consistent
with the existing preference for a lean container image).

Recomputed from the already-fetched period data on each page load; the
existing 1-hour Streamlit cache on load_range_data() already avoids
repeated Nightscout calls for the same period, so no separate storage
layer is needed at the current max. 90-day report window.

Closes gitea #19.
2026-08-01 22:57:54 +02:00
willemjan 9e11dd8d73 Fix bolus/basal insulin categorization: split SMB from manual corrections, add basal calc
AndroidAPS records an automatic SMB micro-bolus as eventType "Correction
Bolus" with type "SMB", not as its own eventType. bolus_stats() was
grouping by eventType alone, so every SMB was silently counted as a manual
correction bolus. Verified against production data: 100% of "Correction
Bolus" treatments over 90 days were actually type=SMB.

Also adds basal_stats(), computing delivered basal directly from Temp
Basal treatments (rate x duration) without needing the pump profile.

Closes gitea #20.
2026-08-01 22:52:54 +02:00
willemjan 441bb84212 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.
2026-08-01 22:33:45 +02:00
willemjan 00fb81b283 Add clinical threshold lines to AGP/Dagoverzicht charts, TIR stacked bar to Samenvatting
Closes gitea #14, #15.
2026-08-01 22:26:26 +02:00
willemjan 699848b479 fix: treatments endpoint needs a created_at cursor, not date
Investigated the "only ~4 days of treatments" report via direct
MongoDB access (issue #13): the collection has 123k+ documents, no
capping, no TTL index — the full year of history is in the database.

The actual cause: /api/v1/treatments.json filters/sorts on the string
field `created_at`, not the numeric `date` field /api/v1/entries uses.
Paginating with find[date][$lte] (or no filter at all) silently caps
treatments to an internal ~4-day window even though every document has
a valid `date` field; find[created_at][$lte] correctly walks back
through the full history.

_paginated_get() now takes an explicit cursor_field per endpoint and
always sends the cursor from the first request (never omitted), so
that hidden default window can't trigger. Verified against the real
instance: a 92-day treatments fetch now returns 39,403 rows (was ~700).
2026-08-01 21:43:08 +02:00
willemjan 55883480c0 docs: record FR1 findings and add profile-tuning design spec
requirements-profile-tuning.md: document the LXC 102/107 investigation
outcome (LXC 102's houthacker/nightscout-autotune image already solves
both the analysis and NS-upload directions) and resolve the two open
questions this depended on.

design-profile-tuning.md: full design spec for the separate
glucose-profile-tuning app/service, reviewed and approved.
2026-07-31 14:21:46 +02:00
willemjan 29d20ca441 fix: Nightscout API silently truncated multi-day fetches to ~3-4 days
_entries_since/_treatments_since requested a single page via `count`,
but Nightscout's /api/v1/entries and /api/v1/treatments ignore a large
`count` and cap the response around ~1150/~700 documents regardless of
how far back the requested period goes. Every report page relying on
fetch_entries_range/fetch_treatments_range (7/14/30/90-day selectors)
was silently only getting the most recent ~3-4 days, no matter the
selected period.

Fixed by paginating with `find[date][$lte]` cursors in a new
_paginated_get(), walking back until the requested `since` boundary is
reached or the server returns a short/empty page (= genuinely no more
data, confirmed by manually paginating against the real instance:
entries go back 50+ days, treatments only ~4 days on this install).

Also added reporting.completeness_warning(), shared by the interactive
pages (via ui_common.render_completeness_warning) and the PDF export,
that distinguishes "a structural gap at the start of the period" (data
wasn't fetched/available) from "scattered gaps below the clinical AGP
coverage threshold" (Danne et al. 2017) — the previous single generic
"X% sensor coverage" message read as a CGM/sensor problem even when
the real cause was this fetch bug.
2026-07-31 14:21:35 +02:00
willemjanandClaude Sonnet 5 fe6a471f17 add PDF export (FR10)
pdf_export.py builds a PDF report (summary stats, AGP chart, hypo/hyper
event summaries) via fpdf2 + matplotlib rather than plotly's kaleido, to
avoid bundling a Chromium build into the image just for this. The Export
page lets the user pick which sections to include and a date range, then
download the result to send to the hospital team.

This completes all ten functional requirements in
docs/requirements-reporting.md.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-26 21:10:46 +02:00
willemjanandClaude Sonnet 5 9929f44daa add Trends page: GMI trend, overnight/daytime, weekday pattern, bolus, site-age (FR7, FR8)
reporting.py gains overnight_daytime_split, day_of_week_pattern,
bolus_stats, and site_interval_stats. The last two are explicitly scoped
to bolus-only insulin (no basal reconstruction) since that needs the
Nightscout profile, which is the separate profile-tuning feature's
territory — documented as a caveat in both the UI and the design doc.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-26 21:06:06 +02:00
willemjanandClaude Sonnet 5 04c5f521fe add Dagoverzicht, Hypo Events, and Hyper Events pages (FR4, FR5, FR6)
Dagoverzicht stacks one glucose trace per calendar day (small multiples
via a shared 0-24h x-axis). The two event pages share a new
render_event_level() helper in ui_common.py so Level 1/Level 2 hypo and
hyper are rendered identically: count/avg/longest/events-per-week
metrics, a time-of-day histogram, and a table of individual events.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-26 20:13:38 +02:00
willemjanandClaude Sonnet 5 1207ff536f add Samenvatting and AGP Profiel pages (FR2, FR3, FR9)
Wires reporting.py's stats into two new pages: a summary panel (data
completeness, GMI, %CV, 5-band time-in-range vs. consensus targets) and
the standard AGP percentile chart (5th-95th and 25th-75th bands plus
median, aggregated by time-of-day across the selected period).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-26 20:09:25 +02:00
willemjanandClaude Sonnet 5 3ef9a7666a add reporting foundation: multipage nav, auth gate, date-range fetch
First increment of the clinical reporting feature (see
docs/requirements-reporting.md and docs/design-reporting.md): moves the
existing live view to pages/1_Live.py, adds a password gate since the
dashboard URL will be shared with the diabetes team, adds
fetch_entries_range/fetch_treatments_range for multi-day report queries,
and adds reporting.py with the core clinical calculations (GMI, %CV,
5-band time-in-range, hypo/hyper event detection per the Battelino et al.
2019 persistence rule). No report pages wired up yet — that's next.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-26 20:00:48 +02:00
willemjanandClaude Sonnet 5 7379f6be8c pin trivy-action to the last docker-based release
@master resolves to a version that installs Trivy via a nested
setup-trivy composite action, which does an actions/checkout against
github.com with a token. On Gitea's act_runner that fails with "Input
required and not supplied: token" even when the token is explicitly
set to an empty string (act_runner doesn't distinguish empty from
unset). v0.26.0 introduced that composite/setup-trivy split; v0.25.0
is the last release that ships as a self-contained Docker image with
Trivy already baked in, so it needs no token at all.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-26 14:54:43 +02:00
willemjanandClaude Sonnet 5 e0d6b79e68 use the working duckdns hostname for the registry, fix trivy github auth
gitea.zb.local resolves but is plain HTTP, which Docker refuses as a
registry without daemon-level insecure-registry config. gitea.zb.lan
resolves but nothing answers there yet (proxy not configured for it).
gitea.zb-kw.duckdns.org is confirmed reachable end-to-end over HTTPS,
including the registry v2 API, from both the runner and the deploy
target, so use that consistently. Also fix aquasecurity/trivy-action's
token-setup-trivy input, which defaults to gitea.token and gets
rejected by github.com when it tries to clone the install script.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-07-25 22:02:53 +02:00
willemjan d6107515c0 updated sonarqube scan action version 2026-07-25 21:22:18 +02:00
29 changed files with 4082 additions and 278 deletions
+5
View File
@@ -10,3 +10,8 @@ NIGHTSCOUT_TOKEN=
# Optie 2: het klassieke "API secret" van je Nightscout-instantie. # Optie 2: het klassieke "API secret" van je Nightscout-instantie.
# NIGHTSCOUT_API_SECRET= # NIGHTSCOUT_API_SECRET=
# Wachtwoord voor toegang tot het dashboard (de URL wordt straks gedeeld met
# het diabetesteam). Zet hier een sha256-hash, NIET het wachtwoord zelf:
# python -c "import hashlib; print(hashlib.sha256(b'jouw-wachtwoord').hexdigest())"
DASHBOARD_PASSWORD_HASH=
+19 -9
View File
@@ -33,7 +33,7 @@ jobs:
with: with:
fetch-depth: 0 # SonarQube wil de volledige git-historie zien fetch-depth: 0 # SonarQube wil de volledige git-historie zien
- name: SonarQube scan - name: SonarQube scan
uses: sonarsource/sonarqube-scan-action@v4 uses: sonarsource/sonarqube-scan-action@v6
env: env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }} SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }}
@@ -47,23 +47,33 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Build Docker image - name: Build Docker image
run: docker build -t gitea.zb.local/willem/glucose-dashboard:${{ gitea.sha }} . run: docker build -t gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:${{ gitea.sha }} .
- name: Trivy scan - name: Trivy scan
uses: aquasecurity/trivy-action@master # Gepind op de laatste Docker-gebaseerde release: vanaf v0.26.0 installeert
# deze action Trivy via een los 'setup-trivy'-composite-action dat zelf een
# actions/checkout met een GitHub-token doet. Op act_runner (Gitea) faalt
# dat met "Input required and not supplied: token" — ook met een expliciet
# lege token-setup-trivy-input, want act_runner onderscheidt "leeg" niet
# van "niet meegegeven". v0.25.0 draait als kant-en-klare Docker-image en
# heeft dat probleem niet.
uses: aquasecurity/[email protected]
with: with:
image-ref: gitea.zb.local/willem/glucose-dashboard:${{ gitea.sha }} image-ref: gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:${{ gitea.sha }}
severity: CRITICAL,HIGH format: table
exit-code: "1" # laat de pipeline falen bij kritieke kwetsbaarheden exit-code: "1" # laat de pipeline falen bij kritieke kwetsbaarheden
ignore-unfixed: true
vuln-type: os,library
severity: CRITICAL,HIGH
- name: Login bij Gitea-registry - name: Login bij Gitea-registry
run: echo "${{ secrets.GLUCOSE_TOKEN }}" | docker login gitea.zb.local -u willem --password-stdin run: echo "${{ secrets.GLUCOSE_TOKEN }}" | docker login gitea.zb-kw.duckdns.org -u willemjan --password-stdin
- name: Tag en push - name: Tag en push
run: | run: |
docker tag gitea.zb.local/willem/glucose-dashboard:${{ gitea.sha }} gitea.zb.local/willem/glucose-dashboard:latest docker tag gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:${{ gitea.sha }} gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:latest
docker push gitea.zb.local/willem/glucose-dashboard:${{ gitea.sha }} docker push gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:${{ gitea.sha }}
docker push gitea.zb.local/willem/glucose-dashboard:latest docker push gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:latest
# --------------------------------------------------------------------- # ---------------------------------------------------------------------
# 4. Deploy — SSH naar de LXC en herstart met de nieuwe image # 4. Deploy — SSH naar de LXC en herstart met de nieuwe image
Vendored
+11
View File
@@ -0,0 +1,11 @@
pipeline {
agent any
stages {
stage('Do nothing') {
steps {
sh '/bin/true'
}
}
}
}
+10 -6
View File
@@ -1,18 +1,22 @@
# glucose-dashboard # glucose-dashboard
Dashboard van glucosedata, live opgehaald uit een [Nightscout](https://nightscout.github.io/)-instantie. Dashboard van glucosedata, live opgehaald uit een [Nightscout](https://nightscout.github.io/)-instantie.
Toont een rollend venster (standaard 24 uur) van je CGM-curve met insuline, Meerdere pagina's (zie zijbalk): een rollend live-overzicht en een set
koolhydraten en pomp-/sensorwissels overlay, plus time-in-range-cijfers. klinische rapportagepagina's (zie `docs/requirements-reporting.md` en
`docs/design-reporting.md`).
## Instellen ## Instellen
1. Zorg voor een draaiende Nightscout-instantie en een API-token (Admin Tools 1. Zorg voor een draaiende Nightscout-instantie en een API-token (Admin Tools
> Manage Tokens in Nightscout — geef het token minimaal `readable`-rechten) > Manage Tokens in Nightscout — geef het token minimaal `readable`-rechten)
of het klassieke API secret. of het klassieke API secret.
2. Kopieer `.env.example` naar `.env` en vul `NIGHTSCOUT_URL` en één van de 2. Kopieer `.env.example` naar `.env` en vul `NIGHTSCOUT_URL`, één van de
twee auth-opties in. `app.py` laadt `.env` zelf in (via `python-dotenv`), twee auth-opties, en `DASHBOARD_PASSWORD_HASH` in (zie het voorbeeldbestand
dus dit werkt hetzelfde onder PowerShell, cmd of bash — je hoeft de voor hoe je die hash genereert — de dashboard-URL wordt gedeeld met het
variabelen niet zelf in je shell te zetten. diabetesteam, dus elke pagina zit achter een wachtwoord). `app.py` laadt
`.env` zelf in (via `python-dotenv`), dus dit werkt hetzelfde onder
PowerShell, cmd of bash — je hoeft de variabelen niet zelf in je shell te
zetten.
3. Lokaal draaien: 3. Lokaal draaien:
```powershell ```powershell
+13 -231
View File
@@ -1,241 +1,23 @@
import plotly.graph_objects as go
import requests
import streamlit as st import streamlit as st
from dotenv import load_dotenv from dotenv import load_dotenv
from data_processing import ( from auth import require_auth
TARGET_HIGH,
TARGET_LOW,
classify_treatments,
summarize_time_in_range,
)
from nightscout_client import NightscoutConfigError, fetch_entries, fetch_treatments
load_dotenv() # laadt .env als die bestaat; bestaande env vars blijven leidend load_dotenv() # laadt .env als die bestaat; bestaande env vars blijven leidend
st.set_page_config(page_title="Glucose dashboard", page_icon="📊", layout="wide") st.set_page_config(page_title="Glucose dashboard", page_icon="📊", layout="wide")
require_auth()
st.title("Glucose dashboard") st.title("Glucose dashboard")
st.write("Kies een pagina in de zijbalk.")
HOURS_OPTIONS = {"6 uur": 6, "12 uur": 12, "24 uur": 24, "48 uur": 48} st.markdown(
"""
# Kleuren per rol, licht/donker — zie de dataviz-conventies in dit project: - **Live** — rollend overzicht van de laatste uren, met insuline/koolhydraten/pomp-/sensorwissels
# categorale kleuren voor identiteit (glucose/insuline/carbs), status-kleuren - **Samenvatting** — AGP-samenvattingsstatistieken en tijd-in-bereik over een gekozen periode
# (vast, nooit hergebruikt) voor te laag/te hoog. - **AGP profiel** — percentielgrafiek over een 24-uurs samengesteld beeld
PALETTE = { - **Dagoverzicht** — losse glucosegrafiek per dag
"light": { - **Hypo events** / **Hyper events** — detectie en analyse van te lage/hoge periodes
"glucose": "#2a78d6", - **Trends** — geschat HbA1c (GMI) over tijd en overige statistieken
"insulin": "#1baf7a", - **Export** — PDF-rapport van geselecteerde onderdelen
"carbs": "#eb6834", """
"low": "#d03b3b",
"high": "#fab219",
"band": "rgba(12,163,12,0.08)",
"grid": "#e1e0d9",
"muted": "#898781",
"text": "#52514e",
},
"dark": {
"glucose": "#3987e5",
"insulin": "#199e70",
"carbs": "#d95926",
"low": "#d03b3b",
"high": "#fab219",
"band": "rgba(12,163,12,0.15)",
"grid": "#2c2c2a",
"muted": "#898781",
"text": "#c3c2b7",
},
}
@st.cache_data(ttl=60, show_spinner="Data ophalen van Nightscout...")
def load_nightscout_data(hours: int):
glucose = fetch_entries(hours=hours)
treatments = fetch_treatments(hours=hours)
return glucose, treatments
MMOL_HOVERTEMPLATE = "%{x|%d-%m %H:%M} · %{y:.1f} mmol/L<extra></extra>"
def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -> go.Figure:
glucose_min = min(glucose["mmol"].min(), TARGET_LOW)
glucose_max = max(glucose["mmol"].max(), TARGET_HIGH)
y_top = glucose_max + 1.0
lane_base = glucose_min - 2.5
y_bottom = lane_base - 0.5
insulin_lane_y = lane_base + 1.5
carbs_lane_y = lane_base + 0.7
fig = go.Figure()
# Streefbereik als achtergrondband, geen losse legenda-entry nodig.
fig.add_hrect(
y0=TARGET_LOW,
y1=TARGET_HIGH,
fillcolor=colors["band"],
line_width=0,
layer="below",
)
fig.add_trace(
go.Scatter(
x=glucose["timestamp"],
y=glucose["mmol"],
mode="lines",
name="Glucose",
line={"color": colors["glucose"], "width": 2, "shape": "spline"},
hovertemplate=MMOL_HOVERTEMPLATE,
)
)
low_points = glucose[glucose["mmol"] < TARGET_LOW]
high_points = glucose[glucose["mmol"] > TARGET_HIGH]
if not low_points.empty:
fig.add_trace(
go.Scatter(
x=low_points["timestamp"],
y=low_points["mmol"],
mode="markers",
name=f"Laag (<{TARGET_LOW})",
marker={"color": colors["low"], "size": 6},
hovertemplate=MMOL_HOVERTEMPLATE,
)
)
if not high_points.empty:
fig.add_trace(
go.Scatter(
x=high_points["timestamp"],
y=high_points["mmol"],
mode="markers",
name=f"Hoog (>{TARGET_HIGH})",
marker={"color": colors["high"], "size": 6},
hovertemplate=MMOL_HOVERTEMPLATE,
)
)
if not insulin.empty:
fig.add_trace(
go.Scatter(
x=insulin["timestamp"],
y=[insulin_lane_y] * len(insulin),
mode="markers",
name="Insuline",
marker={"color": colors["insulin"], "size": 10, "symbol": "triangle-up"},
customdata=insulin["insulin"],
hovertemplate="%{x|%d-%m %H:%M} · %{customdata:.1f} E<extra></extra>",
)
)
if not carbs.empty:
fig.add_trace(
go.Scatter(
x=carbs["timestamp"],
y=[carbs_lane_y] * len(carbs),
mode="markers",
name="Koolhydraten",
marker={"color": colors["carbs"], "size": 10, "symbol": "circle"},
customdata=carbs["carbs"],
hovertemplate="%{x|%d-%m %H:%M} · %{customdata:.0f} g<extra></extra>",
)
)
# Let op: annotation_text/-position via add_vline() zelf triggert een bug
# in plotly's shapeannotation-helper met pandas Timestamp-x-waarden, dus
# de lijn en het label worden hier los toegevoegd.
for _, row in site_changes.iterrows():
fig.add_vline(x=row["timestamp"], line_dash="dot", line_color=colors["muted"], opacity=0.6)
fig.add_annotation(
x=row["timestamp"],
y=y_top,
yanchor="bottom",
text="Pomp",
showarrow=False,
font={"color": colors["muted"], "size": 10},
)
for _, row in sensor_changes.iterrows():
fig.add_vline(x=row["timestamp"], line_dash="dash", line_color=colors["muted"], opacity=0.6)
fig.add_annotation(
x=row["timestamp"],
y=y_top,
yanchor="bottom",
text="Sensor",
showarrow=False,
font={"color": colors["muted"], "size": 10},
)
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
margin={"l": 10, "r": 10, "t": 10, "b": 10},
height=480,
yaxis={
"title": "mmol/L",
"range": [y_bottom, y_top],
"gridcolor": colors["grid"],
"zeroline": False,
},
xaxis={"gridcolor": colors["grid"]},
)
return fig
with st.sidebar:
st.header("Instellingen")
hours_label = st.radio("Periode", list(HOURS_OPTIONS.keys()), index=2)
hours = HOURS_OPTIONS[hours_label]
if st.button("Vernieuwen"):
st.cache_data.clear()
try:
glucose, treatments = load_nightscout_data(hours)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc: # netwerk-/API-fouten van Nightscout
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
events = classify_treatments(treatments)
tir = summarize_time_in_range(glucose)
latest = glucose.iloc[-1]
previous = glucose.iloc[-2] if len(glucose) > 1 else None
delta = round(latest["mmol"] - previous["mmol"], 1) if previous is not None else None
col1, col2, col3, col4 = st.columns(4)
col1.metric("Actuele glucose", f"{latest['mmol']:.1f} mmol/L", delta=delta, delta_color="off")
col2.metric("Tijd in bereik", f"{tir['in_range']:.0f}%")
col3.metric("Tijd laag", f"{tir['low']:.0f}%")
col4.metric("Tijd hoog", f"{tir['high']:.0f}%")
st.caption(
f"Laatste meting: {latest['timestamp'].strftime('%d-%m-%Y %H:%M')} · "
f"streefbereik {TARGET_LOW}-{TARGET_HIGH} mmol/L"
)
theme_type = "light"
try:
theme_type = st.context.theme.type or "light"
except AttributeError:
pass
colors = PALETTE["dark" if theme_type == "dark" else "light"]
fig = build_chart(
glucose,
events["insulin"],
events["carbs"],
events["site_changes"],
events["sensor_changes"],
colors,
)
st.plotly_chart(fig, width="stretch")
st.caption(
"Driehoekjes = insuline · cirkels = koolhydraten · stippellijn = pompwissel · "
"streepjeslijn = sensorwissel"
) )
+49
View File
@@ -0,0 +1,49 @@
"""
Eenvoudige wachtwoord-gate voor de dashboardpagina's.
Streamlit heeft geen ingebouwde authenticatie. Omdat dashboard-URL's straks
gedeeld worden met het diabetesteam, staat hier een lichte sessie-gebaseerde
wachtwoordcontrole voor — geen volwaardig account-systeem, wel een drempel
tegen toevallig meekijken. Het wachtwoord zelf staat nooit in plaintext in de
configuratie: net als bij het Nightscout API secret in nightscout_client.py
wordt hier een hash vergeleken, niet de ruwe waarde.
"""
from __future__ import annotations
import hashlib
import os
import streamlit as st
def require_auth() -> None:
"""Blokkeer de pagina totdat het juiste wachtwoord is ingevoerd.
Slaat de status op in st.session_state zodat dit maar één keer per
browsersessie hoeft. Moet als eerste statement van elke pagina aangeroepen
worden (app.py en elk bestand in pages/), omdat Streamlit iedere pagina
als los script uitvoert.
"""
if st.session_state.get("authenticated"):
return
st.title("Glucose dashboard")
password = st.text_input("Wachtwoord", type="password")
if not password:
st.stop()
if verify_password(password, os.environ.get("DASHBOARD_PASSWORD_HASH", "")):
st.session_state["authenticated"] = True
st.rerun()
st.error("Onjuist wachtwoord")
st.stop()
def verify_password(password: str, expected_hash: str) -> bool:
"""Vergelijk een ingevoerd wachtwoord met de geconfigureerde sha256-hash."""
if not expected_hash:
return False
return hashlib.sha256(password.encode("utf-8")).hexdigest() == expected_hash
+1 -1
View File
@@ -1,6 +1,6 @@
services: services:
glucose-dashboard: glucose-dashboard:
image: gitea.zb.local/willem/glucose-dashboard:latest image: gitea.zb-kw.duckdns.org/willemjan/glucose-dashboard:latest
container_name: glucose-dashboard container_name: glucose-dashboard
restart: unless-stopped restart: unless-stopped
ports: ports:
+328
View File
@@ -0,0 +1,328 @@
> **Moved.** Implementation now lives in the separate `glucose-profile-tuning`
> repo (per this doc's own §2 isolation decision); the canonical, actively
> maintained copy of this file is at `glucose-profile-tuning/docs/design-profile-tuning.md`.
> This copy is kept for history and is no longer updated.
# Design specification: oref0-autotune profile tuning
Status: **final — user reviewed**
Requirements: [requirements-profile-tuning.md](requirements-profile-tuning.md) (FR1–FR9, NFR1–NFR5)
Related: [design-reporting.md](design-reporting.md) (same conventions, separate app)
This is a design spec, not code. Nothing here has been implemented yet —
implementation starts after this doc is reviewed/approved, one phase at a
time, each shipped through its own CI/CD pipeline (§8).
## 1. FR1 recap — infra decision (already executed)
FR1 (boot + inspect LXC 102/107) is done; full findings are recorded directly
in [requirements-profile-tuning.md §4 FR1](requirements-profile-tuning.md).
Summary: **LXC 102 (`autotune`, 192.168.2.13)** already has a working, pinned
Docker image — `ghcr.io/houthacker/nightscout-autotune:latest` — that bundles
the *entire* oref0 npm toolkit, not just the autotune algorithm:
| Tool (already installed in the image) | Role in this design |
|---|---|
| `nightscout-autotune` (image's default CMD) | Fetches NS entries/treatments/profile, runs oref0-autotune, writes results to `$OPENAPS_WORKDIR` |
| `oref0-upload-profile profile.json NSURL secret [--preview] [--switch]` | Converts an oref0-format profile back to Nightscout's profile-store format **and** uploads it, optionally issuing a Profile Switch treatment |
| `convert-ns-profile` / `mm-format-ns-profile` | The NS-format ⇄ oref0-format conversion primitives, used internally by the two tools above |
This changes the shape of the whole feature for the better: **we do not need
to write any Nightscout-profile-format conversion code ourselves.** Both
directions (NS → oref0 for analysis, oref0 → NS for staging) are already
solved, tested, and previously proven against the user's real Nightscout
instance (bash history on LXC 102 shows a full run against
`https://zb-ns.duckdns.org` completing 9 months ago). This is exactly the
"had to manually parse parts of the profile" pain point called out in FR2 —
resolved by wrapping existing tools instead of reimplementing them.
LXC 107 is not used; it's a messier, native (non-Docker) install of the same
underlying toolkit with no functional advantage over 102. It stays stopped.
## 2. Architecture overview
Two new pieces, one existing piece untouched:
```
┌─────────────────────────────┐ ┌──────────────────────────────────┐
│ LXC 120 (glucose-app) │ │ LXC 102 (autotune) │
│ │ │ │
│ ┌──────────────────────────┐ │ HTTPS │ ┌────────────────────────────────┐│
│ │ glucose-dashboard │ │ Bearer│ │ autotune-service (new) ││
│ │ (existing, untouched) │ │ token │ │ Node/Express, image FROM ││
│ └──────────────────────────┘ │◄───────┼─┤ ghcr.io/houthacker/ ││
│ │ │ │ nightscout-autotune ││
│ ┌──────────────────────────┐ │ │ │ - owns the NS write token ││
│ │ autotune-app (new) │─┼────────┼─▶ - owns the SQLite audit DB ││
│ │ Streamlit, own auth gate │ │ │ │ - runs analyses (spawn) ││
│ └──────────────────────────┘ │ │ │ - runs oref0-upload-profile ││
│ │ │ │ - nightly scheduler (04:00) ││
└──────────────────────────────┘ │ └────────────────────────────────┘│
│ │ │
└────────────┼─────────────────────┘
│ HTTPS (existing NS
│ read/write token)
▼
Nightscout (zb-ns.duckdns.org)
```
Key property driving this split: **the frontend never talks to Nightscout
directly, and never holds a Nightscout credential.** It only holds a shared
bearer token to call `autotune-service`. All Nightscout I/O — reading
entries/treatments/profile for analysis, and writing the staged profile /
Profile Switch — happens on LXC 102, inside `autotune-service`, using the one
write-scoped NS token (NFR2). This keeps the dosing-adjacent credential in
exactly one place, matches architecture decision #3 in the requirements doc
(isolating write-capable code from the read-only dashboard), and means the
Streamlit app can be redeployed or rebuilt at any time without touching
secrets or state — it's a pure, stateless UI.
Repo layout: one new repo, **`glucose-profile-tuning`**, with two
subdirectories and their own Dockerfiles:
- `service/` — the Node microservice (deployed to LXC 102)
- `app/` — the Streamlit frontend (deployed to LXC 120, alongside
`glucose-dashboard` as a second `docker-compose` service — that LXC has
~800MB RAM headroom today, plenty for a second, mostly-idle Streamlit UI)
One repo keeps this a single reviewable unit (matching how the user framed
FR1–FR9 as one feature); the two Dockerfiles/deploy targets keep the runtime
isolation NFR1 asks for.
## 3. `autotune-service` (LXC 102)
### 3.1 Why Node, not Python
The base image is Alpine + Node 24 with the entire oref0 toolkit already
installed as Node/shell scripts under `/usr/local/bin`. Adding Python +
FastAPI on top would mean two language runtimes doing the same job one
already does. Building the HTTP layer in Node (Express) lets it `spawn()`
`nightscout-autotune` and `oref0-upload-profile` as sibling processes in the
same container/filesystem — no Docker socket, no Docker-in-Docker. (Mounting
the host's `docker.sock` to let a container launch sibling containers was
considered and rejected — unnecessary privilege escalation for a homelab
service that already has direct in-image access to the tools it needs.)
### 3.2 Job model
A single SQLite table, `analysis_runs`:
| column | type | notes |
|---|---|---|
| `id` | TEXT (uuid) | PK |
| `trigger` | TEXT | `manual` \| `nightly` |
| `requested_at` / `started_at` / `finished_at` | TEXT (ISO 8601) | |
| `status` | TEXT | `pending` \| `running` \| `done` \| `failed` |
| `days`, `profile_name`, `autosens_min`, `autosens_max`, `insulin_type`, `min_5m_carb_impact`, `uam_as_basal` | job params as submitted | `profile_name` nullable — omitted means "NS's current default", per the tool's own documented behavior |
| `error_message` | TEXT, nullable | |
| `current_profile_json` / `proposed_profile_json` | TEXT (JSON), nullable until done | oref0 pump-profile shape (`basalprofile[]`, `isf`, `carbratio`, `dia`, `autosens_min/max`) — this is the *input* `profile.json` and *output* `newprofile.json` the tool already produces |
| `recommendations_log` | TEXT, nullable | verbatim `autotune_recommendations.log` — human-readable Pump/Autotune/Days-missing table, used for FR4's estimation detail |
| `staged_at` | TEXT, nullable | set once FR6 staging succeeds |
| `staged_profile_json` | TEXT (JSON), nullable | the final merged profile actually sent to NS |
| `switched` | INTEGER (bool), nullable | whether `--switch` was used |
| `staging_decisions_json` | TEXT (JSON), nullable | per-slot accept/reject/custom record, for FR7 audit trail |
Only one job may be `pending`/`running` at a time (LXC 102 is 1 core / 1GB —
not built for concurrency); a second trigger while one is in flight gets
`409 Conflict`.
Job execution: `POST /v1/analyses` inserts a `pending` row, immediately
returns `{id, status: "pending"}`, then asynchronously:
1. mark `running`, set `started_at`
2. `spawn("nightscout-autotune", [], {env: {...NS_HOST, AUTOTUNE_DAYS, UAM_AS_BASAL, NS_TOKEN (sha1'd), NS_PROFILE, AUTOSENS_MIN/MAX, INSULIN_TYPE, MIN_5MIN_CARBIMPACT, OPENAPS_WORKDIR: "/data/jobs/<id>"}})`
3. on exit code 0: read `profile.json`, `newprofile.*.json`, and
`autotune_recommendations.log` out of the job's workdir, populate the row,
mark `done`
4. on non-zero exit: capture stderr/stdout tail as `error_message`, mark
`failed`
### 3.3 HTTP API
All endpoints (except `/healthz`) require `Authorization: Bearer
<AUTOTUNE_SERVICE_API_KEY>`.
- `POST /v1/analyses` — body `{days, profile_name?, autosens_min?, autosens_max?, insulin_type?, min_5m_carb_impact?, uam_as_basal, trigger: "manual"}` → `202 {id, status}` or `409` if one's already running.
- `GET /v1/analyses/{id}` — full row as JSON (shape above).
- `GET /v1/analyses?trigger=&limit=` — history list, newest first (backs FR7 and FR9's nightly-runs page).
- `POST /v1/analyses/{id}/stage` — body `{profile: <merged oref0-shape JSON>, switch: bool, decisions: [...]}` → runs `oref0-upload-profile <tmpfile> $NS_HOST <secret> [--switch]`, updates the row, returns `200` or `502` with the CLI's stderr on failure. **To verify during implementation:** whether `oref0-upload-profile`'s positional `api-secret` argument accepts a token interchangeably (the analyze side supports both `NS_API_SECRET` and `NS_TOKEN`; the upload side's `--help` only documents `api-secret` positionally) — confirm against the installed script's source before wiring this up, rather than assuming.
- `GET /v1/profiles` — thin passthrough listing NS profile-store names, so the frontend can offer a dropdown instead of a free-text field for FR3's "select a current profile."
- `GET /healthz` — liveness, no auth required (used by the frontend's connectivity check and Docker's own healthcheck).
### 3.4 Nightly scheduler (FR9)
`node-cron` inside the same process, firing daily at 04:00 (container
timezone set to `Europe/Amsterdam`). Calls the same code path as
`POST /v1/analyses` with `trigger: "nightly"`, `profile_name` omitted (always
tunes from whatever is currently active — correct behavior for an unattended
run), and `days` from `NIGHTLY_AUTOTUNE_DAYS` (env var, default **7** — a
reasonable middle ground between enough data for stable estimates and not
diluting recent pattern changes; the doc's own wording — "whatever gives
usually the most accurate results" — doesn't have one universally-correct
answer, so this is exposed as a tunable env var rather than a hardcoded
guess, and the user can adjust it after watching a few nights of real
output). No result is ever auto-staged; a nightly run populates a `done`/
`failed` row exactly like a manual one, staging is always a separate FR6
action.
### 3.5 Logging (NFR "production grade")
Structured JSON lines to stdout via `pino`, one line per job lifecycle event
(`job.started`, `job.finished`, `job.failed` with `id`/`duration_ms`), `WARN`
for FR8 large-jump flags, `ERROR` for NS/upload failures — **never** logging
the raw token/secret. Captured by Docker's `json-file` driver with
`max-size`/`max-file` set in `docker-compose.yml` (no external log
aggregator exists in the homelab today per inspection of the `monitoring`
LXC, so this is deliberately self-contained rather than assuming a
Loki/Elastic-style sink that isn't there).
## 4. `autotune-app` (LXC 120, Streamlit)
### 4.1 Framework decision (NFR5)
**Streamlit**, not Shiny for Python. Reasons: every functional requirement
here (form inputs, polling with a spinner, a comparison table, an editable
grid, history lists) is already something `glucose-dashboard` does or
Streamlit does natively — `st.data_editor` with
`column_config.NumberColumn(step=0.01)` directly implements FR5's "editable
numeric fields, 0.01 steps" requirement without extra code. Shiny's reactive
model would add a second UI paradigm for the user to maintain with no
functional gain here. The password-gate (`auth.py`), theming, and
`AppTest`-based testing conventions from `glucose-dashboard` carry over
directly (copied into this new repo, not imported cross-repo, per NFR1's
isolation).
### 4.2 Pages
1. **`app.py`** — landing page, `require_auth()`, reads
`AUTOTUNE_SERVICE_URL` + `AUTOTUNE_SERVICE_API_KEY` from env, shows a
connectivity check against `GET /healthz`.
2. **`pages/1_Nieuwe_Analyse.py`** (FR3) — form: days, starting profile
(dropdown from `GET /v1/profiles`), an expander for advanced overrides
(autosens min/max, insulin type, min 5-min carb impact). Submits
`POST /v1/analyses`, then polls `GET /v1/analyses/{id}` (via
`st.spinner` + a rerun loop) until `done`/`failed`; a clear NS-connection
error surfaces the service's `error_message` verbatim (FR3 acceptance:
fail loud, don't hang).
3. **`pages/2_Overzicht_Resultaat.py`** (FR4 + FR5 + FR6 + FR8) — given a job
id: summary cards (ISF/CR pump vs. autotune, `autosens_min`/`max` bounds
shown explicitly per FR8), an `st.data_editor` grid — columns *time-slot*
(hourly), *huidig profiel*, *voorstel*, *bron* (select: current/suggested/
custom), *definitieve waarde* (editable number, step 0.01, disabled unless
*bron* = custom) — plus a raw `autotune_recommendations.log` expander for
the underlying estimation detail. Rows whose suggested value differs from
current by more than a configurable threshold (default: 20% relative or
0.1 U/hr absolute, whichever is smaller magnitude) are visually flagged
(FR8's "unusually large jump"). A "Stage to Nightscout" section requires
an explicit confirmation checkbox before `POST /v1/analyses/{id}/stage`
fires (FR8: no silent staging), with a separate "ook direct activeren
(Profile Switch)" checkbox controlling `switch`.
4. **`pages/3_Nachtelijke_Runs.py`** (FR9) — `GET /v1/analyses?trigger=nightly`,
latest first; failed rows show `error_message` inline; clicking a row
opens it in the same view as page 2.
5. **`pages/4_Geschiedenis.py`** (FR7) — full audit list (manual + nightly),
filterable by status/trigger, showing staged/switched state — this *is*
the audit trail; no separate mechanism needed since every run (and every
staging decision) is already a row in `autotune-service`'s database.
### 4.3 Merge logic (the one piece of real business logic on this side)
`merge_profile(current, proposed, decisions) -> final_profile` — a pure
function, unit-tested exactly like `reporting.py`'s style in
`glucose-dashboard`: for each slot, `decisions[slot]` is
`"current"`/`"suggested"`/`"custom"` (+ a value when `"custom"`); rejecting a
slot must leave `current`'s value byte-for-byte in `final_profile`
(FR5 acceptance criterion). This function, plus the large-jump-flagging
function, are the only two pieces of logic in this app worth unit tests
beyond `AppTest` page smoke tests.
## 5. Nightscout token (NFR2)
A new Subject/Access Token created in Nightscout's Admin Tools, distinct from
`glucose-dashboard`'s existing read-only token. Role: **`careportal`** — the
conventional Nightscout role that grants treatment and profile writes on top
of read access (vs. `readable`, read-only, or `admin`, full control this
doesn't need). **To confirm during implementation**: exact role-string
behavior can vary slightly by Nightscout version — verify a `careportal`-role
token can actually write `/api/v1/profile` on this specific instance before
relying on it, rather than assuming the classic-NS role semantics hold
exactly. Only `autotune-service`'s environment ever holds this token; it is
never sent to or stored in the browser/frontend.
## 6. Data requirements — resolved vs. the original doc
The original requirements doc's §6 assumed `nightscout_client.py`-style
`GET`/`POST /api/v1/profile.json` functions would need to be written. With
the LXC 102 findings, that's no longer true for the write direction
(`oref0-upload-profile` already does it) or the analysis-time read direction
(`nightscout-autotune` already does it). The frontend's only remaining NS-ish
need is the profile-name dropdown, served via `autotune-service`'s
`GET /v1/profiles` passthrough — so **no Nightscout client code is written in
Python at all** for this feature. All NS-format handling stays inside the
existing, already-proven Node/oref0 tooling.
## 7. Testing strategy (NFR3)
- **`service/`**: unit tests mock `child_process.spawn` and the filesystem —
never invoke the real `nightscout-autotune`/`oref0-upload-profile` binaries
or a real Nightscout in CI. Cover: job state transitions, the
pending/running 409 guard, SQLite persistence (temp-file DB per test),
route handlers, and the large-jump/merge-adjacent logic that lives here
(none currently — kept in the frontend, see §4.3).
- **`app/`**: `merge_profile`/large-jump pure-function unit tests; `AppTest`
page tests mocking `requests` against `autotune-service` (same
`FakeResponse`/`monkeypatch` pattern as `glucose-dashboard`'s suite);
`auth.py` tests copied from the existing suite.
- **UAT** (post-implementation, against the real LXC 102 service and the
user's real Nightscout): trigger a manual analysis → review the
comparison/flagged-jump view → reject a slot and confirm it stays at the
current value → accept + custom-edit others → stage without switch →
manually confirm in Nightscout the new profile appears correctly and the
previously active one is untouched → separately test staging *with*
switch → confirm a nightly run appears on the nightly page the next
morning, including a deliberately-forced-failure case showing a clear
reason.
## 8. CI/CD (NFR1, NFR4)
New Gitea repo `glucose-profile-tuning`, pipeline modeled on
`glucose-dashboard/.gitea/workflows/pipeline.yml` with two differences:
- **Two build targets**: `service/Dockerfile` (deploy → LXC 102) and
`app/Dockerfile` (deploy → LXC 120, second compose service alongside
`glucose-dashboard`), each independently Trivy-scanned and pushed to
`gitea.zb-kw.duckdns.org`.
- **`pull_request` trigger added to the test/lint job** (NFR4) — unlike
`glucose-dashboard`'s current `push`-only pipeline, this one can end in a
write to a real medical-data store, so tests must gate merge, not just run
after the fact.
New secrets/variables to provision (mirroring the existing dashboard's
setup): SSH deploy credentials for both target hosts, the new NS
`careportal` token, and a freshly generated `AUTOTUNE_SERVICE_API_KEY`
shared between the two new containers.
## 9. Implementation phasing
Same incremental, ship-behind-CI approach used for the reporting feature —
each phase is a separate PR, merged only once green:
1. **Scaffold** — both Dockerfiles building, empty pipeline green end-to-end
(test → Trivy → deploy to both LXCs), before any real feature — this
phase alone would have caught the hostname/secret/token issues the
reporting feature's deployment hit, ahead of time.
2. **Microservice core** (FR2) — SQLite schema, job runner wrapping
`nightscout-autotune`, `POST`/`GET /v1/analyses` only, unit-tested with
mocked `spawn`. No frontend yet — verified via `curl` against the real
LXC 102 (matches FR2's own acceptance criterion).
3. **Frontend read path** (FR3 + FR4) — pages 1 + 2 up to the comparison
view, no staging yet.
4. **Staging** (FR5 + FR6 + FR8) — `st.data_editor` merge grid, `/stage`
endpoint, confirmation gating, large-jump flags.
5. **Nightly + audit** (FR9 + FR7) — scheduler, nightly-runs page, history
page.
## 10. Open items carried into implementation (not blocking doc approval)
- Verify `oref0-upload-profile`'s secret-vs-token argument behavior (§3.3).
- Verify the `careportal` role actually permits profile writes on this NS
version before building against it (§5).
- Confirm the default `NIGHTLY_AUTOTUNE_DAYS=7` after watching real output
for a week or two; it's a tunable, not a fixed clinical constant (§3.4).
+178
View File
@@ -0,0 +1,178 @@
# Design: Clinical reporting page
Status: **implementation in progress**
Implements: [requirements-reporting.md](requirements-reporting.md) (see that doc for the final, user-edited FR list)
## 1. Architecture overview
Streamlit's classic `pages/` directory convention (numbered filenames, auto-populated
sidebar nav) rather than the newer `st.navigation`/`st.Page` object API — same
end result (multipage nav), simpler to reason about since each page is an
independent script sharing only imported modules, and it's what the project's
own `homelab-cicd-werkinstructie.md` anticipated.
```
app.py # home/landing page — auth gate + short intro
pages/
1_Live.py # existing rolling 6-48h view, moved as-is from current app.py
2_Samenvatting.py # FR2 (summary stats) + FR9 (data completeness)
3_AGP_Profiel.py # FR3 (percentile chart)
4_Dagoverzicht.py # FR4 (day-by-day graphs)
5_Hypo_Events.py # FR5
6_Hyper_Events.py # FR6
7_Trends.py # FR7 (GMI trend) + FR8 (other stats)
8_Export.py # FR10 (PDF export)
auth.py # password gate, imported by app.py and every page
reporting.py # new pure-logic module (mirrors data_processing.py's role)
nightscout_client.py # + fetch_entries_range / fetch_treatments_range
```
Each report page has its **own** period control per the user's edit to FR1
(90-day default for statistics/TIR pages, 14-day default for the daily-log page),
rather than one global selector — consistent with "each page separately."
## 2. Auth (NFR6 — new requirement from the user's edit)
Streamlit has no built-in auth. Given this is a single-user-plus-a-few-clinicians
homelab app (not a multi-tenant product), a lightweight session-based password
gate is proportionate — consistent with how `nightscout_client._auth()` already
hashes the API secret rather than storing/sending it raw:
```python
# auth.py
import hashlib, os
import streamlit as st
def require_auth() -> None:
if st.session_state.get("authenticated"):
return
st.title("Glucose dashboard")
password = st.text_input("Wachtwoord", type="password")
if not password:
st.stop()
expected = os.environ.get("DASHBOARD_PASSWORD_HASH", "")
if hashlib.sha256(password.encode()).hexdigest() == expected:
st.session_state["authenticated"] = True
st.rerun()
st.error("Onjuist wachtwoord")
st.stop()
```
Called as the first line of `app.py` and every `pages/*.py` file (Streamlit runs
each page as an independent script, so the guard must repeat per-file — no
shared middleware). New env var `DASHBOARD_PASSWORD_HASH` (sha256 hex digest,
not the plaintext password) added to `.env.example`/README with instructions to
generate it (`python -c "import hashlib; print(hashlib.sha256(b'yourpassword').hexdigest())"`).
Session-based means each browser session re-enters the password once; this is a
basic gate against casual URL sharing, not a hardened auth system — acceptable
for this context but worth knowing if the diabetes team needs individual
accounts later.
## 3. `nightscout_client.py` additions
`fetch_entries`/`fetch_treatments` scale `count` linearly with `hours` — fine for
the existing rolling 6-48h view, not for a 90-day report (~26,000 5-min
readings). New functions follow the exact same "overfetch by count, then filter
locally by timestamp" pattern already used (rather than introducing Mongo
`find[]` date-query params, which the existing code's own comments flag as
inconsistent across Nightscout versions):
```python
def fetch_entries_range(start_date: date, end_date: date) -> pd.DataFrame:
"""Haal glucosemetingen op tussen start_date en end_date (inclusief)."""
days = (end_date - start_date).days + 1
count = min(days * 300, 100_000) # ruime marge boven 5-min-interval
... # zelfde _get/parse-logica als fetch_entries, lokaal gefilterd op [start_date, end_date]
def fetch_treatments_range(start_date: date, end_date: date) -> pd.DataFrame:
... # analoog, count = min(days * 50, 50_000)
```
## 4. `reporting.py` (new module)
Pure functions only (no Streamlit imports), mirroring `data_processing.py`'s
existing style — testable with the same fixture-based pytest pattern.
- `gmi_percent(mean_mmol: float) -> float` — `3.31 + 0.4311 * mean_mmol`
- `percent_cv(glucose: pd.DataFrame) -> float` — `stdev/mean * 100`
- `tir_breakdown_5band(glucose) -> dict` — extends `data_processing.summarize_time_in_range`
(which only has 3 bands) to the 5 clinical bands (<3.0, 3.0–3.9, 3.9–10.0,
10.0–13.9, >13.9), each as % and as minutes/day
- `detect_events(glucose, threshold, direction, min_duration_minutes=15) -> pd.DataFrame`
— generic engine for FR5/FR6 (direction="below" for hypo, "above" for hyper);
finds runs of consecutive out-of-threshold readings ≥15 min, merging across
brief in-range blips per the persistence rule (a return above/below threshold
only "counts" once it has itself persisted ≥15 min)
- `summarize_events(events: pd.DataFrame, period_days: int) -> dict` — count, avg/longest
duration, total time, events/week
- `overnight_daytime_split(glucose, overnight_start=0, overnight_end=6) -> dict`
— TIR breakdown for each segment
- `day_of_week_pattern(glucose) -> pd.DataFrame` — per-weekday summary stats
- `bolus_stats(treatments) -> dict` — meal vs. correction bolus split, using the
existing `INSULIN_EVENT_TYPES` set from `nightscout_client.py` (currently
defined but unused — this is its first real consumer)
- `site_change_glucose_impact(glucose, site_changes, window_hours=6) -> pd.DataFrame`
— TIR in the N hours after each site change vs. the period baseline
**Scoping caveat surfaced during design** (flagging rather than silently
under-delivering): a true basal:bolus insulin ratio and total-daily-dose trend
need the *scheduled* basal rate (from the Nightscout profile) reconciled against
any temp-basal overrides — neither the profile nor "Temp Basal" treatments are
fetched anywhere in this codebase today, and profile access is explicitly the
other feature's territory ([requirements-profile-tuning.md](requirements-profile-tuning.md)).
Implementing this now would mean quietly duplicating profile-fetch logic between
two features that are supposed to stay separate. First pass ships **bolus-only**
stats (which are fully derivable from `treatments` alone) with an explicit label
that basal totals aren't included; true basal:bolus/TDD becomes a fast-follow
once the profile-tuning feature's Nightscout profile client exists and can be
reused read-only from here.
## 5. PDF export (FR10)
`kaleido` (Plotly's static-image renderer) bundles its own Chromium build —
meaningfully bigger image and more Trivy surface for not much benefit here.
Instead: `matplotlib` (already a transitive pandas dependency's peer, tiny
incremental footprint) renders simplified static charts specifically for the
PDF, and `fpdf2` (pure-Python, no system deps) assembles the PDF — same
approach, smaller/simpler Docker image, consistent with how carefully the
Trivy/registry-hostname issues were chased down in this project's CI history.
`pages/8_Export.py` lets the user check which sections to include, renders the
selected stats/charts via a new `pdf_export.py` (`build_report_pdf(sections: list[str], ...) -> bytes`),
and offers it via `st.download_button`.
## 6. Testing strategy
- `reporting.py` functions: unit tests in `tests/test_reporting.py`, same
fixture style as `tests/test_data_processing.py`, explicitly covering the
edge cases named in the requirements doc (14:59 vs 15:00 min events, two dips
separated by a brief recovery, empty input, 100%-in-range).
- `nightscout_client.py` additions: tests in the existing
`tests/test_nightscout_client.py`, same `monkeypatch`-on-`requests` pattern.
- `auth.py`: the hashing/compare logic is trivial enough to test directly
(`hashlib.sha256(...).hexdigest() == expected`) without needing to drive
Streamlit's UI.
- Page files (`pages/*.py`) are UI wiring only (like the existing `app.py`) —
consistent with this project's existing convention of not unit-testing the
Streamlit UI layer itself, only the logic it calls into.
- `pdf_export.py`: unit test that a given set of sections produces a non-empty,
valid PDF (`fpdf2`'s output starts with `%PDF`), without asserting on exact
rendered pixels.
## 7. Implementation order
1. Foundation: `auth.py`, multipage restructure (move current `app.py` →
`pages/1_Live.py`, new minimal `app.py`), `nightscout_client.py` range-fetch
additions — all independently testable, no visible feature yet.
2. `reporting.py` core: GMI, %CV, 5-band TIR, event detection + summaries —
the clinically load-bearing pieces, fully unit tested.
3. Wire pages 2–3–4–5–6 (summary, AGP, daily, hypo/hyper events) to `reporting.py`.
4. `reporting.py` extras: overnight/daytime split, day-of-week, bolus stats,
site-change impact; wire page 7 (trends).
5. PDF export (page 8) — last, since it's the most novel dependency and lowest
clinical risk if delayed a step.
Each step lands as its own commit(s) behind `ruff check .` + `pytest tests/ -v`,
pushed through the existing `dev` → PR → `main` flow so the CI/CD pipeline
(test → SonarQube → build+Trivy+push → deploy) validates every increment, per
the user's original request to implement requirement-by-requirement with as
much automated testing as possible.
+266
View File
@@ -0,0 +1,266 @@
> **Moved.** Implementation now lives in the separate `glucose-profile-tuning`
> repo; the canonical, actively maintained copy of this file is at
> `glucose-profile-tuning/docs/requirements-profile-tuning.md`. This copy is
> kept for history and is no longer updated.
# Requirements: oref0-autotune profile tuning
Status: **final**
Owner: willemjan
Related: [requirements-reporting.md](requirements-reporting.md) (separate feature, same Nightscout data source)
## 1. Purpose & background
AndroidAPS (AAPS) only gained built-in Autotune in version 3.4, and even that
version tunes only a single ISF/carb-ratio value plus the basal schedule from
on-device history — it doesn't use Nightscout at all, and the user is still on
AAPS 3.3 regardless. Previously, the user ran a hosted tool (inspired by
`MarkMpn/AutotuneWeb`, now archived/discontinued) that analyzed Nightscout data
with `oref0-autotune` and proposed a new pump profile, which was then manually
entered into AAPS — a process the user describes as "a lot of trial and error." Before that, the user ran the tool from `MarkMpn/AutotuneWeb` but that was discontinued and cost a lot of effort to make changes to the profile by manually entering the changes into AAPS.
This feature builds a guided, human-in-the-loop workflow: trigger an
oref0-autotune analysis from an internally self hosted application, review the proposed profile against
the current one with the underlying estimations visible, selectively
accept/adjust values, and stage the result in Nightscout for manual activation.
The user has two LXC containers on Proxmox from earlier experimentation —
`autotune` (VMID 102, 192.168.2.13) and `oref0` (VMID 107, 192.168.2.14) —
currently stopped, of unknown/half-remembered working state. The working container can be used for the profile calculations, but if another solutions surpasses in terms of integratability a new solutions can be set up.
## 2. Scope
**In scope:**
- Booting and inspecting the two existing LXCs to determine (or establish) a
working oref0-autotune setup.
- A small HTTP microservice on that LXC that runs oref0-autotune against the
user's Nightscout data on demand. Either one of the two existing LXCs or a new one.
- A **separate** app/service (own deployment, own CI/CD pipeline) that
triggers the analysis, displays old-vs-new profile comparisons with
estimation detail, lets the user selectively adjust proposed values, and
stages the result in Nightscout. The user can then choose if the profile is automatically activated in AndroidAPS (creating a
`"Profile Switch"` treatment)
- This app could be based on the glucose-dashboard streamlit app, but streamlit is not a fixed requirement, another solution can be used. For example, shiny for python.
- A nightly scheduled autotune run of which the results are visible in the morning. The profile of each run should be stored in a database. The user can read those back from the database in the application and can send it to nightscout/androidAPS, but the nightly scheduled runs should not send profiles automatically to nightscout and/or AAPS, this should always be a user action.
**Out of scope (this iteration):**
- Any change to AAPS settings or on-device configuration.
## 3. Architecture decisions (made during spec review)
1. **Execution**: an always-on HTTP microservice on whichever LXC has (or gets)
a working oref0-autotune setup, rather than SSH-triggering a one-off Docker
run or bundling autotune into the dashboard's own container. The dashboard
calls it over HTTP and polls for job completion.
2. **Profile push safety**: **stage-only**. The service writes a new named
profile into the Nightscout profile store and does create a
`"Profile Switch"` treatment when the user selected that option — final activation stays a manual
step in AAPS when the option is not selected. This matters because AndroidAPS applies
profiles via Profile Switch treatments (gated behind an explicit "accept
profile switch from Nightscout" AAPS setting), not by simply reading
`profile.json`.
3. **Deployment**: a separate app/service from `glucose-dashboard`, with its own
repo-or-directory, Dockerfile, and Gitea CI/CD pipeline — isolating
write-capable, dosing-adjacent code from the read-only dashboard.
## 4. Functional requirements
### FR1 — Infra investigation (first task, needs explicit go-ahead)
Boot LXC 102 (`autotune`) and LXC 107 (`oref0`) and inspect what's installed
(Docker containers, cron jobs, scripts, config, any README/notes left behind)
to determine which one — if either — has a working oref0-autotune setup.
Document findings (what's there, what's missing, what needs rebuilding).
*Acceptance:* a clear decision on which LXC hosts the microservice, and what
(if anything) needs to be installed/fixed there before FR2 can start.
**Status: done (2026-07-26).** Both LXCs were booted and inspected, then
stopped again (back to their original state — no state was left running).
- **LXC 102 (`autotune`, 192.168.2.13, 1 core / 1GB RAM / 16GB disk)** —
Docker installed, with the image `ghcr.io/houthacker/nightscout-autotune:latest`
(Alpine + Node 24, ~279MB) already pulled and previously run successfully
(9 months ago) against the real Nightscout instance
(`https://zb-ns.duckdns.org`). It bundles the full `oref0` npm toolkit
(`oref0-autotune`, `oref0-upload-profile`, `convert-ns-profile`,
`mm-format-ns-profile`, and more) under `/usr/local/bin`, not just the
autotune algorithm itself. Its documented interface is a single container
run with env vars: `NS_HOST`, `AUTOTUNE_DAYS`, `UAM_AS_BASAL` (mandatory),
plus optional `NS_TOKEN`/`NS_API_SECRET` (as sha1 hashes), `NS_PROFILE`,
`AUTOSENS_MIN`/`MAX`, `MIN_5MIN_CARBIMPACT`, `INSULIN_TYPE`,
`OPENAPS_WORKDIR`, `HTML_EXPORT`. A prior run's output is still on disk at
`/root/autotune-output/autotune/`: per-day `ns-entries`/`ns-treatments`
fetched from Nightscout, the oref0-format `profile.json` (input) and
`newprofile.YYYY-MM-DD.json` (recommendation), and a human-readable
`autotune_recommendations.log` (a `Pump | Autotune | Days Missing` table per
parameter/basal-slot — ideal source for FR4's estimation detail). Critically,
the image also has `oref0-upload-profile` (`profile.json NSURL api-secret
[--preview] [--switch]`) already installed — this is the piece that converts
an oref0-format profile back into Nightscout's profile-store format *and*
optionally issues the Profile Switch treatment, i.e. it already implements
what FR6 needs. `--preview` (dry run, no upload) is also useful for FR8's
confirmation step.
- **LXC 107 (`oref0`, 192.168.2.14, same specs)** — no Docker; a native
npm/`openaps` install of the raw `oref0` toolkit. Bash history shows a
messier path to a working run (locale errors needing `locale-gen`, several
retries with different flag spellings) before landing on a working
`oref0-autotune --dir=~/myopenaps --ns-host=... --start-date=...` invocation
and a manual `oref0-upload-profile ... --switch=true` call. It reaches the
same destination but through an unreproducible, hand-patched native
environment rather than a pinned, documented container image.
**Decision: LXC 102 is the base.** It already has a working, versioned,
well-documented container with both the analysis direction (Nightscout →
oref0 profile → recommendation) and the upload direction
(oref0 recommendation → Nightscout profile store, with optional Profile
Switch) solved, via tools already installed in the same image. No new
autotune image needs to be built or evaluated — the open question in §8 about
choosing between `p5nbTgip0r/autotune-docker` /
`houthacker42/nightscout-autotune` / a from-scratch `oref0` build is moot:
`houthacker/nightscout-autotune` is what's already there, already proven
against this Nightscout instance, and turns out to be the most complete of
the three. LXC 107 will be left stopped/decommissioned — its only asset (a
successful manual run) is already superseded by 102's cleaner path. FR2's
microservice will be built as a thin wrapper *around* the CLI tools already
baked into the `nightscout-autotune` image (see
[design-profile-tuning.md](design-profile-tuning.md)), rather than
reimplementing Nightscout-profile ⇄ oref0-profile conversion from scratch —
directly resolving the "had to manually parse parts of the profile" pain
point named in FR2.
### FR2 — Autotune HTTP microservice
A small HTTP API (exact framework TBD during design — e.g. Flask/FastAPI
wrapping a Docker-based oref0-autotune image) exposing at minimum:
- `POST /analyze` — body: Nightscout URL/token, date range, (optionally) the
starting profile to tune from. Returns a job ID.
- `GET /analyze/{job_id}` — status (`pending`/`running`/`done`/`failed`) and,
once done, the recommended profile JSON plus the estimation/recommendation
detail (per-hour deviations, the autotune log).
- In previous tries, the user had to manually parse parts of the profile as obtained from Nightscout to have it accpeted by the autotune service. This should be thoroughly investigated and subsequently automated
*Acceptance:* a manual `curl` against the running service, pointed at the
user's real Nightscout instance, returns a plausible recommended profile within
a reasonable time (minutes, not seconds — oref0-autotune is not instant).
### FR3 — Trigger analysis from the dashboard
A new app where the user picks a date range and selects a
current profile to tune from (fetched live from Nightscout), starts the
analysis, and sees progress while the microservice job runs (via polling).
Nightscout connection should be made using a token with a proper role.
*Acceptance:* starting an analysis with bad/unreachable Nightscout credentials
fails with a clear error rather than hanging silently.
### FR4 — Old-vs-new profile comparison view
Side-by-side display of the current and proposed profile: hourly basal rates,
ISF schedule, carb ratio schedule, DIA — plus the underlying estimation detail
(per-hour deviations, confidence notes) surfaced from the autotune log, so the
user can judge *why* a change is being proposed, not just see the new number.
*Acceptance:* every changed value is visually distinguishable from unchanged
values; the estimation detail for a given time slot is viewable alongside that
slot's proposed change.
### FR5 — Selective adjustment
Per time-slot controls (accept/reject each proposed basal/ISF/CR change
individually) plus editable numeric fields so the user can fine-tune any
accepted value before staging — matching the user's explicit request to
"select parts of the proposed profile and still adjust the values a bit."
This should look like a table with the columns 'time-slot' (per hour), 'current profile', 'suggestion', a input to select which column to select (current vs suggestion) and on the last column the final selected value, but as input numeric fields which can be changed by 0.01 steps.
*Acceptance:* rejecting a slot keeps the current value unchanged in the
staged profile; editing an accepted value's number is reflected in what
actually gets sent to Nightscout.
### FR6 — Stage to Nightscout
Write the resulting merged profile (accepted + manually adjusted values) as a
new named profile in the Nightscout profile store (e.g. `"Autotune
YYYY-MM-DD"` or `"Autotune YYYY-MM-DD ID"`) via a new POST to `/api/v1/profile`, with optionally creating a Profile
Switch treatment. After staging, show clear instructions for manual activation
in AAPS (or the Nightscout UI).
*Acceptance:* the new profile appears in Nightscout's profile list/editor with
exactly the merged values; the previously active profile is untouched and
still active until the user manually switches.
### FR7 — Audit / history
Keep a record of past analysis runs and what was accepted vs. rejected vs.
manually adjusted, for traceability (useful both for the user's own reference
and potentially for the hospital team). Could reuse Nightscout's own profile
history (each staged profile is already a new dated document) rather than a
separate store — **decide during design**.
### FR8 — Safety guardrails
- Surface oref0-autotune's own `autosens_min`/`autosens_max` bounds so the user
can see the algorithm's own safety rails, not just the raw numbers.
- Flag any accepted value that represents an unusually large jump from the
current profile.
- Require an explicit confirmation step (e.g. a review summary + confirmation
checkbox) before the FR6 write happens — no silent/implicit staging.
### FR9 — Automated nightly runs
Each night at 4:00 the analysis is triggered with a fixed amount of days, whatever gives usually the most accurate results, and stores the result in a database. The app should have a page where the latest run is shown and should have the same downstream options as FR3 has (FR4, FR5 and FR6).
*Acceptance:* The analysis appears on the nightly analysis page and gets pulled from the database with autotune results. When the analysis failed a reason for failure must be shown.
## 5. Non-functional requirements
- **NFR1 — Isolation**: separate repository-or-directory, Dockerfile, and Gitea
CI/CD pipeline from `glucose-dashboard`, modeled on the existing pipeline
(test/lint → build+Trivy+push → deploy) but with its own secrets.
- **NFR2 — Nightscout token scope**: the existing dashboard token is documented
read-only by convention (see `glucose-dashboard/README.md`). This feature
needs a **separate, write-scoped** Nightscout token (Nightscout supports
role-based tokens — e.g. a `careportal`-level role) rather than upgrading the
shared read-only token, so the read-only reporting dashboard's blast radius
doesn't change.
- **NFR3 — Test safety**: automated tests must never call a real Nightscout
instance or the real autotune microservice — mock both, following the
existing `monkeypatch`-on-`requests` pattern from `glucose-dashboard`'s test
suite.
- **NFR4 — CI/CD gating**: given this pipeline can end in a write to a real
medical data store, add a `pull_request` trigger
for the test/lint job so changes are validated *before* merge, not only
after — the current `glucose-dashboard` pipeline only triggers on `push` to
`main`.
- **NFR5 — Framework**: make a descision on which framework the solution can be based best. For example streamlit, shiny for python etc.
## 6. Data requirements
- `GET /api/v1/profile.json` — read the current active profile store
(net-new capability; nothing in `nightscout_client.py` handles profiles today).
- `POST /api/v1/profile.json` — write the new named profile (net-new).
- The autotune microservice's own job API (FR2).
- Read access to entries/treatments over the analysis date range (can reuse the
reporting feature's date-range fetch capability once built, or the existing
rolling-window fetch for shorter tuning windows).
## 7. Testing & acceptance criteria
- Unit tests for the profile merge/validation logic (accept/reject/adjust
producing the correct final profile document) — pure functions, no I/O,
fully testable without any live service.
- Unit tests for the new Nightscout profile read/write client functions, using
the existing `FakeResponse`/`monkeypatch.setattr(requests, ...)` pattern.
- Integration-style tests against the autotune microservice using a mocked
HTTP layer (never the real LXC service in CI).
- A UAT checklist (produced during the design phase) exercising the full flow
end-to-end against the user's real Nightscout instance and the real
microservice: trigger → review → adjust → stage → manually verify the new
profile appears correctly in Nightscout, with no unintended Profile Switch.
## 8. Open questions for the user's edit pass
1. ~~Which LXC (102 or 107 or new) ends up hosting the service, once FR1 is
done?~~ **Resolved (FR1 complete, see below): LXC 102 (`autotune`).**
2. ~~Which autotune Docker image to standardize on?~~ **Resolved: the image
already installed on LXC 102 —
`ghcr.io/houthacker/nightscout-autotune:latest`.** See findings below.
3. Should automatic Profile Switch activation become an opt-in "phase 2" later,
once you've built trust in the recommendations — or should manual
activation remain permanent policy regardless of trust? Can already start automate it as i've added in the requirements
4. FR7 (audit/history) — is reusing Nightscout's own profile-document history
sufficient, or do you want a dedicated log outside Nightscout? Create a dedicated store of analysis and include proper production grade logging for the full application so debugging later will be easier.
5. Confirm the separate write-scoped Nightscout token is something you're
comfortable creating/managing (NFR2) — this is a manual one-time setup step
in the Nightscout admin UI, not something the app can do for you. Yes, i can create a new token, if you indicate which rights it needs.
+198
View File
@@ -0,0 +1,198 @@
# Requirements: Clinical reporting page
Status: **draft — for review and editing**
Owner: willemjan
Related: [requirements-profile-tuning.md](requirements-profile-tuning.md) (separate feature, separate app)
## 1. Purpose & background
The previous FreeStyle Libre 2 setup (via LibreView) produced clinical reports
that the hospital/diabetes team wants to keep seeing: a multi-month time-in-range
(TIR) overview, day-by-day glucose graphs, hypoglycemia event analysis, and an
estimated HbA1c. The current DIY closed-loop setup (Medtrum TouchCare Nano 200U +
Lyumjev + Dexcom One+ via xDrip+ + AndroidAPS) stores everything in Nightscout,
which has no equivalent built-in report.
This feature adds a **reporting page to the existing `glucose-dashboard` Streamlit
app**, generating the closest practical equivalent from Nightscout data — read-only,
no new infrastructure, deployed through the existing CI/CD pipeline.
## 2. Scope
**In scope:**
- A new set of pages in the existing Streamlit app, reading `entries` (glucose) and
`treatments` (insulin, carbs) from Nightscout.
- Multi-day statistical summaries, an AGP-style percentile chart, day-by-day
glucose graphs, hypo/hyper event analysis, and an estimated HbA1c (GMI) on separate pages where not closely related.
- Generating PDF output of user selected pages, so the user can send the report to the hospital.
**Out of scope (this feature):**
- Anything that writes to Nightscout (see the separate profile-tuning spec).
- Non-Nightscout data sources.
- The oref0-autotune integration.
## 3. Clinical definitions & standards used
These are the standard definitions this report is built against (international
consensus, mainly based on dutch requirements, not invented for this project) the ranges are described in the table below.
| Term | Definition | Source |
|---|---|---|
| Hypoglycemia Level 1 | < 3.9 mmol/L (<70 mg/dL) | Battelino et al. 2019, *Diabetes Care* 42(8):1593–1603 |
| Hypoglycemia Level 2 | < 3.0 mmol/L (<54 mg/dL) | same |
| Hyperglycemia Level 1 | > 10.0 mmol/L (>180 mg/dL) | same |
| Hyperglycemia Level 2 | > 13.9 mmol/L (>250 mg/dL) | same |
| Event persistence rule | A hypo/hyper **event** starts once glucose has been continuously past the threshold for **≥15 minutes**, and ends once it has recovered past the threshold for **≥15 minutes**. A brief single reading crossing back doesn't end the event. | Battelino et al. 2019 |
| Time-in-range targets (adult, general) | TIR (3.9–10.0) >70% · TBR<3.9 <4% · TBR<3.0 <1% · TAR>10.0 <25% · TAR>13.9 <5% | Battelino et al. 2019 |
| GMI (estimated HbA1c) | `GMI% = 3.31 + 0.02392 × mean(mg/dL)` = `3.31 + 0.4311 × mean(mmol/L)` | Bergenstal et al. 2018, *Diabetes Care* 41(11):2275–2280 |
| Minimum valid report | ≥14 days of data with ≥70% sensor-active time | consensus standard |
Note: this dashboard already uses `TARGET_LOW = 3.9` / `TARGET_HIGH = 10.0` in
[`data_processing.py`](../data_processing.py) — that matches Level 1 thresholds
above, so the existing constants carry over directly; Level 2 thresholds are new.
GMI is explicitly **not** a substitute for a lab HbA1c (can differ by ~0.5
percentage points due to red blood cell/hemoglobin factors) — the report should
label it "estimated HbA1c (GMI)", not "HbA1c", to avoid confusing the hospital
team.
## 4. Functional requirements
Each FR below is meant to be independently implementable and testable, so they
can be delivered one at a time through the CI/CD pipeline.
### FR1 — Report period selector
The user can choose the reporting period: **14 days** (clinical default), 30
days, **90 days** (matches the old Libre 2 quarterly view), or a custom date
range. The period should be settable for each page separately since 90 days are relevant for A1C calculations and time in range but not so much for daily overview where 14 days is more relavant to the clinic. The selection drives every other requirement below.
*Acceptance:* selecting a period reloads the specific report page for that exact date
range; the 90-day option must not time out or hang (see NFR1 on data volume).
### FR2 — AGP-style summary statistics
A summary panel showing, for the selected period:
- % of time CGM was active (data completeness)
- Average glucose (mmol/L)
- Estimated HbA1c (GMI)
- Glucose variability (%CV = stdev/mean × 100)
- Time-in-range breakdown across the 5 standard bands (<3.0, 3.0–3.9, 3.9–10.0,
10.0–13.9, >13.9), each shown as a percentage and as hours:minutes/day
- Each stat shown against its consensus target (pass/fail or color-coded)
*Acceptance:* stats match a hand-calculated reference on a small fixture dataset
(see §7); TIR/TBR/TAR percentages sum to 100%.
### FR3 — AGP percentile chart
A single chart showing the 5th/25th/50th(median)/75th/95th percentile glucose
bands, aggregated by time-of-day across the selected period onto one 24-hour
composite axis (the standard AGP visualization).
*Acceptance:* median line at a given hour matches the median of all readings at
that hour-of-day across the period, computed independently in a test.
### FR4 — Day-by-day glucose graphs
One glucose trace per calendar day in the selected period (reusing the existing
target-range-band chart style from [`app.py`](../app.py)'s `build_chart`, adapted
for a single day per panel), so the hospital team can review specific days the
way the Libre 2 report's daily log did.
*Acceptance:* each day's panel shows exactly that day's readings; days with no
data are shown as empty/skipped rather than causing an error.
### FR5 — Hypoglycemia event analysis
Detect discrete hypo events per the persistence rule in §3, and report:
- Total event count (Level 1 and Level 2 separately)
- Duration of each event, and summary stats (average, longest, total time low)
- Events per week
- Time-of-day distribution (e.g., overnight vs. daytime split)
*Acceptance:* event count/duration matches a hand-traced fixture (a synthetic
glucose series with known dips of known duration, including edge cases: a dip
just under 15 minutes that should NOT count, and two dips separated by a brief
recovery that should count as one continuous event per the persistence rule).
### FR6 — Hyperglycemia event analysis
Same as FR5, symmetric, for Level 1/Level 2 highs. (Not explicitly requested by
the user but a natural complement and confirmed to implement by the user.)
### FR7 — Estimated HbA1c trend
GMI computed per rolling period (e.g., per month within a 90-day report),
plotted as a small trend, so the hospital team can see whether control is
improving/worsening over the quarter, not just the endpoint value.
### FR8 — Candidate additional statistics
The user mentioned having seen "other interesting stats" in other reports
without specifying which. Candidates to consider:
- Day-of-week pattern (e.g., weekends vs. weekdays)
- Overnight (00:00–06:00) vs. daytime TIR split
- Basal:bolus insulin ratio
- Insulin pump site-change and sensor-change adherence (interval between changes,
reusing existing `classify_treatments` output)
- Glucose trends after site-change
- Pump site age vs insuline usage vs glucose levels. Corrected for carb intake to see if age of the pump-site and/or insuline age influence insulin usage
- Total daily insulin dose trend
### FR9 — Data completeness / quality indicator
Flag periods with low sensor-active time (<70%) or visible data gaps, since a
report built on incomplete data is clinically unreliable — the report should
surface this rather than silently computing misleading stats.
### FR10 — Export / print-friendly view (open question)
The Libre 2 reports were shown to or printed for the hospital team.
The pages needs a print-optimized layout, a PDF export, and a
"share the dashboard URL".
## 5. Non-functional requirements
- **NFR1 — Data volume**: the existing `fetch_entries`/`fetch_treatments` in
[`nightscout_client.py`](../nightscout_client.py) scale their `count` parameter
linearly with `hours`, which doesn't scale cleanly to 90 days (~26,000 5-minute
readings). This feature needs either a proper date-range fetch (`find[date]`
query params) or paginated fetching — a new capability, not a reuse of the
existing rolling-window functions as-is.
- **NFR2 — Caching**: historical data for a fixed past period doesn't change; cache
TTL should be much longer than the existing 60-second rolling-view cache
(`app.py`'s `load_nightscout_data`), e.g. cached per exact date-range until
explicitly refreshed.
- **NFR3 — Consistency**: reuse the existing `PALETTE` dict and `st.context.theme`
detection pattern from `app.py` rather than introducing new colors; reuse
`TARGET_LOW`/`TARGET_HIGH` from `data_processing.py`.
- **NFR4 — Language**: Dutch UI strings and docstrings, consistent with the rest
of the app.
- **NFR5 — Multipage navigation**: this is the first feature needing more than one
page — introduces `st.Page`/`st.navigation` (anticipated in the project's own
`homelab-cicd-werkinstructie.md`).
- **NFR6 - Password protection on the dashboard pages**: as dashboard urls will be sharable and reachable by the diabetes team, access should be restricted to authorized users.
## 6. Data requirements
- Glucose entries over an arbitrary date range (new: `fetch_entries` needs a
date-range mode, not just "last N hours").
- Treatments over the same range (same scaling concern).
- No new Nightscout permissions needed — this feature only reads, so the
existing read-only token is sufficient.
## 7. Testing & acceptance criteria
- Each new pure function (event detection, GMI calculation, percentile
aggregation, %CV) gets unit tests in `data_processing.py` or a new
`reporting.py` module, following the existing `tests/test_data_processing.py`
fixture-based pattern — including edge cases called out per FR above (empty
data, exactly-15-minute boundary events, 100% in-range, etc.).
- Any new Nightscout fetch logic gets tests following the existing
`tests/test_nightscout_client.py` `monkeypatch`-on-`requests` pattern.
- A UAT checklist (produced during the design phase) will map each FR's
"Acceptance" line above to a concrete scenario the user can manually verify
against their own real Nightscout data.
## 8. Open questions for the user's edit pass
1. Confirm the clinical thresholds/targets in §3 match what your hospital
actually uses, or note any local adaptations. - Use the suggested clinical thresholds and targets from §3
2. FR6 (hyperglycemia analysis) — keep
3. FR8 — which candidate stats actually matter to you / your team? All that are in FR8 now
4. FR10 — is a print/export view needed, or is viewing the dashboard directly
enough? - pdf export needed
5. Default report period: 14-day (clinical standard) or 90-day (matches your
old Libre 2 habit) as the page's default view? Default 90 days for statistics, but 14 days for recent glucose charts.
+155 -30
View File
@@ -18,7 +18,7 @@ from __future__ import annotations
import hashlib import hashlib
import os import os
from datetime import datetime, timedelta, timezone from datetime import date, datetime, time, timedelta, timezone
import pandas as pd import pandas as pd
import requests import requests
@@ -31,6 +31,38 @@ SENSOR_CHANGE_EVENT_TYPES = {"Sensor Change", "Sensor Start"}
_REQUEST_TIMEOUT = 10 _REQUEST_TIMEOUT = 10
# Nightscout's /api/v1/entries en /api/v1/treatments negeren een groot
# `count`-verzoek: het antwoord wordt hoe dan ook stilzwijgend afgeknipt rond
# een paar honderd tot ~1150 documenten, ongeacht hoe ver de opgevraagde
# periode teruggaat (waargenomen: count=100000 op entries gaf slechts de
# meest recente ~1150 metingen terug — nog geen 4 dagen — terwijl er wel
# degelijk weken oudere data in Nightscout beschikbaar bleek te zijn). Eén
# verzoek is dus niet genoeg voor meerdaagse rapportages; _paginated_get()
# loopt terug in de tijd met `find[...][$lte]`-cursors tot de gevraagde
# `since`-grens bereikt is of de server minder dan een volle pagina teruggeeft
# (= geen oudere data meer beschikbaar, wat verschilt van "afgeknipt").
#
# De twee endpoints filteren op een ANDER veld, en /treatments heeft nog een
# addertje: entries filtert/sorteert op het numerieke `date` (epoch ms) en
# geeft zonder filter gewoon de meest recente `count` terug. treatments
# filtert/sorteert op het string-veld `created_at` (ISO 8601) — filteren op
# `date` levert daar stil een lege pagina op zodra je voorbij een intern
# venster van ~4 dagen gaat, ook al bevatten de documenten prima een geldig
# `date`-veld (geverifieerd rechtstreeks in MongoDB: alle 123k+ treatments
# hebben een numeriek `date`, en zonder enig filter geeft het endpoint alsnog
# stilzwijgend niet meer dan ~4 dagen terug). Zodra je expliciet op
# `created_at` filtert — zelfs met "nu" als bovengrens op de eerste pagina —
# werkt paginering wél correct en is de volledige geschiedenis (maanden,
# geverifieerd in de database) gewoon opvraagbaar. Vandaar: de cursor wordt
# nooit weggelaten (ook niet op de allereerste pagina), en welk veld
# gebruikt wordt is per endpoint expliciet ("date" voor entries,
# "created_at" voor treatments) — zie ENTRIES_CURSOR_FIELD/TREATMENTS_CURSOR_FIELD.
_PAGE_SIZE = 1000
_MAX_PAGES = 150 # 150 000 documenten; ruim boven wat een 90-dagenrapport nodig heeft
ENTRIES_CURSOR_FIELD = "date"
TREATMENTS_CURSOR_FIELD = "created_at"
class NightscoutConfigError(RuntimeError): class NightscoutConfigError(RuntimeError):
"""NIGHTSCOUT_URL ontbreekt of is ongeldig.""" """NIGHTSCOUT_URL ontbreekt of is ongeldig."""
@@ -75,19 +107,62 @@ def _get(path: str, params: dict) -> list:
return response.json() return response.json()
def fetch_entries(hours: int = 24) -> pd.DataFrame: def _format_cursor(cursor_dt: datetime, cursor_field: str) -> int | str:
"""Haal glucosemetingen (SGV) op van de laatste `hours` uur, in mmol/L. """Zet een cursor-datetime om naar de vorm die het gekozen veld verwacht."""
if cursor_field == ENTRIES_CURSOR_FIELD:
return int(cursor_dt.timestamp() * 1000)
# created_at: milliseconde-precisie ISO 8601 met Z-suffix, exact het
# formaat dat Nightscout zelf in created_at opslaat.
return cursor_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
Geeft een DataFrame terug met kolommen 'timestamp' en 'mmol', oplopend
gesorteerd op tijd. def _parse_item_time(item: dict, cursor_field: str) -> datetime | None:
"""Lees het tijdstip van een document uit het veld waar dit endpoint op filtert."""
if cursor_field not in item:
return None
if cursor_field == ENTRIES_CURSOR_FIELD:
return datetime.fromtimestamp(item[cursor_field] / 1000, tz=timezone.utc)
return datetime.fromisoformat(item[cursor_field].replace("Z", "+00:00"))
def _paginated_get(
path: str, since: datetime, until: datetime | None, cursor_field: str
) -> list:
"""Haal alle documenten op tussen `since` en `until` (of tot nu), pagina voor pagina.
Zie de toelichting bij _PAGE_SIZE hierboven voor waarom dit niet één
verzoek met een groot `count` kan zijn, en waarom `cursor_field` per
endpoint verschilt en nooit wordt weggelaten (BUG, zowel de originele
count-truncatie als treatments' verborgen ~4-dagenvenster zonder
expliciet find[created_at]-filter). Elke pagina wordt opgevraagd met een
cursor net onder de oudste timestamp van de vorige pagina, zodat elk
document precies één keer terugkomt. Stopt zodra de oudste timestamp in
een pagina op of voorbij `since` ligt, of zodra de server minder dan een
volle pagina teruggeeft (dan is er geen oudere data meer, punt).
""" """
since = datetime.now(timezone.utc) - timedelta(hours=hours) cursor_dt = until if until is not None else datetime.now(timezone.utc)
# Nightscout geeft resultaten terug in aflopende volgorde; vraag ruim
# genoeg entries op (CGM meet doorgaans elke 5 min) en filter lokaal op results: list = []
# tijd. Dit is robuuster dan server-side find[]-query's, die niet op elke for _ in range(_MAX_PAGES):
# Nightscout-versie identiek werken. params = {"count": _PAGE_SIZE, f"find[{cursor_field}][$lte]": _format_cursor(cursor_dt, cursor_field)}
count = max(300, hours * 15) page = _get(path, params)
data = _get("/api/v1/entries/sgv.json", {"count": count}) if not page:
break
results.extend(page)
item_times = [t for t in (_parse_item_time(item, cursor_field) for item in page) if t is not None]
if not item_times:
break
oldest_dt = min(item_times)
if oldest_dt <= since or len(page) < _PAGE_SIZE:
break
cursor_dt = oldest_dt - timedelta(milliseconds=1)
return results
def _entries_since(since: datetime, until: datetime | None = None) -> pd.DataFrame:
"""Haal entries op sinds `since` (en optioneel tot `until`), lokaal gefilterd."""
data = _paginated_get("/api/v1/entries/sgv.json", since, until, ENTRIES_CURSOR_FIELD)
if not data: if not data:
return pd.DataFrame(columns=["timestamp", "mmol"]) return pd.DataFrame(columns=["timestamp", "mmol"])
@@ -96,9 +171,56 @@ def fetch_entries(hours: int = 24) -> pd.DataFrame:
df["timestamp"] = pd.to_datetime(df["date"], unit="ms", utc=True).dt.tz_localize(None) df["timestamp"] = pd.to_datetime(df["date"], unit="ms", utc=True).dt.tz_localize(None)
df["mmol"] = df["sgv"].astype(float).apply(mgdl_to_mmol) df["mmol"] = df["sgv"].astype(float).apply(mgdl_to_mmol)
df = df[df["timestamp"] >= since.replace(tzinfo=None)] df = df[df["timestamp"] >= since.replace(tzinfo=None)]
if until is not None:
df = df[df["timestamp"] <= until.replace(tzinfo=None)]
return df[["timestamp", "mmol"]].sort_values("timestamp").reset_index(drop=True) return df[["timestamp", "mmol"]].sort_values("timestamp").reset_index(drop=True)
_TREATMENT_COLUMNS = ["timestamp", "eventType", "insulin", "carbs", "type", "absolute", "duration"]
def _treatments_since(since: datetime, until: datetime | None = None) -> pd.DataFrame:
"""Haal treatments op sinds `since` (en optioneel tot `until`), lokaal gefilterd.
`type` en `absolute`/`duration` komen erbij naast de oorspronkelijke
kolommen: AndroidAPS registreert een SMB-microbolus niet als eigen
`eventType`, maar als `eventType == "Correction Bolus"` met
`type == "SMB"` (zie reporting.bolus_stats() / gitea #20) — en
`absolute` (E/uur) + `duration` (minuten) op Temp Basal-treatments maken
het mogelijk afgeleverde basaalinsuline te berekenen zonder het
pompprofiel te hoeven ophalen (zie reporting.basal_stats()).
"""
data = _paginated_get("/api/v1/treatments.json", since, until, TREATMENTS_CURSOR_FIELD)
if not data:
return pd.DataFrame(columns=_TREATMENT_COLUMNS)
df = pd.DataFrame(data)
df["timestamp"] = pd.to_datetime(df["created_at"], utc=True).dt.tz_localize(None)
for col in ("insulin", "carbs", "absolute", "duration"):
if col not in df.columns:
df[col] = pd.NA
df[col] = pd.to_numeric(df[col], errors="coerce")
for col in ("eventType", "type"):
if col not in df.columns:
df[col] = ""
df[col] = df[col].fillna("")
df = df[df["timestamp"] >= since.replace(tzinfo=None)]
if until is not None:
df = df[df["timestamp"] <= until.replace(tzinfo=None)]
return df[_TREATMENT_COLUMNS].sort_values("timestamp").reset_index(drop=True)
def fetch_entries(hours: int = 24) -> pd.DataFrame:
"""Haal glucosemetingen (SGV) op van de laatste `hours` uur, in mmol/L.
Geeft een DataFrame terug met kolommen 'timestamp' en 'mmol', oplopend
gesorteerd op tijd.
"""
since = datetime.now(timezone.utc) - timedelta(hours=hours)
return _entries_since(since)
def fetch_treatments(hours: int = 24) -> pd.DataFrame: def fetch_treatments(hours: int = 24) -> pd.DataFrame:
"""Haal behandelingen op van de laatste `hours` uur: insuline, koolhydraten """Haal behandelingen op van de laatste `hours` uur: insuline, koolhydraten
en pomp-/sensorwissels. en pomp-/sensorwissels.
@@ -107,23 +229,26 @@ def fetch_treatments(hours: int = 24) -> pd.DataFrame:
'insulin' en 'carbs' (de laatste twee NaN waar niet van toepassing). 'insulin' en 'carbs' (de laatste twee NaN waar niet van toepassing).
""" """
since = datetime.now(timezone.utc) - timedelta(hours=hours) since = datetime.now(timezone.utc) - timedelta(hours=hours)
count = max(200, hours * 10) return _treatments_since(since)
data = _get("/api/v1/treatments.json", {"count": count})
if not data:
return pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs"])
df = pd.DataFrame(data) def fetch_entries_range(start_date: date, end_date: date) -> pd.DataFrame:
df["timestamp"] = pd.to_datetime(df["created_at"], utc=True).dt.tz_localize(None) """Haal glucosemetingen op tussen start_date en end_date (beide inclusief).
for col in ("insulin", "carbs"):
if col not in df.columns: Bedoeld voor meerdaagse rapportages (bijv. 90 dagen) waarbij het
df[col] = pd.NA uren-schalende `fetch_entries` niet praktisch is. Zelfde kolommen als
df[col] = pd.to_numeric(df[col], errors="coerce") `fetch_entries`.
if "eventType" not in df.columns: """
df["eventType"] = "" since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
df = df[df["timestamp"] >= since.replace(tzinfo=None)] until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
return ( return _entries_since(since, until)
df[["timestamp", "eventType", "insulin", "carbs"]]
.sort_values("timestamp")
.reset_index(drop=True) def fetch_treatments_range(start_date: date, end_date: date) -> pd.DataFrame:
) """Haal behandelingen op tussen start_date en end_date (beide inclusief).
Zelfde kolommen als `fetch_treatments`.
"""
since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
return _treatments_since(since, until)
+205
View File
@@ -0,0 +1,205 @@
import plotly.graph_objects as go
import requests
import streamlit as st
from auth import require_auth
from data_processing import (
TARGET_HIGH,
TARGET_LOW,
classify_treatments,
summarize_time_in_range,
)
from nightscout_client import NightscoutConfigError, fetch_entries, fetch_treatments
from ui_common import MMOL_HOVERTEMPLATE, get_colors
st.set_page_config(page_title="Glucose dashboard — Live", page_icon="📊", layout="wide")
require_auth()
st.title("Glucose dashboard")
HOURS_OPTIONS = {"6 uur": 6, "12 uur": 12, "24 uur": 24, "48 uur": 48}
@st.cache_data(ttl=60, show_spinner="Data ophalen van Nightscout...")
def load_nightscout_data(hours: int):
glucose = fetch_entries(hours=hours)
treatments = fetch_treatments(hours=hours)
return glucose, treatments
def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -> go.Figure:
glucose_min = min(glucose["mmol"].min(), TARGET_LOW)
glucose_max = max(glucose["mmol"].max(), TARGET_HIGH)
y_top = glucose_max + 1.0
lane_base = glucose_min - 2.5
y_bottom = lane_base - 0.5
insulin_lane_y = lane_base + 1.5
carbs_lane_y = lane_base + 0.7
fig = go.Figure()
# Streefbereik als achtergrondband, geen losse legenda-entry nodig.
fig.add_hrect(
y0=TARGET_LOW,
y1=TARGET_HIGH,
fillcolor=colors["band"],
line_width=0,
layer="below",
)
fig.add_trace(
go.Scatter(
x=glucose["timestamp"],
y=glucose["mmol"],
mode="lines",
name="Glucose",
line={"color": colors["glucose"], "width": 2, "shape": "spline"},
hovertemplate=MMOL_HOVERTEMPLATE,
)
)
low_points = glucose[glucose["mmol"] < TARGET_LOW]
high_points = glucose[glucose["mmol"] > TARGET_HIGH]
if not low_points.empty:
fig.add_trace(
go.Scatter(
x=low_points["timestamp"],
y=low_points["mmol"],
mode="markers",
name=f"Laag (<{TARGET_LOW})",
marker={"color": colors["low"], "size": 6},
hovertemplate=MMOL_HOVERTEMPLATE,
)
)
if not high_points.empty:
fig.add_trace(
go.Scatter(
x=high_points["timestamp"],
y=high_points["mmol"],
mode="markers",
name=f"Hoog (>{TARGET_HIGH})",
marker={"color": colors["high"], "size": 6},
hovertemplate=MMOL_HOVERTEMPLATE,
)
)
if not insulin.empty:
fig.add_trace(
go.Scatter(
x=insulin["timestamp"],
y=[insulin_lane_y] * len(insulin),
mode="markers",
name="Insuline",
marker={"color": colors["insulin"], "size": 10, "symbol": "triangle-up"},
customdata=insulin["insulin"],
hovertemplate="%{x|%d-%m %H:%M} · %{customdata:.1f} E<extra></extra>",
)
)
if not carbs.empty:
fig.add_trace(
go.Scatter(
x=carbs["timestamp"],
y=[carbs_lane_y] * len(carbs),
mode="markers",
name="Koolhydraten",
marker={"color": colors["carbs"], "size": 10, "symbol": "circle"},
customdata=carbs["carbs"],
hovertemplate="%{x|%d-%m %H:%M} · %{customdata:.0f} g<extra></extra>",
)
)
# Let op: annotation_text/-position via add_vline() zelf triggert een bug
# in plotly's shapeannotation-helper met pandas Timestamp-x-waarden, dus
# de lijn en het label worden hier los toegevoegd.
for _, row in site_changes.iterrows():
fig.add_vline(x=row["timestamp"], line_dash="dot", line_color=colors["muted"], opacity=0.6)
fig.add_annotation(
x=row["timestamp"],
y=y_top,
yanchor="bottom",
text="Pomp",
showarrow=False,
font={"color": colors["muted"], "size": 10},
)
for _, row in sensor_changes.iterrows():
fig.add_vline(x=row["timestamp"], line_dash="dash", line_color=colors["muted"], opacity=0.6)
fig.add_annotation(
x=row["timestamp"],
y=y_top,
yanchor="bottom",
text="Sensor",
showarrow=False,
font={"color": colors["muted"], "size": 10},
)
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
margin={"l": 10, "r": 10, "t": 10, "b": 10},
height=480,
yaxis={
"title": "mmol/L",
"range": [y_bottom, y_top],
"gridcolor": colors["grid"],
"zeroline": False,
},
xaxis={"gridcolor": colors["grid"]},
)
return fig
with st.sidebar:
st.header("Instellingen")
hours_label = st.radio("Periode", list(HOURS_OPTIONS.keys()), index=2)
hours = HOURS_OPTIONS[hours_label]
if st.button("Vernieuwen"):
st.cache_data.clear()
try:
glucose, treatments = load_nightscout_data(hours)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc: # netwerk-/API-fouten van Nightscout
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
events = classify_treatments(treatments)
tir = summarize_time_in_range(glucose)
latest = glucose.iloc[-1]
previous = glucose.iloc[-2] if len(glucose) > 1 else None
delta = round(latest["mmol"] - previous["mmol"], 1) if previous is not None else None
col1, col2, col3, col4 = st.columns(4)
col1.metric("Actuele glucose", f"{latest['mmol']:.1f} mmol/L", delta=delta, delta_color="off")
col2.metric("Tijd in bereik", f"{tir['in_range']:.0f}%")
col3.metric("Tijd laag", f"{tir['low']:.0f}%")
col4.metric("Tijd hoog", f"{tir['high']:.0f}%")
st.caption(
f"Laatste meting: {latest['timestamp'].strftime('%d-%m-%Y %H:%M')} · "
f"streefbereik {TARGET_LOW}-{TARGET_HIGH} mmol/L"
)
colors = get_colors()
fig = build_chart(
glucose,
events["insulin"],
events["carbs"],
events["site_changes"],
events["sensor_changes"],
colors,
)
st.plotly_chart(fig, width="stretch")
st.caption(
"Driehoekjes = insuline · cirkels = koolhydraten · stippellijn = pompwissel · "
"streepjeslijn = sensorwissel"
)
+86
View File
@@ -0,0 +1,86 @@
import requests
import streamlit as st
from auth import require_auth
from nightscout_client import NightscoutConfigError
from reporting import (
gmi_mmol_per_mol,
gmi_percent,
percent_cv,
sensor_active_percent,
tir_breakdown_5band,
)
from ui_common import (
build_tir_stacked_bar_figure,
get_colors,
load_range_data,
render_completeness_warning,
select_period_days,
)
st.set_page_config(page_title="Glucose dashboard — Samenvatting", page_icon="📊", layout="wide")
require_auth()
st.title("Samenvatting")
st.caption("AGP-stijl samenvattingsstatistieken over een gekozen periode (FR2, FR9).")
start, end, days = select_period_days(default_label="90 dagen")
try:
glucose, _treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
active_pct = sensor_active_percent(glucose, start, end)
mean_mmol = glucose["mmol"].mean()
gmi = gmi_percent(mean_mmol)
gmi_mmol_mol = gmi_mmol_per_mol(gmi)
cv = percent_cv(glucose)
tir = tir_breakdown_5band(glucose)
st.subheader("Kerncijfers")
col1, col2, col3, col4 = st.columns(4)
col1.metric("Sensordekking", f"{active_pct:.0f}%", help="Streefwaarde: ≥70%")
col2.metric("Gemiddelde glucose", f"{mean_mmol:.1f} mmol/L")
col3.metric(
"Geschat HbA1c (GMI)",
f"{gmi:.1f}% ({gmi_mmol_mol:.0f} mmol/mol)",
help="Bergenstal et al. 2018 — geen labwaarde",
)
col4.metric("Variabiliteit (%CV)", f"{cv:.0f}%", help="Streefwaarde: ≤36%")
st.subheader("Tijd in bereik (5 klinische banden)")
band_labels = {
"very_low": "Zeer laag (<3.0)",
"low": "Laag (3.0-3.9)",
"in_range": "In bereik (3.9-10.0)",
"high": "Hoog (10.0-13.9)",
"very_high": "Zeer hoog (>13.9)",
}
band_targets = {
"very_low": "<1%",
"low": "<4% (samen met zeer laag)",
"in_range": ">70%",
"high": "<25% (samen met zeer hoog)",
"very_high": "<5%",
}
cols = st.columns(5)
for col, band in zip(cols, band_labels, strict=True):
col.metric(band_labels[band], f"{tir[band]:.0f}%", help=f"Streefwaarde: {band_targets[band]}")
st.plotly_chart(build_tir_stacked_bar_figure(tir, get_colors()), width="stretch")
st.caption(
f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')} "
f"({len(glucose)} metingen) · streefwaarden volgens Battelino et al. 2019"
)
+110
View File
@@ -0,0 +1,110 @@
import plotly.graph_objects as go
import requests
import streamlit as st
from auth import require_auth
from data_processing import TARGET_HIGH, TARGET_LOW
from nightscout_client import NightscoutConfigError
from reporting import agp_percentile_bands
from ui_common import (
add_threshold_lines,
get_colors,
hex_to_rgba,
load_range_data,
render_completeness_warning,
select_period_days,
)
st.set_page_config(page_title="Glucose dashboard — AGP profiel", page_icon="📊", layout="wide")
require_auth()
st.title("AGP profiel")
st.caption(
"Percentielgrafiek over een samengesteld 24-uursbeeld (FR3) — de 5e/25e/50e/75e/"
"95e percentiel van alle metingen op elk tijdstip van de dag in de gekozen periode."
)
start, end, days = select_period_days(default_label="90 dagen")
try:
glucose, _treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
bands = agp_percentile_bands(glucose, bin_minutes=30)
colors = get_colors()
hours = bands["minute_of_day"] / 60
fig = go.Figure()
fig.add_hrect(y0=TARGET_LOW, y1=TARGET_HIGH, fillcolor=colors["band"], line_width=0, layer="below")
# 5e-95e percentiel als brede, lichte band.
fig.add_trace(
go.Scatter(x=hours, y=bands["p95"], mode="lines", line={"width": 0}, showlegend=False, hoverinfo="skip")
)
fig.add_trace(
go.Scatter(
x=hours,
y=bands["p5"],
mode="lines",
line={"width": 0},
fill="tonexty",
fillcolor=colors["band"],
name="5e-95e percentiel",
hoverinfo="skip",
)
)
# 25e-75e percentiel als smallere, donkerdere band.
fig.add_trace(
go.Scatter(x=hours, y=bands["p75"], mode="lines", line={"width": 0}, showlegend=False, hoverinfo="skip")
)
fig.add_trace(
go.Scatter(
x=hours,
y=bands["p25"],
mode="lines",
line={"width": 0},
fill="tonexty",
fillcolor=hex_to_rgba(colors["glucose"], 0.3),
name="25e-75e percentiel",
hoverinfo="skip",
)
)
# Mediaan.
fig.add_trace(
go.Scatter(
x=hours,
y=bands["p50"],
mode="lines",
line={"color": colors["glucose"], "width": 2},
name="Mediaan",
hovertemplate="%{x:.0f}u · %{y:.1f} mmol/L<extra></extra>",
)
)
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
margin={"l": 10, "r": 10, "t": 10, "b": 10},
height=480,
yaxis={"title": "mmol/L", "gridcolor": colors["grid"], "zeroline": False},
xaxis={"title": "Uur van de dag", "gridcolor": colors["grid"], "tickmode": "linear", "dtick": 2},
)
add_threshold_lines(fig, colors)
st.plotly_chart(fig, width="stretch")
st.caption(
f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')} ({len(glucose)} metingen)"
)
+90
View File
@@ -0,0 +1,90 @@
import plotly.graph_objects as go
import requests
import streamlit as st
from plotly.subplots import make_subplots
from auth import require_auth
from data_processing import TARGET_HIGH, TARGET_LOW
from nightscout_client import NightscoutConfigError
from ui_common import (
add_threshold_lines,
get_colors,
load_range_data,
render_completeness_warning,
select_period_days,
)
st.set_page_config(page_title="Glucose dashboard — Dagoverzicht", page_icon="📊", layout="wide")
require_auth()
st.title("Dagoverzicht")
st.caption("Eén glucosegrafiek per kalenderdag (FR4).")
start, end, days = select_period_days(default_label="14 dagen")
if days > 31:
st.info(
"Bij langere periodes wordt de pagina lang en kan laden traag zijn — "
"voor het bekijken van individuele dagen is 14 of 30 dagen prettiger."
)
try:
glucose, _treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
colors = get_colors()
glucose = glucose.copy()
glucose["date"] = glucose["timestamp"].dt.date
glucose["hour"] = glucose["timestamp"].dt.hour + glucose["timestamp"].dt.minute / 60
dates = sorted(glucose["date"].unique())
row_height = 150
fig = make_subplots(
rows=len(dates),
cols=1,
shared_xaxes=True,
subplot_titles=[d.strftime("%A %d-%m-%Y") for d in dates],
vertical_spacing=min(0.4 / max(len(dates) - 1, 1), 0.05),
)
for i, day in enumerate(dates, start=1):
day_df = glucose[glucose["date"] == day]
fig.add_hrect(
y0=TARGET_LOW, y1=TARGET_HIGH, fillcolor=colors["band"], line_width=0, layer="below", row=i, col=1
)
fig.add_trace(
go.Scatter(
x=day_df["hour"],
y=day_df["mmol"],
mode="lines",
line={"color": colors["glucose"], "width": 2},
showlegend=False,
hovertemplate="%{y:.1f} mmol/L<extra></extra>",
),
row=i,
col=1,
)
fig.update_yaxes(title_text="mmol/L", gridcolor=colors["grid"], row=i, col=1)
add_threshold_lines(fig, colors, row=i)
fig.update_xaxes(title_text="Uur van de dag", range=[0, 24], dtick=4, gridcolor=colors["grid"])
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
height=row_height * len(dates),
showlegend=False,
margin={"l": 10, "r": 10, "t": 30, "b": 10},
)
st.plotly_chart(fig, width="stretch")
st.caption(f"{len(dates)} dagen · {len(glucose)} metingen")
+48
View File
@@ -0,0 +1,48 @@
import requests
import streamlit as st
from auth import require_auth
from nightscout_client import NightscoutConfigError
from reporting import LOW, VERY_LOW
from ui_common import (
get_colors,
load_range_data,
render_completeness_warning,
render_event_level,
select_period_days,
)
st.set_page_config(page_title="Glucose dashboard — Hypo events", page_icon="📊", layout="wide")
require_auth()
st.title("Hypo events")
st.caption(
"Detectie van hypoglykemie-events volgens de persistentieregel (FR5): een event "
"telt pas na >=15 minuten ononderbroken onder de drempel, en eindigt pas na "
">=15 minuten ononderbroken herstel."
)
start, end, days = select_period_days(default_label="90 dagen")
try:
glucose, _treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
colors = get_colors()
render_event_level(glucose, LOW, "below", f"Level 1 (<{LOW} mmol/L)", days, colors)
st.divider()
render_event_level(glucose, VERY_LOW, "below", f"Level 2 (<{VERY_LOW} mmol/L)", days, colors)
st.caption(f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}")
+47
View File
@@ -0,0 +1,47 @@
import requests
import streamlit as st
from auth import require_auth
from nightscout_client import NightscoutConfigError
from reporting import HIGH, VERY_HIGH
from ui_common import (
get_colors,
load_range_data,
render_completeness_warning,
render_event_level,
select_period_days,
)
st.set_page_config(page_title="Glucose dashboard — Hyper events", page_icon="📊", layout="wide")
require_auth()
st.title("Hyper events")
st.caption(
"Detectie van hyperglykemie-events volgens dezelfde persistentieregel als de "
"Hypo Events-pagina (FR6), symmetrisch toegepast op de bovengrenzen."
)
start, end, days = select_period_days(default_label="90 dagen")
try:
glucose, _treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
colors = get_colors()
render_event_level(glucose, HIGH, "above", f"Level 1 (>{HIGH} mmol/L)", days, colors)
st.divider()
render_event_level(glucose, VERY_HIGH, "above", f"Level 2 (>{VERY_HIGH} mmol/L)", days, colors)
st.caption(f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}")
+178
View File
@@ -0,0 +1,178 @@
import plotly.graph_objects as go
import requests
import streamlit as st
from auth import require_auth
from data_processing import classify_treatments
from nightscout_client import NightscoutConfigError
from reporting import (
basal_stats,
bolus_stats,
day_of_week_pattern,
gmi_trend,
overnight_daytime_split,
site_interval_stats,
)
from ui_common import (
get_colors,
hex_to_rgba,
load_range_data,
render_completeness_warning,
select_period_days,
)
st.set_page_config(page_title="Glucose dashboard — Trends", page_icon="📊", layout="wide")
require_auth()
st.title("Trends")
st.caption("Geschat HbA1c (GMI) over tijd en overige statistieken (FR7, FR8).")
start, end, days = select_period_days(default_label="90 dagen")
try:
glucose, treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
colors = get_colors()
events = classify_treatments(treatments)
# --- FR7: geschat HbA1c (GMI) trend ----------------------------------------
st.subheader("Geschat HbA1c (GMI) trend")
trend = gmi_trend(glucose)
if len(trend) >= 2:
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=trend["date"], y=trend["trend_upper"], mode="lines", line={"width": 0}, showlegend=False,
hoverinfo="skip",
)
)
fig.add_trace(
go.Scatter(
x=trend["date"],
y=trend["trend_lower"],
mode="lines",
line={"width": 0},
fill="tonexty",
fillcolor=hex_to_rgba(colors["muted"], 0.2),
name="95% betrouwbaarheidsband",
hoverinfo="skip",
)
)
fig.add_trace(
go.Scatter(
x=trend["date"],
y=trend["trend"],
mode="lines",
line={"color": colors["muted"], "width": 2, "dash": "dash"},
name="Trend (lineair)",
)
)
fig.add_trace(
go.Scatter(
x=trend["date"],
y=trend["rolling_avg"],
mode="lines",
line={"color": colors["glucose"], "width": 2},
name="Voortschrijdend gemiddelde (7d)",
)
)
fig.add_trace(
go.Scatter(
x=trend["date"],
y=trend["gmi"],
mode="markers",
marker={"color": colors["glucose"], "size": 5, "opacity": 0.5},
name="Dag-GMI",
)
)
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
height=320,
margin={"l": 10, "r": 10, "t": 10, "b": 10},
yaxis={"title": "GMI (%)", "gridcolor": colors["grid"]},
xaxis={"title": "Datum", "gridcolor": colors["grid"]},
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
)
st.plotly_chart(fig, width="stretch")
else:
st.info("Niet genoeg dagen met data voor een trendlijn (minstens 2 nodig).")
st.caption("GMI is een schatting (Bergenstal et al. 2018), geen labwaarde.")
# --- FR8: nacht vs. overdag --------------------------------------------------
st.subheader("Nacht (00:00-06:00) vs. overdag")
split = overnight_daytime_split(glucose)
col1, col2 = st.columns(2)
col1.metric("Tijd in bereik 's nachts", f"{split['overnight']['in_range']:.0f}%")
col2.metric("Tijd in bereik overdag", f"{split['daytime']['in_range']:.0f}%")
# --- FR8: patroon per weekdag -------------------------------------------------
st.subheader("Patroon per weekdag")
weekday_df = day_of_week_pattern(glucose)
weekday_plot = weekday_df.dropna(subset=["mean_mmol"])
if not weekday_plot.empty:
fig = go.Figure(
go.Bar(x=weekday_plot["weekday"], y=weekday_plot["mean_mmol"], marker_color=colors["glucose"])
)
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
height=280,
margin={"l": 10, "r": 10, "t": 10, "b": 10},
yaxis={"title": "Gem. glucose (mmol/L)", "gridcolor": colors["grid"]},
xaxis={"gridcolor": colors["grid"]},
)
st.plotly_chart(fig, width="stretch")
# --- FR8: insuline (basaal + bolus-uitsplitsing) ---------------------------
st.subheader("Insuline")
st.caption(
"Basaal berekend uit Temp Basal-treatments (snelheid x duur), zonder pompprofiel "
"nodig — een ondergrens bij periodes zonder actieve temp basal. Boluses "
"opgesplitst naar voeding, handmatige correctie en automatische SMB-microbolus "
"(gitea #20)."
)
bolus = bolus_stats(treatments)
basal = basal_stats(treatments, days)
total_units = bolus["total_units"] + basal["total_units"]
col1, col2, col3 = st.columns(3)
col1.metric("Totaal insuline", f"{total_units:.1f} E")
col2.metric("Gem. per dag", f"{total_units / days:.1f} E")
col3.metric("Aantal boluses", bolus["count"])
breakdown = {"Basaal": basal["total_units"], **bolus["by_type"]}
if any(breakdown.values()):
st.table({"Categorie": list(breakdown.keys()), "Eenheden": list(breakdown.values())})
# --- FR8: pompsite-leeftijd vs. glucose/insuline ---------------------------
st.subheader("Pompsite-leeftijd vs. glucose en insuline")
st.caption(
"Statistieken per interval tussen opeenvolgende pompwissels — een benadering "
"(zonder basaalinsuline) van of insulinebehoefte samenhangt met de leeftijd "
"van de pompsite."
)
site_stats = site_interval_stats(glucose, treatments, events["site_changes"])
if site_stats.empty:
st.info("Geen pompwissels gevonden in deze periode.")
else:
display = site_stats.copy()
display["start"] = display["start"].dt.strftime("%d-%m-%Y")
display["end"] = display["end"].dt.strftime("%d-%m-%Y")
st.dataframe(display, width="stretch", hide_index=True)
st.caption(f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}")
+54
View File
@@ -0,0 +1,54 @@
import requests
import streamlit as st
from auth import require_auth
from nightscout_client import NightscoutConfigError
from pdf_export import AVAILABLE_SECTIONS, SECTION_EVENTS, build_report_pdf
from reporting import HIGH, LOW, VERY_HIGH, VERY_LOW, detect_events, summarize_events
from ui_common import load_range_data, render_completeness_warning, select_period_days
st.set_page_config(page_title="Glucose dashboard — Export", page_icon="📊", layout="wide")
require_auth()
st.title("Export")
st.caption("Stel een PDF-rapport samen om naar het diabetesteam te sturen (FR10).")
start, end, days = select_period_days(default_label="90 dagen")
sections = st.multiselect("Onderdelen", AVAILABLE_SECTIONS, default=AVAILABLE_SECTIONS)
try:
glucose, _treatments = load_range_data(start, end)
except NightscoutConfigError as exc:
st.error(str(exc))
st.stop()
except (requests.RequestException, ValueError) as exc:
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
st.stop()
if glucose.empty:
st.info("Geen glucosemetingen gevonden in deze periode.")
st.stop()
render_completeness_warning(glucose, start, end)
events_summary = {}
if SECTION_EVENTS in sections:
levels = {
f"Hypo Level 1 (<{LOW})": (LOW, "below"),
f"Hypo Level 2 (<{VERY_LOW})": (VERY_LOW, "below"),
f"Hyper Level 1 (>{HIGH})": (HIGH, "above"),
f"Hyper Level 2 (>{VERY_HIGH})": (VERY_HIGH, "above"),
}
for label, (threshold, direction) in levels.items():
events = detect_events(glucose, threshold, direction)
events_summary[label] = summarize_events(events, days)
pdf_bytes = build_report_pdf(sections, glucose, events_summary, start, end)
st.download_button(
"Download PDF",
data=pdf_bytes,
file_name=f"glucoserapport_{start.strftime('%Y%m%d')}_{end.strftime('%Y%m%d')}.pdf",
mime="application/pdf",
)
st.caption(f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}")
+286
View File
@@ -0,0 +1,286 @@
"""
PDF-rapportgeneratie voor geselecteerde rapportageonderdelen (FR10).
Gebruikt fpdf2 (puur Python, geen systeemdependencies) voor de PDF-opbouw en
matplotlib voor een eenvoudige statische AGP-grafiek specifiek voor de PDF —
bewust niet dezelfde Plotly-figuren als op de pagina's zelf (die zouden
kaleido vereisen, met een ingebakken Chromium-build: een groter image en meer
Trivy-oppervlak, voor dit doel niet nodig).
"""
from __future__ import annotations
import io
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
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_mmol_per_mol,
gmi_percent,
percent_cv,
sensor_active_percent,
tir_breakdown_5band,
)
SECTION_SUMMARY = "Samenvatting"
SECTION_AGP = "AGP profiel"
SECTION_DAGOVERZICHT = "Dagoverzicht"
SECTION_EVENTS = "Hypo-/hyperevents"
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)
fig, ax = plt.subplots(figsize=(7, 3))
hours = bands["minute_of_day"] / 60
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)
ax.legend(loc="upper right", fontsize=8)
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=150)
plt.close(fig)
buf.seek(0)
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)
active_pct = sensor_active_percent(glucose, start, end)
pdf.set_font("Helvetica", "B", 13)
pdf.cell(0, 8, "Samenvatting", **_LINE_KWARGS)
warning = completeness_warning(glucose, start, end)
if warning:
pdf.set_font("Helvetica", "BI", 10)
pdf.multi_cell(0, 5, warning)
pdf.ln(2)
pdf.set_font("Helvetica", "", 11)
pdf.cell(0, 6, f"Sensordekking: {active_pct:.0f}%", **_LINE_KWARGS)
pdf.cell(0, 6, f"Gemiddelde glucose: {mean_mmol:.1f} mmol/L", **_LINE_KWARGS)
gmi = gmi_percent(mean_mmol)
pdf.cell(0, 6, f"Geschat HbA1c (GMI): {gmi:.1f}% ({gmi_mmol_per_mol(gmi):.0f} mmol/mol)", **_LINE_KWARGS)
pdf.cell(0, 6, f"Variabiliteit (%CV): {percent_cv(glucose):.0f}%", **_LINE_KWARGS)
pdf.ln(2)
pdf.cell(0, 6, f"Zeer laag (<3.0 mmol/L): {tir['very_low']:.0f}%", **_LINE_KWARGS)
pdf.cell(0, 6, f"Laag (3.0-3.9 mmol/L): {tir['low']:.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"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)
def _add_agp_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
pdf.set_font("Helvetica", "B", 13)
pdf.cell(0, 8, "AGP profiel", **_LINE_KWARGS)
png_bytes = _agp_figure_png(glucose)
pdf.image(io.BytesIO(png_bytes), w=180)
pdf.ln(4)
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)
for label, summary in events_summary.items():
pdf.cell(
0,
6,
f"{label}: {summary['count']} events, gemiddeld {summary['avg_duration_minutes']:.0f} min, "
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)
def build_report_pdf(
sections: list[str],
glucose: pd.DataFrame,
events_summary: dict[str, dict],
start,
end,
) -> bytes:
"""Bouw een PDF met de geselecteerde onderdelen.
`events_summary` bevat vooraf berekende hypo/hyper-samenvattingen (label ->
resultaat van reporting.summarize_events), zodat deze module geen
event-detectie hoeft te herhalen.
"""
pdf = FPDF()
pdf.add_page()
pdf.set_font("Helvetica", "B", 16)
pdf.cell(0, 10, "Glucoserapport", **_LINE_KWARGS)
pdf.set_font("Helvetica", "", 11)
pdf.cell(0, 8, f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}", **_LINE_KWARGS)
pdf.ln(4)
if not glucose.empty:
if SECTION_SUMMARY in sections:
_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, glucose, events_summary)
return bytes(pdf.output())
+527
View File
@@ -0,0 +1,527 @@
"""
Rapportage-logica voor de klinische rapportagepagina's.
Zelfde opzet als data_processing.py: pure functies, geen Streamlit-imports, dus
los te unit-testen. Zie docs/requirements-reporting.md voor de klinische
definities waarop dit gebaseerd is (Battelino et al. 2019, Bergenstal et al.
2018).
"""
from __future__ import annotations
from itertools import pairwise
import numpy as np
import pandas as pd
from nightscout_client import INSULIN_EVENT_TYPES
# Klinische drempels in mmol/L (Battelino et al. 2019, Diabetes Care 42(8):1593-1603).
VERY_LOW = 3.0
LOW = 3.9
HIGH = 10.0
VERY_HIGH = 13.9
MINUTES_PER_DAY = 24 * 60
def gmi_percent(mean_mmol: float) -> float:
"""Geschat HbA1c (Glucose Management Indicator) uit gemiddelde glucose.
GMI% = 3.31 + 0.4311 * gemiddelde(mmol/L) — Bergenstal et al. 2018,
Diabetes Care 41(11):2275-2280. Dit is GEEN vervanging voor een labwaarde
(kan tot ~0.5 procentpunt afwijken door o.a. rode-bloedcel-factoren) en moet
als zodanig gelabeld worden in de UI.
"""
return round(3.31 + 0.4311 * mean_mmol, 1)
def gmi_mmol_per_mol(gmi_pct: float) -> int:
"""Zet een GMI-percentage (DCCT/NGSP) om naar IFCC mmol/mol.
mmol/mol = 10.929 x (% - 2.15) — de standaard IFCC-omrekening
(Hoelzel et al. 2004, Clin Chem 50(1):166-174), gangbare eenheid in
Nederlandse labuitslagen naast het %-getal (gitea #25). Bijv. 6.5% =
48 mmol/mol, de bekende diagnostische drempel.
"""
return round(10.929 * (gmi_pct - 2.15))
GMI_TREND_COLUMNS = ["date", "gmi", "rolling_avg", "trend", "trend_lower", "trend_upper"]
def daily_gmi(glucose: pd.DataFrame) -> pd.DataFrame:
"""Geschat HbA1c (GMI) per kalenderdag — scatterpunten voor de trendgrafiek (gitea #19)."""
if glucose.empty:
return pd.DataFrame(columns=["date", "gmi"])
df = glucose.copy()
df["date"] = df["timestamp"].dt.date
daily_mean = df.groupby("date")["mmol"].mean()
result = daily_mean.apply(gmi_percent).reset_index()
result.columns = ["date", "gmi"]
return result.sort_values("date").reset_index(drop=True)
def gmi_trend(glucose: pd.DataFrame, rolling_window_days: int = 7) -> pd.DataFrame:
"""Dagelijkse GMI-punten plus voortschrijdend gemiddelde en een lineaire
trendlijn met 95%-betrouwbaarheidsband (gitea #19).
Gebruikt een normaalbenadering (z=1.96) voor de betrouwbaarheidsband i.p.v.
een exacte t-verdeling — dat zou een scipy-dependency toevoegen aan een
verder bewust lichte container (dezelfde afweging als het niet gebruiken
van kaleido in pdf_export.py). Bij de hier gebruikelijke steekproefgroottes
(14-90 dagpunten) is het verschil met de exacte t-kritieke waarde
verwaarloosbaar voor een visuele trendindicatie.
Elke keer opnieuw berekend uit de al-opgehaalde periode-data (geen aparte
database) — de bestaande 1-uurs Streamlit-cache op load_range_data()
voorkomt al herhaalde Nightscout-calls voor dezelfde periode. Bij een
veel langere trend (jaren i.p.v. de huidige max. 90 dagen) zou een aparte
opslag wél de moeite waard worden.
"""
daily = daily_gmi(glucose)
if len(daily) < 2:
return daily.reindex(columns=GMI_TREND_COLUMNS)
daily = daily.copy()
daily["rolling_avg"] = daily["gmi"].rolling(window=rolling_window_days, min_periods=1).mean()
x = np.arange(len(daily), dtype=float)
y = daily["gmi"].to_numpy()
slope, intercept = np.polyfit(x, y, 1)
fitted = intercept + slope * x
residuals = y - fitted
degrees_of_freedom = max(len(x) - 2, 1)
residual_std = np.sqrt(np.sum(residuals**2) / degrees_of_freedom)
x_mean = x.mean()
sum_sq_x = np.sum((x - x_mean) ** 2)
standard_error = (
np.zeros_like(x)
if sum_sq_x == 0
else residual_std * np.sqrt(1 / len(x) + (x - x_mean) ** 2 / sum_sq_x)
)
z_95 = 1.96
daily["trend"] = fitted
daily["trend_lower"] = fitted - z_95 * standard_error
daily["trend_upper"] = fitted + z_95 * standard_error
return daily[GMI_TREND_COLUMNS]
def percent_cv(glucose: pd.DataFrame) -> float:
"""Glucosevariabiliteit als %CV (standaarddeviatie / gemiddelde * 100)."""
if glucose.empty:
return 0.0
mean = glucose["mmol"].mean()
if mean == 0:
return 0.0
return round(glucose["mmol"].std() / mean * 100, 1)
def tir_breakdown_5band(glucose: pd.DataFrame) -> dict[str, float]:
"""Percentage metingen in elk van de 5 klinische glucosebanden.
Banden: very_low (<3.0), low (3.0-3.9), in_range (3.9-10.0),
high (10.0-13.9), very_high (>13.9). Sluit exact aan op de 5-bands AGP-
indeling uit de consensus.
"""
if glucose.empty:
return {"very_low": 0.0, "low": 0.0, "in_range": 0.0, "high": 0.0, "very_high": 0.0}
def _band(mmol: float) -> str:
if mmol < VERY_LOW:
return "very_low"
if mmol < LOW:
return "low"
if mmol <= HIGH:
return "in_range"
if mmol <= VERY_HIGH:
return "high"
return "very_high"
counts = glucose["mmol"].apply(_band).value_counts(normalize=True) * 100
return {
band: round(counts.get(band, 0.0), 1)
for band in ("very_low", "low", "in_range", "high", "very_high")
}
def minutes_per_day(percentage: float) -> float:
"""Reken een percentage van de tijd om naar minuten per dag (ruwe vuistregel)."""
return round(percentage / 100 * MINUTES_PER_DAY, 0)
def sensor_active_percent(glucose: pd.DataFrame, start, end, expected_interval_minutes: int = 5) -> float:
"""Percentage van de periode waarin daadwerkelijk metingen binnenkwamen.
Vuistregel op basis van het verwachte meetinterval (CGM's meten doorgaans
elke 5 minuten) — geen exacte sensor-uptime-registratie, maar voldoende om
een periode met te veel hiaten te signaleren (zie FR9 / NFR "minimaal
geldig rapport").
"""
total_minutes = (pd.Timestamp(end) - pd.Timestamp(start)).total_seconds() / 60
if total_minutes <= 0:
return 0.0
expected_readings = total_minutes / expected_interval_minutes
if expected_readings <= 0:
return 0.0
return round(min(len(glucose) / expected_readings, 1.0) * 100, 1)
def completeness_warning(glucose: pd.DataFrame, start, end) -> str | None:
"""Bouw een waarschuwingstekst als er te weinig data is voor de gekozen periode.
Pure functie zodat zowel de interactieve pagina's (ui_common.py, als
st.warning) als het PDF-rapport (pdf_export.py, als tekstregel) exact
dezelfde beoordeling en bewoording gebruiken — een rapport dat naar het
diabetesteam gaat moet dezelfde disclaimer bevatten als wat de gebruiker
zelf op het scherm ziet.
Onderscheidt twee oorzaken:
- een structureel gat aan het BEGIN van de periode (de vroegste
binnengekomen meting ligt later dan de gekozen startdatum) — data is
simpelweg niet opgehaald/beschikbaar voor dat stuk, geen sensorhiaat.
- een lagere dekking dan de klinische AGP-ondergrens (Danne et al. 2017)
zonder zo'n gat aan het begin — verspreide hiaten.
Returns:
None als er geen waarschuwing nodig is; anders de te tonen tekst.
"""
if glucose.empty:
return "Geen glucosedata gevonden in deze periode."
start_date = pd.Timestamp(start).date()
end_date = pd.Timestamp(end).date()
active_pct = sensor_active_percent(glucose, start, end)
earliest = glucose["timestamp"].min().date()
missing_days_at_start = max((earliest - start_date).days, 0)
if missing_days_at_start > 0:
return (
f"Nightscout heeft pas data vanaf {earliest:%d-%m-%Y} teruggegeven — "
f"de eerste {missing_days_at_start} dag(en) van de gekozen periode "
f"({start_date:%d-%m-%Y} t/m {end_date:%d-%m-%Y}) ontbreken volledig, niet alleen "
f"losse sensorhiaten. Sensordekking over de wél opgehaalde periode: "
f"{active_pct:.0f}%. Onderstaande cijfers zijn dus berekend over een "
"kortere periode dan geselecteerd."
)
if active_pct < 70:
# ">=" i.p.v. "≥": deze tekst komt ook in het PDF-rapport terecht
# (pdf_export.py), en fpdf2's ingebouwde Helvetica-font ondersteunt
# alleen Latin-1 — zie gitea issue #11 voor het opruimen hiervan
# (Unicode-lettertype embedden) zodra dat de moeite waard is.
return (
f"Slechts {active_pct:.0f}% sensordekking in deze periode (streefwaarde "
">=70% voor een klinisch betrouwbaar rapport, Danne et al. 2017). De "
"onderstaande cijfers zijn mogelijk minder betrouwbaar door de vele hiaten."
)
return None
def _state_blocks(df: pd.DataFrame, out: pd.Series) -> list[dict]:
"""Groepeer aaneengesloten metingen met dezelfde in/out-status.
Eindtijd van elk blok = starttijd van het volgende blok (de status geldt
tot de eerstvolgende meting anders aangeeft); het laatste blok behoudt
zijn eigen laatste meting als eind.
"""
block_id = (out != out.shift()).cumsum()
blocks = [
{
"is_out": bool(out.loc[group.index[0]]),
"start": group["timestamp"].iloc[0],
"end": group["timestamp"].iloc[-1],
}
for _, group in df.groupby(block_id)
]
for i in range(len(blocks) - 1):
blocks[i]["end"] = blocks[i + 1]["start"]
return blocks
def _maybe_add_episode(events: list[dict], start, end, min_duration_minutes: int) -> None:
duration = (end - start).total_seconds() / 60
if duration >= min_duration_minutes:
events.append({"start": start, "end": end, "duration_minutes": round(duration, 1)})
def _scan_episodes(blocks: list[dict], min_duration_minutes: int) -> list[dict]:
"""Statelijke doorloop van de blokken volgens de persistentieregel.
Een lopende episode wordt alleen verlengd voorbij een kort in-bereik-blok
als er daarna weer een out-blok komt (het korte herstel wordt dan met
terugwerkende kracht "geabsorbeerd"). Een kort slot-blok waarna de data
simpelweg ophoudt telt dus NIET automatisch mee als voortzetting — anders
zou een niet-bevestigd herstel de duur van het event kunstmatig oprekken.
"""
events: list[dict] = []
episode_start = None
episode_end = None
for block in blocks:
if block["is_out"]:
episode_start = episode_start or block["start"]
episode_end = block["end"]
continue
if episode_start is None:
continue
recovery_minutes = (block["end"] - block["start"]).total_seconds() / 60
if recovery_minutes >= min_duration_minutes:
_maybe_add_episode(events, episode_start, episode_end, min_duration_minutes)
episode_start = None
episode_end = None
# anders: kortstondig herstel — episode blijft open, wordt pas
# verlengd als er weer een out-blok volgt (hierboven).
if episode_start is not None:
_maybe_add_episode(events, episode_start, episode_end, min_duration_minutes)
return events
def detect_events(
glucose: pd.DataFrame,
threshold: float,
direction: str,
min_duration_minutes: int = 15,
) -> pd.DataFrame:
"""Detecteer discrete hypo-/hyperglykemie-events volgens de persistentieregel.
Een event begint zodra glucose ononderbroken voorbij de drempel is
geweest voor >= min_duration_minutes, en eindigt pas zodra glucose
ononderbroken hersteld is voor >= min_duration_minutes — een korte terugval
binnen die hersteltijd beëindigt het event dus niet (Battelino et al.
2019). `direction` is "below" (hypo) of "above" (hyper).
Geeft een DataFrame terug met kolommen 'start', 'end', 'duration_minutes'.
"""
if glucose.empty:
return pd.DataFrame(columns=["start", "end", "duration_minutes"])
df = glucose.sort_values("timestamp").reset_index(drop=True)
if direction == "below":
out = df["mmol"] < threshold
elif direction == "above":
out = df["mmol"] > threshold
else:
raise ValueError("direction moet 'below' of 'above' zijn")
blocks = _state_blocks(df, out)
events = _scan_episodes(blocks, min_duration_minutes)
return pd.DataFrame(events, columns=["start", "end", "duration_minutes"])
def summarize_events(events: pd.DataFrame, period_days: float) -> dict[str, float]:
"""Samenvattende statistieken over een set gedetecteerde events."""
if events.empty or period_days <= 0:
return {
"count": 0,
"avg_duration_minutes": 0.0,
"longest_duration_minutes": 0.0,
"total_minutes": 0.0,
"events_per_week": 0.0,
}
total_minutes = events["duration_minutes"].sum()
return {
"count": len(events),
"avg_duration_minutes": round(events["duration_minutes"].mean(), 1),
"longest_duration_minutes": round(events["duration_minutes"].max(), 1),
"total_minutes": round(total_minutes, 1),
"events_per_week": round(len(events) / period_days * 7, 1),
}
AGP_PERCENTILE_COLUMNS = ["minute_of_day", "p5", "p25", "p50", "p75", "p95"]
def agp_percentile_bands(glucose: pd.DataFrame, bin_minutes: int = 30) -> pd.DataFrame:
"""Aggregeer glucosewaarden per tijdstip-van-de-dag naar percentielbanden.
Groepeert alle metingen in de periode naar hun tijd-van-de-dag (in bins
van `bin_minutes`), en berekent per bin de 5e/25e/50e/75e/95e percentiel
— de standaard AGP-percentielgrafiek over een samengesteld 24-uursbeeld
(Danne et al. 2017, Diabetes Care 40(12):1631-1640).
"""
if glucose.empty:
return pd.DataFrame(columns=AGP_PERCENTILE_COLUMNS)
df = glucose.copy()
minute_of_day = df["timestamp"].dt.hour * 60 + df["timestamp"].dt.minute
df["bin"] = (minute_of_day // bin_minutes) * bin_minutes
grouped = df.groupby("bin")["mmol"].quantile([0.05, 0.25, 0.5, 0.75, 0.95]).unstack()
grouped.columns = ["p5", "p25", "p50", "p75", "p95"]
grouped = grouped.reset_index().rename(columns={"bin": "minute_of_day"})
return grouped[AGP_PERCENTILE_COLUMNS].sort_values("minute_of_day").reset_index(drop=True)
def overnight_daytime_split(
glucose: pd.DataFrame, overnight_start: int = 0, overnight_end: int = 6
) -> dict[str, dict]:
"""Tijd-in-bereik apart voor de nacht (overnight_start-overnight_end uur) en overdag."""
empty = tir_breakdown_5band(glucose)
if glucose.empty:
return {"overnight": empty, "daytime": empty}
hour = glucose["timestamp"].dt.hour
is_overnight = (hour >= overnight_start) & (hour < overnight_end)
return {
"overnight": tir_breakdown_5band(glucose[is_overnight]),
"daytime": tir_breakdown_5band(glucose[~is_overnight]),
}
WEEKDAY_NAMES = ["Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"]
def day_of_week_pattern(glucose: pd.DataFrame) -> pd.DataFrame:
"""Gemiddelde glucose en tijd-in-bereik per weekdag."""
columns = ["weekday", "mean_mmol", "in_range_pct", "count"]
if glucose.empty:
return pd.DataFrame(columns=columns)
df = glucose.copy()
df["weekday"] = df["timestamp"].dt.dayofweek
rows = []
for weekday in range(7):
day_df = df[df["weekday"] == weekday]
if day_df.empty:
rows.append(
{"weekday": WEEKDAY_NAMES[weekday], "mean_mmol": None, "in_range_pct": None, "count": 0}
)
continue
tir = tir_breakdown_5band(day_df)
rows.append(
{
"weekday": WEEKDAY_NAMES[weekday],
"mean_mmol": round(day_df["mmol"].mean(), 1),
"in_range_pct": tir["in_range"],
"count": len(day_df),
}
)
return pd.DataFrame(rows, columns=columns)
SMB_TYPE = "SMB"
BASAL_EVENT_TYPE = "Temp Basal"
def bolus_stats(treatments: pd.DataFrame) -> dict:
"""Samenvatting van bolus-insuline, opgesplitst naar type.
AndroidAPS in SMB-looping registreert een automatische micro-bolus niet
als eigen `eventType`, maar als `eventType == "Correction Bolus"` met
`type == "SMB"` — zonder dit onderscheid werden alle SMB's stilzwijgend
als "Correction Bolus" (handmatige correctie) meegeteld, wat gitea #20
meldde als "bolus stats empty/onduidelijk". Geverifieerd rechtstreeks
tegen de productiedata: bij deze gebruiker is vrijwel elke "Correction
Bolus" in werkelijkheid een automatische SMB.
Let op: dit betreft alleen bolusinsuline (voeding/correctie/combo/SMB).
Basaalinsuline zit hier niet in — zie basal_stats().
"""
if treatments.empty:
return {"total_units": 0.0, "count": 0, "by_type": {}}
bolus = treatments[treatments["eventType"].isin(INSULIN_EVENT_TYPES) & treatments["insulin"].notna()].copy()
if bolus.empty:
return {"total_units": 0.0, "count": 0, "by_type": {}}
is_smb = (bolus["eventType"] == "Correction Bolus") & (bolus.get("type", "") == SMB_TYPE)
bolus["category"] = bolus["eventType"].where(~is_smb, SMB_TYPE)
by_type = bolus.groupby("category")["insulin"].sum().round(1).to_dict()
return {
"total_units": round(bolus["insulin"].sum(), 1),
"count": len(bolus),
"by_type": by_type,
}
def basal_stats(treatments: pd.DataFrame, period_days: float) -> dict:
"""Totale basaalinsuline uit Temp Basal-treatments (rate x duur), zonder pompprofiel.
AndroidAPS zet in gesloten-lus-modus vrijwel continu Temp Basal-treatments
met een `absolute` snelheid (E/uur) en `duration` (minuten); de som van
afgeleverde eenheden daaruit benadert de daadwerkelijke basaaldosis
nauwkeurig genoeg zonder het pompprofiel te hoeven ophalen (gitea #20).
Periodes zonder actieve temp basal (dan geldt het profiel-basaaltempo)
worden hierin gemist — dit is dus een ondergrens, geen exacte totale-
dagdosis.
"""
if treatments.empty or period_days <= 0:
return {"total_units": 0.0, "avg_units_per_day": 0.0}
temp_basal = treatments[
(treatments["eventType"] == BASAL_EVENT_TYPE)
& treatments["absolute"].notna()
& treatments["duration"].notna()
]
if temp_basal.empty:
return {"total_units": 0.0, "avg_units_per_day": 0.0}
total_units = (temp_basal["absolute"] * temp_basal["duration"] / 60).sum()
return {
"total_units": round(total_units, 1),
"avg_units_per_day": round(total_units / period_days, 1),
}
SITE_INTERVAL_COLUMNS = [
"start",
"end",
"duration_days",
"mean_mmol",
"in_range_pct",
"total_bolus_units",
"avg_bolus_units_per_day",
"total_carbs_g",
]
def _site_interval_row(glucose: pd.DataFrame, treatments: pd.DataFrame, start, end) -> dict:
duration_days = max((end - start).total_seconds() / 86400, 1e-9)
window_glucose = glucose[(glucose["timestamp"] >= start) & (glucose["timestamp"] < end)]
window_treatments = (
treatments[(treatments["timestamp"] >= start) & (treatments["timestamp"] < end)]
if not treatments.empty
else treatments
)
bolus = bolus_stats(window_treatments)
total_carbs = window_treatments["carbs"].fillna(0).sum() if not treatments.empty else 0.0
tir = tir_breakdown_5band(window_glucose)
return {
"start": start,
"end": end,
"duration_days": round(duration_days, 1),
"mean_mmol": round(window_glucose["mmol"].mean(), 1) if not window_glucose.empty else None,
"in_range_pct": tir["in_range"],
"total_bolus_units": bolus["total_units"],
"avg_bolus_units_per_day": round(bolus["total_units"] / duration_days, 1),
"total_carbs_g": round(total_carbs, 0),
}
def site_interval_stats(
glucose: pd.DataFrame, treatments: pd.DataFrame, site_changes: pd.DataFrame
) -> pd.DataFrame:
"""Statistieken per interval tussen opeenvolgende pompwissels (FR8).
Voor elk interval sinds een pompwissel: duur in dagen ("leeftijd" van de
pompsite bij het einde van het interval), gemiddelde glucose,
tijd-in-bereik, en bolus-insuline/koolhydraten in dat interval — als
benadering van of insulinebehoefte samenhangt met de leeftijd van de
pompsite. Zie bolus_stats() voor de kanttekening dat basaalinsuline hier
niet in zit.
"""
if site_changes.empty or glucose.empty:
return pd.DataFrame(columns=SITE_INTERVAL_COLUMNS)
change_times = sorted(site_changes["timestamp"])
boundaries = [*change_times, glucose["timestamp"].max()]
rows = [_site_interval_row(glucose, treatments, start, end) for start, end in pairwise(boundaries)]
return pd.DataFrame(rows, columns=SITE_INTERVAL_COLUMNS)
+2
View File
@@ -3,5 +3,7 @@ pandas>=2.2,<3.0
requests>=2.32,<3.0 requests>=2.32,<3.0
plotly>=5.24,<6.0 plotly>=5.24,<6.0
python-dotenv>=1.0,<2.0 python-dotenv>=1.0,<2.0
matplotlib>=3.9,<4.0
fpdf2>=2.7,<3.0
pytest>=8.0,<9.0 pytest>=8.0,<9.0
ruff>=0.6,<1.0 ruff>=0.6,<1.0
+17
View File
@@ -0,0 +1,17 @@
import hashlib
from auth import verify_password
def test_verify_password_accepts_matching_hash():
expected = hashlib.sha256(b"correct-horse").hexdigest()
assert verify_password("correct-horse", expected) is True
def test_verify_password_rejects_wrong_password():
expected = hashlib.sha256(b"correct-horse").hexdigest()
assert verify_password("wrong-password", expected) is False
def test_verify_password_rejects_when_no_hash_configured():
assert verify_password("anything", "") is False
+284 -1
View File
@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
import pytest import pytest
@@ -90,9 +90,292 @@ def test_fetch_treatments_fills_missing_columns(monkeypatch):
assert result.iloc[0]["eventType"] == "Site Change" assert result.iloc[0]["eventType"] == "Site Change"
assert pd_isna(result.iloc[0]["insulin"]) assert pd_isna(result.iloc[0]["insulin"])
assert pd_isna(result.iloc[0]["carbs"]) assert pd_isna(result.iloc[0]["carbs"])
assert result.iloc[0]["type"] == ""
assert pd_isna(result.iloc[0]["absolute"])
assert pd_isna(result.iloc[0]["duration"])
def test_fetch_treatments_passes_through_type_and_temp_basal_fields(monkeypatch):
"""SMB-classificatie (reporting.bolus_stats) en basaalberekening
(reporting.basal_stats) hebben deze velden nodig — zie gitea #20."""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
now = datetime.now(timezone.utc)
payload = [
{
"created_at": now.isoformat(),
"eventType": "Correction Bolus",
"insulin": 0.5,
"type": "SMB",
},
{
"created_at": now.isoformat(),
"eventType": "Temp Basal",
"absolute": 1.2,
"duration": 30,
},
]
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse(payload))
result = ns.fetch_treatments(hours=24)
smb_row = result[result["eventType"] == "Correction Bolus"].iloc[0]
basal_row = result[result["eventType"] == "Temp Basal"].iloc[0]
assert smb_row["type"] == "SMB"
assert basal_row["absolute"] == pytest.approx(1.2)
assert basal_row["duration"] == pytest.approx(30)
def pd_isna(value): def pd_isna(value):
import pandas as pd import pandas as pd
return pd.isna(value) return pd.isna(value)
def test_fetch_entries_range_filters_to_date_boundaries(monkeypatch):
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
monkeypatch.delenv("NIGHTSCOUT_TOKEN", raising=False)
monkeypatch.delenv("NIGHTSCOUT_API_SECRET", raising=False)
payload = [
{"date": int(datetime(2026, 1, 15, 12, 0, tzinfo=timezone.utc).timestamp() * 1000), "sgv": 126},
{"date": int(datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc).timestamp() * 1000), "sgv": 90},
{"date": int(datetime(2026, 2, 1, 12, 0, tzinfo=timezone.utc).timestamp() * 1000), "sgv": 100},
]
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse(payload))
result = ns.fetch_entries_range(date(2026, 1, 1), date(2026, 1, 31))
assert len(result) == 2 # de 1 feb-meting valt buiten het bereik
assert list(result.columns) == ["timestamp", "mmol"]
def test_fetch_entries_range_handles_empty_response(monkeypatch):
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse([]))
result = ns.fetch_entries_range(date(2026, 1, 1), date(2026, 1, 31))
assert result.empty
def test_fetch_treatments_range_filters_to_date_boundaries(monkeypatch):
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
payload = [
{"created_at": "2026-01-15T12:00:00Z", "eventType": "Meal Bolus", "insulin": 4.0, "carbs": 40},
{"created_at": "2026-02-01T12:00:00Z", "eventType": "Meal Bolus", "insulin": 3.0, "carbs": 30},
]
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse(payload))
result = ns.fetch_treatments_range(date(2026, 1, 1), date(2026, 1, 31))
assert len(result) == 1
assert result.iloc[0]["insulin"] == pytest.approx(4.0)
def _entry(dt, sgv=100):
return {"date": int(dt.timestamp() * 1000), "sgv": sgv, "dateString": dt.isoformat()}
def test_paginated_get_stops_when_a_short_page_is_returned(monkeypatch):
"""Nightscout kan minder dan _PAGE_SIZE teruggeven omdat er simpelweg niet meer data is.
Dit was precies de bug: een enkel groot count-verzoek werd stilzwijgend
afgeknipt. Met paginering moet een pagina die kleiner is dan de gevraagde
paginagrootte de paginering laten stoppen — dat betekent "geen oudere
data beschikbaar", niet "er ging iets mis".
"""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
now = datetime.now(timezone.utc)
payload = [_entry(now - timedelta(minutes=5 * i)) for i in range(5)] # << _PAGE_SIZE
calls = []
monkeypatch.setattr(
ns.requests,
"get",
lambda *a, **k: (calls.append(k), FakeResponse(payload))[1],
)
result = ns._paginated_get(
"/api/v1/entries/sgv.json", now - timedelta(days=1), None, ns.ENTRIES_CURSOR_FIELD
)
assert len(result) == 5
assert len(calls) == 1 # één pagina was genoeg, geen verdere paginering nodig
def test_paginated_get_walks_back_multiple_pages_until_since_is_reached(monkeypatch):
"""De kern-regressietest voor de bug: data die verder terugligt dan één
pagina (~1000 documenten) moet toch volledig worden opgehaald door
meerdere pagina's met find[date][$lte] te doorlopen."""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
now = datetime.now(timezone.utc)
# 3 volle pagina's (elk _PAGE_SIZE groot, 5 minuten uit elkaar, aflopend in tijd)
# + een laatste kleinere pagina die de paginering laat stoppen.
page_size = ns._PAGE_SIZE
pages = []
cursor = now
for _ in range(3):
page = [_entry(cursor - timedelta(minutes=5 * i)) for i in range(page_size)]
pages.append(page)
cursor = cursor - timedelta(minutes=5 * (page_size - 1)) - timedelta(minutes=5)
pages.append([_entry(cursor - timedelta(minutes=5 * i)) for i in range(10)])
call_count = {"n": 0}
def fake_get(*_a, **_k):
response = FakeResponse(pages[call_count["n"]])
call_count["n"] += 1
return response
monkeypatch.setattr(ns.requests, "get", fake_get)
since = now - timedelta(days=365) # ruim voorbij alle test-pagina's
result = ns._paginated_get(
"/api/v1/entries/sgv.json", since, None, ns.ENTRIES_CURSOR_FIELD
)
assert call_count["n"] == 4 # 3 volle pagina's + 1 korte slotpagina
assert len(result) == 3 * page_size + 10
def test_paginated_get_stops_at_since_boundary_without_fetching_further(monkeypatch):
"""Zodra een pagina data ouder dan `since` bevat, hoeft er geen volgende
pagina meer opgehaald te worden, ook al was de pagina zelf vol."""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
now = datetime.now(timezone.utc)
page_size = ns._PAGE_SIZE
# deze ene pagina spant ruim meer dan een dag, dus bevat al data voorbij `since`
page = [_entry(now - timedelta(minutes=5 * i)) for i in range(page_size)]
calls = {"n": 0}
def fake_get(*_a, **_k):
calls["n"] += 1
return FakeResponse(page)
monkeypatch.setattr(ns.requests, "get", fake_get)
since = now - timedelta(hours=6) # ruim binnen de eerste pagina
result = ns._paginated_get(
"/api/v1/entries/sgv.json", since, None, ns.ENTRIES_CURSOR_FIELD
)
assert calls["n"] == 1
assert len(result) == page_size # filtering op since gebeurt pas in _entries_since, niet hier
def test_fetch_entries_range_retrieves_data_spanning_multiple_pages(monkeypatch):
"""End-to-end regressietest: een 90-dagenrapport moet echt 90 dagen data
krijgen, niet stilzwijgend worden afgeknipt tot de meest recente pagina."""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
monkeypatch.delenv("NIGHTSCOUT_TOKEN", raising=False)
monkeypatch.delenv("NIGHTSCOUT_API_SECRET", raising=False)
end_date = date(2026, 3, 31)
start_date = date(2026, 1, 1) # 90 dagen
# simuleer Nightscout: elke 5 minuten een meting over de volle periode,
# opgeknipt in door de server afgedwongen pagina's van _PAGE_SIZE
until = datetime.combine(end_date, datetime.max.time(), tzinfo=timezone.utc)
since = datetime.combine(start_date, datetime.min.time(), tzinfo=timezone.utc)
all_entries = []
t = until
while t >= since:
all_entries.append(_entry(t))
t -= timedelta(minutes=5)
page_size = ns._PAGE_SIZE
def fake_get(*_args, **kwargs):
cursor_ms = kwargs["params"].get("find[date][$lte]")
pool = all_entries if cursor_ms is None else [e for e in all_entries if e["date"] <= cursor_ms]
return FakeResponse(pool[:page_size])
monkeypatch.setattr(ns.requests, "get", fake_get)
result = ns.fetch_entries_range(start_date, end_date)
assert len(result) == len(all_entries)
assert result["timestamp"].min().date() == start_date
assert result["timestamp"].max().date() == end_date
def _treatment(dt, event_type="Temp Basal"):
return {
"created_at": dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
"date": int(dt.timestamp() * 1000),
"eventType": event_type,
}
def test_fetch_treatments_range_retrieves_full_history_even_with_a_hidden_server_side_window(
monkeypatch,
):
"""Regressietest voor de echte productiebug (2026-07-31): treatments.json
filtert/sorteert intern op `created_at` (string), niet op `date`
(numeriek) zoals entries. Filteren op `date` — of helemaal geen filter
meegeven — leverde stilzwijgend hooguit de laatste ~4 dagen op, ook al
bevatten de documenten een geldig `date`-veld en stond de rest van de
geschiedenis (maanden) gewoon in de database (geverifieerd rechtstreeks
in MongoDB: 123k+ documenten, geen TTL-index, geen capped collection).
Deze test simuleert precies dat servergedrag: een find[date]-filter (of
het ontbreken van elk filter) geeft alleen de laatste 4 dagen terug;
alleen find[created_at] geeft de volledige, langere geschiedenis.
"""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
monkeypatch.delenv("NIGHTSCOUT_TOKEN", raising=False)
monkeypatch.delenv("NIGHTSCOUT_API_SECRET", raising=False)
end_date = date(2026, 7, 31)
start_date = date(2026, 5, 1) # 92 dagen, ruim voorbij het 4-dagen-venster
until = datetime.combine(end_date, datetime.max.time(), tzinfo=timezone.utc)
since = datetime.combine(start_date, datetime.min.time(), tzinfo=timezone.utc)
all_treatments = []
t = until
while t >= since:
all_treatments.append(_treatment(t))
t -= timedelta(minutes=30)
hidden_window_start = until - timedelta(days=4)
page_size = ns._PAGE_SIZE
def fake_get(*_args, **kwargs):
params = kwargs["params"]
cursor = params.get("find[created_at][$lte]")
if cursor is None:
# geen (of het verkeerde) filter -> verborgen 4-dagenvenster
pool = [e for e in all_treatments if e["created_at"] >= hidden_window_start.strftime(
"%Y-%m-%dT%H:%M:%S.%f"
)[:-3] + "Z"]
else:
pool = [e for e in all_treatments if e["created_at"] <= cursor]
pool = sorted(pool, key=lambda e: e["created_at"], reverse=True)
return FakeResponse(pool[:page_size])
monkeypatch.setattr(ns.requests, "get", fake_get)
result = ns.fetch_treatments_range(start_date, end_date)
assert len(result) == len(all_treatments)
assert result["timestamp"].min().date() == start_date
assert result["timestamp"].max().date() == end_date
def test_paginated_get_uses_created_at_field_for_treatments_cursor(monkeypatch):
"""Losstaande, gerichte assertie op het daadwerkelijke queryparameter-veld
— moet `find[created_at][$lte]` zijn, nooit `find[date][$lte]`, voor het
treatments-endpoint."""
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
now = datetime.now(timezone.utc)
payload = [_treatment(now - timedelta(minutes=30 * i)) for i in range(5)]
seen_params = []
def fake_get(*_a, **kwargs):
seen_params.append(kwargs["params"])
return FakeResponse(payload)
monkeypatch.setattr(ns.requests, "get", fake_get)
ns._paginated_get(
"/api/v1/treatments.json", now - timedelta(days=1), None, ns.TREATMENTS_CURSOR_FIELD
)
assert "find[created_at][$lte]" in seen_params[0]
assert "find[date][$lte]" not in seen_params[0]
+92
View File
@@ -0,0 +1,92 @@
from datetime import date
import pandas as pd
from pdf_export import (
DAGOVERZICHT_MAX_DAYS,
SECTION_AGP,
SECTION_DAGOVERZICHT,
SECTION_EVENTS,
SECTION_SUMMARY,
build_report_pdf,
)
def _sample_glucose():
timestamps = pd.date_range("2026-01-01", periods=48, freq="30min")
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():
glucose = _sample_glucose()
events_summary = {
"Hypo Level 1": {"count": 2, "avg_duration_minutes": 20.0, "events_per_week": 1.0},
}
pdf_bytes = build_report_pdf(
[SECTION_SUMMARY, SECTION_AGP, SECTION_EVENTS],
glucose,
events_summary,
date(2026, 1, 1),
date(2026, 1, 2),
)
assert isinstance(pdf_bytes, bytes)
assert pdf_bytes.startswith(b"%PDF")
assert len(pdf_bytes) > 500
def test_build_report_pdf_handles_empty_glucose():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
pdf_bytes = build_report_pdf(
[SECTION_SUMMARY, SECTION_AGP], empty, {}, date(2026, 1, 1), date(2026, 1, 2)
)
assert pdf_bytes.startswith(b"%PDF")
def test_build_report_pdf_handles_no_sections_selected():
glucose = _sample_glucose()
pdf_bytes = build_report_pdf([], glucose, {}, date(2026, 1, 1), date(2026, 1, 2))
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
+533
View File
@@ -0,0 +1,533 @@
from datetime import date
import pandas as pd
import pytest
from reporting import (
GMI_TREND_COLUMNS,
agp_percentile_bands,
basal_stats,
bolus_stats,
completeness_warning,
daily_gmi,
day_of_week_pattern,
detect_events,
gmi_mmol_per_mol,
gmi_percent,
gmi_trend,
minutes_per_day,
overnight_daytime_split,
percent_cv,
sensor_active_percent,
site_interval_stats,
summarize_events,
tir_breakdown_5band,
)
def _series(pairs):
"""Bouw een glucose-DataFrame uit (tijd-string, mmol)-paren."""
timestamps, values = zip(*pairs, strict=True)
return pd.DataFrame({"timestamp": pd.to_datetime(list(timestamps)), "mmol": list(values)})
def test_gmi_percent_matches_bergenstal_formula():
# 3.31 + 0.4311 * 7.0 = 6.3277 -> 6.3
assert gmi_percent(7.0) == pytest.approx(6.3, abs=0.05)
def test_gmi_mmol_per_mol_matches_known_ifcc_reference_values():
# 6.5% is de bekende diagnostische drempel = 48 mmol/mol (IFCC).
assert gmi_mmol_per_mol(6.5) == 48
assert gmi_mmol_per_mol(7.0) == 53
def test_daily_gmi_aggregates_per_calendar_day():
glucose = _series(
[
("2026-01-01 08:00", 6.0),
("2026-01-01 20:00", 8.0),
("2026-01-02 08:00", 7.0),
]
)
result = daily_gmi(glucose)
assert list(result["date"].astype(str)) == ["2026-01-01", "2026-01-02"]
assert result["gmi"].iloc[0] == pytest.approx(gmi_percent(7.0)) # gemiddelde van 6.0 en 8.0
assert result["gmi"].iloc[1] == pytest.approx(gmi_percent(7.0))
def test_daily_gmi_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
result = daily_gmi(empty)
assert result.empty
assert list(result.columns) == ["date", "gmi"]
def test_gmi_trend_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
result = gmi_trend(empty)
assert result.empty
assert list(result.columns) == GMI_TREND_COLUMNS
def test_gmi_trend_returns_no_line_for_a_single_day():
glucose = _series([("2026-01-01 08:00", 6.0)])
result = gmi_trend(glucose)
assert list(result.columns) == GMI_TREND_COLUMNS
assert len(result) == 1
assert pd.isna(result["trend"].iloc[0])
def test_gmi_trend_fits_increasing_linear_trend_with_band_around_it():
pairs = [(f"2026-01-{i + 1:02d} 08:00", 6.0 + i * 0.2) for i in range(10)]
glucose = _series(pairs)
result = gmi_trend(glucose, rolling_window_days=3)
assert len(result) == 10
assert result["trend"].iloc[-1] > result["trend"].iloc[0]
assert (result["trend_lower"] <= result["trend"]).all()
assert (result["trend"] <= result["trend_upper"]).all()
# Vrijwel lineaire input (gmi_percent rondt af op 1 decimaal, dus een
# kleine restfout blijft over) -> smalle betrouwbaarheidsband.
assert (result["trend_upper"] - result["trend_lower"]).max() == pytest.approx(0, abs=0.15)
assert result["rolling_avg"].iloc[-1] > result["rolling_avg"].iloc[0]
def test_percent_cv_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
assert percent_cv(empty) == 0.0
def test_percent_cv_computes_stdev_over_mean():
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-01 00:05", 8.0),
("2026-01-01 00:10", 6.0),
("2026-01-01 00:15", 8.0),
]
)
expected = glucose["mmol"].std() / glucose["mmol"].mean() * 100
assert percent_cv(glucose) == pytest.approx(round(expected, 1))
def test_tir_breakdown_5band_covers_all_bands_and_sums_to_100():
glucose = _series(
[
("2026-01-01 00:00", 2.5), # very_low
("2026-01-01 00:05", 3.5), # low
("2026-01-01 00:10", 6.0), # in_range
("2026-01-01 00:15", 11.0), # high
("2026-01-01 00:20", 14.0), # very_high
]
)
result = tir_breakdown_5band(glucose)
assert result == {
"very_low": 20.0,
"low": 20.0,
"in_range": 20.0,
"high": 20.0,
"very_high": 20.0,
}
assert sum(result.values()) == pytest.approx(100.0)
def test_tir_breakdown_5band_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
result = tir_breakdown_5band(empty)
assert result == {"very_low": 0.0, "low": 0.0, "in_range": 0.0, "high": 0.0, "very_high": 0.0}
def test_minutes_per_day_converts_percentage():
assert minutes_per_day(50.0) == 720.0
assert minutes_per_day(100.0) == 1440.0
def test_sensor_active_percent_full_coverage():
# 12 metingen om de 5 minuten = precies 1 uur dekking
timestamps = pd.date_range("2026-01-01 00:00", periods=12, freq="5min")
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [6.0] * 12})
result = sensor_active_percent(glucose, "2026-01-01 00:00", "2026-01-01 01:00")
assert result == pytest.approx(100.0, abs=1.0)
def test_sensor_active_percent_handles_gaps():
timestamps = pd.date_range("2026-01-01 00:00", periods=6, freq="5min") # maar 30 min dekking
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [6.0] * 6})
result = sensor_active_percent(glucose, "2026-01-01 00:00", "2026-01-01 01:00")
assert result == pytest.approx(50.0, abs=1.0)
def test_completeness_warning_none_for_empty_glucose():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
assert completeness_warning(empty, "2026-01-01", "2026-01-14") == "Geen glucosedata gevonden in deze periode."
def test_completeness_warning_none_when_period_is_fully_covered():
# 14 volle dagen aan 5-minuten-metingen, precies de gekozen periode
timestamps = pd.date_range("2026-01-01 00:00", "2026-01-14 23:55", freq="5min")
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [6.0] * len(timestamps)})
assert completeness_warning(glucose, date(2026, 1, 1), date(2026, 1, 14)) is None
def test_completeness_warning_flags_missing_days_at_start_of_period():
# gevraagd: 1 t/m 14 januari, maar data begint pas op 11 januari (de
# exacte bug: alleen de laatste ~4 dagen van een langere periode zijn
# opgehaald)
timestamps = pd.date_range("2026-01-11 00:00", "2026-01-14 23:55", freq="5min")
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [6.0] * len(timestamps)})
message = completeness_warning(glucose, date(2026, 1, 1), date(2026, 1, 14))
assert message is not None
assert "11-01-2026" in message
assert "10 dag" in message # 1 t/m 10 januari ontbreken volledig = 10 dagen
assert "sensorhiaten" in message
def test_completeness_warning_flags_low_coverage_without_start_gap():
# data start op tijd, maar met veel verspreide hiaten -> lage dekking
# zonder dat er een aaneengesloten gat aan het begin is
timestamps = pd.date_range("2026-01-01 00:00", periods=20, freq="5min")
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [6.0] * 20})
message = completeness_warning(glucose, date(2026, 1, 1), date(2026, 1, 14))
assert message is not None
assert "sensordekking" in message
assert "sensorhiaten" not in message # dit is de generieke, niet de "ontbreekt volledig"-boodschap
def test_detect_events_ignores_dip_shorter_than_minimum_duration():
# dip van 10 minuten (< 15 min drempel) mag niet meetellen
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-01 00:05", 3.5),
("2026-01-01 00:10", 3.4),
("2026-01-01 00:15", 6.0),
("2026-01-01 00:20", 6.1),
("2026-01-01 00:25", 6.2),
]
)
events = detect_events(glucose, threshold=3.9, direction="below")
assert events.empty
def test_detect_events_counts_dip_of_exactly_20_minutes():
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-01 00:05", 3.5),
("2026-01-01 00:10", 3.4),
("2026-01-01 00:15", 3.3),
("2026-01-01 00:20", 3.2),
("2026-01-01 00:25", 6.0),
("2026-01-01 00:30", 6.1),
("2026-01-01 00:35", 6.2),
("2026-01-01 00:40", 6.3),
]
)
events = detect_events(glucose, threshold=3.9, direction="below")
assert len(events) == 1
assert events.iloc[0]["duration_minutes"] == pytest.approx(20.0)
def test_detect_events_merges_across_brief_recovery():
# twee dips gescheiden door een kort (5 min) herstel moeten één
# doorlopend event vormen volgens de persistentieregel
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-01 00:05", 3.5),
("2026-01-01 00:10", 3.4),
("2026-01-01 00:15", 6.0), # kort herstel, 5 min
("2026-01-01 00:20", 3.3),
("2026-01-01 00:25", 3.2),
("2026-01-01 00:30", 3.1),
("2026-01-01 00:35", 6.0),
("2026-01-01 00:40", 6.1),
("2026-01-01 00:45", 6.2),
("2026-01-01 00:50", 6.3), # bevestigd herstel, 15 min
]
)
events = detect_events(glucose, threshold=3.9, direction="below")
assert len(events) == 1
assert events.iloc[0]["start"] == pd.Timestamp("2026-01-01 00:05")
assert events.iloc[0]["end"] == pd.Timestamp("2026-01-01 00:35")
assert events.iloc[0]["duration_minutes"] == pytest.approx(30.0)
def test_detect_events_does_not_inflate_duration_on_trailing_brief_blip():
# regressie: een out-periode van 10 min gevolgd door een niet-bevestigd
# (kort, en aan het eind van de data) herstel mag niet meetellen
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-01 00:05", 3.5),
("2026-01-01 00:10", 3.4),
("2026-01-01 00:15", 6.0),
("2026-01-01 00:20", 6.1),
("2026-01-01 00:25", 6.2),
]
)
events = detect_events(glucose, threshold=3.9, direction="below")
assert events.empty
def test_detect_events_supports_hyperglycemia_direction():
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-01 00:05", 12.0),
("2026-01-01 00:10", 12.5),
("2026-01-01 00:15", 13.0),
("2026-01-01 00:20", 12.8),
("2026-01-01 00:25", 6.0),
("2026-01-01 00:30", 6.1),
("2026-01-01 00:35", 6.2),
("2026-01-01 00:40", 6.3),
]
)
events = detect_events(glucose, threshold=10.0, direction="above")
assert len(events) == 1
assert events.iloc[0]["duration_minutes"] == pytest.approx(20.0)
def test_detect_events_rejects_invalid_direction():
glucose = _series([("2026-01-01 00:00", 6.0)])
with pytest.raises(ValueError, match="direction"):
detect_events(glucose, threshold=3.9, direction="sideways")
def test_detect_events_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
events = detect_events(empty, threshold=3.9, direction="below")
assert events.empty
assert list(events.columns) == ["start", "end", "duration_minutes"]
def test_summarize_events_computes_expected_stats():
events = pd.DataFrame(
{
"start": pd.to_datetime(["2026-01-01 00:00", "2026-01-03 00:00"]),
"end": pd.to_datetime(["2026-01-01 00:20", "2026-01-03 01:00"]),
"duration_minutes": [20.0, 60.0],
}
)
result = summarize_events(events, period_days=7)
assert result["count"] == 2
assert result["avg_duration_minutes"] == pytest.approx(40.0)
assert result["longest_duration_minutes"] == pytest.approx(60.0)
assert result["total_minutes"] == pytest.approx(80.0)
assert result["events_per_week"] == pytest.approx(2.0)
def test_agp_percentile_bands_groups_by_time_of_day_across_days():
# zelfde tijdstip (08:00) op twee verschillende dagen, met bekende waarden
glucose = _series(
[
("2026-01-01 08:00", 6.0),
("2026-01-02 08:00", 8.0),
("2026-01-01 20:00", 10.0),
("2026-01-02 20:00", 10.0),
]
)
result = agp_percentile_bands(glucose, bin_minutes=30)
assert list(result.columns) == ["minute_of_day", "p5", "p25", "p50", "p75", "p95"]
morning_bin = 8 * 60
row = result[result["minute_of_day"] == morning_bin].iloc[0]
assert row["p50"] == pytest.approx(7.0) # mediaan van 6.0 en 8.0
evening_bin = 20 * 60
evening_row = result[result["minute_of_day"] == evening_bin].iloc[0]
assert evening_row["p50"] == pytest.approx(10.0)
def test_agp_percentile_bands_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
result = agp_percentile_bands(empty)
assert result.empty
assert list(result.columns) == ["minute_of_day", "p5", "p25", "p50", "p75", "p95"]
def test_overnight_daytime_split_separates_by_hour():
glucose = _series(
[
("2026-01-01 02:00", 3.0), # nacht, laag
("2026-01-01 03:00", 3.0), # nacht, laag
("2026-01-01 12:00", 6.0), # dag, in bereik
("2026-01-01 13:00", 6.0), # dag, in bereik
]
)
result = overnight_daytime_split(glucose, overnight_start=0, overnight_end=6)
assert result["overnight"]["low"] == pytest.approx(100.0)
assert result["daytime"]["in_range"] == pytest.approx(100.0)
def test_overnight_daytime_split_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
result = overnight_daytime_split(empty)
assert result["overnight"] == result["daytime"]
def test_day_of_week_pattern_computes_per_weekday_stats():
# 2026-01-05 is een maandag
glucose = _series(
[
("2026-01-05 08:00", 6.0),
("2026-01-05 09:00", 8.0),
("2026-01-12 08:00", 7.0), # ook een maandag
]
)
result = day_of_week_pattern(glucose)
monday = result[result["weekday"] == "Maandag"].iloc[0]
assert monday["count"] == 3
assert monday["mean_mmol"] == pytest.approx(7.0)
tuesday = result[result["weekday"] == "Dinsdag"].iloc[0]
assert tuesday["count"] == 0
assert pd.isna(tuesday["mean_mmol"])
def test_day_of_week_pattern_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "mmol"])
result = day_of_week_pattern(empty)
assert result.empty
assert list(result.columns) == ["weekday", "mean_mmol", "in_range_pct", "count"]
def test_bolus_stats_splits_by_event_type():
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 12:00", "2026-01-01 20:00"]),
"eventType": ["Meal Bolus", "Correction Bolus", "Site Change"],
"insulin": [4.0, 1.5, None],
"carbs": [45.0, None, None],
"type": ["NORMAL", "NORMAL", ""],
}
)
result = bolus_stats(treatments)
assert result["total_units"] == pytest.approx(5.5)
assert result["count"] == 2
assert result["by_type"] == {"Meal Bolus": 4.0, "Correction Bolus": 1.5}
def test_bolus_stats_reclassifies_smb_correction_boluses_separately():
"""AndroidAPS registreert een automatische SMB-microbolus als
eventType == "Correction Bolus" met type == "SMB" — dit moet apart van
een handmatige correctiebolus (type != "SMB") geteld worden (gitea #20)."""
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 12:00"]),
"eventType": ["Correction Bolus", "Correction Bolus"],
"insulin": [0.3, 0.9],
"carbs": [None, None],
"type": ["SMB", "NORMAL"],
}
)
result = bolus_stats(treatments)
assert result["by_type"] == {"SMB": 0.3, "Correction Bolus": 0.9}
def test_bolus_stats_treats_missing_type_column_as_non_smb():
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00"]),
"eventType": ["Correction Bolus"],
"insulin": [0.9],
"carbs": [None],
}
)
result = bolus_stats(treatments)
assert result["by_type"] == {"Correction Bolus": 0.9}
def test_bolus_stats_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs", "type"])
result = bolus_stats(empty)
assert result == {"total_units": 0.0, "count": 0, "by_type": {}}
def test_basal_stats_sums_temp_basal_rate_times_duration():
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 08:30"]),
"eventType": ["Temp Basal", "Temp Basal"],
"absolute": [1.2, 0.6],
"duration": [30, 60],
}
)
# 1.2 E/u * 0.5u + 0.6 E/u * 1u = 0.6 + 0.6 = 1.2 E over 1 dag
result = basal_stats(treatments, period_days=1)
assert result["total_units"] == pytest.approx(1.2)
assert result["avg_units_per_day"] == pytest.approx(1.2)
def test_basal_stats_ignores_non_temp_basal_rows_and_missing_fields():
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 08:30"]),
"eventType": ["Meal Bolus", "Temp Basal"],
"absolute": [None, None],
"duration": [None, 30],
}
)
result = basal_stats(treatments, period_days=1)
assert result == {"total_units": 0.0, "avg_units_per_day": 0.0}
def test_basal_stats_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "eventType", "absolute", "duration"])
result = basal_stats(empty, period_days=1)
assert result == {"total_units": 0.0, "avg_units_per_day": 0.0}
def test_site_interval_stats_splits_by_site_change():
glucose = _series(
[
("2026-01-01 00:00", 6.0),
("2026-01-05 00:00", 6.0),
("2026-01-10 00:00", 8.0),
]
)
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-02 00:00", "2026-01-06 00:00"]),
"eventType": ["Meal Bolus", "Meal Bolus"],
"insulin": [3.0, 4.0],
"carbs": [30.0, 40.0],
}
)
site_changes = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 00:00", "2026-01-06 00:00"]),
"eventType": ["Site Change", "Site Change"],
"insulin": [None, None],
"carbs": [None, None],
}
)
result = site_interval_stats(glucose, treatments, site_changes)
assert len(result) == 2
assert result.iloc[0]["duration_days"] == pytest.approx(5.0)
assert result.iloc[0]["total_bolus_units"] == pytest.approx(3.0)
# de bolus op 6 jan valt binnen het tweede interval ([6 jan, 10 jan))
assert result.iloc[1]["total_bolus_units"] == pytest.approx(4.0)
def test_site_interval_stats_handles_no_site_changes():
glucose = _series([("2026-01-01 00:00", 6.0)])
treatments = pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs"])
empty_site_changes = pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs"])
result = site_interval_stats(glucose, treatments, empty_site_changes)
assert result.empty
def test_summarize_events_handles_empty_input():
empty = pd.DataFrame(columns=["start", "end", "duration_minutes"])
result = summarize_events(empty, period_days=14)
assert result == {
"count": 0,
"avg_duration_minutes": 0.0,
"longest_duration_minutes": 0.0,
"total_minutes": 0.0,
"events_per_week": 0.0,
}
+38
View File
@@ -0,0 +1,38 @@
import plotly.graph_objects as go
from ui_common import (
PALETTE,
THRESHOLD_LINES,
add_threshold_lines,
build_tir_stacked_bar_figure,
hex_to_rgba,
)
def test_hex_to_rgba_converts_correctly():
assert hex_to_rgba("#2a78d6", 0.3) == "rgba(42,120,214,0.3)"
def test_hex_to_rgba_handles_hash_optional():
assert hex_to_rgba("2a78d6", 0.3) == "rgba(42,120,214,0.3)"
def test_add_threshold_lines_adds_one_line_per_clinical_threshold():
fig = go.Figure()
add_threshold_lines(fig, PALETTE["light"])
assert len(fig.layout.shapes) == len(THRESHOLD_LINES)
def test_add_threshold_lines_targets_subplot_row_when_given():
fig = go.Figure()
fig.add_trace(go.Scatter(x=[0], y=[0]))
add_threshold_lines(fig, PALETTE["light"], row=1)
assert len(fig.layout.shapes) == len(THRESHOLD_LINES)
def test_build_tir_stacked_bar_figure_has_one_bar_trace_per_band():
tir = {"very_low": 1.0, "low": 3.0, "in_range": 80.0, "high": 12.0, "very_high": 4.0}
fig = build_tir_stacked_bar_figure(tir, PALETTE["light"])
assert len(fig.data) == 5
assert [trace.y[0] for trace in fig.data] == [1.0, 3.0, 80.0, 12.0, 4.0]
assert fig.layout.barmode == "stack"
+252
View File
@@ -0,0 +1,252 @@
"""
Gedeelde UI-hulpmiddelen voor app.py en alle pages/*.py.
Elke Streamlit-pagina draait als los script, dus gedeelde constanten/functies
(kleurenpalet, thema-detectie) horen hier thuis in plaats van gedupliceerd te
worden per pagina.
"""
from __future__ import annotations
from datetime import date, datetime, timedelta, timezone
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from nightscout_client import fetch_entries_range, fetch_treatments_range
from reporting import (
HIGH,
LOW,
VERY_HIGH,
VERY_LOW,
completeness_warning,
detect_events,
summarize_events,
)
MMOL_HOVERTEMPLATE = "%{x|%d-%m %H:%M} · %{y:.1f} mmol/L<extra></extra>"
# Periode-opties voor de rapportagepagina's (FR1): elke pagina kiest zijn eigen
# standaard (90 dagen voor statistiek/TIR, 14 dagen voor recente
# glucosegrafieken) via `default_label`.
PERIOD_OPTIONS_DAYS = {"14 dagen": 14, "30 dagen": 30, "90 dagen": 90}
# Kleuren per rol, licht/donker — categorale kleuren voor identiteit
# (glucose/insuline/carbs), status-kleuren (vast, nooit hergebruikt) voor
# te laag/te hoog.
PALETTE = {
"light": {
"glucose": "#2a78d6",
"insulin": "#1baf7a",
"carbs": "#eb6834",
"low": "#d03b3b",
"very_low": "#d03b3b",
"high": "#fab219",
"very_high": "#fab219",
"band": "rgba(12,163,12,0.08)",
"grid": "#e1e0d9",
"muted": "#898781",
"text": "#52514e",
"good": "#0ca30c",
# Losstaand van "low"/"high" hierboven (die blijven gedeeld tussen
# andere grafieken): de 5-bands TIR-grafiek (gitea #14) heeft juist
# zichtbaar onderscheid tussen laag/zeer-laag en hoog/zeer-hoog nodig.
"tir_very_low": "#8b1a1a",
"tir_low": "#d03b3b",
"tir_in_range": "#0ca30c",
"tir_high": "#fab219",
"tir_very_high": "#c76f0a",
},
"dark": {
"glucose": "#3987e5",
"insulin": "#199e70",
"carbs": "#d95926",
"low": "#d03b3b",
"very_low": "#d03b3b",
"high": "#fab219",
"very_high": "#fab219",
"band": "rgba(12,163,12,0.15)",
"grid": "#2c2c2a",
"muted": "#898781",
"text": "#c3c2b7",
"good": "#0ca30c",
"tir_very_low": "#a32626",
"tir_low": "#d95d5d",
"tir_in_range": "#0ca30c",
"tir_high": "#fab219",
"tir_very_high": "#d9852e",
},
}
# Klinische drempellijnen (Battelino et al. 2019), gedeeld tussen de AGP- en
# Dagoverzicht-pagina's (FR3, FR4 — gitea #15) zodat beide grafieken exact
# dezelfde 4 lijnen op dezelfde manier tonen.
THRESHOLD_LINES = [
(VERY_LOW, "3.0"),
(LOW, "3.9"),
(HIGH, "10.0"),
(VERY_HIGH, "13.9"),
]
def hex_to_rgba(hex_color: str, alpha: float) -> str:
"""Zet een '#rrggbb'-kleur om naar een 'rgba(r,g,b,a)'-string voor Plotly-fills."""
hex_color = hex_color.lstrip("#")
r, g, b = (int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
return f"rgba({r},{g},{b},{alpha})"
def get_colors() -> dict:
"""Geef de kleurenset terug die past bij het actieve Streamlit-thema."""
theme_type = "light"
try:
theme_type = st.context.theme.type or "light"
except AttributeError:
pass
return PALETTE["dark" if theme_type == "dark" else "light"]
def select_period_days(default_label: str) -> tuple[date, date, int]:
"""Periodekiezer voor rapportagepagina's; geeft (start, eind, aantal_dagen) terug."""
labels = list(PERIOD_OPTIONS_DAYS.keys())
label = st.radio("Periode", labels, index=labels.index(default_label), horizontal=True)
days = PERIOD_OPTIONS_DAYS[label]
end = datetime.now(tz=timezone.utc).date()
start = end - timedelta(days=days - 1)
return start, end, days
@st.cache_data(ttl=3600, show_spinner="Data ophalen van Nightscout...")
def load_range_data(start: date, end: date):
"""Gecachete Nightscout-fetch voor een vaste periode.
Lange TTL (in tegenstelling tot de 60s van de live-pagina): historische
data van een afgeronde periode verandert niet.
"""
glucose = fetch_entries_range(start, end)
treatments = fetch_treatments_range(start, end)
return glucose, treatments
def add_threshold_lines(fig: go.Figure, colors: dict, row: int | None = None) -> None:
"""Teken de 4 klinische drempellijnen (3.0/3.9/10.0/13.9 mmol/L) op een grafiek.
Gedeeld door de AGP- en Dagoverzicht-pagina's (gitea #15). `row` wordt
doorgegeven aan `add_hline` voor subplot-figuren (Dagoverzicht); voor een
los-staande figuur (AGP) blijft dit `None`.
"""
kwargs = {} if row is None else {"row": row, "col": 1}
for value, label in THRESHOLD_LINES:
fig.add_hline(
y=value,
line={"color": colors["muted"], "width": 1, "dash": "dot"},
annotation_text=label,
annotation_position="right",
annotation_font={"size": 9, "color": colors["muted"]},
**kwargs,
)
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",
}
def build_tir_stacked_bar_figure(tir: dict, colors: dict) -> go.Figure:
"""Bouw de 5-bands tijd-in-bereik als één gestapelde staafgrafiek (gitea #14).
Eén staaf, geen x-as-label, percentage op de y-as; van onder naar boven
"Zeer laag" -> "Zeer hoog" — dezelfde volgorde als de klinische banden.
"""
fig = go.Figure()
for band in TIR_BAND_ORDER:
fig.add_trace(
go.Bar(
x=[""],
y=[tir[band]],
name=TIR_BAND_LABELS[band],
marker_color=colors[f"tir_{band}"],
hovertemplate=f"{TIR_BAND_LABELS[band]}: %{{y:.0f}}%<extra></extra>",
)
)
fig.update_layout(
barmode="stack",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
height=140,
margin={"l": 10, "r": 10, "t": 10, "b": 10},
yaxis={"title": "%", "range": [0, 100], "gridcolor": colors["grid"]},
xaxis={"visible": False},
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
)
return fig
def render_completeness_warning(glucose: pd.DataFrame, start: date, end: date) -> None:
"""Toon reporting.completeness_warning()'s oordeel als st.warning, indien nodig.
Gebruikt door elke rapportagepagina, direct na de load_range_data-call.
De beoordelingslogica zelf staat in reporting.py (pure functie) zodat het
PDF-rapport (pdf_export.py) exact dezelfde disclaimer kan hergebruiken.
"""
message = completeness_warning(glucose, start, end)
if message:
st.warning(message)
def render_event_level(
glucose: pd.DataFrame,
threshold: float,
direction: str,
level_name: str,
period_days: int,
colors: dict,
) -> None:
"""Render de metrics/tabel/tijdstip-histogram voor één hypo-/hyperniveau.
Gedeeld tussen de Hypo Events- en Hyper Events-pagina's (FR5/FR6), die
elk twee niveaus (Level 1/Level 2) op dezelfde manier tonen.
"""
events = detect_events(glucose, threshold, direction)
summary = summarize_events(events, period_days)
st.subheader(level_name)
cols = st.columns(4)
cols[0].metric("Aantal events", summary["count"])
cols[1].metric("Gem. duur", f"{summary['avg_duration_minutes']:.0f} min")
cols[2].metric("Langste event", f"{summary['longest_duration_minutes']:.0f} min")
cols[3].metric("Events/week", f"{summary['events_per_week']:.1f}")
if events.empty:
st.info("Geen events gevonden in deze periode.")
return
bar_color = colors["low"] if direction == "below" else colors["high"]
hours = events["start"].dt.hour
hour_counts = hours.value_counts().reindex(range(24), fill_value=0).sort_index()
fig = go.Figure(go.Bar(x=list(hour_counts.index), y=hour_counts.to_numpy(), marker_color=bar_color))
fig.update_layout(
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font_color=colors["text"],
height=220,
margin={"l": 10, "r": 10, "t": 10, "b": 10},
xaxis={"title": "Uur van de dag", "dtick": 2, "gridcolor": colors["grid"]},
yaxis={"title": "Aantal events", "gridcolor": colors["grid"]},
)
st.plotly_chart(fig, width="stretch")
display = events.copy()
display["start"] = display["start"].dt.strftime("%d-%m-%Y %H:%M")
display["end"] = display["end"].dt.strftime("%d-%m-%Y %H:%M")
display = display.rename(
columns={"start": "Start", "end": "Einde", "duration_minutes": "Duur (min)"}
)
st.dataframe(display, width="stretch", hide_index=True)