Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de0ecebce5 | ||
|
|
caf28046cb | ||
|
|
a4d29e85a8 | ||
|
|
7f4377329a | ||
|
|
a10a4c0414 | ||
|
|
a3d89c4d21 | ||
|
|
1376101212 | ||
|
|
f2c3f97b1f | ||
|
|
d33516e2a1 | ||
|
|
c54dcf616a | ||
|
|
79249958c2 | ||
|
|
8641022219 | ||
|
|
e08f269855 | ||
|
|
db3204ab58 | ||
|
|
b8e01fa8c9 | ||
|
|
25c3fe6730 | ||
|
|
374ead70e5 | ||
|
|
d637ad39e4 | ||
|
|
9e11dd8d73 | ||
|
|
5addd6a49b | ||
|
|
441bb84212 | ||
|
|
95f006078f | ||
|
|
00fb81b283 | ||
|
|
4bb9251d7d | ||
|
|
699848b479 | ||
|
|
6c6b175a28 | ||
|
|
55883480c0 | ||
|
|
29d20ca441 | ||
|
|
c39646ceaa | ||
|
|
fe6a471f17 | ||
|
|
52c9284f85 | ||
|
|
9929f44daa | ||
|
|
419508dd5e | ||
|
|
04c5f521fe | ||
|
|
689452cf4c | ||
|
|
1207ff536f | ||
|
|
e600d6cf7d | ||
|
|
3ef9a7666a | ||
|
|
10aa315e40 | ||
|
|
7379f6be8c |
@@ -5,4 +5,6 @@ __pycache__/
|
|||||||
.git/
|
.git/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
tests/
|
tests/
|
||||||
|
|||||||
@@ -10,3 +10,14 @@ 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=
|
||||||
|
|
||||||
|
# Optioneel: apparatuurinfo voor de kop van het PDF-rapport (pages/8_Export.py).
|
||||||
|
# Puur informatief, geen effect op de berekeningen — leeg = "Onbekend ...".
|
||||||
|
REPORT_INSULIN_TYPE=Lyumjev 100U
|
||||||
|
REPORT_PUMP_TYPE=
|
||||||
|
REPORT_SENSOR_TYPE=
|
||||||
|
|||||||
@@ -19,11 +19,21 @@ jobs:
|
|||||||
run: pip install -r requirements.txt
|
run: pip install -r requirements.txt
|
||||||
- name: Lint (ruff)
|
- name: Lint (ruff)
|
||||||
run: ruff check .
|
run: ruff check .
|
||||||
- name: Unit tests (pytest)
|
- name: Unit tests + coverage-gate (pytest)
|
||||||
run: pytest tests/ -v
|
# fail_under (pyproject.toml, [tool.coverage.report]) laat deze stap
|
||||||
|
# falen als de dekking op de gemeten modules onder 80% zakt — app.py/
|
||||||
|
# pages/*.py zijn uitgesloten (zie pyproject.toml se coverage-omit),
|
||||||
|
# dat zijn dunne Streamlit-UI-scripts die niet zinvol te unit-testen
|
||||||
|
# zijn zonder een draaiende Streamlit-sessie.
|
||||||
|
run: pytest tests/ -v --cov=. --cov-report=term-missing --cov-report=xml
|
||||||
|
- name: Bewaar coverage-rapport
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: coverage-report
|
||||||
|
path: coverage.xml
|
||||||
|
|
||||||
# ---------------------------------------------------------------------
|
# ---------------------------------------------------------------------
|
||||||
# 2. SonarQube — codekwaliteit-gate
|
# 2. SonarQube — codekwaliteit-gate (incl. coverage uit de vorige stap)
|
||||||
# ---------------------------------------------------------------------
|
# ---------------------------------------------------------------------
|
||||||
sonarqube:
|
sonarqube:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -32,6 +42,10 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0 # SonarQube wil de volledige git-historie zien
|
fetch-depth: 0 # SonarQube wil de volledige git-historie zien
|
||||||
|
- name: Download coverage-rapport
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: coverage-report
|
||||||
- name: SonarQube scan
|
- name: SonarQube scan
|
||||||
uses: sonarsource/sonarqube-scan-action@v6
|
uses: sonarsource/sonarqube-scan-action@v6
|
||||||
env:
|
env:
|
||||||
@@ -50,15 +64,21 @@ jobs:
|
|||||||
run: docker build -t gitea.zb-kw.duckdns.org/willemjan/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-kw.duckdns.org/willemjan/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
|
||||||
# gitea.token is geen geldig GitHub-token; leeg laten zodat setup-trivy
|
ignore-unfixed: true
|
||||||
# de aquasecurity/trivy-repo anoniem kan clonen in plaats van een
|
vuln-type: os,library
|
||||||
# ongeldige Authorization-header naar github.com te sturen.
|
severity: CRITICAL,HIGH
|
||||||
token-setup-trivy: ""
|
|
||||||
|
|
||||||
- name: Login bij Gitea-registry
|
- name: Login bij Gitea-registry
|
||||||
run: echo "${{ secrets.GLUCOSE_TOKEN }}" | docker login gitea.zb-kw.duckdns.org -u willemjan --password-stdin
|
run: echo "${{ secrets.GLUCOSE_TOKEN }}" | docker login gitea.zb-kw.duckdns.org -u willemjan --password-stdin
|
||||||
|
|||||||
@@ -4,4 +4,6 @@ __pycache__/
|
|||||||
.env
|
.env
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
homelab-cicd-werkinstructie.md
|
homelab-cicd-werkinstructie.md
|
||||||
Vendored
+11
@@ -0,0 +1,11 @@
|
|||||||
|
pipeline {
|
||||||
|
agent any
|
||||||
|
|
||||||
|
stages {
|
||||||
|
stage('Do nothing') {
|
||||||
|
steps {
|
||||||
|
sh '/bin/true'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,18 +1,23 @@
|
|||||||
# 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. `REPORT_INSULIN_TYPE`/`REPORT_PUMP_TYPE`/`REPORT_SENSOR_TYPE` zijn
|
||||||
|
optioneel en puur informatief (getoond in de kop van het PDF-rapport).
|
||||||
3. Lokaal draaien:
|
3. Lokaal draaien:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
@@ -36,3 +41,12 @@ koolhydraten en pomp-/sensorwissels overlay, plus time-in-range-cijfers.
|
|||||||
pytest tests/ -v
|
pytest tests/ -v
|
||||||
ruff check .
|
ruff check .
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Coverage (zie `pyproject.toml` se `[tool.coverage.*]`): de CI-pipeline faalt
|
||||||
|
als de dekking op de gemeten modules onder 80% zakt (`app.py`/`pages/*.py`
|
||||||
|
zijn uitgesloten — dunne Streamlit-UI-scripts, niet zinvol te unit-testen
|
||||||
|
zonder een draaiende Streamlit-sessie).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest tests/ --cov=. --cov-report=term-missing
|
||||||
|
```
|
||||||
|
|||||||
@@ -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"
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||||
|
<path d="M32 4 C20 22, 10 34, 10 46 A22 22 0 0 0 54 46 C54 34, 44 22, 32 4 Z" fill="#2a78d6"/>
|
||||||
|
<polyline points="14,42 24,42 28,32 34,52 40,38 46,42 50,42" fill="none" stroke="#ffffff" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 325 B |
@@ -0,0 +1,54 @@
|
|||||||
|
"""
|
||||||
|
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: # pragma: no cover
|
||||||
|
"""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.
|
||||||
|
|
||||||
|
Pure Streamlit-widget-orkestratie (st.text_input/st.session_state/
|
||||||
|
st.rerun) — buiten scope van de unit-testdekking net als pages/*.py,
|
||||||
|
zie pyproject.toml se coverage-omit-lijst. De veiligheidsrelevante
|
||||||
|
logica zelf (verify_password()) is wel volledig getest.
|
||||||
|
"""
|
||||||
|
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
|
||||||
@@ -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).
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
+173
-30
@@ -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,44 @@ 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})
|
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_entries_range(start_date: date, end_date: date) -> pd.DataFrame:
|
||||||
|
"""Haal glucosemetingen op tussen start_date en end_date (beide inclusief).
|
||||||
|
|
||||||
|
Bedoeld voor meerdaagse rapportages (bijv. 90 dagen) waarbij het
|
||||||
|
uren-schalende `fetch_entries` niet praktisch is. Zelfde kolommen als
|
||||||
|
`fetch_entries`.
|
||||||
|
"""
|
||||||
|
since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
|
||||||
|
until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
|
||||||
|
return _entries_since(since, until)
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_profile() -> dict:
|
||||||
|
"""Haal het meest recent gebruikte pompprofiel op.
|
||||||
|
|
||||||
|
Nightscout's /api/v1/profile.json geeft profieldocumenten terug, nieuwste
|
||||||
|
eerst; met count=1 krijgen we alleen het actief gebruikte document. Een
|
||||||
|
profiel is geen tijdreeks (in tegenstelling tot entries/treatments) dus
|
||||||
|
geen paginering nodig — één klein verzoek volstaat.
|
||||||
|
|
||||||
|
Geeft {} terug als er geen profiel bestaat (bijv. lege Nightscout-instantie).
|
||||||
|
Het resultaat is het rauwe Nightscout-documument; zie profile_data.parse_profile()
|
||||||
|
voor de genormaliseerde vorm (basaalschema, ISF, koolhydraatratio, DIA, streefwaarden).
|
||||||
|
"""
|
||||||
|
data = _get("/api/v1/profile.json", {"count": 1})
|
||||||
if not data:
|
if not data:
|
||||||
return pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs"])
|
return {}
|
||||||
|
return data[0]
|
||||||
df = pd.DataFrame(data)
|
|
||||||
df["timestamp"] = pd.to_datetime(df["created_at"], utc=True).dt.tz_localize(None)
|
|
||||||
for col in ("insulin", "carbs"):
|
|
||||||
if col not in df.columns:
|
|
||||||
df[col] = pd.NA
|
|
||||||
df[col] = pd.to_numeric(df[col], errors="coerce")
|
|
||||||
if "eventType" not in df.columns:
|
|
||||||
df["eventType"] = ""
|
|
||||||
df = df[df["timestamp"] >= since.replace(tzinfo=None)]
|
|
||||||
return (
|
|
||||||
df[["timestamp", "eventType", "insulin", "carbs"]]
|
|
||||||
.sort_values("timestamp")
|
|
||||||
.reset_index(drop=True)
|
|
||||||
)
|
|
||||||
|
|||||||
+252
@@ -0,0 +1,252 @@
|
|||||||
|
import pandas as pd
|
||||||
|
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,
|
||||||
|
classify_treatments,
|
||||||
|
summarize_time_in_range,
|
||||||
|
)
|
||||||
|
from nightscout_client import NightscoutConfigError, fetch_entries, fetch_treatments
|
||||||
|
from reporting import classify_bolus, effective_basal_series, target_glucose_series
|
||||||
|
from ui_common import (
|
||||||
|
MMOL_HOVERTEMPLATE,
|
||||||
|
add_basal_area_trace,
|
||||||
|
add_bolus_marker_traces,
|
||||||
|
add_target_line_trace,
|
||||||
|
get_colors,
|
||||||
|
load_profile,
|
||||||
|
)
|
||||||
|
|
||||||
|
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 _basal_and_target_series(profile: dict, treatments: pd.DataFrame, window_start, window_end):
|
||||||
|
"""Basaal- en streefwaarde-reeksen over een rollend venster dat meerdere
|
||||||
|
kalenderdagen kan overspannen: per dag berekend (reporting.effective_basal_series/
|
||||||
|
target_glucose_series zijn dag-begrensd) en daarna aan elkaar geplakt en
|
||||||
|
geclipt tot het venster."""
|
||||||
|
dates = pd.date_range(window_start.normalize(), window_end.normalize(), freq="D")
|
||||||
|
basal_parts, target_parts = [], []
|
||||||
|
for day_start in dates:
|
||||||
|
day_end = day_start + pd.Timedelta(1, unit="D")
|
||||||
|
basal_parts.append(effective_basal_series(profile, treatments, day_start, day_end))
|
||||||
|
target_parts.append(target_glucose_series(profile, day_start, day_end))
|
||||||
|
|
||||||
|
basal = pd.concat(basal_parts, ignore_index=True) if basal_parts else pd.DataFrame(columns=["timestamp", "rate"])
|
||||||
|
target = (
|
||||||
|
pd.concat(target_parts, ignore_index=True) if target_parts else pd.DataFrame(columns=["timestamp", "target"])
|
||||||
|
)
|
||||||
|
basal = basal[(basal["timestamp"] >= window_start) & (basal["timestamp"] <= window_end)]
|
||||||
|
target = target[(target["timestamp"] >= window_start) & (target["timestamp"] <= window_end)]
|
||||||
|
return basal.reset_index(drop=True), target.reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def build_chart(glucose, bolus, carbs, basal, target, 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 = make_subplots(specs=[[{"secondary_y": True}]])
|
||||||
|
|
||||||
|
# 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",
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
add_basal_area_trace(fig, basal, colors, row=1, secondary_y=True)
|
||||||
|
add_target_line_trace(fig, target, colors, row=1)
|
||||||
|
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
add_bolus_marker_traces(fig, bolus, colors, insulin_lane_y, row=1)
|
||||||
|
|
||||||
|
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>",
|
||||||
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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, row=1, col=1)
|
||||||
|
fig.add_annotation(
|
||||||
|
x=row["timestamp"],
|
||||||
|
y=y_top,
|
||||||
|
yanchor="bottom",
|
||||||
|
text="Pomp",
|
||||||
|
showarrow=False,
|
||||||
|
font={"color": colors["muted"], "size": 10},
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
for _, row in sensor_changes.iterrows():
|
||||||
|
fig.add_vline(x=row["timestamp"], line_dash="dash", line_color=colors["muted"], opacity=0.6, row=1, col=1)
|
||||||
|
fig.add_annotation(
|
||||||
|
x=row["timestamp"],
|
||||||
|
y=y_top,
|
||||||
|
yanchor="bottom",
|
||||||
|
text="Sensor",
|
||||||
|
showarrow=False,
|
||||||
|
font={"color": colors["muted"], "size": 10},
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
fig.update_yaxes(
|
||||||
|
title_text="mmol/L",
|
||||||
|
range=[y_bottom, y_top],
|
||||||
|
gridcolor=colors["grid"],
|
||||||
|
zeroline=False,
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
secondary_y=False,
|
||||||
|
)
|
||||||
|
fig.update_yaxes(title_text="Basaal (E/uur)", showgrid=False, row=1, col=1, secondary_y=True)
|
||||||
|
fig.update_xaxes(gridcolor=colors["grid"], row=1, col=1)
|
||||||
|
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)
|
||||||
|
profile = load_profile()
|
||||||
|
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)
|
||||||
|
bolus = classify_bolus(treatments)
|
||||||
|
tir = summarize_time_in_range(glucose)
|
||||||
|
basal, target = _basal_and_target_series(profile, treatments, glucose["timestamp"].min(), glucose["timestamp"].max())
|
||||||
|
|
||||||
|
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,
|
||||||
|
bolus,
|
||||||
|
events["carbs"],
|
||||||
|
basal,
|
||||||
|
target,
|
||||||
|
events["site_changes"],
|
||||||
|
events["sensor_changes"],
|
||||||
|
colors,
|
||||||
|
)
|
||||||
|
st.plotly_chart(fig, width="stretch")
|
||||||
|
st.caption(
|
||||||
|
"Stippen = bolusinsuline (voeding/correctie/SMB, grootte naar dosis) · cirkels = koolhydraten · "
|
||||||
|
"vlak = basaal · streepstippellijn = streefwaarde uit pompprofiel · "
|
||||||
|
"stippellijn = pompwissel · streepjeslijn = sensorwissel"
|
||||||
|
)
|
||||||
@@ -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"
|
||||||
|
)
|
||||||
@@ -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)"
|
||||||
|
)
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import pandas as pd
|
||||||
|
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, classify_treatments
|
||||||
|
from nightscout_client import NightscoutConfigError
|
||||||
|
from reporting import classify_bolus, effective_basal_series, target_glucose_series
|
||||||
|
from ui_common import (
|
||||||
|
add_basal_area_trace,
|
||||||
|
add_bolus_marker_traces,
|
||||||
|
add_carb_bars_trace,
|
||||||
|
add_target_line_trace,
|
||||||
|
add_threshold_lines,
|
||||||
|
get_colors,
|
||||||
|
load_profile,
|
||||||
|
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, met basaal/bolus/koolhydraten-overlay (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)
|
||||||
|
profile = load_profile()
|
||||||
|
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
|
||||||
|
|
||||||
|
carbs_events = classify_treatments(treatments)["carbs"].copy()
|
||||||
|
if not carbs_events.empty:
|
||||||
|
carbs_events["date"] = carbs_events["timestamp"].dt.date
|
||||||
|
carbs_events["hour"] = carbs_events["timestamp"].dt.hour + carbs_events["timestamp"].dt.minute / 60
|
||||||
|
|
||||||
|
bolus_events = classify_bolus(treatments)
|
||||||
|
if not bolus_events.empty:
|
||||||
|
bolus_events["date"] = bolus_events["timestamp"].dt.date
|
||||||
|
bolus_events["hour"] = bolus_events["timestamp"].dt.hour + bolus_events["timestamp"].dt.minute / 60
|
||||||
|
|
||||||
|
|
||||||
|
def _close_step_to_day_end(df: pd.DataFrame, value_col: str) -> pd.DataFrame:
|
||||||
|
"""Voeg een laatste punt op hour=24 toe (zelfde waarde als het laatste
|
||||||
|
segment) zodat een stapvlak/-lijn de volle dag doortekent i.p.v. te
|
||||||
|
stoppen bij het laatste breekpunt."""
|
||||||
|
if df.empty:
|
||||||
|
return df
|
||||||
|
last_value = df.iloc[-1][value_col]
|
||||||
|
closing_row = pd.DataFrame([{"hour": 24.0, value_col: last_value}])
|
||||||
|
return pd.concat([df, closing_row], ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
|
dates = sorted(glucose["date"].unique())
|
||||||
|
row_height = 190
|
||||||
|
fig = make_subplots(
|
||||||
|
rows=len(dates),
|
||||||
|
cols=1,
|
||||||
|
shared_xaxes=True,
|
||||||
|
vertical_spacing=min(0.4 / max(len(dates) - 1, 1), 0.05),
|
||||||
|
specs=[[{"secondary_y": True}]] * len(dates),
|
||||||
|
)
|
||||||
|
|
||||||
|
for i, day in enumerate(dates, start=1):
|
||||||
|
day_df = glucose[glucose["date"] == day]
|
||||||
|
day_start = pd.Timestamp(day)
|
||||||
|
day_end = day_start + pd.Timedelta(1, unit="D")
|
||||||
|
|
||||||
|
fig.add_hrect(
|
||||||
|
y0=TARGET_LOW, y1=TARGET_HIGH, fillcolor=colors["band"], line_width=0, layer="below", row=i, col=1
|
||||||
|
)
|
||||||
|
# Handmatige titel-annotatie t.o.v. het domein van déze rij i.p.v.
|
||||||
|
# make_subplots' subplot_titles (die t.o.v. de hele figuur positioneert en
|
||||||
|
# daardoor bij veel dagen de gedeelde legenda bovenaan kan overlappen).
|
||||||
|
fig.add_annotation(
|
||||||
|
text=day.strftime("%A %d-%m-%Y"),
|
||||||
|
xref="x domain",
|
||||||
|
yref="y domain",
|
||||||
|
x=0.0,
|
||||||
|
y=1.15,
|
||||||
|
xanchor="left",
|
||||||
|
yanchor="bottom",
|
||||||
|
showarrow=False,
|
||||||
|
font={"size": 13, "color": colors["text"]},
|
||||||
|
row=i,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
basal_day = effective_basal_series(profile, treatments, day_start, day_end)
|
||||||
|
if not basal_day.empty:
|
||||||
|
basal_day["hour"] = (basal_day["timestamp"] - day_start).dt.total_seconds() / 3600
|
||||||
|
basal_day = _close_step_to_day_end(basal_day, "rate")
|
||||||
|
add_basal_area_trace(fig, basal_day, colors, row=i, secondary_y=True, x_col="hour")
|
||||||
|
|
||||||
|
target_day = target_glucose_series(profile, day_start, day_end)
|
||||||
|
if not target_day.empty:
|
||||||
|
target_day["hour"] = (target_day["timestamp"] - day_start).dt.total_seconds() / 3600
|
||||||
|
target_day = _close_step_to_day_end(target_day, "target")
|
||||||
|
add_target_line_trace(fig, target_day, colors, row=i, x_col="hour")
|
||||||
|
|
||||||
|
add_carb_bars_trace(fig, carbs_events[carbs_events["date"] == day], colors, row=i, secondary_y=True, x_col="hour")
|
||||||
|
|
||||||
|
lane_y = day_df["mmol"].min() - 1.0 if not day_df.empty else TARGET_LOW - 1.0
|
||||||
|
add_bolus_marker_traces(fig, bolus_events[bolus_events["date"] == day], colors, lane_y, row=i, x_col="hour")
|
||||||
|
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=day_df["hour"],
|
||||||
|
y=day_df["mmol"],
|
||||||
|
mode="lines",
|
||||||
|
line={"color": colors["glucose"], "width": 2},
|
||||||
|
name="Glucose",
|
||||||
|
hovertemplate="%{y:.1f} mmol/L<extra></extra>",
|
||||||
|
),
|
||||||
|
row=i,
|
||||||
|
col=1,
|
||||||
|
secondary_y=False,
|
||||||
|
)
|
||||||
|
fig.update_yaxes(title_text="mmol/L", gridcolor=colors["grid"], row=i, col=1, secondary_y=False)
|
||||||
|
fig.update_yaxes(
|
||||||
|
title_text="Basaal (E/uur) · KH (g)", showgrid=False, row=i, col=1, secondary_y=True
|
||||||
|
)
|
||||||
|
add_threshold_lines(fig, colors, row=i)
|
||||||
|
|
||||||
|
# Elke dag herhaalt dezelfde spoornamen (Glucose/Basaal/Koolhydraten/...) — zonder
|
||||||
|
# deduplicatie zou de legenda 7x "Glucose" etc. tonen. Alleen de eerste keer per
|
||||||
|
# naam blijft in de legenda staan.
|
||||||
|
seen_names = set()
|
||||||
|
for trace in fig.data:
|
||||||
|
if trace.name in seen_names:
|
||||||
|
trace.showlegend = False
|
||||||
|
else:
|
||||||
|
seen_names.add(trace.name)
|
||||||
|
|
||||||
|
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) + 40,
|
||||||
|
showlegend=True,
|
||||||
|
legend={"orientation": "h", "yanchor": "bottom", "y": 1.0, "xanchor": "left", "x": 0},
|
||||||
|
margin={"l": 10, "r": 10, "t": 40, "b": 10},
|
||||||
|
)
|
||||||
|
st.plotly_chart(fig, width="stretch")
|
||||||
|
st.caption(
|
||||||
|
f"{len(dates)} dagen · {len(glucose)} metingen · stippen = bolusinsuline "
|
||||||
|
"(voeding/correctie/SMB, grootte naar dosis) · vlak = basaal · staafjes = koolhydraten · "
|
||||||
|
"streepstippellijn = streefwaarde uit pompprofiel"
|
||||||
|
)
|
||||||
@@ -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')}")
|
||||||
@@ -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')}")
|
||||||
@@ -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')}")
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
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_profile,
|
||||||
|
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)
|
||||||
|
profile = load_profile()
|
||||||
|
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, treatments=treatments, profile=profile)
|
||||||
|
|
||||||
|
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')}")
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import plotly.graph_objects as go
|
||||||
|
import requests
|
||||||
|
import streamlit as st
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from nightscout_client import NightscoutConfigError
|
||||||
|
from profile_data import segments_table, segments_to_hourly_bars, total_daily_basal
|
||||||
|
from ui_common import get_colors, load_profile
|
||||||
|
|
||||||
|
st.set_page_config(page_title="Glucose dashboard — Insulineprofiel", page_icon="📊", layout="wide")
|
||||||
|
require_auth()
|
||||||
|
|
||||||
|
st.title("Insulineprofiel")
|
||||||
|
st.caption("Het meest recent gebruikte pompprofiel: basaalschema, ISF, koolhydraatratio en DIA.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
profile = load_profile()
|
||||||
|
except NightscoutConfigError as exc:
|
||||||
|
st.error(str(exc))
|
||||||
|
st.stop()
|
||||||
|
except (requests.RequestException, ValueError) as exc:
|
||||||
|
st.error(f"Kon geen profiel ophalen van Nightscout: {exc}")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
|
if not profile:
|
||||||
|
st.info("Geen pompprofiel gevonden op deze Nightscout-instantie.")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
|
colors = get_colors()
|
||||||
|
|
||||||
|
col1, col2 = st.columns(2)
|
||||||
|
col1.metric("DIA (werkingsduur insuline)", f"{profile['dia']:.1f} uur")
|
||||||
|
col2.caption(f"Profielnaam: {profile['name'] or '—'}")
|
||||||
|
|
||||||
|
st.subheader("Basaalschema")
|
||||||
|
bars = segments_to_hourly_bars(profile["basal"])
|
||||||
|
fig = go.Figure(
|
||||||
|
go.Scatter(
|
||||||
|
x=[b["hour"] for b in bars],
|
||||||
|
y=[b["value"] for b in bars],
|
||||||
|
mode="lines",
|
||||||
|
line={"shape": "hv", "color": colors["basal"], "width": 2},
|
||||||
|
fill="tozeroy",
|
||||||
|
fillcolor=colors["basal"],
|
||||||
|
opacity=0.7,
|
||||||
|
name="Basaal",
|
||||||
|
hovertemplate="%{x:.0f}:00 · %{y:.2f} E/uur<extra></extra>",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
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},
|
||||||
|
xaxis={"title": "Uur van de dag", "range": [0, 24], "dtick": 2, "gridcolor": colors["grid"]},
|
||||||
|
yaxis={"title": "E/uur", "gridcolor": colors["grid"], "rangemode": "tozero"},
|
||||||
|
showlegend=False,
|
||||||
|
)
|
||||||
|
st.plotly_chart(fig, width="stretch")
|
||||||
|
|
||||||
|
basal_rows = segments_table(profile["basal"])
|
||||||
|
st.dataframe(
|
||||||
|
pd.DataFrame(basal_rows).rename(
|
||||||
|
columns={"start": "Van", "end": "Tot", "value": "Basaalsnelheid (E/uur)"}
|
||||||
|
),
|
||||||
|
width="stretch",
|
||||||
|
hide_index=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
col_isf, col_ratio = st.columns(2)
|
||||||
|
with col_isf:
|
||||||
|
st.subheader("Insulinegevoeligheid (ISF)")
|
||||||
|
isf_rows = segments_table(profile["sens"])
|
||||||
|
st.dataframe(
|
||||||
|
pd.DataFrame(isf_rows).rename(
|
||||||
|
columns={"start": "Van", "end": "Tot", "value": "ISF (mmol/L per E)"}
|
||||||
|
),
|
||||||
|
width="stretch",
|
||||||
|
hide_index=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
with col_ratio:
|
||||||
|
st.subheader("Koolhydraatratio")
|
||||||
|
ratio_rows = segments_table(profile["carbratio"])
|
||||||
|
st.dataframe(
|
||||||
|
pd.DataFrame(ratio_rows).rename(
|
||||||
|
columns={"start": "Van", "end": "Tot", "value": "Ratio (g koolhydraten per E)"}
|
||||||
|
),
|
||||||
|
width="stretch",
|
||||||
|
hide_index=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
st.caption(
|
||||||
|
f"Totale dagelijkse basaal: {total_daily_basal(profile['basal']):.1f} E "
|
||||||
|
"(volgens profielschema, exclusief tijdelijke aanpassingen)."
|
||||||
|
)
|
||||||
+553
@@ -0,0 +1,553 @@
|
|||||||
|
"""
|
||||||
|
PDF-rapportgeneratie voor geselecteerde rapportageonderdelen (FR10).
|
||||||
|
|
||||||
|
Gebruikt fpdf2 (puur Python, geen systeemdependencies) voor de PDF-opbouw en
|
||||||
|
matplotlib voor de statische grafieken 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).
|
||||||
|
|
||||||
|
Elke sectie is één (of, voor Dagoverzicht, meerdere) liggende A4-pagina('s)
|
||||||
|
met een vaste kop-/voettekst (device-info, paginanummering, genereerdatum,
|
||||||
|
Nightscout-link) via de GlucoseReportPDF-subklasse hieronder — geïnspireerd op
|
||||||
|
de LibreView/AGP-rapportopmaak (zie docs/design-reporting.md).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
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 profile_data import segments_table, segments_to_hourly_bars, total_daily_basal
|
||||||
|
from reporting import (
|
||||||
|
BOLUS_CATEGORY_CORRECTION,
|
||||||
|
BOLUS_CATEGORY_FOOD,
|
||||||
|
BOLUS_CATEGORY_SMB,
|
||||||
|
HIGH,
|
||||||
|
LOW,
|
||||||
|
VERY_HIGH,
|
||||||
|
VERY_LOW,
|
||||||
|
agp_percentile_bands,
|
||||||
|
classify_bolus,
|
||||||
|
completeness_warning,
|
||||||
|
daily_stats,
|
||||||
|
detect_events,
|
||||||
|
effective_basal_series,
|
||||||
|
glucose_min_max,
|
||||||
|
gmi_mmol_per_mol,
|
||||||
|
gmi_percent,
|
||||||
|
percent_cv,
|
||||||
|
sensor_active_percent,
|
||||||
|
target_glucose_series,
|
||||||
|
tir_breakdown_5band,
|
||||||
|
)
|
||||||
|
|
||||||
|
SECTION_SUMMARY = "Samenvatting"
|
||||||
|
SECTION_AGP = "AGP profiel"
|
||||||
|
SECTION_INSULIN_PROFILE = "Insulineprofiel"
|
||||||
|
SECTION_DAGOVERZICHT = "Dagoverzicht"
|
||||||
|
SECTION_EVENTS = "Hypo-/hyperevents"
|
||||||
|
|
||||||
|
AVAILABLE_SECTIONS = [
|
||||||
|
SECTION_SUMMARY,
|
||||||
|
SECTION_AGP,
|
||||||
|
SECTION_INSULIN_PROFILE,
|
||||||
|
SECTION_DAGOVERZICHT,
|
||||||
|
SECTION_EVENTS,
|
||||||
|
]
|
||||||
|
|
||||||
|
REPORT_VERSION = "1.0"
|
||||||
|
_ICON_PATH = Path(__file__).parent / "assets" / "icon.svg"
|
||||||
|
|
||||||
|
_LINE_KWARGS = {"new_x": XPos.LMARGIN, "new_y": YPos.NEXT}
|
||||||
|
_SAME_LINE_KWARGS = {"new_x": XPos.RIGHT, "new_y": YPos.TOP}
|
||||||
|
|
||||||
|
# Zelfde kleuren als het PALETTE["light"] in ui_common.py — bewust hier
|
||||||
|
# gedupliceerd 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]
|
||||||
|
_BASAL_COLOR = "#7b5ea3"
|
||||||
|
_CARBS_COLOR = "#eb6834"
|
||||||
|
_TARGET_COLOR = "#52514e"
|
||||||
|
_BOLUS_CATEGORY_STYLE = {
|
||||||
|
BOLUS_CATEGORY_FOOD: ("#1baf7a", "Bolus (voeding)"),
|
||||||
|
BOLUS_CATEGORY_CORRECTION: ("#2a78d6", "Bolus (correctie)"),
|
||||||
|
BOLUS_CATEGORY_SMB: ("#898781", "SMB"),
|
||||||
|
}
|
||||||
|
_EMPTY_TREATMENT_COLUMNS = ["timestamp", "eventType", "insulin", "carbs", "type", "absolute", "duration"]
|
||||||
|
DAGOVERZICHT_MAX_DAYS = 14
|
||||||
|
_HOUR_OF_DAY_LABEL = "Uur van de dag"
|
||||||
|
|
||||||
|
|
||||||
|
def _report_config() -> dict:
|
||||||
|
"""Rapportmetadata uit environment variables (insuline/pomp/sensor-type,
|
||||||
|
Nightscout-URL) — zelfde os.environ-patroon als nightscout_client.py.
|
||||||
|
Alles heeft een fallback zodat een rapport ook zonder configuratie werkt."""
|
||||||
|
return {
|
||||||
|
"insulin_type": os.environ.get("REPORT_INSULIN_TYPE", "").strip() or "Onbekend insulinetype",
|
||||||
|
"pump_type": os.environ.get("REPORT_PUMP_TYPE", "").strip() or "Onbekende pomp",
|
||||||
|
"sensor_type": os.environ.get("REPORT_SENSOR_TYPE", "").strip() or "Onbekende sensor",
|
||||||
|
"nightscout_url": os.environ.get("NIGHTSCOUT_URL", "").strip().rstrip("/"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class GlucoseReportPDF(FPDF):
|
||||||
|
"""FPDF-subklasse met een vaste kop-/voettekst op elke pagina en één sectie
|
||||||
|
per liggende pagina (zie begin_report_section())."""
|
||||||
|
|
||||||
|
def __init__(self, config: dict, generated_at: datetime) -> None:
|
||||||
|
super().__init__(orientation="L", unit="mm", format="A4")
|
||||||
|
self._config = config
|
||||||
|
self._generated_at = generated_at
|
||||||
|
self.section_title = ""
|
||||||
|
self.set_auto_page_break(auto=True, margin=18)
|
||||||
|
self.alias_nb_pages()
|
||||||
|
|
||||||
|
def begin_report_section(self, title: str) -> None:
|
||||||
|
"""Begin een nieuwe pagina voor sectie `title`. Voor secties die over
|
||||||
|
meerdere pagina's lopen (Dagoverzicht: één pagina per dag) wordt dit
|
||||||
|
per pagina aangeroepen zodat de kop op elke pagina klopt."""
|
||||||
|
self.section_title = title
|
||||||
|
self.add_page()
|
||||||
|
|
||||||
|
def header(self) -> None:
|
||||||
|
if _ICON_PATH.exists():
|
||||||
|
self.image(str(_ICON_PATH), x=10, y=8, w=8)
|
||||||
|
self.set_xy(20, 8)
|
||||||
|
self.set_font("Helvetica", "B", 14)
|
||||||
|
self.cell(0, 6, self.section_title, **_LINE_KWARGS)
|
||||||
|
self.set_x(20)
|
||||||
|
self.set_font("Helvetica", "", 8)
|
||||||
|
self.set_text_color(120, 120, 120)
|
||||||
|
device_line = (
|
||||||
|
f"Glucoserapport v{REPORT_VERSION} · Insuline: {self._config['insulin_type']} · "
|
||||||
|
f"Pomp: {self._config['pump_type']} · Sensor: {self._config['sensor_type']}"
|
||||||
|
)
|
||||||
|
self.cell(0, 4, device_line, **_LINE_KWARGS)
|
||||||
|
self.set_text_color(0, 0, 0)
|
||||||
|
self.ln(3)
|
||||||
|
self.set_draw_color(200, 200, 200)
|
||||||
|
self.line(10, self.get_y(), self.w - 10, self.get_y())
|
||||||
|
self.ln(4)
|
||||||
|
|
||||||
|
def footer(self) -> None:
|
||||||
|
self.set_y(-14)
|
||||||
|
self.set_font("Helvetica", "I", 8)
|
||||||
|
self.set_text_color(120, 120, 120)
|
||||||
|
left = f"Gegenereerd: {self._generated_at.strftime('%d-%m-%Y %H:%M')}"
|
||||||
|
if self._config["nightscout_url"]:
|
||||||
|
left += f" · {self._config['nightscout_url']}"
|
||||||
|
self.cell(200, 8, left, **_SAME_LINE_KWARGS)
|
||||||
|
self.cell(0, 8, f"Pagina {self.page_no()}/{{nb}}", align="R")
|
||||||
|
self.set_text_color(0, 0, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def _fig_to_png(fig) -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
fig.savefig(buf, format="png", dpi=150)
|
||||||
|
plt.close(fig)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
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."""
|
||||||
|
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=(11, 4.2))
|
||||||
|
hours = bands["minute_of_day"] / 60
|
||||||
|
ax.axhspan(LOW, HIGH, color="#0ca30c", alpha=0.08, label="Doelbereik")
|
||||||
|
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.5, label="Mediaan")
|
||||||
|
_add_threshold_lines(ax)
|
||||||
|
ax.set_xlabel(_HOUR_OF_DAY_LABEL)
|
||||||
|
ax.set_ylabel("mmol/L")
|
||||||
|
ax.set_xlim(0, 24)
|
||||||
|
ax.set_xticks(range(0, 25, 3))
|
||||||
|
ax.legend(loc="upper right", fontsize=9, ncol=4, frameon=False)
|
||||||
|
fig.tight_layout()
|
||||||
|
return _fig_to_png(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def _tir_bar_figure_png(tir: dict) -> bytes:
|
||||||
|
"""Gestapelde staafgrafiek van de 5 TIR-banden."""
|
||||||
|
fig, ax = plt.subplots(figsize=(9, 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 _insulin_profile_figure_png(profile: dict) -> bytes:
|
||||||
|
bars = segments_to_hourly_bars(profile.get("basal", []))
|
||||||
|
fig, ax = plt.subplots(figsize=(11, 3.2))
|
||||||
|
if bars:
|
||||||
|
hours = [b["hour"] for b in bars]
|
||||||
|
values = [b["value"] for b in bars]
|
||||||
|
ax.step(hours, values, where="post", color=_BASAL_COLOR, linewidth=1.5)
|
||||||
|
ax.fill_between(hours, values, step="post", color=_BASAL_COLOR, alpha=0.3)
|
||||||
|
ax.set_xlim(0, 24)
|
||||||
|
ax.set_xticks(range(0, 25, 2))
|
||||||
|
ax.set_ylim(bottom=0)
|
||||||
|
ax.set_xlabel(_HOUR_OF_DAY_LABEL)
|
||||||
|
ax.set_ylabel("E/uur")
|
||||||
|
fig.tight_layout()
|
||||||
|
return _fig_to_png(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_basal_overlay(ax2, basal: pd.DataFrame, day_start) -> None:
|
||||||
|
if basal.empty:
|
||||||
|
return
|
||||||
|
hours = (basal["timestamp"] - day_start).dt.total_seconds() / 3600
|
||||||
|
hours = pd.concat([hours, pd.Series([24.0])], ignore_index=True)
|
||||||
|
values = pd.concat([basal["rate"], basal["rate"].iloc[-1:]], ignore_index=True)
|
||||||
|
ax2.fill_between(hours, values, step="post", color=_BASAL_COLOR, alpha=0.3, label="Basaal")
|
||||||
|
ax2.step(hours, values, where="post", color=_BASAL_COLOR, linewidth=1, alpha=0.8)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_carbs_overlay(ax2, day_treatments: pd.DataFrame, day_start) -> None:
|
||||||
|
if day_treatments.empty:
|
||||||
|
return
|
||||||
|
carbs = day_treatments[day_treatments["carbs"].fillna(0) > 0]
|
||||||
|
if carbs.empty:
|
||||||
|
return
|
||||||
|
hours = (carbs["timestamp"] - day_start).dt.total_seconds() / 3600
|
||||||
|
ax2.bar(hours, carbs["carbs"], width=0.25, color=_CARBS_COLOR, alpha=0.55, label="Koolhydraten")
|
||||||
|
|
||||||
|
|
||||||
|
def _add_bolus_overlay(ax, day_treatments: pd.DataFrame, day_start, lane_y: float) -> None:
|
||||||
|
bolus = classify_bolus(day_treatments)
|
||||||
|
for category in (BOLUS_CATEGORY_SMB, BOLUS_CATEGORY_CORRECTION, BOLUS_CATEGORY_FOOD):
|
||||||
|
subset = bolus[bolus["category"] == category] if not bolus.empty else bolus
|
||||||
|
if subset.empty:
|
||||||
|
continue
|
||||||
|
color, label = _BOLUS_CATEGORY_STYLE[category]
|
||||||
|
hours = (subset["timestamp"] - day_start).dt.total_seconds() / 3600
|
||||||
|
sizes = (subset["insulin"] * 25).clip(lower=15, upper=200)
|
||||||
|
ax.scatter(hours, [lane_y] * len(subset), s=sizes, color=color, alpha=0.75, label=label, zorder=5)
|
||||||
|
if category != BOLUS_CATEGORY_SMB:
|
||||||
|
for x, units in zip(hours, subset["insulin"], strict=True):
|
||||||
|
ax.annotate(
|
||||||
|
f"{units:.1f}E", (x, lane_y), textcoords="offset points", xytext=(0, 8), fontsize=6, ha="center"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_target_overlay(ax, profile: dict | None, day_start, day_end) -> None:
|
||||||
|
target = target_glucose_series(profile, day_start, day_end)
|
||||||
|
if target.empty:
|
||||||
|
return
|
||||||
|
hours = (target["timestamp"] - day_start).dt.total_seconds() / 3600
|
||||||
|
hours = pd.concat([hours, pd.Series([24.0])], ignore_index=True)
|
||||||
|
values = pd.concat([target["target"], target["target"].iloc[-1:]], ignore_index=True)
|
||||||
|
ax.step(hours, values, where="post", color=_TARGET_COLOR, linewidth=1.2, linestyle="-.", label="Streefwaarde (pomp)")
|
||||||
|
|
||||||
|
|
||||||
|
def _daily_figure_png(
|
||||||
|
day_df: pd.DataFrame, day_treatments: pd.DataFrame, profile: dict | None, day_label: str, day_start, day_end
|
||||||
|
) -> bytes:
|
||||||
|
"""Eén dag als grafiek: glucoselijn + basaal/bolus/koolhydraten/streefwaarde-overlay."""
|
||||||
|
hours = day_df["timestamp"].dt.hour + day_df["timestamp"].dt.minute / 60
|
||||||
|
fig, ax = plt.subplots(figsize=(11, 3.8))
|
||||||
|
ax2 = ax.twinx()
|
||||||
|
|
||||||
|
basal = effective_basal_series(profile, day_treatments, day_start, day_end)
|
||||||
|
_add_basal_overlay(ax2, basal, day_start)
|
||||||
|
_add_carbs_overlay(ax2, day_treatments, day_start)
|
||||||
|
|
||||||
|
lane_y = (day_df["mmol"].min() - 1.0) if not day_df.empty else LOW - 1.0
|
||||||
|
_add_bolus_overlay(ax, day_treatments, day_start, lane_y)
|
||||||
|
_add_target_overlay(ax, profile, day_start, day_end)
|
||||||
|
|
||||||
|
ax.plot(hours, day_df["mmol"], color="#2a78d6", linewidth=1.4, label="Glucose", zorder=6)
|
||||||
|
_add_threshold_lines(ax)
|
||||||
|
ax.set_xlim(0, 24)
|
||||||
|
ax.set_xticks(range(0, 25, 2))
|
||||||
|
ax.set_ylabel("mmol/L", fontsize=9)
|
||||||
|
ax2.set_ylabel("Basaal (E/uur) · KH (g)", fontsize=9)
|
||||||
|
ax.set_title(day_label, fontsize=11, loc="left")
|
||||||
|
ax.tick_params(labelsize=8)
|
||||||
|
ax2.tick_params(labelsize=8)
|
||||||
|
|
||||||
|
lines1, labels1 = ax.get_legend_handles_labels()
|
||||||
|
lines2, labels2 = ax2.get_legend_handles_labels()
|
||||||
|
ax.legend(
|
||||||
|
lines1 + lines2, labels1 + labels2, loc="upper center", bbox_to_anchor=(0.5, -0.2), ncol=6, fontsize=7, frameon=False
|
||||||
|
)
|
||||||
|
fig.tight_layout()
|
||||||
|
return _fig_to_png(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def _event_hour_histogram_png(events: pd.DataFrame, color: str) -> bytes:
|
||||||
|
"""Aantal events per uur-van-de-dag."""
|
||||||
|
hour_counts = events["start"].dt.hour.value_counts().reindex(range(24), fill_value=0).sort_index()
|
||||||
|
fig, ax = plt.subplots(figsize=(11, 2.6))
|
||||||
|
ax.bar(hour_counts.index, hour_counts.to_numpy(), color=color)
|
||||||
|
ax.set_xlabel(_HOUR_OF_DAY_LABEL)
|
||||||
|
ax.set_ylabel("Aantal events")
|
||||||
|
ax.set_xlim(-0.5, 23.5)
|
||||||
|
ax.set_xticks(range(0, 24, 2))
|
||||||
|
fig.tight_layout()
|
||||||
|
return _fig_to_png(fig)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_summary_section(pdf: GlucoseReportPDF, glucose: pd.DataFrame, start, end) -> None:
|
||||||
|
pdf.begin_report_section(SECTION_SUMMARY)
|
||||||
|
mean_mmol = glucose["mmol"].mean()
|
||||||
|
min_mmol, max_mmol = glucose_min_max(glucose)
|
||||||
|
tir = tir_breakdown_5band(glucose)
|
||||||
|
active_pct = sensor_active_percent(glucose, start, end)
|
||||||
|
|
||||||
|
pdf.set_font("Helvetica", "", 11)
|
||||||
|
pdf.cell(0, 6, f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}", **_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 (min {min_mmol:.1f} · max {max_mmol:.1f})",
|
||||||
|
**_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=220)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_agp_section(pdf: GlucoseReportPDF, glucose: pd.DataFrame) -> None:
|
||||||
|
pdf.begin_report_section(SECTION_AGP)
|
||||||
|
png_bytes = _agp_figure_png(glucose)
|
||||||
|
pdf.image(io.BytesIO(png_bytes), w=270)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_insulin_profile_section(pdf: GlucoseReportPDF, profile: dict | None) -> None:
|
||||||
|
pdf.begin_report_section(SECTION_INSULIN_PROFILE)
|
||||||
|
if not profile:
|
||||||
|
pdf.set_font("Helvetica", "", 11)
|
||||||
|
pdf.cell(0, 6, "Geen pompprofiel gevonden op deze Nightscout-instantie.", **_LINE_KWARGS)
|
||||||
|
return
|
||||||
|
|
||||||
|
pdf.set_font("Helvetica", "", 11)
|
||||||
|
pdf.cell(0, 6, f"Profielnaam: {profile.get('name') or '-'}", **_LINE_KWARGS)
|
||||||
|
pdf.cell(0, 6, f"DIA (werkingsduur insuline): {profile['dia']:.1f} uur", **_LINE_KWARGS)
|
||||||
|
pdf.cell(0, 6, f"Totale dagelijkse basaal: {total_daily_basal(profile['basal']):.1f} E", **_LINE_KWARGS)
|
||||||
|
pdf.ln(2)
|
||||||
|
|
||||||
|
png_bytes = _insulin_profile_figure_png(profile)
|
||||||
|
pdf.image(io.BytesIO(png_bytes), w=270)
|
||||||
|
pdf.ln(4)
|
||||||
|
|
||||||
|
pdf.set_font("Helvetica", "B", 11)
|
||||||
|
pdf.cell(90, 6, "Insulinegevoeligheid (ISF)", **_SAME_LINE_KWARGS)
|
||||||
|
pdf.cell(0, 6, "Koolhydraatratio", **_LINE_KWARGS)
|
||||||
|
pdf.set_font("Helvetica", "", 10)
|
||||||
|
isf_rows = segments_table(profile["sens"])
|
||||||
|
ratio_rows = segments_table(profile["carbratio"])
|
||||||
|
for i in range(max(len(isf_rows), len(ratio_rows))):
|
||||||
|
isf_text = (
|
||||||
|
f"{isf_rows[i]['start']}-{isf_rows[i]['end']}: {isf_rows[i]['value']:.1f} mmol/L per E"
|
||||||
|
if i < len(isf_rows)
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
ratio_text = (
|
||||||
|
f"{ratio_rows[i]['start']}-{ratio_rows[i]['end']}: {ratio_rows[i]['value']:.0f} g per E"
|
||||||
|
if i < len(ratio_rows)
|
||||||
|
else ""
|
||||||
|
)
|
||||||
|
pdf.cell(90, 5, isf_text, **_SAME_LINE_KWARGS)
|
||||||
|
pdf.cell(0, 5, ratio_text, **_LINE_KWARGS)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_daily_stats_lines(pdf: GlucoseReportPDF, stats: dict) -> None:
|
||||||
|
pdf.set_font("Helvetica", "", 10)
|
||||||
|
pdf.cell(
|
||||||
|
0,
|
||||||
|
6,
|
||||||
|
f"Glucose: gem. {stats['mean_mmol']:.1f} · min {stats['min_mmol']:.1f} · "
|
||||||
|
f"max {stats['max_mmol']:.1f} mmol/L",
|
||||||
|
**_LINE_KWARGS,
|
||||||
|
)
|
||||||
|
pdf.cell(
|
||||||
|
0,
|
||||||
|
6,
|
||||||
|
f"Insuline: totaal {stats['total_insulin']:.1f} E · basaal {stats['basal_insulin']:.1f} E · "
|
||||||
|
f"bolus {stats['bolus_insulin']:.1f} E · SMB {stats['smb_insulin']:.1f} E",
|
||||||
|
**_LINE_KWARGS,
|
||||||
|
)
|
||||||
|
pdf.cell(
|
||||||
|
0,
|
||||||
|
6,
|
||||||
|
f"Hypo's: {stats['hypo_count']} ({stats['hypo_duration_minutes']:.0f} min) · "
|
||||||
|
f"Hyper's: {stats['hyper_count']} ({stats['hyper_duration_minutes']:.0f} min)",
|
||||||
|
**_LINE_KWARGS,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_dagoverzicht_section(
|
||||||
|
pdf: GlucoseReportPDF, glucose: pd.DataFrame, treatments: pd.DataFrame, profile: dict | None
|
||||||
|
) -> None:
|
||||||
|
"""Eén liggende pagina per kalenderdag, max. de meest recente
|
||||||
|
DAGOVERZICHT_MAX_DAYS dagen — voor langere periodes zou de PDF anders
|
||||||
|
onwerkbaar lang worden."""
|
||||||
|
df = glucose.copy()
|
||||||
|
df["date"] = df["timestamp"].dt.date
|
||||||
|
dates = sorted(df["date"].unique())
|
||||||
|
show_limited_note = len(dates) > DAGOVERZICHT_MAX_DAYS
|
||||||
|
if show_limited_note:
|
||||||
|
dates = dates[-DAGOVERZICHT_MAX_DAYS:]
|
||||||
|
|
||||||
|
for day in dates:
|
||||||
|
pdf.begin_report_section(SECTION_DAGOVERZICHT)
|
||||||
|
if show_limited_note:
|
||||||
|
pdf.set_font("Helvetica", "I", 9)
|
||||||
|
pdf.cell(0, 5, f"Beperkt tot de meest recente {DAGOVERZICHT_MAX_DAYS} dagen.", **_LINE_KWARGS)
|
||||||
|
show_limited_note = False # alleen op de eerste paginas van deze sectie
|
||||||
|
|
||||||
|
day_start = pd.Timestamp(day)
|
||||||
|
day_end = day_start + pd.Timedelta(1, unit="D")
|
||||||
|
day_df = df[df["date"] == day]
|
||||||
|
day_treatments = (
|
||||||
|
treatments[(treatments["timestamp"] >= day_start) & (treatments["timestamp"] < day_end)]
|
||||||
|
if not treatments.empty
|
||||||
|
else treatments
|
||||||
|
)
|
||||||
|
|
||||||
|
png_bytes = _daily_figure_png(day_df, day_treatments, profile, day.strftime("%A %d-%m-%Y"), day_start, day_end)
|
||||||
|
pdf.image(io.BytesIO(png_bytes), w=270)
|
||||||
|
pdf.ln(2)
|
||||||
|
|
||||||
|
stats = daily_stats(day_df, day_treatments, profile, day_start, day_end)
|
||||||
|
_add_daily_stats_lines(pdf, stats)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_events_section(pdf: GlucoseReportPDF, glucose: pd.DataFrame, events_summary: dict[str, dict]) -> None:
|
||||||
|
pdf.begin_report_section(SECTION_EVENTS)
|
||||||
|
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 — 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=260)
|
||||||
|
pdf.ln(2)
|
||||||
|
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=260)
|
||||||
|
|
||||||
|
|
||||||
|
def build_report_pdf(
|
||||||
|
sections: list[str],
|
||||||
|
glucose: pd.DataFrame,
|
||||||
|
events_summary: dict[str, dict],
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
treatments: pd.DataFrame | None = None,
|
||||||
|
profile: dict | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
"""Bouw een PDF met de geselecteerde onderdelen: één liggende voorpagina,
|
||||||
|
daarna één (of voor Dagoverzicht: meerdere) liggende pagina('s) per sectie.
|
||||||
|
|
||||||
|
`events_summary` bevat vooraf berekende hypo/hyper-samenvattingen (label ->
|
||||||
|
resultaat van reporting.summarize_events), zodat deze module geen
|
||||||
|
event-detectie hoeft te herhalen. `treatments`/`profile` zijn optioneel
|
||||||
|
(leeg/None) zodat oudere aanroepen zonder insulinedata blijven werken.
|
||||||
|
"""
|
||||||
|
if treatments is None:
|
||||||
|
treatments = pd.DataFrame(columns=_EMPTY_TREATMENT_COLUMNS)
|
||||||
|
|
||||||
|
config = _report_config()
|
||||||
|
pdf = GlucoseReportPDF(config, datetime.now(timezone.utc))
|
||||||
|
|
||||||
|
pdf.begin_report_section("Glucoserapport")
|
||||||
|
pdf.set_font("Helvetica", "B", 22)
|
||||||
|
pdf.cell(0, 14, "Glucoserapport", **_LINE_KWARGS)
|
||||||
|
pdf.set_font("Helvetica", "", 13)
|
||||||
|
pdf.cell(0, 8, f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}", **_LINE_KWARGS)
|
||||||
|
if sections:
|
||||||
|
pdf.cell(0, 8, f"Onderdelen: {', '.join(sections)}", **_LINE_KWARGS)
|
||||||
|
|
||||||
|
if SECTION_INSULIN_PROFILE in sections:
|
||||||
|
_add_insulin_profile_section(pdf, profile)
|
||||||
|
|
||||||
|
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, treatments, profile)
|
||||||
|
|
||||||
|
if SECTION_EVENTS in sections and events_summary:
|
||||||
|
_add_events_section(pdf, glucose, events_summary)
|
||||||
|
|
||||||
|
return bytes(pdf.output())
|
||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
"""
|
||||||
|
Parsing van het Nightscout-pompprofiel (/api/v1/profile): basaalschema,
|
||||||
|
insulinegevoeligheid (ISF), koolhydraatratio, DIA en streefwaarden.
|
||||||
|
|
||||||
|
Framework-vrije module (geen streamlit-import), zelfde opzet als reporting.py:
|
||||||
|
puur functies op dicts, zodat dit los van de UI te unit-testen is. Zie
|
||||||
|
nightscout_client.fetch_profile() voor de ruwe fetch; deze module normaliseert
|
||||||
|
alleen (uren -> minuten sinds middernacht, mg/dl -> mmol/L waar nodig).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from nightscout_client import mgdl_to_mmol
|
||||||
|
|
||||||
|
SEGMENT_FIELDS = ("basal", "sens", "carbratio", "target_low", "target_high")
|
||||||
|
|
||||||
|
|
||||||
|
def _time_to_minutes(time_str: str) -> int:
|
||||||
|
"""Zet 'HH:MM' (Nightscout's segmenttijd-notatie) om naar minuten sinds middernacht."""
|
||||||
|
hours, minutes = time_str.split(":")
|
||||||
|
return int(hours) * 60 + int(minutes)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_segments(raw_segments: list[dict], *, to_mmol: bool = False) -> list[dict]:
|
||||||
|
"""Zet Nightscout-segmenten ([{'time': 'HH:MM', 'value': ...}, ...]) om naar
|
||||||
|
[{'minutes': int, 'value': float}, ...], oplopend gesorteerd op tijd."""
|
||||||
|
segments = []
|
||||||
|
for seg in raw_segments:
|
||||||
|
value = float(seg["value"])
|
||||||
|
if to_mmol:
|
||||||
|
value = mgdl_to_mmol(value)
|
||||||
|
segments.append({"minutes": _time_to_minutes(seg["time"]), "value": value})
|
||||||
|
return sorted(segments, key=lambda s: s["minutes"])
|
||||||
|
|
||||||
|
|
||||||
|
def parse_profile(raw: dict) -> dict:
|
||||||
|
"""Parse één Nightscout-profieldocument (zoals teruggegeven door
|
||||||
|
nightscout_client.fetch_profile()) naar een genormaliseerde dict:
|
||||||
|
|
||||||
|
{
|
||||||
|
"name": str,
|
||||||
|
"units": "mmol", # altijd genormaliseerd, ongeacht bronformaat
|
||||||
|
"dia": float, # uur
|
||||||
|
"basal": [{"minutes": int, "value": float}, ...], # E/uur
|
||||||
|
"sens": [{"minutes": int, "value": float}, ...], # mmol/L per E (ISF)
|
||||||
|
"carbratio": [{"minutes": int, "value": float}, ...], # g koolhydraten per E
|
||||||
|
"target_low": [{"minutes": int, "value": float}, ...], # mmol/L
|
||||||
|
"target_high": [{"minutes": int, "value": float}, ...], # mmol/L
|
||||||
|
}
|
||||||
|
|
||||||
|
Geeft {} terug als er geen (bruikbaar) profiel is.
|
||||||
|
"""
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
default_name = raw.get("defaultProfile")
|
||||||
|
store = raw.get("store", {})
|
||||||
|
profile = store.get(default_name) if default_name else None
|
||||||
|
if profile is None and store:
|
||||||
|
# defaultProfile ontbreekt of matcht niet met een sleutel in store:
|
||||||
|
# val terug op het enige/eerste beschikbare profiel.
|
||||||
|
profile = next(iter(store.values()))
|
||||||
|
if profile is None:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
units = str(profile.get("units", "mg/dl")).strip().lower()
|
||||||
|
to_mmol = units != "mmol"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"name": default_name or "",
|
||||||
|
"units": "mmol",
|
||||||
|
"dia": float(profile.get("dia", 0) or 0),
|
||||||
|
"basal": _parse_segments(profile.get("basal", [])),
|
||||||
|
"sens": _parse_segments(profile.get("sens", []), to_mmol=to_mmol),
|
||||||
|
"carbratio": _parse_segments(profile.get("carbratio", [])),
|
||||||
|
"target_low": _parse_segments(profile.get("target_low", []), to_mmol=to_mmol),
|
||||||
|
"target_high": _parse_segments(profile.get("target_high", []), to_mmol=to_mmol),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def value_at(segments: list[dict], minutes: int) -> float | None:
|
||||||
|
"""Geef de waarde terug die actief is op het gegeven tijdstip (minuten
|
||||||
|
sinds middernacht) — het laatste segment met `minutes <= t`. Ligt `t` vóór
|
||||||
|
het eerste segment van de dag, dan geldt het laatste segment (dat loopt
|
||||||
|
door vanaf de vorige dag, want een profiel dekt altijd de volle 24 uur).
|
||||||
|
|
||||||
|
Geeft None terug als `segments` leeg is.
|
||||||
|
"""
|
||||||
|
if not segments:
|
||||||
|
return None
|
||||||
|
active = None
|
||||||
|
for seg in segments:
|
||||||
|
if seg["minutes"] <= minutes:
|
||||||
|
active = seg
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
if active is None:
|
||||||
|
active = segments[-1]
|
||||||
|
return active["value"]
|
||||||
|
|
||||||
|
|
||||||
|
def _format_time(minutes: int) -> str:
|
||||||
|
"""Zet minuten sinds middernacht om naar 'HH:MM'."""
|
||||||
|
return f"{minutes // 60:02d}:{minutes % 60:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def segments_table(segments: list[dict]) -> list[dict]:
|
||||||
|
"""Zet segmenten om naar rijen met een start- en eindtijd voor tabelweergave:
|
||||||
|
[{'start': 'HH:MM', 'end': 'HH:MM', 'value': float}, ...]. Het laatste
|
||||||
|
segment loopt door tot 24:00 (een profiel dekt altijd de volle dag)."""
|
||||||
|
rows = []
|
||||||
|
for i, seg in enumerate(segments):
|
||||||
|
end_minutes = segments[i + 1]["minutes"] if i + 1 < len(segments) else 24 * 60
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"start": _format_time(seg["minutes"]),
|
||||||
|
"end": "24:00" if end_minutes == 24 * 60 else _format_time(end_minutes),
|
||||||
|
"value": seg["value"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def total_daily_basal(segments: list[dict]) -> float:
|
||||||
|
"""Totale basaaldosis per dag in E: som van elk segment se duur (uur) x snelheid (E/uur)."""
|
||||||
|
if not segments:
|
||||||
|
return 0.0
|
||||||
|
total = 0.0
|
||||||
|
for i, seg in enumerate(segments):
|
||||||
|
end_minutes = segments[i + 1]["minutes"] if i + 1 < len(segments) else 24 * 60
|
||||||
|
total += seg["value"] * (end_minutes - seg["minutes"]) / 60
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
def segments_to_hourly_bars(segments: list[dict]) -> list[dict]:
|
||||||
|
"""Zet segmenten om naar een lijst geschikt voor een staafgrafiek per uur van
|
||||||
|
de dag: [{'hour': float, 'value': float}, ...], met een extra punt op uur 24
|
||||||
|
(gelijk aan het eerste segment) zodat een staaf/stap-grafiek de volle dag dekt.
|
||||||
|
|
||||||
|
Gebruikt door de basaalgrafiek op de Insulineprofiel-pagina.
|
||||||
|
"""
|
||||||
|
if not segments:
|
||||||
|
return []
|
||||||
|
bars = [{"hour": seg["minutes"] / 60, "value": seg["value"]} for seg in segments]
|
||||||
|
bars.append({"hour": 24.0, "value": segments[0]["value"]})
|
||||||
|
return bars
|
||||||
@@ -1,2 +1,15 @@
|
|||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
pythonpath = ["."]
|
pythonpath = ["."]
|
||||||
|
|
||||||
|
[tool.coverage.run]
|
||||||
|
# app.py en pages/*.py zijn dunne Streamlit-UI-scripts (net als de
|
||||||
|
# functies in ui_common.py/auth.py die zelf al met "# pragma: no cover"
|
||||||
|
# gemarkeerd zijn) — niet zinvol te unit-testen zonder een draaiende
|
||||||
|
# Streamlit-sessie, en buiten scope van de coverage-eis. De logica die ze
|
||||||
|
# aanroepen (reporting.py, nightscout_client.py, data_processing.py,
|
||||||
|
# pdf_export.py, profile_data.py, ui_common.py) wordt wél volledig gemeten.
|
||||||
|
omit = ["app.py", "pages/*", "tests/*", ".venv/*"]
|
||||||
|
|
||||||
|
[tool.coverage.report]
|
||||||
|
fail_under = 80
|
||||||
|
show_missing = true
|
||||||
|
|||||||
+755
@@ -0,0 +1,755 @@
|
|||||||
|
"""
|
||||||
|
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
|
||||||
|
from profile_data import value_at
|
||||||
|
|
||||||
|
# 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
BOLUS_CATEGORY_FOOD = "food"
|
||||||
|
BOLUS_CATEGORY_CORRECTION = "correction"
|
||||||
|
BOLUS_CATEGORY_SMB = "smb"
|
||||||
|
|
||||||
|
BOLUS_CATEGORY_COLUMNS = ["timestamp", "eventType", "insulin", "carbs", "category"]
|
||||||
|
|
||||||
|
|
||||||
|
def classify_bolus(treatments: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
"""Splits bolus-insuline op in 'food'/'correction'/'smb', voor grafiekoverlays
|
||||||
|
(gitea insulineprofiel-werk, vervolg op bolus_stats()'s SMB-detectie).
|
||||||
|
|
||||||
|
Herkenningsregels, in volgorde:
|
||||||
|
- SMB: `eventType == "SMB"`, of `eventType == "Correction Bolus"` met
|
||||||
|
`type == "SMB"` (zie bolus_stats()) — automatische AndroidAPS-microbolus.
|
||||||
|
- food: `eventType == "Meal Bolus"`, of een andere bolus-eventType
|
||||||
|
(`Bolus`/`Combo Bolus`) met koolhydraten op dezelfde treatment-rij (een
|
||||||
|
sterke aanwijzing dat het om een maaltijdbolus gaat).
|
||||||
|
- correction: alle overige bolus-rijen (typisch `Correction Bolus` zonder
|
||||||
|
SMB-markering, of een generieke `Bolus`/`Combo Bolus` zonder koolhydraten).
|
||||||
|
|
||||||
|
Geeft een DataFrame terug met kolommen 'timestamp', 'eventType', 'insulin',
|
||||||
|
'carbs', 'category' — alleen de rijen die daadwerkelijk bolusinsuline zijn.
|
||||||
|
"""
|
||||||
|
if treatments.empty:
|
||||||
|
return pd.DataFrame(columns=BOLUS_CATEGORY_COLUMNS)
|
||||||
|
|
||||||
|
bolus = treatments[treatments["eventType"].isin(INSULIN_EVENT_TYPES) & treatments["insulin"].notna()].copy()
|
||||||
|
if bolus.empty:
|
||||||
|
return pd.DataFrame(columns=BOLUS_CATEGORY_COLUMNS)
|
||||||
|
|
||||||
|
is_smb = (bolus["eventType"] == SMB_TYPE) | (
|
||||||
|
(bolus["eventType"] == "Correction Bolus") & (bolus.get("type", "") == SMB_TYPE)
|
||||||
|
)
|
||||||
|
has_carbs = pd.to_numeric(bolus["carbs"], errors="coerce").fillna(0) > 0
|
||||||
|
is_food = ~is_smb & ((bolus["eventType"] == "Meal Bolus") | has_carbs)
|
||||||
|
|
||||||
|
bolus["category"] = BOLUS_CATEGORY_CORRECTION
|
||||||
|
bolus.loc[is_food, "category"] = BOLUS_CATEGORY_FOOD
|
||||||
|
bolus.loc[is_smb, "category"] = BOLUS_CATEGORY_SMB
|
||||||
|
return bolus[BOLUS_CATEGORY_COLUMNS].sort_values("timestamp").reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def glucose_min_max(glucose: pd.DataFrame) -> tuple[float, float]:
|
||||||
|
"""Minimum en maximum glucosewaarde (mmol/L) in de gegeven data."""
|
||||||
|
if glucose.empty:
|
||||||
|
return (0.0, 0.0)
|
||||||
|
return (round(glucose["mmol"].min(), 1), round(glucose["mmol"].max(), 1))
|
||||||
|
|
||||||
|
|
||||||
|
def _temp_basal_intervals(treatments: pd.DataFrame, day_start, day_end) -> list[tuple]:
|
||||||
|
"""Temp Basal-intervallen (start, eind, rate) die (deels) binnen [day_start, day_end) vallen,
|
||||||
|
geclipt aan de daggrenzen."""
|
||||||
|
if treatments is None or treatments.empty:
|
||||||
|
return []
|
||||||
|
temp_basal = treatments[
|
||||||
|
(treatments["eventType"] == BASAL_EVENT_TYPE)
|
||||||
|
& treatments["absolute"].notna()
|
||||||
|
& treatments["duration"].notna()
|
||||||
|
]
|
||||||
|
intervals = []
|
||||||
|
for _, row in temp_basal.iterrows():
|
||||||
|
start = row["timestamp"]
|
||||||
|
end = start + pd.Timedelta(float(row["duration"]), unit="min")
|
||||||
|
if end <= day_start or start >= day_end:
|
||||||
|
continue
|
||||||
|
intervals.append((max(start, day_start), min(end, day_end), row["absolute"]))
|
||||||
|
return intervals
|
||||||
|
|
||||||
|
|
||||||
|
def _basal_breakpoints(basal_segments: list[dict], temp_intervals: list[tuple], day_start, day_end) -> list:
|
||||||
|
"""Alle tijdstippen waarop de effectieve basaalsnelheid kan wijzigen: daggrens,
|
||||||
|
profielsegment-grenzen, en temp-basal start/eind — oplopend gesorteerd."""
|
||||||
|
breakpoints = {day_start}
|
||||||
|
for seg in basal_segments:
|
||||||
|
ts = day_start + pd.Timedelta(float(seg["minutes"]), unit="min")
|
||||||
|
if day_start <= ts < day_end:
|
||||||
|
breakpoints.add(ts)
|
||||||
|
for start, end, _ in temp_intervals:
|
||||||
|
breakpoints.add(start)
|
||||||
|
breakpoints.add(end)
|
||||||
|
return sorted(t for t in breakpoints if day_start <= t < day_end)
|
||||||
|
|
||||||
|
|
||||||
|
def _rate_at(ts, basal_segments: list[dict], temp_intervals: list[tuple], day_start) -> float:
|
||||||
|
"""Effectieve basaalsnelheid op tijdstip `ts`: een actieve Temp Basal wint van het profieltempo."""
|
||||||
|
for start, end, rate in temp_intervals:
|
||||||
|
if start <= ts < end:
|
||||||
|
return rate
|
||||||
|
minutes_of_day = int((ts - day_start).total_seconds() / 60) % MINUTES_PER_DAY
|
||||||
|
value = value_at(basal_segments, minutes_of_day)
|
||||||
|
return value if value is not None else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def effective_basal_series(profile: dict | None, treatments: pd.DataFrame, day_start, day_end) -> pd.DataFrame:
|
||||||
|
"""Basaalsnelheid (E/uur) als stapfunctie over [day_start, day_end).
|
||||||
|
|
||||||
|
Basislijn is het pompprofiel se basaalschema (`profile["basal"]`); waar een
|
||||||
|
Temp Basal-treatment actief is (rate/duur uit de treatment) overschrijft
|
||||||
|
die het profieltempo voor de duur van die tijdelijke aanpassing — dit is de
|
||||||
|
daadwerkelijk afgeleverde basaal, in tegenstelling tot basal_stats() (die
|
||||||
|
alleen temp-basal-periodes optelt en periodes zonder actieve temp basal
|
||||||
|
mist omdat het profiel daar niet bij betrokken wordt).
|
||||||
|
|
||||||
|
Zonder profiel (`profile` is None/leeg) is de basislijn 0 — dan toont dit
|
||||||
|
alleen de temp-basal-periodes, net als basal_stats().
|
||||||
|
|
||||||
|
Geeft een DataFrame terug met kolommen 'timestamp' en 'rate': elke rij
|
||||||
|
geldt tot de volgende rij (stapfunctie), geschikt voor een
|
||||||
|
step-area-plot (line_shape='hv', fill='tozeroy').
|
||||||
|
"""
|
||||||
|
day_start = pd.Timestamp(day_start)
|
||||||
|
day_end = pd.Timestamp(day_end)
|
||||||
|
basal_segments = (profile or {}).get("basal", [])
|
||||||
|
temp_intervals = _temp_basal_intervals(treatments, day_start, day_end)
|
||||||
|
breakpoints = _basal_breakpoints(basal_segments, temp_intervals, day_start, day_end)
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
{"timestamp": ts, "rate": _rate_at(ts, basal_segments, temp_intervals, day_start)} for ts in breakpoints
|
||||||
|
]
|
||||||
|
return pd.DataFrame(rows, columns=["timestamp", "rate"])
|
||||||
|
|
||||||
|
|
||||||
|
def _target_midpoint_at(minutes_of_day: int, target_low: list[dict], target_high: list[dict]) -> float | None:
|
||||||
|
low = value_at(target_low, minutes_of_day) if target_low else None
|
||||||
|
high = value_at(target_high, minutes_of_day) if target_high else None
|
||||||
|
if low is not None and high is not None:
|
||||||
|
return (low + high) / 2
|
||||||
|
return low if low is not None else high
|
||||||
|
|
||||||
|
|
||||||
|
def target_glucose_series(profile: dict | None, day_start, day_end) -> pd.DataFrame:
|
||||||
|
"""Streefglucose (mmol/L) uit het profiel als stapfunctie over [day_start, day_end) —
|
||||||
|
het midden van target_low/target_high per tijdsegment (de pomp kent vaak één
|
||||||
|
streefwaarde per segment; met losse low/high-segmenten is dat gewoon het
|
||||||
|
gemiddelde). Geeft een lege DataFrame terug als het profiel geen streefwaarden
|
||||||
|
bevat.
|
||||||
|
|
||||||
|
Zelfde stapfunctie-vorm als effective_basal_series(): elke rij geldt tot de
|
||||||
|
volgende rij.
|
||||||
|
"""
|
||||||
|
day_start = pd.Timestamp(day_start)
|
||||||
|
day_end = pd.Timestamp(day_end)
|
||||||
|
target_low = (profile or {}).get("target_low", [])
|
||||||
|
target_high = (profile or {}).get("target_high", [])
|
||||||
|
if not target_low and not target_high:
|
||||||
|
return pd.DataFrame(columns=["timestamp", "target"])
|
||||||
|
|
||||||
|
breakpoints = _basal_breakpoints(target_low + target_high, [], day_start, day_end)
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
"timestamp": ts,
|
||||||
|
"target": _target_midpoint_at(
|
||||||
|
int((ts - day_start).total_seconds() / 60) % MINUTES_PER_DAY, target_low, target_high
|
||||||
|
),
|
||||||
|
}
|
||||||
|
for ts in breakpoints
|
||||||
|
]
|
||||||
|
return pd.DataFrame(rows, columns=["timestamp", "target"])
|
||||||
|
|
||||||
|
|
||||||
|
def _integrate_step_series(series: pd.DataFrame, value_col: str, day_end) -> float:
|
||||||
|
"""Oppervlakte onder een stapfunctie-DataFrame (zoals effective_basal_series()):
|
||||||
|
som van elke rij se waarde x duur (in uur) tot de volgende rij, of tot
|
||||||
|
`day_end` voor de laatste rij. Gebruikt om een E/uur-stapfunctie om te
|
||||||
|
rekenen naar een totaal aantal eenheden."""
|
||||||
|
if series.empty:
|
||||||
|
return 0.0
|
||||||
|
rows = series.reset_index(drop=True)
|
||||||
|
total = 0.0
|
||||||
|
for i in range(len(rows)):
|
||||||
|
start = rows.loc[i, "timestamp"]
|
||||||
|
end = rows.loc[i + 1, "timestamp"] if i + 1 < len(rows) else day_end
|
||||||
|
total += rows.loc[i, value_col] * (end - start).total_seconds() / 3600
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
|
DAILY_STATS_KEYS = [
|
||||||
|
"mean_mmol",
|
||||||
|
"min_mmol",
|
||||||
|
"max_mmol",
|
||||||
|
"total_insulin",
|
||||||
|
"basal_insulin",
|
||||||
|
"bolus_insulin",
|
||||||
|
"smb_insulin",
|
||||||
|
"hypo_count",
|
||||||
|
"hypo_duration_minutes",
|
||||||
|
"hyper_count",
|
||||||
|
"hyper_duration_minutes",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def daily_stats(day_glucose: pd.DataFrame, day_treatments: pd.DataFrame, profile: dict | None, day_start, day_end) -> dict:
|
||||||
|
"""Samenvattende statistieken voor één kalenderdag, voor naast de dagelijkse
|
||||||
|
grafiek in het PDF-rapport: gemiddelde/min/max glucose, totale/basaal-/bolus-/
|
||||||
|
SMB-insuline (SMB apart gerapporteerd omdat dit zowel als basaal- als
|
||||||
|
bolus-vervanging kan gelden, zie classify_bolus()), en het aantal + de totale
|
||||||
|
duur van hypo- en hyperevents die dag.
|
||||||
|
"""
|
||||||
|
min_mmol, max_mmol = glucose_min_max(day_glucose)
|
||||||
|
mean_mmol = round(day_glucose["mmol"].mean(), 1) if not day_glucose.empty else 0.0
|
||||||
|
|
||||||
|
bolus = classify_bolus(day_treatments)
|
||||||
|
by_category = bolus.groupby("category")["insulin"].sum().to_dict() if not bolus.empty else {}
|
||||||
|
bolus_units = by_category.get(BOLUS_CATEGORY_FOOD, 0.0) + by_category.get(BOLUS_CATEGORY_CORRECTION, 0.0)
|
||||||
|
smb_units = by_category.get(BOLUS_CATEGORY_SMB, 0.0)
|
||||||
|
|
||||||
|
basal_series = effective_basal_series(profile, day_treatments, day_start, day_end)
|
||||||
|
basal_units = _integrate_step_series(basal_series, "rate", day_end)
|
||||||
|
|
||||||
|
hypo_summary = summarize_events(detect_events(day_glucose, LOW, "below"), period_days=1)
|
||||||
|
hyper_summary = summarize_events(detect_events(day_glucose, HIGH, "above"), period_days=1)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"mean_mmol": mean_mmol,
|
||||||
|
"min_mmol": min_mmol,
|
||||||
|
"max_mmol": max_mmol,
|
||||||
|
"total_insulin": round(bolus_units + smb_units + basal_units, 1),
|
||||||
|
"basal_insulin": round(basal_units, 1),
|
||||||
|
"bolus_insulin": round(bolus_units, 1),
|
||||||
|
"smb_insulin": round(smb_units, 1),
|
||||||
|
"hypo_count": hypo_summary["count"],
|
||||||
|
"hypo_duration_minutes": hypo_summary["total_minutes"],
|
||||||
|
"hyper_count": hyper_summary["count"],
|
||||||
|
"hyper_duration_minutes": hyper_summary["total_minutes"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
||||||
@@ -3,5 +3,8 @@ 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
|
||||||
|
pytest-cov>=5.0,<6.0
|
||||||
ruff>=0.6,<1.0
|
ruff>=0.6,<1.0
|
||||||
|
|||||||
@@ -4,3 +4,4 @@ sonar.sources=.
|
|||||||
sonar.exclusions=data/**,tests/**
|
sonar.exclusions=data/**,tests/**
|
||||||
sonar.tests=tests
|
sonar.tests=tests
|
||||||
sonar.python.version=3.12
|
sonar.python.version=3.12
|
||||||
|
sonar.python.coverage.reportPaths=coverage.xml
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -90,9 +90,315 @@ 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_fetch_profile_returns_first_document(monkeypatch):
|
||||||
|
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
|
||||||
|
payload = [{"defaultProfile": "Default", "store": {"Default": {"dia": "5"}}}]
|
||||||
|
|
||||||
|
seen_params = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
ns.requests,
|
||||||
|
"get",
|
||||||
|
lambda *a, **k: (seen_params.append(k["params"]), FakeResponse(payload))[1],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = ns.fetch_profile()
|
||||||
|
assert result == payload[0]
|
||||||
|
assert seen_params[0]["count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_profile_handles_empty_response(monkeypatch):
|
||||||
|
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
|
||||||
|
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse([]))
|
||||||
|
|
||||||
|
assert ns.fetch_profile() == {}
|
||||||
|
|
||||||
|
|
||||||
|
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]
|
||||||
|
|||||||
@@ -0,0 +1,289 @@
|
|||||||
|
import re
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from pdf_export import (
|
||||||
|
DAGOVERZICHT_MAX_DAYS,
|
||||||
|
SECTION_AGP,
|
||||||
|
SECTION_DAGOVERZICHT,
|
||||||
|
SECTION_EVENTS,
|
||||||
|
SECTION_INSULIN_PROFILE,
|
||||||
|
SECTION_SUMMARY,
|
||||||
|
_report_config,
|
||||||
|
build_report_pdf,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _page_count(pdf_bytes: bytes) -> int:
|
||||||
|
"""Grof-maar-betrouwbaar paginatelling op de ruwe PDF-bytes: elke
|
||||||
|
paginaobject bevat een '/Type /Page' (zonder de 's' van '/Type /Pages')
|
||||||
|
in zijn objectdictionary, wat altijd onleesbaar-platte tekst blijft ook
|
||||||
|
al staat contentstream-compressie aan — geen losse PDF-parser nodig voor
|
||||||
|
deze structurele check (zelfde black-box-filosofie als de rest van deze
|
||||||
|
testset: geen pixel-vergelijkingen, wel structuur)."""
|
||||||
|
return len(re.findall(rb"/Type\s*/Page[^s]", pdf_bytes))
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_always_has_at_least_a_cover_page():
|
||||||
|
empty = pd.DataFrame(columns=["timestamp", "mmol"])
|
||||||
|
pdf_bytes = build_report_pdf([], empty, {}, date(2026, 1, 1), date(2026, 1, 2))
|
||||||
|
assert _page_count(pdf_bytes) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_one_page_per_single_page_section():
|
||||||
|
glucose = _sample_glucose()
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_SUMMARY, SECTION_AGP], glucose, {}, date(2026, 1, 1), date(2026, 1, 2)
|
||||||
|
)
|
||||||
|
# cover + summary + agp = 3
|
||||||
|
assert _page_count(pdf_bytes) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_one_page_per_day_for_dagoverzicht():
|
||||||
|
timestamps = pd.date_range("2026-01-01", periods=3 * 24 * 12, freq="5min") # 3 dagen
|
||||||
|
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [7.0] * len(timestamps)})
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_DAGOVERZICHT], glucose, {}, date(2026, 1, 1), date(2026, 1, 3)
|
||||||
|
)
|
||||||
|
# cover + 3 dagen
|
||||||
|
assert _page_count(pdf_bytes) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_caps_dagoverzicht_page_count_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()
|
||||||
|
)
|
||||||
|
# cover + max. DAGOVERZICHT_MAX_DAYS dagpagina's, ondanks (DAGOVERZICHT_MAX_DAYS + 10) dagen aan data
|
||||||
|
assert _page_count(pdf_bytes) == 1 + DAGOVERZICHT_MAX_DAYS
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_includes_insulin_profile_section_page():
|
||||||
|
glucose = _sample_glucose()
|
||||||
|
profile = {
|
||||||
|
"name": "Default",
|
||||||
|
"dia": 5.0,
|
||||||
|
"basal": [{"minutes": 0, "value": 0.8}, {"minutes": 720, "value": 1.1}],
|
||||||
|
"sens": [{"minutes": 0, "value": 2.8}],
|
||||||
|
"carbratio": [{"minutes": 0, "value": 10.0}],
|
||||||
|
"target_low": [{"minutes": 0, "value": 4.5}],
|
||||||
|
"target_high": [{"minutes": 0, "value": 8.0}],
|
||||||
|
}
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_INSULIN_PROFILE], glucose, {}, date(2026, 1, 1), date(2026, 1, 2), profile=profile
|
||||||
|
)
|
||||||
|
# cover + insulineprofiel
|
||||||
|
assert _page_count(pdf_bytes) == 2
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_insulin_profile_section_handles_missing_profile():
|
||||||
|
glucose = _sample_glucose()
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_INSULIN_PROFILE], glucose, {}, date(2026, 1, 1), date(2026, 1, 2), profile=None
|
||||||
|
)
|
||||||
|
assert _page_count(pdf_bytes) == 2
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_insulin_profile_section_renders_without_glucose():
|
||||||
|
"""De Insulineprofiel-sectie gaat niet over glucosedata en moet dus ook
|
||||||
|
renderen als er geen glucosemetingen zijn (in tegenstelling tot
|
||||||
|
Samenvatting/AGP/Dagoverzicht, die wel glucosedata vereisen)."""
|
||||||
|
empty = pd.DataFrame(columns=["timestamp", "mmol"])
|
||||||
|
profile = {
|
||||||
|
"name": "Default",
|
||||||
|
"dia": 5.0,
|
||||||
|
"basal": [{"minutes": 0, "value": 0.8}],
|
||||||
|
"sens": [{"minutes": 0, "value": 2.8}],
|
||||||
|
"carbratio": [{"minutes": 0, "value": 10.0}],
|
||||||
|
"target_low": [],
|
||||||
|
"target_high": [],
|
||||||
|
}
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_INSULIN_PROFILE], empty, {}, date(2026, 1, 1), date(2026, 1, 2), profile=profile
|
||||||
|
)
|
||||||
|
assert _page_count(pdf_bytes) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_dagoverzicht_uses_treatments_and_profile_without_error():
|
||||||
|
"""Regressietest: de dagpagina moet basaal/bolus/koolhydraten/streefwaarde-
|
||||||
|
overlays tekenen zonder te crashen als er echte treatments/profile worden
|
||||||
|
meegegeven (in plaats van de lege defaults)."""
|
||||||
|
timestamps = pd.date_range("2026-01-01", periods=24 * 12, freq="5min") # 1 dag
|
||||||
|
glucose = pd.DataFrame({"timestamp": timestamps, "mmol": [7.0] * len(timestamps)})
|
||||||
|
treatments = pd.DataFrame(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"timestamp": pd.Timestamp("2026-01-01 08:00"),
|
||||||
|
"eventType": "Meal Bolus",
|
||||||
|
"insulin": 4.0,
|
||||||
|
"carbs": 40.0,
|
||||||
|
"type": "",
|
||||||
|
"absolute": None,
|
||||||
|
"duration": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": pd.Timestamp("2026-01-01 12:00"),
|
||||||
|
"eventType": "Correction Bolus",
|
||||||
|
"insulin": 0.3,
|
||||||
|
"carbs": None,
|
||||||
|
"type": "SMB",
|
||||||
|
"absolute": None,
|
||||||
|
"duration": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": pd.Timestamp("2026-01-01 06:00"),
|
||||||
|
"eventType": "Temp Basal",
|
||||||
|
"insulin": None,
|
||||||
|
"carbs": None,
|
||||||
|
"type": "",
|
||||||
|
"absolute": 2.0,
|
||||||
|
"duration": 60,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
profile = {
|
||||||
|
"name": "Default",
|
||||||
|
"dia": 5.0,
|
||||||
|
"basal": [{"minutes": 0, "value": 0.8}],
|
||||||
|
"sens": [{"minutes": 0, "value": 2.8}],
|
||||||
|
"carbratio": [{"minutes": 0, "value": 10.0}],
|
||||||
|
"target_low": [{"minutes": 0, "value": 4.5}],
|
||||||
|
"target_high": [{"minutes": 0, "value": 8.0}],
|
||||||
|
}
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_DAGOVERZICHT],
|
||||||
|
glucose,
|
||||||
|
{},
|
||||||
|
date(2026, 1, 1),
|
||||||
|
date(2026, 1, 1),
|
||||||
|
treatments=treatments,
|
||||||
|
profile=profile,
|
||||||
|
)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
assert _page_count(pdf_bytes) == 2 # cover + 1 dag
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_config_uses_defaults_when_env_vars_unset(monkeypatch):
|
||||||
|
for var in ("REPORT_INSULIN_TYPE", "REPORT_PUMP_TYPE", "REPORT_SENSOR_TYPE", "NIGHTSCOUT_URL"):
|
||||||
|
monkeypatch.delenv(var, raising=False)
|
||||||
|
config = _report_config()
|
||||||
|
assert config["insulin_type"] == "Onbekend insulinetype"
|
||||||
|
assert config["pump_type"] == "Onbekende pomp"
|
||||||
|
assert config["sensor_type"] == "Onbekende sensor"
|
||||||
|
assert config["nightscout_url"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_config_reads_env_vars_when_set(monkeypatch):
|
||||||
|
monkeypatch.setenv("REPORT_INSULIN_TYPE", "Lyumjev 100U")
|
||||||
|
monkeypatch.setenv("REPORT_PUMP_TYPE", "Omnipod DASH")
|
||||||
|
monkeypatch.setenv("REPORT_SENSOR_TYPE", "Dexcom G7")
|
||||||
|
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com/")
|
||||||
|
config = _report_config()
|
||||||
|
assert config["insulin_type"] == "Lyumjev 100U"
|
||||||
|
assert config["pump_type"] == "Omnipod DASH"
|
||||||
|
assert config["sensor_type"] == "Dexcom G7"
|
||||||
|
assert config["nightscout_url"] == "https://example.com" # trailing slash gestript
|
||||||
|
|
||||||
|
|
||||||
|
def test_icon_asset_exists():
|
||||||
|
icon_path = Path(__file__).parent.parent / "assets" / "icon.svg"
|
||||||
|
assert icon_path.exists()
|
||||||
|
assert icon_path.read_text(encoding="utf-8").strip().startswith("<svg")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("section", [SECTION_SUMMARY, SECTION_AGP, SECTION_DAGOVERZICHT, SECTION_EVENTS])
|
||||||
|
def test_all_sections_still_work_without_treatments_or_profile_args(section):
|
||||||
|
"""Achterwaartse compatibiliteit: treatments/profile zijn optioneel — een
|
||||||
|
aanroep zoals vóór deze PR (zonder die argumenten) moet blijven werken."""
|
||||||
|
glucose = _glucose_with_hypo_and_hyper_events() if section == SECTION_EVENTS else _sample_glucose()
|
||||||
|
events_summary = {"Hypo Level 1": {"count": 1, "avg_duration_minutes": 25.0, "events_per_week": 2.3}}
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[section], glucose, events_summary if section == SECTION_EVENTS else {}, date(2026, 1, 1), date(2026, 1, 4)
|
||||||
|
)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
import profile_data as pd_
|
||||||
|
|
||||||
|
|
||||||
|
def _raw_profile(units="mg/dl", default_name="Default"):
|
||||||
|
return {
|
||||||
|
"defaultProfile": default_name,
|
||||||
|
"store": {
|
||||||
|
"Default": {
|
||||||
|
"units": units,
|
||||||
|
"dia": "5",
|
||||||
|
"basal": [
|
||||||
|
{"time": "00:00", "value": "0.8"},
|
||||||
|
{"time": "06:00", "value": "1.2"},
|
||||||
|
{"time": "22:00", "value": "0.7"},
|
||||||
|
],
|
||||||
|
"sens": [{"time": "00:00", "value": "50"}],
|
||||||
|
"carbratio": [{"time": "00:00", "value": "10"}],
|
||||||
|
"target_low": [{"time": "00:00", "value": "90"}],
|
||||||
|
"target_high": [{"time": "00:00", "value": "120"}],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_returns_empty_dict_for_empty_input():
|
||||||
|
assert pd_.parse_profile({}) == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_converts_mgdl_to_mmol():
|
||||||
|
profile = pd_.parse_profile(_raw_profile(units="mg/dl"))
|
||||||
|
assert profile["units"] == "mmol"
|
||||||
|
# 90 mg/dl -> ~5.0 mmol/L, 120 mg/dl -> ~6.7 mmol/L, 50 mg/dl (ISF) -> ~2.8 mmol/L
|
||||||
|
assert profile["target_low"][0]["value"] == pytest.approx(5.0, abs=0.05)
|
||||||
|
assert profile["target_high"][0]["value"] == pytest.approx(6.7, abs=0.05)
|
||||||
|
assert profile["sens"][0]["value"] == pytest.approx(2.8, abs=0.05)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_leaves_mmol_profiles_unconverted():
|
||||||
|
profile = pd_.parse_profile(_raw_profile(units="mmol"))
|
||||||
|
assert profile["target_low"][0]["value"] == pytest.approx(90.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_does_not_convert_basal_or_carbratio():
|
||||||
|
profile = pd_.parse_profile(_raw_profile(units="mg/dl"))
|
||||||
|
assert profile["basal"][0]["value"] == pytest.approx(0.8)
|
||||||
|
assert profile["carbratio"][0]["value"] == pytest.approx(10.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_sorts_basal_segments_by_time():
|
||||||
|
raw = _raw_profile()
|
||||||
|
raw["store"]["Default"]["basal"] = [
|
||||||
|
{"time": "22:00", "value": "0.7"},
|
||||||
|
{"time": "00:00", "value": "0.8"},
|
||||||
|
{"time": "06:00", "value": "1.2"},
|
||||||
|
]
|
||||||
|
profile = pd_.parse_profile(raw)
|
||||||
|
assert [seg["minutes"] for seg in profile["basal"]] == [0, 360, 1320]
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_falls_back_to_first_profile_when_default_name_missing():
|
||||||
|
raw = _raw_profile(default_name="DoesNotExist")
|
||||||
|
profile = pd_.parse_profile(raw)
|
||||||
|
assert profile["dia"] == pytest.approx(5.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_profile_dia_and_name():
|
||||||
|
profile = pd_.parse_profile(_raw_profile())
|
||||||
|
assert profile["dia"] == pytest.approx(5.0)
|
||||||
|
assert profile["name"] == "Default"
|
||||||
|
|
||||||
|
|
||||||
|
def test_value_at_returns_active_segment():
|
||||||
|
segments = [{"minutes": 0, "value": 0.8}, {"minutes": 360, "value": 1.2}, {"minutes": 1320, "value": 0.7}]
|
||||||
|
assert pd_.value_at(segments, 100) == pytest.approx(0.8)
|
||||||
|
assert pd_.value_at(segments, 360) == pytest.approx(1.2)
|
||||||
|
assert pd_.value_at(segments, 1000) == pytest.approx(1.2)
|
||||||
|
assert pd_.value_at(segments, 1350) == pytest.approx(0.7)
|
||||||
|
|
||||||
|
|
||||||
|
def test_value_at_wraps_to_last_segment_before_first():
|
||||||
|
segments = [{"minutes": 360, "value": 1.2}, {"minutes": 1320, "value": 0.7}]
|
||||||
|
assert pd_.value_at(segments, 100) == pytest.approx(0.7)
|
||||||
|
|
||||||
|
|
||||||
|
def test_value_at_empty_segments_returns_none():
|
||||||
|
assert pd_.value_at([], 100) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_segments_table_computes_end_times_from_next_segment():
|
||||||
|
segments = [{"minutes": 0, "value": 0.8}, {"minutes": 360, "value": 1.2}]
|
||||||
|
rows = pd_.segments_table(segments)
|
||||||
|
assert rows == [
|
||||||
|
{"start": "00:00", "end": "06:00", "value": 0.8},
|
||||||
|
{"start": "06:00", "end": "24:00", "value": 1.2},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_segments_to_hourly_bars_closes_the_24h_loop():
|
||||||
|
segments = [{"minutes": 0, "value": 0.8}, {"minutes": 360, "value": 1.2}]
|
||||||
|
bars = pd_.segments_to_hourly_bars(segments)
|
||||||
|
assert bars[-1] == {"hour": 24.0, "value": 0.8}
|
||||||
|
|
||||||
|
|
||||||
|
def test_segments_to_hourly_bars_empty_input():
|
||||||
|
assert pd_.segments_to_hourly_bars([]) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_total_daily_basal_weights_by_segment_duration():
|
||||||
|
# 6h @ 0.8 + 18h @ 1.2 = 4.8 + 21.6 = 26.4
|
||||||
|
segments = [{"minutes": 0, "value": 0.8}, {"minutes": 360, "value": 1.2}]
|
||||||
|
assert pd_.total_daily_basal(segments) == pytest.approx(26.4)
|
||||||
|
|
||||||
|
|
||||||
|
def test_total_daily_basal_empty_input():
|
||||||
|
assert pd_.total_daily_basal([]) == 0.0
|
||||||
@@ -0,0 +1,741 @@
|
|||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from reporting import (
|
||||||
|
GMI_TREND_COLUMNS,
|
||||||
|
agp_percentile_bands,
|
||||||
|
basal_stats,
|
||||||
|
bolus_stats,
|
||||||
|
classify_bolus,
|
||||||
|
completeness_warning,
|
||||||
|
daily_gmi,
|
||||||
|
daily_stats,
|
||||||
|
day_of_week_pattern,
|
||||||
|
detect_events,
|
||||||
|
effective_basal_series,
|
||||||
|
glucose_min_max,
|
||||||
|
gmi_mmol_per_mol,
|
||||||
|
gmi_percent,
|
||||||
|
gmi_trend,
|
||||||
|
minutes_per_day,
|
||||||
|
overnight_daytime_split,
|
||||||
|
percent_cv,
|
||||||
|
sensor_active_percent,
|
||||||
|
site_interval_stats,
|
||||||
|
summarize_events,
|
||||||
|
target_glucose_series,
|
||||||
|
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_glucose_min_max_returns_min_and_max():
|
||||||
|
glucose = _series([("2026-01-01 00:00", 6.5), ("2026-01-01 01:00", 3.2), ("2026-01-01 02:00", 14.1)])
|
||||||
|
assert glucose_min_max(glucose) == (3.2, 14.1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_glucose_min_max_handles_empty_input():
|
||||||
|
empty = pd.DataFrame(columns=["timestamp", "mmol"])
|
||||||
|
assert glucose_min_max(empty) == (0.0, 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def _bolus_treatment(dt, event_type, insulin=1.0, carbs=None, bolus_type=""):
|
||||||
|
return {
|
||||||
|
"timestamp": pd.Timestamp(dt),
|
||||||
|
"eventType": event_type,
|
||||||
|
"insulin": insulin,
|
||||||
|
"carbs": carbs,
|
||||||
|
"type": bolus_type,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_recognizes_meal_bolus_as_food():
|
||||||
|
treatments = pd.DataFrame([_bolus_treatment("2026-01-01 08:00", "Meal Bolus", insulin=4.0)])
|
||||||
|
result = classify_bolus(treatments)
|
||||||
|
assert result.iloc[0]["category"] == "food"
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_recognizes_smb_via_type_field():
|
||||||
|
treatments = pd.DataFrame(
|
||||||
|
[_bolus_treatment("2026-01-01 08:00", "Correction Bolus", insulin=0.3, bolus_type="SMB")]
|
||||||
|
)
|
||||||
|
result = classify_bolus(treatments)
|
||||||
|
assert result.iloc[0]["category"] == "smb"
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_recognizes_smb_via_event_type():
|
||||||
|
treatments = pd.DataFrame([_bolus_treatment("2026-01-01 08:00", "SMB", insulin=0.3)])
|
||||||
|
result = classify_bolus(treatments)
|
||||||
|
assert result.iloc[0]["category"] == "smb"
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_treats_correction_bolus_without_carbs_as_correction():
|
||||||
|
treatments = pd.DataFrame([_bolus_treatment("2026-01-01 08:00", "Correction Bolus", insulin=1.5)])
|
||||||
|
result = classify_bolus(treatments)
|
||||||
|
assert result.iloc[0]["category"] == "correction"
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_treats_generic_bolus_with_carbs_as_food():
|
||||||
|
treatments = pd.DataFrame([_bolus_treatment("2026-01-01 08:00", "Bolus", insulin=3.0, carbs=40.0)])
|
||||||
|
result = classify_bolus(treatments)
|
||||||
|
assert result.iloc[0]["category"] == "food"
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_ignores_non_bolus_rows():
|
||||||
|
treatments = pd.DataFrame(
|
||||||
|
[
|
||||||
|
_bolus_treatment("2026-01-01 08:00", "Meal Bolus", insulin=4.0),
|
||||||
|
{"timestamp": pd.Timestamp("2026-01-01 08:05"), "eventType": "Site Change", "insulin": None, "carbs": None, "type": ""},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
result = classify_bolus(treatments)
|
||||||
|
assert len(result) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_classify_bolus_handles_empty_input():
|
||||||
|
empty = pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs", "type"])
|
||||||
|
result = classify_bolus(empty)
|
||||||
|
assert result.empty
|
||||||
|
assert list(result.columns) == ["timestamp", "eventType", "insulin", "carbs", "category"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_effective_basal_series_uses_profile_baseline_without_temp_basal():
|
||||||
|
profile = {"basal": [{"minutes": 0, "value": 0.8}, {"minutes": 360, "value": 1.2}]}
|
||||||
|
empty_treatments = pd.DataFrame(columns=["timestamp", "eventType", "absolute", "duration"])
|
||||||
|
result = effective_basal_series(
|
||||||
|
profile, empty_treatments, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02")
|
||||||
|
)
|
||||||
|
assert result.iloc[0]["rate"] == pytest.approx(0.8)
|
||||||
|
assert result[result["timestamp"] == pd.Timestamp("2026-01-01 06:00")].iloc[0]["rate"] == pytest.approx(1.2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_effective_basal_series_temp_basal_overrides_profile_rate():
|
||||||
|
profile = {"basal": [{"minutes": 0, "value": 0.8}]}
|
||||||
|
treatments = pd.DataFrame(
|
||||||
|
[{"timestamp": pd.Timestamp("2026-01-01 08:00"), "eventType": "Temp Basal", "absolute": 2.0, "duration": 30}]
|
||||||
|
)
|
||||||
|
result = effective_basal_series(profile, treatments, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
during_temp = result[result["timestamp"] == pd.Timestamp("2026-01-01 08:00")].iloc[0]
|
||||||
|
after_temp = result[result["timestamp"] == pd.Timestamp("2026-01-01 08:30")].iloc[0]
|
||||||
|
assert during_temp["rate"] == pytest.approx(2.0)
|
||||||
|
assert after_temp["rate"] == pytest.approx(0.8) # terug naar het profieltempo
|
||||||
|
|
||||||
|
|
||||||
|
def test_effective_basal_series_without_profile_defaults_to_zero_baseline():
|
||||||
|
empty_treatments = pd.DataFrame(columns=["timestamp", "eventType", "absolute", "duration"])
|
||||||
|
result = effective_basal_series(None, empty_treatments, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
assert result.iloc[0]["rate"] == pytest.approx(0.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_effective_basal_series_clips_temp_basal_to_day_boundaries():
|
||||||
|
profile = {"basal": [{"minutes": 0, "value": 0.8}]}
|
||||||
|
# Temp basal begint de dag ervoor en loopt door tot 01:00 van de dag zelf.
|
||||||
|
treatments = pd.DataFrame(
|
||||||
|
[{"timestamp": pd.Timestamp("2025-12-31 23:00"), "eventType": "Temp Basal", "absolute": 2.0, "duration": 120}]
|
||||||
|
)
|
||||||
|
result = effective_basal_series(profile, treatments, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
assert result.iloc[0]["timestamp"] == pd.Timestamp("2026-01-01")
|
||||||
|
assert result.iloc[0]["rate"] == pytest.approx(2.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_glucose_series_averages_low_and_high():
|
||||||
|
profile = {
|
||||||
|
"target_low": [{"minutes": 0, "value": 4.5}],
|
||||||
|
"target_high": [{"minutes": 0, "value": 8.5}],
|
||||||
|
}
|
||||||
|
result = target_glucose_series(profile, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
assert result.iloc[0]["target"] == pytest.approx(6.5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_glucose_series_falls_back_to_single_bound():
|
||||||
|
profile = {"target_low": [{"minutes": 0, "value": 5.0}], "target_high": []}
|
||||||
|
result = target_glucose_series(profile, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
assert result.iloc[0]["target"] == pytest.approx(5.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_glucose_series_empty_without_targets_in_profile():
|
||||||
|
result = target_glucose_series({}, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
assert result.empty
|
||||||
|
|
||||||
|
|
||||||
|
def test_target_glucose_series_handles_none_profile():
|
||||||
|
result = target_glucose_series(None, pd.Timestamp("2026-01-01"), pd.Timestamp("2026-01-02"))
|
||||||
|
assert result.empty
|
||||||
|
|
||||||
|
|
||||||
|
def test_daily_stats_computes_glucose_and_insulin_breakdown():
|
||||||
|
day_start = pd.Timestamp("2026-01-01")
|
||||||
|
day_end = pd.Timestamp("2026-01-02")
|
||||||
|
glucose = _series(
|
||||||
|
[("2026-01-01 08:00", 3.2), ("2026-01-01 12:00", 14.1), ("2026-01-01 20:00", 6.5)]
|
||||||
|
)
|
||||||
|
treatments = pd.DataFrame(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"timestamp": pd.Timestamp("2026-01-01 08:00"),
|
||||||
|
"eventType": "Meal Bolus",
|
||||||
|
"insulin": 4.0,
|
||||||
|
"carbs": 40.0,
|
||||||
|
"type": "",
|
||||||
|
"absolute": None,
|
||||||
|
"duration": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": pd.Timestamp("2026-01-01 12:00"),
|
||||||
|
"eventType": "Correction Bolus",
|
||||||
|
"insulin": 0.3,
|
||||||
|
"carbs": None,
|
||||||
|
"type": "SMB",
|
||||||
|
"absolute": None,
|
||||||
|
"duration": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"timestamp": pd.Timestamp("2026-01-01 06:00"),
|
||||||
|
"eventType": "Temp Basal",
|
||||||
|
"insulin": None,
|
||||||
|
"carbs": None,
|
||||||
|
"type": "",
|
||||||
|
"absolute": 2.0,
|
||||||
|
"duration": 60,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
profile = {"basal": [{"minutes": 0, "value": 0.8}]}
|
||||||
|
|
||||||
|
result = daily_stats(glucose, treatments, profile, day_start, day_end)
|
||||||
|
|
||||||
|
assert result["mean_mmol"] == pytest.approx((3.2 + 14.1 + 6.5) / 3, abs=0.05)
|
||||||
|
assert result["min_mmol"] == pytest.approx(3.2)
|
||||||
|
assert result["max_mmol"] == pytest.approx(14.1)
|
||||||
|
assert result["bolus_insulin"] == pytest.approx(4.0)
|
||||||
|
assert result["smb_insulin"] == pytest.approx(0.3)
|
||||||
|
# basaal: 23h @ 0.8 profieltempo + 1h @ 2.0 (temp basal 06:00-07:00) = 18.4 + 2.0 = 20.4
|
||||||
|
assert result["basal_insulin"] == pytest.approx(20.4, abs=0.05)
|
||||||
|
assert result["total_insulin"] == pytest.approx(4.0 + 0.3 + 20.4, abs=0.05)
|
||||||
|
assert result["hypo_count"] == 1
|
||||||
|
assert result["hyper_count"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_daily_stats_handles_empty_glucose_and_treatments():
|
||||||
|
day_start = pd.Timestamp("2026-01-01")
|
||||||
|
day_end = pd.Timestamp("2026-01-02")
|
||||||
|
empty_glucose = pd.DataFrame(columns=["timestamp", "mmol"])
|
||||||
|
empty_treatments = pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs", "type", "absolute", "duration"])
|
||||||
|
|
||||||
|
result = daily_stats(empty_glucose, empty_treatments, None, day_start, day_end)
|
||||||
|
|
||||||
|
assert result["mean_mmol"] == 0.0
|
||||||
|
assert result["min_mmol"] == 0.0
|
||||||
|
assert result["max_mmol"] == 0.0
|
||||||
|
assert result["total_insulin"] == 0.0
|
||||||
|
assert result["hypo_count"] == 0
|
||||||
|
assert result["hyper_count"] == 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,
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import plotly.graph_objects as go
|
||||||
|
import streamlit as st
|
||||||
|
|
||||||
|
from ui_common import (
|
||||||
|
PALETTE,
|
||||||
|
THRESHOLD_LINES,
|
||||||
|
add_basal_area_trace,
|
||||||
|
add_bolus_marker_traces,
|
||||||
|
add_carb_bars_trace,
|
||||||
|
add_target_line_trace,
|
||||||
|
add_threshold_lines,
|
||||||
|
build_tir_stacked_bar_figure,
|
||||||
|
get_colors,
|
||||||
|
hex_to_rgba,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_colors_returns_dark_palette_when_theme_is_dark(monkeypatch):
|
||||||
|
monkeypatch.setattr(st, "context", SimpleNamespace(theme=SimpleNamespace(type="dark")))
|
||||||
|
assert get_colors() == PALETTE["dark"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_colors_returns_light_palette_when_theme_is_light(monkeypatch):
|
||||||
|
monkeypatch.setattr(st, "context", SimpleNamespace(theme=SimpleNamespace(type="light")))
|
||||||
|
assert get_colors() == PALETTE["light"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_colors_falls_back_to_light_when_theme_context_unavailable(monkeypatch):
|
||||||
|
monkeypatch.setattr(st, "context", SimpleNamespace()) # geen .theme-attribuut
|
||||||
|
assert get_colors() == PALETTE["light"]
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_basal_area_trace_adds_one_filled_step_trace():
|
||||||
|
basal = pd.DataFrame(
|
||||||
|
{"timestamp": pd.to_datetime(["2026-01-01 00:00", "2026-01-01 06:00"]), "rate": [0.8, 1.2]}
|
||||||
|
)
|
||||||
|
fig = go.Figure()
|
||||||
|
add_basal_area_trace(fig, basal, PALETTE["light"])
|
||||||
|
assert len(fig.data) == 1
|
||||||
|
assert fig.data[0].name == "Basaal"
|
||||||
|
assert fig.data[0].fill == "tozeroy"
|
||||||
|
assert fig.data[0].line.shape == "hv"
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_basal_area_trace_supports_secondary_y_on_a_subplot_figure():
|
||||||
|
from plotly.subplots import make_subplots
|
||||||
|
|
||||||
|
basal = pd.DataFrame(
|
||||||
|
{"timestamp": pd.to_datetime(["2026-01-01 00:00", "2026-01-01 06:00"]), "rate": [0.8, 1.2]}
|
||||||
|
)
|
||||||
|
fig = make_subplots(specs=[[{"secondary_y": True}]])
|
||||||
|
add_basal_area_trace(fig, basal, PALETTE["light"], row=1, secondary_y=True)
|
||||||
|
assert len(fig.data) == 1
|
||||||
|
assert fig.data[0].yaxis == "y2"
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_basal_area_trace_skips_empty_input():
|
||||||
|
fig = go.Figure()
|
||||||
|
add_basal_area_trace(fig, pd.DataFrame(columns=["timestamp", "rate"]), PALETTE["light"])
|
||||||
|
assert len(fig.data) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_carb_bars_trace_supports_secondary_y_on_a_subplot_figure():
|
||||||
|
from plotly.subplots import make_subplots
|
||||||
|
|
||||||
|
carbs = pd.DataFrame({"timestamp": pd.to_datetime(["2026-01-01 08:00"]), "carbs": [40.0]})
|
||||||
|
fig = make_subplots(specs=[[{"secondary_y": True}]])
|
||||||
|
add_carb_bars_trace(fig, carbs, PALETTE["light"], row=1, secondary_y=True)
|
||||||
|
assert len(fig.data) == 1
|
||||||
|
assert fig.data[0].yaxis == "y2"
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_carb_bars_trace_adds_one_bar_trace():
|
||||||
|
carbs = pd.DataFrame({"timestamp": pd.to_datetime(["2026-01-01 08:00"]), "carbs": [40.0]})
|
||||||
|
fig = go.Figure()
|
||||||
|
add_carb_bars_trace(fig, carbs, PALETTE["light"])
|
||||||
|
assert len(fig.data) == 1
|
||||||
|
assert fig.data[0].name == "Koolhydraten"
|
||||||
|
assert isinstance(fig.data[0], go.Bar)
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_carb_bars_trace_skips_empty_input():
|
||||||
|
fig = go.Figure()
|
||||||
|
add_carb_bars_trace(fig, pd.DataFrame(columns=["timestamp", "carbs"]), PALETTE["light"])
|
||||||
|
assert len(fig.data) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_bolus_marker_traces_adds_one_trace_per_category_present():
|
||||||
|
bolus = pd.DataFrame(
|
||||||
|
{
|
||||||
|
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 12:00"]),
|
||||||
|
"insulin": [4.0, 0.3],
|
||||||
|
"category": ["food", "smb"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
fig = go.Figure()
|
||||||
|
add_bolus_marker_traces(fig, bolus, PALETTE["light"], lane_y=2.0)
|
||||||
|
names = {trace.name for trace in fig.data}
|
||||||
|
assert names == {"Bolus (voeding)", "SMB"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_bolus_marker_traces_labels_food_and_correction_but_not_smb():
|
||||||
|
bolus = pd.DataFrame(
|
||||||
|
{
|
||||||
|
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 12:00"]),
|
||||||
|
"insulin": [4.0, 0.3],
|
||||||
|
"category": ["food", "smb"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
fig = go.Figure()
|
||||||
|
add_bolus_marker_traces(fig, bolus, PALETTE["light"], lane_y=2.0)
|
||||||
|
by_name = {trace.name: trace for trace in fig.data}
|
||||||
|
assert by_name["Bolus (voeding)"].mode == "markers+text"
|
||||||
|
assert by_name["SMB"].mode == "markers"
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_bolus_marker_traces_skips_empty_input():
|
||||||
|
fig = go.Figure()
|
||||||
|
add_bolus_marker_traces(fig, pd.DataFrame(columns=["timestamp", "insulin", "category"]), PALETTE["light"], 2.0)
|
||||||
|
assert len(fig.data) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_target_line_trace_adds_one_line_trace():
|
||||||
|
target = pd.DataFrame({"timestamp": pd.to_datetime(["2026-01-01 00:00"]), "target": [6.5]})
|
||||||
|
fig = go.Figure()
|
||||||
|
add_target_line_trace(fig, target, PALETTE["light"])
|
||||||
|
assert len(fig.data) == 1
|
||||||
|
assert fig.data[0].name == "Streefwaarde (pomp)"
|
||||||
|
|
||||||
|
|
||||||
|
def test_add_target_line_trace_skips_empty_input():
|
||||||
|
fig = go.Figure()
|
||||||
|
add_target_line_trace(fig, pd.DataFrame(columns=["timestamp", "target"]), PALETTE["light"])
|
||||||
|
assert len(fig.data) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_overlay_traces_support_an_hour_based_x_column_for_dagoverzicht():
|
||||||
|
"""Dagoverzicht plot elke dag op een gedeelde 0-24u-as ('hour') i.p.v. echte
|
||||||
|
datums; de hover mag daar dan ook geen datumformattering tonen."""
|
||||||
|
basal = pd.DataFrame({"hour": [0.0, 6.0], "rate": [0.8, 1.2]})
|
||||||
|
carbs = pd.DataFrame({"hour": [8.0], "carbs": [40.0]})
|
||||||
|
bolus = pd.DataFrame({"hour": [8.0], "insulin": [4.0], "category": ["food"]})
|
||||||
|
target = pd.DataFrame({"hour": [0.0], "target": [6.5]})
|
||||||
|
|
||||||
|
fig = go.Figure()
|
||||||
|
add_basal_area_trace(fig, basal, PALETTE["light"], x_col="hour")
|
||||||
|
add_carb_bars_trace(fig, carbs, PALETTE["light"], x_col="hour")
|
||||||
|
add_bolus_marker_traces(fig, bolus, PALETTE["light"], lane_y=2.0, x_col="hour")
|
||||||
|
add_target_line_trace(fig, target, PALETTE["light"], x_col="hour")
|
||||||
|
|
||||||
|
assert len(fig.data) == 4
|
||||||
|
bolus_trace = next(t for t in fig.data if t.name == "Bolus (voeding)")
|
||||||
|
assert list(bolus_trace.x) == [8.0]
|
||||||
|
assert "%d-%m" not in bolus_trace.hovertemplate
|
||||||
+443
@@ -0,0 +1,443 @@
|
|||||||
|
"""
|
||||||
|
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_profile, fetch_treatments_range
|
||||||
|
from profile_data import parse_profile
|
||||||
|
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",
|
||||||
|
"basal": "#7b5ea3",
|
||||||
|
"bolus_food": "#1baf7a",
|
||||||
|
"bolus_correction": "#2a78d6",
|
||||||
|
"bolus_smb": "#898781",
|
||||||
|
"target": "#52514e",
|
||||||
|
},
|
||||||
|
"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",
|
||||||
|
"basal": "#9b7ec2",
|
||||||
|
"bolus_food": "#199e70",
|
||||||
|
"bolus_correction": "#3987e5",
|
||||||
|
"bolus_smb": "#898781",
|
||||||
|
"target": "#c3c2b7",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 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]: # pragma: no cover
|
||||||
|
"""Periodekiezer voor rapportagepagina's; geeft (start, eind, aantal_dagen) terug.
|
||||||
|
|
||||||
|
Pure Streamlit-widget-orkestratie (st.radio) — buiten scope van de
|
||||||
|
unit-testdekking net als pages/*.py, zie pyproject.toml se coverage-omit-lijst.
|
||||||
|
"""
|
||||||
|
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): # pragma: no cover
|
||||||
|
"""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.
|
||||||
|
|
||||||
|
Dunne st.cache_data-wrapper rond al-geteste fetch_entries_range()/
|
||||||
|
fetch_treatments_range() — buiten scope van de unit-testdekking net als
|
||||||
|
pages/*.py, zie pyproject.toml se coverage-omit-lijst.
|
||||||
|
"""
|
||||||
|
glucose = fetch_entries_range(start, end)
|
||||||
|
treatments = fetch_treatments_range(start, end)
|
||||||
|
return glucose, treatments
|
||||||
|
|
||||||
|
|
||||||
|
@st.cache_data(ttl=21600, show_spinner="Profiel ophalen van Nightscout...")
|
||||||
|
def load_profile() -> dict: # pragma: no cover
|
||||||
|
"""Gecachete profiel-fetch. Langere TTL dan load_range_data (6 uur i.p.v.
|
||||||
|
1 uur): een pompprofiel wijzigt zelden, in tegenstelling tot glucose-/
|
||||||
|
behandeldata van een lopende periode.
|
||||||
|
|
||||||
|
Dunne st.cache_data-wrapper rond al-geteste fetch_profile()/parse_profile()
|
||||||
|
— buiten scope van de unit-testdekking net als pages/*.py.
|
||||||
|
"""
|
||||||
|
raw = fetch_profile()
|
||||||
|
return parse_profile(raw)
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
BOLUS_CATEGORY_LABELS = {
|
||||||
|
"food": "Bolus (voeding)",
|
||||||
|
"correction": "Bolus (correctie)",
|
||||||
|
"smb": "SMB",
|
||||||
|
}
|
||||||
|
BOLUS_CATEGORY_COLOR_KEYS = {
|
||||||
|
"food": "bolus_food",
|
||||||
|
"correction": "bolus_correction",
|
||||||
|
"smb": "bolus_smb",
|
||||||
|
}
|
||||||
|
# Tekenvolgorde van bolus-categorieën: SMB eerst (onderop, meestal talrijker en
|
||||||
|
# kleiner), voeding/correctie erbovenop (grotere, gelabelde stippen blijven
|
||||||
|
# zichtbaar in plaats van bedolven te raken onder de SMB-stippen).
|
||||||
|
BOLUS_CATEGORY_DRAW_ORDER = ["smb", "correction", "food"]
|
||||||
|
|
||||||
|
|
||||||
|
def add_basal_area_trace(
|
||||||
|
fig: go.Figure,
|
||||||
|
basal: pd.DataFrame,
|
||||||
|
colors: dict,
|
||||||
|
*,
|
||||||
|
row: int | None = None,
|
||||||
|
secondary_y: bool = False,
|
||||||
|
x_col: str = "timestamp",
|
||||||
|
) -> None:
|
||||||
|
"""Basaal-insuline als semi-transparant stapvlak (line_shape='hv'), met alpha
|
||||||
|
zodat onderliggende data zichtbaar blijft. Verwacht kolommen 'rate' en
|
||||||
|
`x_col` (standaard 'timestamp'; de Dagoverzicht-pagina geeft hier 'hour'
|
||||||
|
aan omdat elke dag daar op een gedeelde 0-24u-as staat i.p.v. echte
|
||||||
|
datums — zie reporting.effective_basal_series). Bedoeld voor een
|
||||||
|
secundaire y-as (E/uur past niet op de mmol/L-schaal van de glucoselijn).
|
||||||
|
"""
|
||||||
|
if basal.empty:
|
||||||
|
return
|
||||||
|
kwargs: dict = {"row": row, "col": 1} if row is not None else {}
|
||||||
|
if secondary_y:
|
||||||
|
kwargs["secondary_y"] = True
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=basal[x_col],
|
||||||
|
y=basal["rate"],
|
||||||
|
mode="lines",
|
||||||
|
line={"shape": "hv", "color": colors["basal"], "width": 1},
|
||||||
|
fill="tozeroy",
|
||||||
|
fillcolor=hex_to_rgba(colors["basal"], 0.3),
|
||||||
|
opacity=0.8,
|
||||||
|
name="Basaal",
|
||||||
|
hovertemplate="%{y:.2f} E/uur<extra></extra>",
|
||||||
|
),
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def add_carb_bars_trace(
|
||||||
|
fig: go.Figure,
|
||||||
|
carbs: pd.DataFrame,
|
||||||
|
colors: dict,
|
||||||
|
*,
|
||||||
|
row: int | None = None,
|
||||||
|
secondary_y: bool = False,
|
||||||
|
x_col: str = "timestamp",
|
||||||
|
) -> None:
|
||||||
|
"""Koolhydraten als staafjes op het moment van invoer. Verwacht kolommen
|
||||||
|
'carbs' en `x_col` (zie add_basal_area_trace voor waarom dit configureerbaar
|
||||||
|
is). Zelfde secundaire as als de basaal-area (allebei geen mmol/L-grootheid),
|
||||||
|
met een eigen kleur en alpha zodat beide onderscheidbaar blijven."""
|
||||||
|
if carbs.empty:
|
||||||
|
return
|
||||||
|
kwargs: dict = {"row": row, "col": 1} if row is not None else {}
|
||||||
|
if secondary_y:
|
||||||
|
kwargs["secondary_y"] = True
|
||||||
|
fig.add_trace(
|
||||||
|
go.Bar(
|
||||||
|
x=carbs[x_col],
|
||||||
|
y=carbs["carbs"],
|
||||||
|
marker_color=colors["carbs"],
|
||||||
|
opacity=0.55,
|
||||||
|
name="Koolhydraten",
|
||||||
|
hovertemplate="%{y:.0f} g<extra></extra>",
|
||||||
|
),
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def add_bolus_marker_traces(
|
||||||
|
fig: go.Figure,
|
||||||
|
bolus: pd.DataFrame,
|
||||||
|
colors: dict,
|
||||||
|
lane_y: float,
|
||||||
|
*,
|
||||||
|
row: int | None = None,
|
||||||
|
x_col: str = "timestamp",
|
||||||
|
) -> None:
|
||||||
|
"""Eén Scatter-trace per boluscategorie (food/correction/smb), gepositioneerd
|
||||||
|
op een vaste 'lane'-hoogte op de primaire (mmol/L-)as — net als de bestaande
|
||||||
|
insuline/carbs-lanes op de Live-pagina. De hoogte zelf draagt geen
|
||||||
|
kwantitatieve betekenis; de markergrootte (geschaald naar toegediende
|
||||||
|
eenheden) en hoverwaarde wel. Voeding/correctie krijgen een tekstlabel met
|
||||||
|
de dosis; SMB's niet (te talrijk/te klein voor leesbare labels). Verwacht
|
||||||
|
kolommen 'insulin'/'category' en `x_col` (zie reporting.classify_bolus).
|
||||||
|
"""
|
||||||
|
# Datumformattering in de hover werkt alleen op een echte datetime-as; de
|
||||||
|
# Dagoverzicht-pagina geeft hier 'hour' (een kaal getal 0-24) aan, dus
|
||||||
|
# daar laten we het tijdstip weg en toont de hover alleen de dosis.
|
||||||
|
hover_prefix = "%{x|%d-%m %H:%M} · " if x_col == "timestamp" else ""
|
||||||
|
kwargs: dict = {"row": row, "col": 1} if row is not None else {}
|
||||||
|
for category in BOLUS_CATEGORY_DRAW_ORDER:
|
||||||
|
subset = bolus[bolus["category"] == category] if not bolus.empty else bolus
|
||||||
|
if subset.empty:
|
||||||
|
continue
|
||||||
|
show_label = category != "smb"
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=subset[x_col],
|
||||||
|
y=[lane_y] * len(subset),
|
||||||
|
mode="markers+text" if show_label else "markers",
|
||||||
|
marker={
|
||||||
|
"size": (subset["insulin"] * 8).clip(lower=6, upper=30),
|
||||||
|
"color": colors[BOLUS_CATEGORY_COLOR_KEYS[category]],
|
||||||
|
"opacity": 0.75,
|
||||||
|
},
|
||||||
|
text=[f"{v:.1f}E" for v in subset["insulin"]] if show_label else None,
|
||||||
|
textposition="top center",
|
||||||
|
textfont={"size": 9, "color": colors["text"]},
|
||||||
|
name=BOLUS_CATEGORY_LABELS[category],
|
||||||
|
customdata=subset["insulin"],
|
||||||
|
hovertemplate=f"{hover_prefix}%{{customdata:.2f}} E<extra></extra>",
|
||||||
|
),
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def add_target_line_trace(
|
||||||
|
fig: go.Figure, target: pd.DataFrame, colors: dict, *, row: int | None = None, x_col: str = "timestamp"
|
||||||
|
) -> None:
|
||||||
|
"""Streefglucose uit het pompprofiel als lijn op de primaire (mmol/L-)as.
|
||||||
|
Verwacht kolommen 'target' en `x_col` (zie reporting.target_glucose_series)."""
|
||||||
|
if target.empty:
|
||||||
|
return
|
||||||
|
kwargs: dict = {"row": row, "col": 1} if row is not None else {}
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=target[x_col],
|
||||||
|
y=target["target"],
|
||||||
|
mode="lines",
|
||||||
|
line={"shape": "hv", "color": colors["target"], "width": 1.5, "dash": "dashdot"},
|
||||||
|
opacity=0.9,
|
||||||
|
name="Streefwaarde (pomp)",
|
||||||
|
hovertemplate="%{y:.1f} mmol/L<extra></extra>",
|
||||||
|
),
|
||||||
|
**kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def render_completeness_warning(glucose: pd.DataFrame, start: date, end: date) -> None: # pragma: no cover
|
||||||
|
"""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, wél volledig
|
||||||
|
getest) zodat het PDF-rapport (pdf_export.py) exact dezelfde disclaimer kan
|
||||||
|
hergebruiken. Deze functie is alleen de st.warning-weergave — buiten scope
|
||||||
|
van de unit-testdekking net als pages/*.py.
|
||||||
|
"""
|
||||||
|
message = completeness_warning(glucose, start, end)
|
||||||
|
if message:
|
||||||
|
st.warning(message)
|
||||||
|
|
||||||
|
|
||||||
|
def render_event_level( # pragma: no cover
|
||||||
|
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. Pure
|
||||||
|
Streamlit-widget-weergave rond al-geteste reporting.detect_events()/
|
||||||
|
summarize_events() — buiten scope van de unit-testdekking net als
|
||||||
|
pages/*.py.
|
||||||
|
"""
|
||||||
|
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)
|
||||||
Reference in New Issue
Block a user