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')}")