Compare commits
14
Commits
dev
..
d637ad39e4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d637ad39e4 | ||
|
|
5addd6a49b | ||
|
|
95f006078f | ||
|
|
4bb9251d7d | ||
|
|
6c6b175a28 | ||
|
|
c39646ceaa | ||
|
|
52c9284f85 | ||
|
|
419508dd5e | ||
|
|
689452cf4c | ||
|
|
e600d6cf7d | ||
|
|
10aa315e40 | ||
|
|
e3443e9f9f | ||
|
|
274d27c5bc | ||
|
|
f17e4f6c39 |
Vendored
-11
@@ -1,11 +0,0 @@
|
|||||||
pipeline {
|
|
||||||
agent any
|
|
||||||
|
|
||||||
stages {
|
|
||||||
stage('Do nothing') {
|
|
||||||
steps {
|
|
||||||
sh '/bin/true'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,6 @@ import streamlit as st
|
|||||||
from auth import require_auth
|
from auth import require_auth
|
||||||
from nightscout_client import NightscoutConfigError
|
from nightscout_client import NightscoutConfigError
|
||||||
from reporting import (
|
from reporting import (
|
||||||
gmi_mmol_per_mol,
|
|
||||||
gmi_percent,
|
gmi_percent,
|
||||||
percent_cv,
|
percent_cv,
|
||||||
sensor_active_percent,
|
sensor_active_percent,
|
||||||
@@ -44,7 +43,6 @@ active_pct = sensor_active_percent(glucose, start, end)
|
|||||||
|
|
||||||
mean_mmol = glucose["mmol"].mean()
|
mean_mmol = glucose["mmol"].mean()
|
||||||
gmi = gmi_percent(mean_mmol)
|
gmi = gmi_percent(mean_mmol)
|
||||||
gmi_mmol_mol = gmi_mmol_per_mol(gmi)
|
|
||||||
cv = percent_cv(glucose)
|
cv = percent_cv(glucose)
|
||||||
tir = tir_breakdown_5band(glucose)
|
tir = tir_breakdown_5band(glucose)
|
||||||
|
|
||||||
@@ -52,11 +50,7 @@ st.subheader("Kerncijfers")
|
|||||||
col1, col2, col3, col4 = st.columns(4)
|
col1, col2, col3, col4 = st.columns(4)
|
||||||
col1.metric("Sensordekking", f"{active_pct:.0f}%", help="Streefwaarde: ≥70%")
|
col1.metric("Sensordekking", f"{active_pct:.0f}%", help="Streefwaarde: ≥70%")
|
||||||
col2.metric("Gemiddelde glucose", f"{mean_mmol:.1f} mmol/L")
|
col2.metric("Gemiddelde glucose", f"{mean_mmol:.1f} mmol/L")
|
||||||
col3.metric(
|
col3.metric("Geschat HbA1c (GMI)", f"{gmi:.1f}%", help="Bergenstal et al. 2018 — geen labwaarde")
|
||||||
"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%")
|
col4.metric("Variabiliteit (%CV)", f"{cv:.0f}%", help="Streefwaarde: ≤36%")
|
||||||
|
|
||||||
st.subheader("Tijd in bereik (5 klinische banden)")
|
st.subheader("Tijd in bereik (5 klinische banden)")
|
||||||
|
|||||||
+11
-56
@@ -9,13 +9,12 @@ from reporting import (
|
|||||||
basal_stats,
|
basal_stats,
|
||||||
bolus_stats,
|
bolus_stats,
|
||||||
day_of_week_pattern,
|
day_of_week_pattern,
|
||||||
gmi_trend,
|
gmi_percent,
|
||||||
overnight_daytime_split,
|
overnight_daytime_split,
|
||||||
site_interval_stats,
|
site_interval_stats,
|
||||||
)
|
)
|
||||||
from ui_common import (
|
from ui_common import (
|
||||||
get_colors,
|
get_colors,
|
||||||
hex_to_rgba,
|
|
||||||
load_range_data,
|
load_range_data,
|
||||||
render_completeness_warning,
|
render_completeness_warning,
|
||||||
select_period_days,
|
select_period_days,
|
||||||
@@ -47,70 +46,26 @@ render_completeness_warning(glucose, start, end)
|
|||||||
colors = get_colors()
|
colors = get_colors()
|
||||||
events = classify_treatments(treatments)
|
events = classify_treatments(treatments)
|
||||||
|
|
||||||
# --- FR7: geschat HbA1c (GMI) trend ----------------------------------------
|
# --- FR7: geschat HbA1c (GMI) per maand ------------------------------------
|
||||||
st.subheader("Geschat HbA1c (GMI) trend")
|
st.subheader("Geschat HbA1c (GMI) per maand")
|
||||||
trend = gmi_trend(glucose)
|
monthly = glucose.copy()
|
||||||
|
monthly["month"] = monthly["timestamp"].dt.to_period("M").astype(str)
|
||||||
|
monthly_gmi = monthly.groupby("month")["mmol"].mean().apply(gmi_percent)
|
||||||
|
|
||||||
if len(trend) >= 2:
|
if len(monthly_gmi) >= 1:
|
||||||
fig = go.Figure()
|
fig = go.Figure(
|
||||||
fig.add_trace(
|
go.Bar(x=monthly_gmi.index, y=monthly_gmi.to_numpy(), marker_color=colors["glucose"])
|
||||||
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(
|
fig.update_layout(
|
||||||
paper_bgcolor="rgba(0,0,0,0)",
|
paper_bgcolor="rgba(0,0,0,0)",
|
||||||
plot_bgcolor="rgba(0,0,0,0)",
|
plot_bgcolor="rgba(0,0,0,0)",
|
||||||
font_color=colors["text"],
|
font_color=colors["text"],
|
||||||
height=320,
|
height=280,
|
||||||
margin={"l": 10, "r": 10, "t": 10, "b": 10},
|
margin={"l": 10, "r": 10, "t": 10, "b": 10},
|
||||||
yaxis={"title": "GMI (%)", "gridcolor": colors["grid"]},
|
yaxis={"title": "GMI (%)", "gridcolor": colors["grid"]},
|
||||||
xaxis={"title": "Datum", "gridcolor": colors["grid"]},
|
xaxis={"title": "Maand", "gridcolor": colors["grid"]},
|
||||||
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
|
|
||||||
)
|
)
|
||||||
st.plotly_chart(fig, width="stretch")
|
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.")
|
st.caption("GMI is een schatting (Bergenstal et al. 2018), geen labwaarde.")
|
||||||
|
|
||||||
# --- FR8: nacht vs. overdag --------------------------------------------------
|
# --- FR8: nacht vs. overdag --------------------------------------------------
|
||||||
|
|||||||
+1
-3
@@ -28,7 +28,6 @@ from reporting import (
|
|||||||
agp_percentile_bands,
|
agp_percentile_bands,
|
||||||
completeness_warning,
|
completeness_warning,
|
||||||
detect_events,
|
detect_events,
|
||||||
gmi_mmol_per_mol,
|
|
||||||
gmi_percent,
|
gmi_percent,
|
||||||
percent_cv,
|
percent_cv,
|
||||||
sensor_active_percent,
|
sensor_active_percent,
|
||||||
@@ -179,8 +178,7 @@ def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
|
|||||||
pdf.set_font("Helvetica", "", 11)
|
pdf.set_font("Helvetica", "", 11)
|
||||||
pdf.cell(0, 6, f"Sensordekking: {active_pct:.0f}%", **_LINE_KWARGS)
|
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"Gemiddelde glucose: {mean_mmol:.1f} mmol/L", **_LINE_KWARGS)
|
||||||
gmi = gmi_percent(mean_mmol)
|
pdf.cell(0, 6, f"Geschat HbA1c (GMI): {gmi_percent(mean_mmol):.1f}%", **_LINE_KWARGS)
|
||||||
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.cell(0, 6, f"Variabiliteit (%CV): {percent_cv(glucose):.0f}%", **_LINE_KWARGS)
|
||||||
pdf.ln(2)
|
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"Zeer laag (<3.0 mmol/L): {tir['very_low']:.0f}%", **_LINE_KWARGS)
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from itertools import pairwise
|
from itertools import pairwise
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
from nightscout_client import INSULIN_EVENT_TYPES
|
from nightscout_client import INSULIN_EVENT_TYPES
|
||||||
@@ -36,79 +35,6 @@ def gmi_percent(mean_mmol: float) -> float:
|
|||||||
return round(3.31 + 0.4311 * mean_mmol, 1)
|
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:
|
def percent_cv(glucose: pd.DataFrame) -> float:
|
||||||
"""Glucosevariabiliteit als %CV (standaarddeviatie / gemiddelde * 100)."""
|
"""Glucosevariabiliteit als %CV (standaarddeviatie / gemiddelde * 100)."""
|
||||||
if glucose.empty:
|
if glucose.empty:
|
||||||
|
|||||||
@@ -4,17 +4,13 @@ import pandas as pd
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from reporting import (
|
from reporting import (
|
||||||
GMI_TREND_COLUMNS,
|
|
||||||
agp_percentile_bands,
|
agp_percentile_bands,
|
||||||
basal_stats,
|
basal_stats,
|
||||||
bolus_stats,
|
bolus_stats,
|
||||||
completeness_warning,
|
completeness_warning,
|
||||||
daily_gmi,
|
|
||||||
day_of_week_pattern,
|
day_of_week_pattern,
|
||||||
detect_events,
|
detect_events,
|
||||||
gmi_mmol_per_mol,
|
|
||||||
gmi_percent,
|
gmi_percent,
|
||||||
gmi_trend,
|
|
||||||
minutes_per_day,
|
minutes_per_day,
|
||||||
overnight_daytime_split,
|
overnight_daytime_split,
|
||||||
percent_cv,
|
percent_cv,
|
||||||
@@ -36,63 +32,6 @@ def test_gmi_percent_matches_bergenstal_formula():
|
|||||||
assert gmi_percent(7.0) == pytest.approx(6.3, abs=0.05)
|
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():
|
def test_percent_cv_handles_empty_input():
|
||||||
empty = pd.DataFrame(columns=["timestamp", "mmol"])
|
empty = pd.DataFrame(columns=["timestamp", "mmol"])
|
||||||
assert percent_cv(empty) == 0.0
|
assert percent_cv(empty) == 0.0
|
||||||
|
|||||||
Reference in New Issue
Block a user