Author SHA1 Message Date
willemjan c4ae6fc037 test indent issue
willemjan/glucose-dashboard/pipeline/head This commit looks good
2026-08-28 21:51:40 +02:00
willemjan 11489bccdd removed secrets
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-28 21:47:39 +02:00
willemjan 53bc8a0121 fix configmap in jenkins
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-28 21:45:41 +02:00
willemjan 8dd3d5acea added secrets and env variables to openshift deployment
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-28 21:43:16 +02:00
willemjan 0fb9a0c0a2 fix oc_project
willemjan/glucose-dashboard/pipeline/head This commit looks good
2026-08-28 14:42:03 +02:00
willemjan 0017d14936 fix test issue
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-28 14:33:13 +02:00
willemjan 17279b69f1 updated test stage
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-28 14:29:49 +02:00
willemjan ae0c736ea7 updated scan stage
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-28 14:24:48 +02:00
willemjan 1f2b0d917a test
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-15 22:20:12 +02:00
willemjan 908fd6f730 req dev file removed
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 23:58:57 +02:00
willemjan c2bbc5a753 test in own container
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 23:56:28 +02:00
willemjan abf0c95bac roll back
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 23:49:47 +02:00
willemjan 76f27f674d any agent
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 23:42:45 +02:00
willemjan 3e18aadc8f updated commenting
willemjan/glucose-dashboard/pipeline/head Something is wrong with the build of this commit
2026-08-13 23:31:33 +02:00
willemjan 290022ab8e test
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 23:24:16 +02:00
willemjan e8159771de test scratch pipeline
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 22:30:37 +02:00
willemjan 3c534fec3a updated credentials Id
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-13 22:24:38 +02:00
willemjan 7c729f38ec test
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-11 01:01:30 +02:00
willemjan 164ac5e42d test openshigt
willemjan/glucose-dashboard/pipeline/head There was a failure building this commit
2026-08-11 00:28:56 +02:00
willemjan e08f269855 test jenkins
willemjan/glucose-dashboard/pipeline/head Something is wrong with the build of this commit
2026-08-10 23:19:27 +02:00
willemjan b8e01fa8c9 Show estimated HbA1c in mmol/mol (IFCC) alongside the % value
Dutch lab results conventionally report HbA1c in mmol/mol rather than
DCCT/NGSP %. Adds gmi_mmol_per_mol() using the standard IFCC conversion
(Hoelzel et al. 2004) and shows it next to the existing % value on the
Samenvatting page and in the PDF summary.

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

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

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

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

Closes gitea #20.
2026-08-01 22:52:54 +02:00
13 changed files with 563 additions and 42 deletions
+11 -3
View File
@@ -1,5 +1,12 @@
FROM python:3.12-slim
ENV HOME=/app \
PYTHONUNBUFFERED=1 \
STREAMLIT_SERVER_PORT=8501 \
STREAMLIT_SERVER_ADDRESS=0.0.0.0 \
STREAMLIT_SERVER_HEADLESS=true \
STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
WORKDIR /app
# Systeem-dependency voor de HEALTHCHECK hieronder
@@ -11,8 +18,9 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN chgrp -R 0 /app && chmod -R g=u /app
USER 1001
EXPOSE 8501
HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health || exit 1
ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
CMD ["streamlit", "run", "app.py"]
Vendored
+103
View File
@@ -0,0 +1,103 @@
pipeline {
agent {
label 'ssh-agent'
}
environment {
REGISTRY = 'gitea.zb-kw.duckdns.org'
IMAGE = "${REGISTRY}/willemjan/glucose-dashboard"
OC_SERVER = 'https://api.rm1.0a51.p1.openshiftapps.com:6443'
OC_PROJECT = 'wulsspaans-dev'
}
options {
buildDiscarder(logRotator(numToKeepStr: '20'))
timeout(time: 20, unit: 'MINUTES')
}
stages {
stage('Checkout') {
steps {
checkout scm
script {
env.TAG = sh(script: 'git rev-parse --short HEAD',
returnStdout: true).trim()
}
}
}
stage('Test') {
steps {
sh '''
pip install --break-system-packages --no-warn-script-location -q -r requirements.txt
python -m pytest -q --junitxml=report.xml
'''
}
post {
always { junit allowEmptyResults: true, testResults: 'report.xml' }
}
}
stage('Build & push image') {
steps {
withCredentials([usernamePassword(
credentialsId: 'gitea_user',
usernameVariable: 'REG_USER',
passwordVariable: 'REG_PASS')]) {
sh '''
echo "$REG_PASS" | docker login $REGISTRY -u "$REG_USER" --password-stdin
docker build -t $IMAGE:$TAG -t $IMAGE:latest .
docker push $IMAGE:$TAG
docker push $IMAGE:latest
'''
}
}
}
stage('Scan') {
steps {
sh '''
docker run --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
-v trivy-cache:/root/.cache/trivy \
aquasec/trivy:latest image \
--severity HIGH,CRITICAL \
--ignore-unfixed \
--exit-code 0 \
$IMAGE:$TAG
'''
}
}
stage('Deploy to OpenShift') {
steps {
withCredentials([string(
credentialsId: 'openshift-token',
variable: 'OC_TOKEN')]) {
sh '''
oc login --token="$OC_TOKEN" --server="$OC_SERVER"
oc project $OC_PROJECT
oc apply -f openshift/service.yaml
oc apply -f openshift/route.yaml
oc apply -f openshift/configmap.yaml
oc apply -f openshift/deployment.yaml
oc set image deployment/glucose-dashboard \
glucose-dashboard=$IMAGE:$TAG
oc rollout status deployment/glucose-dashboard --timeout=5m
'''
}
}
post {
always { sh 'oc logout || true' }
success {
sh 'echo "Deployed: $(oc get route glucose-dashboard -o jsonpath={.spec.host})" || true'
}
}
}
}
}
+20 -10
View File
@@ -176,29 +176,39 @@ def _entries_since(since: datetime, until: datetime | None = None) -> pd.DataFra
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."""
"""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=["timestamp", "eventType", "insulin", "carbs"])
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"):
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")
if "eventType" not in df.columns:
df["eventType"] = ""
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[["timestamp", "eventType", "insulin", "carbs"]]
.sort_values("timestamp")
.reset_index(drop=True)
)
return df[_TREATMENT_COLUMNS].sort_values("timestamp").reset_index(drop=True)
def fetch_entries(hours: int = 24) -> pd.DataFrame:
+6
View File
@@ -0,0 +1,6 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: glucose-dashboard-config
data:
NIGHTSCOUT_URL: "https://zb-ns.duckdns.org"
+35
View File
@@ -0,0 +1,35 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: glucose-dashboard
labels:
app: glucose-dashboard
spec:
replicas: 1
selector:
matchLabels:
app: glucose-dashboard
template:
metadata:
labels:
app: glucose-dashboard
spec:
imagePullSecrets:
- name: gitea-registry
containers:
- name: glucose-dashboard
image: PLACEHOLDER
envFrom:
- configMapRef:
name: glucose-dashboard-config
ports:
- containerPort: 8501
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { cpu: 500m, memory: 512Mi }
readinessProbe:
httpGet: { path: /_stcore/health, port: 8501 }
initialDelaySeconds: 10
livenessProbe:
httpGet: { path: /_stcore/health, port: 8501 }
initialDelaySeconds: 30
+13
View File
@@ -0,0 +1,13 @@
apiVersion: route.openshift.io/v1
kind: Route
metadata:
name: glucose-dashboard
spec:
to:
kind: Service
name: glucose-dashboard
port:
targetPort: 8501
tls:
termination: edge
insecureEdgeTerminationPolicy: Redirect
+10
View File
@@ -0,0 +1,10 @@
apiVersion: v1
kind: Service
metadata:
name: glucose-dashboard
spec:
selector:
app: glucose-dashboard
ports:
- port: 8501
targetPort: 8501
+7 -1
View File
@@ -4,6 +4,7 @@ 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,
@@ -43,6 +44,7 @@ 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)
@@ -50,7 +52,11 @@ 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}%", help="Bergenstal et al. 2018 — geen labwaarde")
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)")
+73 -20
View File
@@ -6,14 +6,16 @@ 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_percent,
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,
@@ -45,26 +47,70 @@ render_completeness_warning(glucose, start, end)
colors = get_colors()
events = classify_treatments(treatments)
# --- FR7: geschat HbA1c (GMI) per maand ------------------------------------
st.subheader("Geschat HbA1c (GMI) per maand")
monthly = glucose.copy()
monthly["month"] = monthly["timestamp"].dt.to_period("M").astype(str)
monthly_gmi = monthly.groupby("month")["mmol"].mean().apply(gmi_percent)
# --- FR7: geschat HbA1c (GMI) trend ----------------------------------------
st.subheader("Geschat HbA1c (GMI) trend")
trend = gmi_trend(glucose)
if len(monthly_gmi) >= 1:
fig = go.Figure(
go.Bar(x=monthly_gmi.index, y=monthly_gmi.to_numpy(), marker_color=colors["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=280,
height=320,
margin={"l": 10, "r": 10, "t": 10, "b": 10},
yaxis={"title": "GMI (%)", "gridcolor": colors["grid"]},
xaxis={"title": "Maand", "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 --------------------------------------------------
@@ -93,18 +139,25 @@ if not weekday_plot.empty:
)
st.plotly_chart(fig, width="stretch")
# --- FR8: bolus-insuline --------------------------------------------------
st.subheader("Bolus-insuline")
# --- FR8: insuline (basaal + bolus-uitsplitsing) ---------------------------
st.subheader("Insuline")
st.caption(
"Alleen bolusinsuline (maaltijd/correctie/combo/SMB) — basaalinsuline vereist "
"profielgegevens en is hier niet in verwerkt (zie docs/design-reporting.md)."
"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)
col1, col2 = st.columns(2)
col1.metric("Totaal bolus", f"{bolus['total_units']:.1f} E")
col2.metric("Aantal boluses", bolus["count"])
if bolus["by_type"]:
st.table({"type": list(bolus["by_type"].keys()), "eenheden": list(bolus["by_type"].values())})
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")
+3 -1
View File
@@ -28,6 +28,7 @@ from reporting import (
agp_percentile_bands,
completeness_warning,
detect_events,
gmi_mmol_per_mol,
gmi_percent,
percent_cv,
sensor_active_percent,
@@ -178,7 +179,8 @@ def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
pdf.set_font("Helvetica", "", 11)
pdf.cell(0, 6, f"Sensordekking: {active_pct:.0f}%", **_LINE_KWARGS)
pdf.cell(0, 6, f"Gemiddelde glucose: {mean_mmol:.1f} mmol/L", **_LINE_KWARGS)
pdf.cell(0, 6, f"Geschat HbA1c (GMI): {gmi_percent(mean_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)
+122 -6
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
from itertools import pairwise
import numpy as np
import pandas as pd
from nightscout_client import INSULIN_EVENT_TYPES
@@ -35,6 +36,79 @@ def gmi_percent(mean_mmol: float) -> float:
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:
@@ -330,22 +404,35 @@ def day_of_week_pattern(glucose: pd.DataFrame) -> pd.DataFrame:
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.
Let op: dit betreft alleen bolusinsuline (maaltijd/correctie/combo/SMB).
Basaalinsuline wordt hier niet in meegenomen — dat vereist profielgegevens
(zie docs/design-reporting.md, scoping-kanttekening) en levert dus geen
volledige totale-dagdosis op.
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()]
bolus = treatments[treatments["eventType"].isin(INSULIN_EVENT_TYPES) & treatments["insulin"].notna()].copy()
if bolus.empty:
return {"total_units": 0.0, "count": 0, "by_type": {}}
by_type = bolus.groupby("eventType")["insulin"].sum().round(1).to_dict()
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),
@@ -353,6 +440,35 @@ def bolus_stats(treatments: pd.DataFrame) -> dict:
}
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",
+32
View File
@@ -90,6 +90,38 @@ def test_fetch_treatments_fills_missing_columns(monkeypatch):
assert result.iloc[0]["eventType"] == "Site Change"
assert pd_isna(result.iloc[0]["insulin"])
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):
+128 -1
View File
@@ -4,12 +4,17 @@ import pandas as pd
import pytest
from reporting import (
GMI_TREND_COLUMNS,
agp_percentile_bands,
basal_stats,
bolus_stats,
completeness_warning,
daily_gmi,
day_of_week_pattern,
detect_events,
gmi_mmol_per_mol,
gmi_percent,
gmi_trend,
minutes_per_day,
overnight_daytime_split,
percent_cv,
@@ -31,6 +36,63 @@ def test_gmi_percent_matches_bergenstal_formula():
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
@@ -339,6 +401,7 @@ def test_bolus_stats_splits_by_event_type():
"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)
@@ -347,12 +410,76 @@ def test_bolus_stats_splits_by_event_type():
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"])
empty = pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs", "type"])
result = bolus_stats(empty)
assert result == {"total_units": 0.0, "count": 0, "by_type": {}}
def test_basal_stats_sums_temp_basal_rate_times_duration():
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 08:30"]),
"eventType": ["Temp Basal", "Temp Basal"],
"absolute": [1.2, 0.6],
"duration": [30, 60],
}
)
# 1.2 E/u * 0.5u + 0.6 E/u * 1u = 0.6 + 0.6 = 1.2 E over 1 dag
result = basal_stats(treatments, period_days=1)
assert result["total_units"] == pytest.approx(1.2)
assert result["avg_units_per_day"] == pytest.approx(1.2)
def test_basal_stats_ignores_non_temp_basal_rows_and_missing_fields():
treatments = pd.DataFrame(
{
"timestamp": pd.to_datetime(["2026-01-01 08:00", "2026-01-01 08:30"]),
"eventType": ["Meal Bolus", "Temp Basal"],
"absolute": [None, None],
"duration": [None, 30],
}
)
result = basal_stats(treatments, period_days=1)
assert result == {"total_units": 0.0, "avg_units_per_day": 0.0}
def test_basal_stats_handles_empty_input():
empty = pd.DataFrame(columns=["timestamp", "eventType", "absolute", "duration"])
result = basal_stats(empty, period_days=1)
assert result == {"total_units": 0.0, "avg_units_per_day": 0.0}
def test_site_interval_stats_splits_by_site_change():
glucose = _series(
[