Compare commits
42
Commits
e600d6cf7d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7a0b94a54 | ||
|
|
95b3aff310 | ||
|
|
bd66d3dacd | ||
|
|
47050bf031 | ||
|
|
de0ecebce5 | ||
|
|
caf28046cb | ||
|
|
a4d29e85a8 | ||
|
|
7f4377329a | ||
|
|
c617f4e41b | ||
|
|
a10a4c0414 | ||
|
|
a3d89c4d21 | ||
|
|
1376101212 | ||
|
|
f2c3f97b1f | ||
|
|
d33516e2a1 | ||
|
|
c54dcf616a | ||
|
|
6004f76d76 | ||
|
|
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 |
@@ -5,4 +5,6 @@ __pycache__/
|
|||||||
.git/
|
.git/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
tests/
|
tests/
|
||||||
|
|||||||
@@ -15,3 +15,9 @@ NIGHTSCOUT_TOKEN=
|
|||||||
# het diabetesteam). Zet hier een sha256-hash, NIET het wachtwoord zelf:
|
# het diabetesteam). Zet hier een sha256-hash, NIET het wachtwoord zelf:
|
||||||
# python -c "import hashlib; print(hashlib.sha256(b'jouw-wachtwoord').hexdigest())"
|
# python -c "import hashlib; print(hashlib.sha256(b'jouw-wachtwoord').hexdigest())"
|
||||||
DASHBOARD_PASSWORD_HASH=
|
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@v3
|
||||||
|
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@v3
|
||||||
|
with:
|
||||||
|
name: coverage-report
|
||||||
- name: SonarQube scan
|
- name: SonarQube scan
|
||||||
uses: sonarsource/sonarqube-scan-action@v6
|
uses: sonarsource/sonarqube-scan-action@v6
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -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'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,8 @@ klinische rapportagepagina's (zie `docs/requirements-reporting.md` en
|
|||||||
diabetesteam, dus elke pagina zit achter een wachtwoord). `app.py` laadt
|
diabetesteam, dus elke pagina zit achter een wachtwoord). `app.py` laadt
|
||||||
`.env` zelf in (via `python-dotenv`), dus dit werkt hetzelfde onder
|
`.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
|
PowerShell, cmd of bash — je hoeft de variabelen niet zelf in je shell te
|
||||||
zetten.
|
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
|
||||||
@@ -40,3 +41,12 @@ klinische rapportagepagina's (zie `docs/requirements-reporting.md` en
|
|||||||
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
|
||||||
|
```
|
||||||
|
|||||||
@@ -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 |
@@ -17,13 +17,18 @@ import os
|
|||||||
import streamlit as st
|
import streamlit as st
|
||||||
|
|
||||||
|
|
||||||
def require_auth() -> None:
|
def require_auth() -> None: # pragma: no cover
|
||||||
"""Blokkeer de pagina totdat het juiste wachtwoord is ingevoerd.
|
"""Blokkeer de pagina totdat het juiste wachtwoord is ingevoerd.
|
||||||
|
|
||||||
Slaat de status op in st.session_state zodat dit maar één keer per
|
Slaat de status op in st.session_state zodat dit maar één keer per
|
||||||
browsersessie hoeft. Moet als eerste statement van elke pagina aangeroepen
|
browsersessie hoeft. Moet als eerste statement van elke pagina aangeroepen
|
||||||
worden (app.py en elk bestand in pages/), omdat Streamlit iedere pagina
|
worden (app.py en elk bestand in pages/), omdat Streamlit iedere pagina
|
||||||
als los script uitvoert.
|
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"):
|
if st.session_state.get("authenticated"):
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -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).
|
||||||
@@ -1,6 +1,11 @@
|
|||||||
|
> **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
|
# Requirements: oref0-autotune profile tuning
|
||||||
|
|
||||||
Status: **draft — for review and editing**
|
Status: **final**
|
||||||
Owner: willemjan
|
Owner: willemjan
|
||||||
Related: [requirements-reporting.md](requirements-reporting.md) (separate feature, same Nightscout data source)
|
Related: [requirements-reporting.md](requirements-reporting.md) (separate feature, same Nightscout data source)
|
||||||
|
|
||||||
@@ -12,16 +17,16 @@ 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
|
AAPS 3.3 regardless. Previously, the user ran a hosted tool (inspired by
|
||||||
`MarkMpn/AutotuneWeb`, now archived/discontinued) that analyzed Nightscout data
|
`MarkMpn/AutotuneWeb`, now archived/discontinued) that analyzed Nightscout data
|
||||||
with `oref0-autotune` and proposed a new pump profile, which was then manually
|
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."
|
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
|
This feature builds a guided, human-in-the-loop workflow: trigger an
|
||||||
oref0-autotune analysis from a dashboard, review the proposed profile against
|
oref0-autotune analysis from an internally self hosted application, review the proposed profile against
|
||||||
the current one with the underlying estimations visible, selectively
|
the current one with the underlying estimations visible, selectively
|
||||||
accept/adjust values, and stage the result in Nightscout for manual activation.
|
accept/adjust values, and stage the result in Nightscout for manual activation.
|
||||||
|
|
||||||
The user has two LXC containers on Proxmox from earlier experimentation —
|
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) —
|
`autotune` (VMID 102, 192.168.2.13) and `oref0` (VMID 107, 192.168.2.14) —
|
||||||
currently stopped, of unknown/half-remembered working state.
|
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
|
## 2. Scope
|
||||||
|
|
||||||
@@ -29,20 +34,17 @@ currently stopped, of unknown/half-remembered working state.
|
|||||||
- Booting and inspecting the two existing LXCs to determine (or establish) a
|
- Booting and inspecting the two existing LXCs to determine (or establish) a
|
||||||
working oref0-autotune setup.
|
working oref0-autotune setup.
|
||||||
- A small HTTP microservice on that LXC that runs oref0-autotune against the
|
- A small HTTP microservice on that LXC that runs oref0-autotune against the
|
||||||
user's Nightscout data on demand.
|
user's Nightscout data on demand. Either one of the two existing LXCs or a new one.
|
||||||
- A **separate** Streamlit app/service (own deployment, own CI/CD pipeline) that
|
- A **separate** app/service (own deployment, own CI/CD pipeline) that
|
||||||
triggers the analysis, displays old-vs-new profile comparisons with
|
triggers the analysis, displays old-vs-new profile comparisons with
|
||||||
estimation detail, lets the user selectively adjust proposed values, and
|
estimation detail, lets the user selectively adjust proposed values, and
|
||||||
stages the result in Nightscout.
|
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):**
|
**Out of scope (this iteration):**
|
||||||
- Automatically activating the new profile in AndroidAPS (creating a
|
|
||||||
`"Profile Switch"` treatment) — the dashboard stages the profile only; the
|
|
||||||
user activates it manually. This may become an opt-in "phase 2" once trust is
|
|
||||||
established (see §8).
|
|
||||||
- Any change to AAPS settings or on-device configuration.
|
- Any change to AAPS settings or on-device configuration.
|
||||||
- Continuous/scheduled autotune runs — this is a manually triggered, on-demand
|
|
||||||
analysis, not a nightly automated loop.
|
|
||||||
|
|
||||||
## 3. Architecture decisions (made during spec review)
|
## 3. Architecture decisions (made during spec review)
|
||||||
|
|
||||||
@@ -51,13 +53,12 @@ currently stopped, of unknown/half-remembered working state.
|
|||||||
run or bundling autotune into the dashboard's own container. The dashboard
|
run or bundling autotune into the dashboard's own container. The dashboard
|
||||||
calls it over HTTP and polls for job completion.
|
calls it over HTTP and polls for job completion.
|
||||||
2. **Profile push safety**: **stage-only**. The service writes a new named
|
2. **Profile push safety**: **stage-only**. The service writes a new named
|
||||||
profile into the Nightscout profile store but does **not** create a
|
profile into the Nightscout profile store and does create a
|
||||||
`"Profile Switch"` treatment — final activation stays a deliberate manual
|
`"Profile Switch"` treatment when the user selected that option — final activation stays a manual
|
||||||
step in AAPS or the Nightscout UI. This matters because AndroidAPS applies
|
step in AAPS when the option is not selected. This matters because AndroidAPS applies
|
||||||
profiles via Profile Switch treatments (gated behind an explicit "accept
|
profiles via Profile Switch treatments (gated behind an explicit "accept
|
||||||
profile switch from Nightscout" AAPS setting), not by simply reading
|
profile switch from Nightscout" AAPS setting), not by simply reading
|
||||||
`profile.json` — so "stage-only" is a real, meaningful safety boundary, not
|
`profile.json`.
|
||||||
just a formality.
|
|
||||||
3. **Deployment**: a separate app/service from `glucose-dashboard`, with its own
|
3. **Deployment**: a separate app/service from `glucose-dashboard`, with its own
|
||||||
repo-or-directory, Dockerfile, and Gitea CI/CD pipeline — isolating
|
repo-or-directory, Dockerfile, and Gitea CI/CD pipeline — isolating
|
||||||
write-capable, dosing-adjacent code from the read-only dashboard.
|
write-capable, dosing-adjacent code from the read-only dashboard.
|
||||||
@@ -73,6 +74,60 @@ Document findings (what's there, what's missing, what needs rebuilding).
|
|||||||
*Acceptance:* a clear decision on which LXC hosts the microservice, and what
|
*Acceptance:* a clear decision on which LXC hosts the microservice, and what
|
||||||
(if anything) needs to be installed/fixed there before FR2 can start.
|
(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
|
### FR2 — Autotune HTTP microservice
|
||||||
A small HTTP API (exact framework TBD during design — e.g. Flask/FastAPI
|
A small HTTP API (exact framework TBD during design — e.g. Flask/FastAPI
|
||||||
wrapping a Docker-based oref0-autotune image) exposing at minimum:
|
wrapping a Docker-based oref0-autotune image) exposing at minimum:
|
||||||
@@ -81,15 +136,17 @@ wrapping a Docker-based oref0-autotune image) exposing at minimum:
|
|||||||
- `GET /analyze/{job_id}` — status (`pending`/`running`/`done`/`failed`) and,
|
- `GET /analyze/{job_id}` — status (`pending`/`running`/`done`/`failed`) and,
|
||||||
once done, the recommended profile JSON plus the estimation/recommendation
|
once done, the recommended profile JSON plus the estimation/recommendation
|
||||||
detail (per-hour deviations, the autotune log).
|
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
|
*Acceptance:* a manual `curl` against the running service, pointed at the
|
||||||
user's real Nightscout instance, returns a plausible recommended profile within
|
user's real Nightscout instance, returns a plausible recommended profile within
|
||||||
a reasonable time (minutes, not seconds — oref0-autotune is not instant).
|
a reasonable time (minutes, not seconds — oref0-autotune is not instant).
|
||||||
|
|
||||||
### FR3 — Trigger analysis from the dashboard
|
### FR3 — Trigger analysis from the dashboard
|
||||||
A new Streamlit app page where the user picks a date range (and confirms which
|
A new app where the user picks a date range and selects a
|
||||||
current profile to tune from, fetched live from Nightscout), starts the
|
current profile to tune from (fetched live from Nightscout), starts the
|
||||||
analysis, and sees progress while the microservice job runs (via polling).
|
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
|
*Acceptance:* starting an analysis with bad/unreachable Nightscout credentials
|
||||||
fails with a clear error rather than hanging silently.
|
fails with a clear error rather than hanging silently.
|
||||||
@@ -109,6 +166,7 @@ Per time-slot controls (accept/reject each proposed basal/ISF/CR change
|
|||||||
individually) plus editable numeric fields so the user can fine-tune any
|
individually) plus editable numeric fields so the user can fine-tune any
|
||||||
accepted value before staging — matching the user's explicit request to
|
accepted value before staging — matching the user's explicit request to
|
||||||
"select parts of the proposed profile and still adjust the values a bit."
|
"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
|
*Acceptance:* rejecting a slot keeps the current value unchanged in the
|
||||||
staged profile; editing an accepted value's number is reflected in what
|
staged profile; editing an accepted value's number is reflected in what
|
||||||
@@ -117,7 +175,7 @@ actually gets sent to Nightscout.
|
|||||||
### FR6 — Stage to Nightscout
|
### FR6 — Stage to Nightscout
|
||||||
Write the resulting merged profile (accepted + manually adjusted values) as a
|
Write the resulting merged profile (accepted + manually adjusted values) as a
|
||||||
new named profile in the Nightscout profile store (e.g. `"Autotune
|
new named profile in the Nightscout profile store (e.g. `"Autotune
|
||||||
YYYY-MM-DD"`) via a new POST to `/api/v1/profile`, without creating a Profile
|
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
|
Switch treatment. After staging, show clear instructions for manual activation
|
||||||
in AAPS (or the Nightscout UI).
|
in AAPS (or the Nightscout UI).
|
||||||
|
|
||||||
@@ -140,6 +198,11 @@ separate store — **decide during design**.
|
|||||||
- Require an explicit confirmation step (e.g. a review summary + confirmation
|
- Require an explicit confirmation step (e.g. a review summary + confirmation
|
||||||
checkbox) before the FR6 write happens — no silent/implicit staging.
|
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
|
## 5. Non-functional requirements
|
||||||
|
|
||||||
- **NFR1 — Isolation**: separate repository-or-directory, Dockerfile, and Gitea
|
- **NFR1 — Isolation**: separate repository-or-directory, Dockerfile, and Gitea
|
||||||
@@ -156,10 +219,11 @@ separate store — **decide during design**.
|
|||||||
existing `monkeypatch`-on-`requests` pattern from `glucose-dashboard`'s test
|
existing `monkeypatch`-on-`requests` pattern from `glucose-dashboard`'s test
|
||||||
suite.
|
suite.
|
||||||
- **NFR4 — CI/CD gating**: given this pipeline can end in a write to a real
|
- **NFR4 — CI/CD gating**: given this pipeline can end in a write to a real
|
||||||
medical data store, consider (during design) adding a `pull_request` trigger
|
medical data store, add a `pull_request` trigger
|
||||||
for the test/lint job so changes are validated *before* merge, not only
|
for the test/lint job so changes are validated *before* merge, not only
|
||||||
after — the current `glucose-dashboard` pipeline only triggers on `push` to
|
after — the current `glucose-dashboard` pipeline only triggers on `push` to
|
||||||
`main`.
|
`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
|
## 6. Data requirements
|
||||||
|
|
||||||
@@ -187,16 +251,16 @@ separate store — **decide during design**.
|
|||||||
|
|
||||||
## 8. Open questions for the user's edit pass
|
## 8. Open questions for the user's edit pass
|
||||||
|
|
||||||
1. Which LXC (102 or 107) ends up hosting the service, once FR1 is done?
|
1. ~~Which LXC (102 or 107 or new) ends up hosting the service, once FR1 is
|
||||||
2. Which autotune Docker image to standardize on —
|
done?~~ **Resolved (FR1 complete, see below): LXC 102 (`autotune`).**
|
||||||
`p5nbTgip0r/autotune-docker`, `houthacker42/nightscout-autotune`, or
|
2. ~~Which autotune Docker image to standardize on?~~ **Resolved: the image
|
||||||
building directly from the `oref0` npm package? (Design-phase decision,
|
already installed on LXC 102 —
|
||||||
informed by FR1's findings.)
|
`ghcr.io/houthacker/nightscout-autotune:latest`.** See findings below.
|
||||||
3. Should automatic Profile Switch activation become an opt-in "phase 2" later,
|
3. Should automatic Profile Switch activation become an opt-in "phase 2" later,
|
||||||
once you've built trust in the recommendations — or should manual
|
once you've built trust in the recommendations — or should manual
|
||||||
activation remain permanent policy regardless of trust?
|
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
|
4. FR7 (audit/history) — is reusing Nightscout's own profile-document history
|
||||||
sufficient, or do you want a dedicated log outside Nightscout?
|
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
|
5. Confirm the separate write-scoped Nightscout token is something you're
|
||||||
comfortable creating/managing (NFR2) — this is a manual one-time setup step
|
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.
|
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.
|
||||||
|
|||||||
+157
-29
@@ -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,15 +107,62 @@ def _get(path: str, params: dict) -> list:
|
|||||||
return response.json()
|
return response.json()
|
||||||
|
|
||||||
|
|
||||||
def _entries_since(since: datetime, count: int, until: datetime | None = None) -> pd.DataFrame:
|
def _format_cursor(cursor_dt: datetime, cursor_field: str) -> int | str:
|
||||||
"""Haal entries op sinds `since` (en optioneel tot `until`), lokaal gefilterd.
|
"""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"
|
||||||
|
|
||||||
Nightscout geeft resultaten terug in aflopende volgorde; vraag ruim genoeg
|
|
||||||
entries op (CGM meet doorgaans elke 5 min) en filter lokaal op tijd. Dit is
|
def _parse_item_time(item: dict, cursor_field: str) -> datetime | None:
|
||||||
robuuster dan server-side find[]-query's, die niet op elke Nightscout-versie
|
"""Lees het tijdstip van een document uit het veld waar dit endpoint op filtert."""
|
||||||
identiek werken.
|
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).
|
||||||
"""
|
"""
|
||||||
data = _get("/api/v1/entries/sgv.json", {"count": count})
|
cursor_dt = until if until is not None else datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
results: list = []
|
||||||
|
for _ in range(_MAX_PAGES):
|
||||||
|
params = {"count": _PAGE_SIZE, f"find[{cursor_field}][$lte]": _format_cursor(cursor_dt, cursor_field)}
|
||||||
|
page = _get(path, params)
|
||||||
|
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"])
|
||||||
@@ -97,29 +176,39 @@ def _entries_since(since: datetime, count: int, until: datetime | None = None) -
|
|||||||
return df[["timestamp", "mmol"]].sort_values("timestamp").reset_index(drop=True)
|
return df[["timestamp", "mmol"]].sort_values("timestamp").reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
def _treatments_since(since: datetime, count: int, until: datetime | None = None) -> pd.DataFrame:
|
_TREATMENT_COLUMNS = ["timestamp", "eventType", "insulin", "carbs", "type", "absolute", "duration"]
|
||||||
"""Haal treatments op sinds `since` (en optioneel tot `until`), lokaal gefilterd."""
|
|
||||||
data = _get("/api/v1/treatments.json", {"count": count})
|
|
||||||
|
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:
|
if not data:
|
||||||
return pd.DataFrame(columns=["timestamp", "eventType", "insulin", "carbs"])
|
return pd.DataFrame(columns=_TREATMENT_COLUMNS)
|
||||||
|
|
||||||
df = pd.DataFrame(data)
|
df = pd.DataFrame(data)
|
||||||
df["timestamp"] = pd.to_datetime(df["created_at"], utc=True).dt.tz_localize(None)
|
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:
|
if col not in df.columns:
|
||||||
df[col] = pd.NA
|
df[col] = pd.NA
|
||||||
df[col] = pd.to_numeric(df[col], errors="coerce")
|
df[col] = pd.to_numeric(df[col], errors="coerce")
|
||||||
if "eventType" not in df.columns:
|
for col in ("eventType", "type"):
|
||||||
df["eventType"] = ""
|
if col not in df.columns:
|
||||||
|
df[col] = ""
|
||||||
|
df[col] = df[col].fillna("")
|
||||||
df = df[df["timestamp"] >= since.replace(tzinfo=None)]
|
df = df[df["timestamp"] >= since.replace(tzinfo=None)]
|
||||||
if until is not None:
|
if until is not None:
|
||||||
df = df[df["timestamp"] <= until.replace(tzinfo=None)]
|
df = df[df["timestamp"] <= until.replace(tzinfo=None)]
|
||||||
return (
|
return df[_TREATMENT_COLUMNS].sort_values("timestamp").reset_index(drop=True)
|
||||||
df[["timestamp", "eventType", "insulin", "carbs"]]
|
|
||||||
.sort_values("timestamp")
|
|
||||||
.reset_index(drop=True)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_entries(hours: int = 24) -> pd.DataFrame:
|
def fetch_entries(hours: int = 24) -> pd.DataFrame:
|
||||||
@@ -129,8 +218,7 @@ def fetch_entries(hours: int = 24) -> pd.DataFrame:
|
|||||||
gesorteerd op tijd.
|
gesorteerd op tijd.
|
||||||
"""
|
"""
|
||||||
since = datetime.now(timezone.utc) - timedelta(hours=hours)
|
since = datetime.now(timezone.utc) - timedelta(hours=hours)
|
||||||
count = max(300, hours * 15)
|
return _entries_since(since)
|
||||||
return _entries_since(since, count)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_treatments(hours: int = 24) -> pd.DataFrame:
|
def fetch_treatments(hours: int = 24) -> pd.DataFrame:
|
||||||
@@ -141,8 +229,7 @@ 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)
|
||||||
return _treatments_since(since, count)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_entries_range(start_date: date, end_date: date) -> pd.DataFrame:
|
def fetch_entries_range(start_date: date, end_date: date) -> pd.DataFrame:
|
||||||
@@ -154,9 +241,7 @@ def fetch_entries_range(start_date: date, end_date: date) -> pd.DataFrame:
|
|||||||
"""
|
"""
|
||||||
since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
|
since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
|
||||||
until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
|
until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
|
||||||
days = (end_date - start_date).days + 1
|
return _entries_since(since, until)
|
||||||
count = min(days * 300, 100_000) # ruime marge boven 5-min-interval
|
|
||||||
return _entries_since(since, count, until)
|
|
||||||
|
|
||||||
|
|
||||||
def fetch_treatments_range(start_date: date, end_date: date) -> pd.DataFrame:
|
def fetch_treatments_range(start_date: date, end_date: date) -> pd.DataFrame:
|
||||||
@@ -166,6 +251,49 @@ def fetch_treatments_range(start_date: date, end_date: date) -> pd.DataFrame:
|
|||||||
"""
|
"""
|
||||||
since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
|
since = datetime.combine(start_date, time.min, tzinfo=timezone.utc)
|
||||||
until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
|
until = datetime.combine(end_date, time.max, tzinfo=timezone.utc)
|
||||||
days = (end_date - start_date).days + 1
|
return _treatments_since(since, until)
|
||||||
count = min(days * 50, 50_000)
|
|
||||||
return _treatments_since(since, count, until)
|
|
||||||
|
def fetch_entries_for_day(day: date) -> pd.DataFrame:
|
||||||
|
"""Haal glucosemetingen op voor precies één kalenderdag.
|
||||||
|
|
||||||
|
Dunne wrapper om fetch_entries_range() met start=end=day, voor de
|
||||||
|
dag-navigatie op de Dagoverzicht-pagina: laadt alleen de geselecteerde
|
||||||
|
dag in plaats van een hele periode, zodat het wisselen tussen dagen snel
|
||||||
|
blijft.
|
||||||
|
"""
|
||||||
|
return fetch_entries_range(day, day)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_treatments_for_day(day: date, lookback_hours: int = 6) -> pd.DataFrame:
|
||||||
|
"""Haal behandelingen op voor één kalenderdag, met een lookback-marge vóór middernacht.
|
||||||
|
|
||||||
|
reporting.effective_basal_series() heeft de starttijd van een Temp Basal
|
||||||
|
nodig om de basaalsnelheid vroeg in de dag correct te berekenen — ook als
|
||||||
|
die temp basal al vóór middernacht is gestart en doorloopt. Zonder deze
|
||||||
|
marge zou de eerste uren van elke los opgevraagde dag ten onrechte het
|
||||||
|
profieltempo tonen in plaats van een nog actieve temp basal. 6 uur ligt
|
||||||
|
ruim boven de gebruikelijke temp-basal-duur in gesloten-lus-modus
|
||||||
|
(doorgaans 30-60 minuten).
|
||||||
|
"""
|
||||||
|
since = datetime.combine(day, time.min, tzinfo=timezone.utc) - timedelta(hours=lookback_hours)
|
||||||
|
until = datetime.combine(day, 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:
|
||||||
|
return {}
|
||||||
|
return data[0]
|
||||||
|
|||||||
+78
-31
@@ -1,6 +1,8 @@
|
|||||||
|
import pandas as pd
|
||||||
import plotly.graph_objects as go
|
import plotly.graph_objects as go
|
||||||
import requests
|
import requests
|
||||||
import streamlit as st
|
import streamlit as st
|
||||||
|
from plotly.subplots import make_subplots
|
||||||
|
|
||||||
from auth import require_auth
|
from auth import require_auth
|
||||||
from data_processing import (
|
from data_processing import (
|
||||||
@@ -10,7 +12,15 @@ from data_processing import (
|
|||||||
summarize_time_in_range,
|
summarize_time_in_range,
|
||||||
)
|
)
|
||||||
from nightscout_client import NightscoutConfigError, fetch_entries, fetch_treatments
|
from nightscout_client import NightscoutConfigError, fetch_entries, fetch_treatments
|
||||||
from ui_common import MMOL_HOVERTEMPLATE, get_colors
|
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")
|
st.set_page_config(page_title="Glucose dashboard — Live", page_icon="📊", layout="wide")
|
||||||
require_auth()
|
require_auth()
|
||||||
@@ -27,7 +37,28 @@ def load_nightscout_data(hours: int):
|
|||||||
return glucose, treatments
|
return glucose, treatments
|
||||||
|
|
||||||
|
|
||||||
def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -> go.Figure:
|
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_min = min(glucose["mmol"].min(), TARGET_LOW)
|
||||||
glucose_max = max(glucose["mmol"].max(), TARGET_HIGH)
|
glucose_max = max(glucose["mmol"].max(), TARGET_HIGH)
|
||||||
y_top = glucose_max + 1.0
|
y_top = glucose_max + 1.0
|
||||||
@@ -36,7 +67,7 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
insulin_lane_y = lane_base + 1.5
|
insulin_lane_y = lane_base + 1.5
|
||||||
carbs_lane_y = lane_base + 0.7
|
carbs_lane_y = lane_base + 0.7
|
||||||
|
|
||||||
fig = go.Figure()
|
fig = make_subplots(specs=[[{"secondary_y": True}]])
|
||||||
|
|
||||||
# Streefbereik als achtergrondband, geen losse legenda-entry nodig.
|
# Streefbereik als achtergrondband, geen losse legenda-entry nodig.
|
||||||
fig.add_hrect(
|
fig.add_hrect(
|
||||||
@@ -45,8 +76,13 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
fillcolor=colors["band"],
|
fillcolor=colors["band"],
|
||||||
line_width=0,
|
line_width=0,
|
||||||
layer="below",
|
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(
|
fig.add_trace(
|
||||||
go.Scatter(
|
go.Scatter(
|
||||||
x=glucose["timestamp"],
|
x=glucose["timestamp"],
|
||||||
@@ -55,7 +91,9 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
name="Glucose",
|
name="Glucose",
|
||||||
line={"color": colors["glucose"], "width": 2, "shape": "spline"},
|
line={"color": colors["glucose"], "width": 2, "shape": "spline"},
|
||||||
hovertemplate=MMOL_HOVERTEMPLATE,
|
hovertemplate=MMOL_HOVERTEMPLATE,
|
||||||
)
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
)
|
)
|
||||||
|
|
||||||
low_points = glucose[glucose["mmol"] < TARGET_LOW]
|
low_points = glucose[glucose["mmol"] < TARGET_LOW]
|
||||||
@@ -69,7 +107,9 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
name=f"Laag (<{TARGET_LOW})",
|
name=f"Laag (<{TARGET_LOW})",
|
||||||
marker={"color": colors["low"], "size": 6},
|
marker={"color": colors["low"], "size": 6},
|
||||||
hovertemplate=MMOL_HOVERTEMPLATE,
|
hovertemplate=MMOL_HOVERTEMPLATE,
|
||||||
)
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
)
|
)
|
||||||
if not high_points.empty:
|
if not high_points.empty:
|
||||||
fig.add_trace(
|
fig.add_trace(
|
||||||
@@ -80,21 +120,12 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
name=f"Hoog (>{TARGET_HIGH})",
|
name=f"Hoog (>{TARGET_HIGH})",
|
||||||
marker={"color": colors["high"], "size": 6},
|
marker={"color": colors["high"], "size": 6},
|
||||||
hovertemplate=MMOL_HOVERTEMPLATE,
|
hovertemplate=MMOL_HOVERTEMPLATE,
|
||||||
)
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not insulin.empty:
|
add_bolus_marker_traces(fig, bolus, colors, insulin_lane_y, row=1)
|
||||||
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:
|
if not carbs.empty:
|
||||||
fig.add_trace(
|
fig.add_trace(
|
||||||
@@ -106,14 +137,16 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
marker={"color": colors["carbs"], "size": 10, "symbol": "circle"},
|
marker={"color": colors["carbs"], "size": 10, "symbol": "circle"},
|
||||||
customdata=carbs["carbs"],
|
customdata=carbs["carbs"],
|
||||||
hovertemplate="%{x|%d-%m %H:%M} · %{customdata:.0f} g<extra></extra>",
|
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
|
# Let op: annotation_text/-position via add_vline() zelf triggert een bug
|
||||||
# in plotly's shapeannotation-helper met pandas Timestamp-x-waarden, dus
|
# in plotly's shapeannotation-helper met pandas Timestamp-x-waarden, dus
|
||||||
# de lijn en het label worden hier los toegevoegd.
|
# de lijn en het label worden hier los toegevoegd.
|
||||||
for _, row in site_changes.iterrows():
|
for _, row in site_changes.iterrows():
|
||||||
fig.add_vline(x=row["timestamp"], line_dash="dot", line_color=colors["muted"], opacity=0.6)
|
fig.add_vline(x=row["timestamp"], line_dash="dot", line_color=colors["muted"], opacity=0.6, row=1, col=1)
|
||||||
fig.add_annotation(
|
fig.add_annotation(
|
||||||
x=row["timestamp"],
|
x=row["timestamp"],
|
||||||
y=y_top,
|
y=y_top,
|
||||||
@@ -121,9 +154,11 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
text="Pomp",
|
text="Pomp",
|
||||||
showarrow=False,
|
showarrow=False,
|
||||||
font={"color": colors["muted"], "size": 10},
|
font={"color": colors["muted"], "size": 10},
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
)
|
)
|
||||||
for _, row in sensor_changes.iterrows():
|
for _, row in sensor_changes.iterrows():
|
||||||
fig.add_vline(x=row["timestamp"], line_dash="dash", line_color=colors["muted"], opacity=0.6)
|
fig.add_vline(x=row["timestamp"], line_dash="dash", line_color=colors["muted"], opacity=0.6, row=1, col=1)
|
||||||
fig.add_annotation(
|
fig.add_annotation(
|
||||||
x=row["timestamp"],
|
x=row["timestamp"],
|
||||||
y=y_top,
|
y=y_top,
|
||||||
@@ -131,6 +166,8 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
text="Sensor",
|
text="Sensor",
|
||||||
showarrow=False,
|
showarrow=False,
|
||||||
font={"color": colors["muted"], "size": 10},
|
font={"color": colors["muted"], "size": 10},
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
)
|
)
|
||||||
|
|
||||||
fig.update_layout(
|
fig.update_layout(
|
||||||
@@ -140,14 +177,18 @@ def build_chart(glucose, insulin, carbs, site_changes, sensor_changes, colors) -
|
|||||||
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
|
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
|
||||||
margin={"l": 10, "r": 10, "t": 10, "b": 10},
|
margin={"l": 10, "r": 10, "t": 10, "b": 10},
|
||||||
height=480,
|
height=480,
|
||||||
yaxis={
|
|
||||||
"title": "mmol/L",
|
|
||||||
"range": [y_bottom, y_top],
|
|
||||||
"gridcolor": colors["grid"],
|
|
||||||
"zeroline": False,
|
|
||||||
},
|
|
||||||
xaxis={"gridcolor": colors["grid"]},
|
|
||||||
)
|
)
|
||||||
|
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
|
return fig
|
||||||
|
|
||||||
|
|
||||||
@@ -160,6 +201,7 @@ with st.sidebar:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
glucose, treatments = load_nightscout_data(hours)
|
glucose, treatments = load_nightscout_data(hours)
|
||||||
|
profile = load_profile()
|
||||||
except NightscoutConfigError as exc:
|
except NightscoutConfigError as exc:
|
||||||
st.error(str(exc))
|
st.error(str(exc))
|
||||||
st.stop()
|
st.stop()
|
||||||
@@ -172,7 +214,9 @@ if glucose.empty:
|
|||||||
st.stop()
|
st.stop()
|
||||||
|
|
||||||
events = classify_treatments(treatments)
|
events = classify_treatments(treatments)
|
||||||
|
bolus = classify_bolus(treatments)
|
||||||
tir = summarize_time_in_range(glucose)
|
tir = summarize_time_in_range(glucose)
|
||||||
|
basal, target = _basal_and_target_series(profile, treatments, glucose["timestamp"].min(), glucose["timestamp"].max())
|
||||||
|
|
||||||
latest = glucose.iloc[-1]
|
latest = glucose.iloc[-1]
|
||||||
previous = glucose.iloc[-2] if len(glucose) > 1 else None
|
previous = glucose.iloc[-2] if len(glucose) > 1 else None
|
||||||
@@ -192,14 +236,17 @@ colors = get_colors()
|
|||||||
|
|
||||||
fig = build_chart(
|
fig = build_chart(
|
||||||
glucose,
|
glucose,
|
||||||
events["insulin"],
|
bolus,
|
||||||
events["carbs"],
|
events["carbs"],
|
||||||
|
basal,
|
||||||
|
target,
|
||||||
events["site_changes"],
|
events["site_changes"],
|
||||||
events["sensor_changes"],
|
events["sensor_changes"],
|
||||||
colors,
|
colors,
|
||||||
)
|
)
|
||||||
st.plotly_chart(fig, width="stretch")
|
st.plotly_chart(fig, width="stretch")
|
||||||
st.caption(
|
st.caption(
|
||||||
"Driehoekjes = insuline · cirkels = koolhydraten · stippellijn = pompwissel · "
|
"Stippen = bolusinsuline (voeding/correctie/SMB, grootte naar dosis) · cirkels = koolhydraten · "
|
||||||
"streepjeslijn = sensorwissel"
|
"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,208 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
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 (
|
||||||
|
BOLUS_CATEGORY_SMB,
|
||||||
|
classify_bolus,
|
||||||
|
daily_stats,
|
||||||
|
effective_basal_series,
|
||||||
|
target_glucose_series,
|
||||||
|
)
|
||||||
|
from ui_common import (
|
||||||
|
MMOL_HOVERTEMPLATE,
|
||||||
|
add_basal_area_trace,
|
||||||
|
add_bolus_marker_traces,
|
||||||
|
add_carb_bars_trace,
|
||||||
|
add_target_line_trace,
|
||||||
|
add_threshold_lines,
|
||||||
|
get_colors,
|
||||||
|
load_day_data,
|
||||||
|
load_profile,
|
||||||
|
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 dag per keer: boven glucose met koolhydraten/bolus-overlay, onder basaal "
|
||||||
|
"en SMB — apart gehouden omdat één gecombineerde grafiek te veel informatie bevatte."
|
||||||
|
)
|
||||||
|
|
||||||
|
# De periode-knop bepaalt alleen het navigeerbare venster (hoe ver terug je kunt
|
||||||
|
# bladeren), niet welke data wordt opgehaald — dat gebeurt hieronder voor precies
|
||||||
|
# de geselecteerde dag (load_day_data), zodat het wisselen tussen dagen snel blijft.
|
||||||
|
window_start, window_end, days = select_period_days(default_label="14 dagen")
|
||||||
|
|
||||||
|
state_key = "dagoverzicht_selected_day"
|
||||||
|
if state_key not in st.session_state:
|
||||||
|
st.session_state[state_key] = window_end
|
||||||
|
if not (window_start <= st.session_state[state_key] <= window_end):
|
||||||
|
st.session_state[state_key] = window_end
|
||||||
|
|
||||||
|
selected_day = st.session_state[state_key]
|
||||||
|
|
||||||
|
col_prev, col_date, col_next = st.columns([1, 3, 1])
|
||||||
|
with col_prev:
|
||||||
|
if st.button("← Vorige dag", disabled=selected_day <= window_start, width="stretch"):
|
||||||
|
selected_day = selected_day - timedelta(days=1)
|
||||||
|
st.session_state[state_key] = selected_day
|
||||||
|
with col_next:
|
||||||
|
if st.button("Volgende dag →", disabled=selected_day >= window_end, width="stretch"):
|
||||||
|
selected_day = selected_day + timedelta(days=1)
|
||||||
|
st.session_state[state_key] = selected_day
|
||||||
|
with col_date:
|
||||||
|
date_options = [window_end - timedelta(days=i) for i in range(days)]
|
||||||
|
chosen = st.selectbox(
|
||||||
|
"Datum",
|
||||||
|
options=date_options,
|
||||||
|
index=date_options.index(selected_day),
|
||||||
|
format_func=lambda d: d.strftime("%A %d-%m-%Y"),
|
||||||
|
label_visibility="collapsed",
|
||||||
|
)
|
||||||
|
if chosen != selected_day:
|
||||||
|
selected_day = chosen
|
||||||
|
st.session_state[state_key] = selected_day
|
||||||
|
|
||||||
|
try:
|
||||||
|
glucose, treatments = load_day_data(selected_day)
|
||||||
|
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 op deze dag.")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
|
render_completeness_warning(glucose, selected_day, selected_day)
|
||||||
|
|
||||||
|
colors = get_colors()
|
||||||
|
day_start = pd.Timestamp(selected_day)
|
||||||
|
day_end = day_start + pd.Timedelta(1, unit="D")
|
||||||
|
|
||||||
|
# treatments bevat een lookback-marge vóór middernacht (zie
|
||||||
|
# nightscout_client.fetch_treatments_for_day) zodat een temp basal die al
|
||||||
|
# vóór deze dag begon toch meetelt — effective_basal_series() clipt dat
|
||||||
|
# zelf aan [day_start, day_end). Voor de koolhydraten/bolus-overlays willen
|
||||||
|
# we die marge juist NIET, anders duiken gisteravond se stippen op vandaag op.
|
||||||
|
day_treatments = treatments[(treatments["timestamp"] >= day_start) & (treatments["timestamp"] < day_end)]
|
||||||
|
|
||||||
|
carbs_day = classify_treatments(day_treatments)["carbs"]
|
||||||
|
bolus_day = classify_bolus(day_treatments)
|
||||||
|
basal_day = effective_basal_series(profile, treatments, day_start, day_end)
|
||||||
|
target_day = target_glucose_series(profile, day_start, day_end)
|
||||||
|
|
||||||
|
|
||||||
|
def _close_step_to_day_end(df: pd.DataFrame, value_col: str) -> pd.DataFrame:
|
||||||
|
"""Voeg een laatste punt op day_end 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([{"timestamp": day_end, value_col: last_value}])
|
||||||
|
return pd.concat([df, closing_row], ignore_index=True)
|
||||||
|
|
||||||
|
|
||||||
|
basal_day = _close_step_to_day_end(basal_day, "rate")
|
||||||
|
target_day = _close_step_to_day_end(target_day, "target")
|
||||||
|
|
||||||
|
|
||||||
|
def build_day_figure(glucose_day, carbs_day, bolus_day, basal_day, target_day, colors) -> go.Figure:
|
||||||
|
fig = make_subplots(
|
||||||
|
rows=2,
|
||||||
|
cols=1,
|
||||||
|
shared_xaxes=True,
|
||||||
|
row_heights=[0.68, 0.32],
|
||||||
|
vertical_spacing=0.08,
|
||||||
|
specs=[[{"secondary_y": True}], [{"secondary_y": False}]],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Rij 1: glucose + streefwaarde + koolhydraten + voeding-/correctiebolus.
|
||||||
|
fig.add_hrect(
|
||||||
|
y0=TARGET_LOW, y1=TARGET_HIGH, fillcolor=colors["band"], line_width=0, layer="below", row=1, col=1
|
||||||
|
)
|
||||||
|
add_target_line_trace(fig, target_day, colors, row=1)
|
||||||
|
add_carb_bars_trace(fig, carbs_day, colors, row=1, secondary_y=True)
|
||||||
|
|
||||||
|
top_bolus = bolus_day[bolus_day["category"] != BOLUS_CATEGORY_SMB] if not bolus_day.empty else bolus_day
|
||||||
|
lane_y = glucose_day["mmol"].min() - 1.0 if not glucose_day.empty else TARGET_LOW - 1.0
|
||||||
|
add_bolus_marker_traces(fig, top_bolus, colors, lane_y, row=1)
|
||||||
|
|
||||||
|
fig.add_trace(
|
||||||
|
go.Scatter(
|
||||||
|
x=glucose_day["timestamp"],
|
||||||
|
y=glucose_day["mmol"],
|
||||||
|
mode="lines",
|
||||||
|
line={"color": colors["glucose"], "width": 2},
|
||||||
|
name="Glucose",
|
||||||
|
hovertemplate=MMOL_HOVERTEMPLATE,
|
||||||
|
),
|
||||||
|
row=1,
|
||||||
|
col=1,
|
||||||
|
)
|
||||||
|
add_threshold_lines(fig, colors, row=1)
|
||||||
|
fig.update_yaxes(title_text="mmol/L", gridcolor=colors["grid"], row=1, col=1, secondary_y=False)
|
||||||
|
fig.update_yaxes(title_text="Koolhydraten (g)", showgrid=False, row=1, col=1, secondary_y=True)
|
||||||
|
|
||||||
|
# Rij 2: basaal + SMB — apart van rij 1 zodat de glucosegrafiek niet
|
||||||
|
# overladen raakt met insulinedetails.
|
||||||
|
add_basal_area_trace(fig, basal_day, colors, row=2)
|
||||||
|
smb_bolus = bolus_day[bolus_day["category"] == BOLUS_CATEGORY_SMB] if not bolus_day.empty else bolus_day
|
||||||
|
smb_lane_y = (basal_day["rate"].max() * 1.15) if not basal_day.empty else 1.0
|
||||||
|
add_bolus_marker_traces(fig, smb_bolus, colors, smb_lane_y, row=2)
|
||||||
|
fig.update_yaxes(
|
||||||
|
title_text="Basaal (E/uur)", gridcolor=colors["grid"], rangemode="tozero", row=2, col=1
|
||||||
|
)
|
||||||
|
|
||||||
|
fig.update_xaxes(range=[day_start, day_end], dtick=4 * 3600 * 1000, 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=560,
|
||||||
|
showlegend=True,
|
||||||
|
legend={"orientation": "h", "yanchor": "bottom", "y": 1.02, "xanchor": "left", "x": 0},
|
||||||
|
margin={"l": 10, "r": 10, "t": 40, "b": 10},
|
||||||
|
)
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
fig = build_day_figure(glucose, carbs_day, bolus_day, basal_day, target_day, colors)
|
||||||
|
st.plotly_chart(fig, width="stretch")
|
||||||
|
|
||||||
|
stats = daily_stats(glucose, day_treatments, profile, day_start, day_end)
|
||||||
|
col1, col2, col3, col4 = st.columns(4)
|
||||||
|
col1.metric(
|
||||||
|
"Glucose (gem./min/max)",
|
||||||
|
f"{stats['mean_mmol']:.1f} mmol/L",
|
||||||
|
delta=f"{stats['min_mmol']:.1f} - {stats['max_mmol']:.1f}",
|
||||||
|
delta_color="off",
|
||||||
|
)
|
||||||
|
col2.metric("Totale insuline", f"{stats['total_insulin']:.1f} E")
|
||||||
|
col3.metric("Basaal / bolus / SMB", f"{stats['basal_insulin']:.1f} / {stats['bolus_insulin']:.1f} / {stats['smb_insulin']:.1f} E")
|
||||||
|
col4.metric(
|
||||||
|
"Hypo's / hyper's",
|
||||||
|
f"{stats['hypo_count']} / {stats['hyper_count']}",
|
||||||
|
delta=f"{stats['hypo_duration_minutes']:.0f} / {stats['hyper_duration_minutes']:.0f} min",
|
||||||
|
delta_color="off",
|
||||||
|
)
|
||||||
|
|
||||||
|
st.caption(
|
||||||
|
"Boven: stippen = bolusinsuline (voeding/correctie, grootte naar dosis) · staafjes = koolhydraten · "
|
||||||
|
"streepstippellijn = streefwaarde uit pompprofiel. Onder: vlak = basaal · stippen = SMB."
|
||||||
|
)
|
||||||
@@ -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, hex_to_rgba, 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=hex_to_rgba(colors["basal"], 0.3),
|
||||||
|
opacity=0.8,
|
||||||
|
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)."
|
||||||
|
)
|
||||||
+573
@@ -0,0 +1,573 @@
|
|||||||
|
"""
|
||||||
|
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, alpha=0.8)
|
||||||
|
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, bolus: pd.DataFrame, day_start, lane_y: float, categories: tuple[str, ...]) -> None:
|
||||||
|
for category in categories:
|
||||||
|
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 twee gestapelde grafieken (gedeelde tijdas, één gedeelde legenda):
|
||||||
|
boven glucose + streefwaarde + koolhydraten + voeding/correctiebolus, onder
|
||||||
|
basaal + SMB — gescheiden omdat één gecombineerde grafiek te veel informatie
|
||||||
|
bevatte om nog leesbaar te zijn."""
|
||||||
|
hours = day_df["timestamp"].dt.hour + day_df["timestamp"].dt.minute / 60
|
||||||
|
fig, (ax, ax_basal) = plt.subplots(2, 1, figsize=(11, 5.2), sharex=True, height_ratios=[2.2, 1])
|
||||||
|
ax2 = ax.twinx()
|
||||||
|
|
||||||
|
bolus = classify_bolus(day_treatments)
|
||||||
|
_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, bolus, day_start, lane_y, categories=(BOLUS_CATEGORY_CORRECTION, BOLUS_CATEGORY_FOOD))
|
||||||
|
_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_ylabel("mmol/L", fontsize=9)
|
||||||
|
ax2.set_ylabel("Koolhydraten (g)", fontsize=9)
|
||||||
|
ax.set_title(day_label, fontsize=11, loc="left")
|
||||||
|
ax.tick_params(labelsize=8)
|
||||||
|
ax2.tick_params(labelsize=8)
|
||||||
|
|
||||||
|
basal = effective_basal_series(profile, day_treatments, day_start, day_end)
|
||||||
|
_add_basal_overlay(ax_basal, basal, day_start)
|
||||||
|
smb_lane_y = (basal["rate"].max() * 1.15) if not basal.empty else 1.0
|
||||||
|
_add_bolus_overlay(ax_basal, bolus, day_start, smb_lane_y, categories=(BOLUS_CATEGORY_SMB,))
|
||||||
|
ax_basal.set_xlim(0, 24)
|
||||||
|
ax_basal.set_xticks(range(0, 25, 2))
|
||||||
|
ax_basal.set_xlabel(_HOUR_OF_DAY_LABEL)
|
||||||
|
ax_basal.set_ylabel("Basaal (E/uur)", fontsize=9)
|
||||||
|
ax_basal.tick_params(labelsize=8)
|
||||||
|
|
||||||
|
lines1, labels1 = ax.get_legend_handles_labels()
|
||||||
|
lines2, labels2 = ax2.get_legend_handles_labels()
|
||||||
|
lines3, labels3 = ax_basal.get_legend_handles_labels()
|
||||||
|
ax_basal.legend(
|
||||||
|
lines1 + lines2 + lines3,
|
||||||
|
labels1 + labels2 + labels3,
|
||||||
|
loc="upper center",
|
||||||
|
bbox_to_anchor=(0.5, -0.35),
|
||||||
|
ncol=6,
|
||||||
|
fontsize=7,
|
||||||
|
frameon=False,
|
||||||
|
)
|
||||||
|
# fig.tight_layout() introspecteert elke as se bounding box om marges te
|
||||||
|
# berekenen, en matplotlib ondersteunt dat niet betrouwbaar zodra er twee
|
||||||
|
# hoofd-assen (ax/ax_basal) plus een twinx (ax2) tegelijk in de figuur
|
||||||
|
# zitten (waarschuwing "Axes ... not compatible with tight_layout").
|
||||||
|
# subplots_adjust() met vaste marges omzeilt die introspectie.
|
||||||
|
fig.subplots_adjust(left=0.06, right=0.94, top=0.93, bottom=0.24, hspace=0.35)
|
||||||
|
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
|
||||||
|
|||||||
+551
@@ -9,8 +9,14 @@ definities waarop dit gebaseerd is (Battelino et al. 2019, Bergenstal et al.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from itertools import pairwise
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
import pandas as pd
|
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).
|
# Klinische drempels in mmol/L (Battelino et al. 2019, Diabetes Care 42(8):1593-1603).
|
||||||
VERY_LOW = 3.0
|
VERY_LOW = 3.0
|
||||||
LOW = 3.9
|
LOW = 3.9
|
||||||
@@ -31,6 +37,79 @@ 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:
|
||||||
@@ -91,6 +170,56 @@ def sensor_active_percent(glucose: pd.DataFrame, start, end, expected_interval_m
|
|||||||
return round(min(len(glucose) / expected_readings, 1.0) * 100, 1)
|
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]:
|
def _state_blocks(df: pd.DataFrame, out: pd.Series) -> list[dict]:
|
||||||
"""Groepeer aaneengesloten metingen met dezelfde in/out-status.
|
"""Groepeer aaneengesloten metingen met dezelfde in/out-status.
|
||||||
|
|
||||||
@@ -202,3 +331,425 @@ def summarize_events(events: pd.DataFrame, period_days: float) -> dict[str, floa
|
|||||||
"total_minutes": round(total_minutes, 1),
|
"total_minutes": round(total_minutes, 1),
|
||||||
"events_per_week": round(len(events) / period_days * 7, 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
|
||||||
|
|||||||
@@ -90,6 +90,38 @@ 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):
|
||||||
@@ -134,3 +166,283 @@ def test_fetch_treatments_range_filters_to_date_boundaries(monkeypatch):
|
|||||||
result = ns.fetch_treatments_range(date(2026, 1, 1), date(2026, 1, 31))
|
result = ns.fetch_treatments_range(date(2026, 1, 1), date(2026, 1, 31))
|
||||||
assert len(result) == 1
|
assert len(result) == 1
|
||||||
assert result.iloc[0]["insulin"] == pytest.approx(4.0)
|
assert result.iloc[0]["insulin"] == pytest.approx(4.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_entries_for_day_scopes_to_a_single_calendar_day(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, 16, 12, 0, tzinfo=timezone.utc).timestamp() * 1000), "sgv": 100},
|
||||||
|
]
|
||||||
|
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse(payload))
|
||||||
|
|
||||||
|
result = ns.fetch_entries_for_day(date(2026, 1, 15))
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result.iloc[0]["timestamp"].date() == date(2026, 1, 15)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_treatments_for_day_includes_lookback_before_midnight(monkeypatch):
|
||||||
|
"""Een Temp Basal die net vóór middernacht is gestart moet toch meekomen
|
||||||
|
(zie de docstring bij fetch_treatments_for_day) — zonder lookback-marge
|
||||||
|
zou effective_basal_series() de vroege ochtenduren fout berekenen."""
|
||||||
|
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
|
||||||
|
payload = [
|
||||||
|
{"created_at": "2026-01-14T22:00:00Z", "eventType": "Temp Basal", "absolute": 1.2, "duration": 480},
|
||||||
|
{"created_at": "2026-01-15T12:00:00Z", "eventType": "Meal Bolus", "insulin": 4.0, "carbs": 40},
|
||||||
|
{"created_at": "2026-01-10T08:00:00Z", "eventType": "Meal Bolus", "insulin": 3.0, "carbs": 30},
|
||||||
|
]
|
||||||
|
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse(payload))
|
||||||
|
|
||||||
|
result = ns.fetch_treatments_for_day(date(2026, 1, 15), lookback_hours=6)
|
||||||
|
assert len(result) == 2 # de 10 januari-bolus valt buiten de lookback-marge
|
||||||
|
assert set(result["eventType"]) == {"Temp Basal", "Meal Bolus"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_treatments_for_day_excludes_treatments_before_the_lookback_window(monkeypatch):
|
||||||
|
monkeypatch.setenv("NIGHTSCOUT_URL", "https://example.com")
|
||||||
|
payload = [
|
||||||
|
{"created_at": "2026-01-14T12:00:00Z", "eventType": "Meal Bolus", "insulin": 4.0, "carbs": 40},
|
||||||
|
]
|
||||||
|
monkeypatch.setattr(ns.requests, "get", lambda *a, **k: FakeResponse(payload))
|
||||||
|
|
||||||
|
result = ns.fetch_treatments_for_day(date(2026, 1, 15), lookback_hours=6)
|
||||||
|
assert result.empty
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
@@ -1,13 +1,31 @@
|
|||||||
|
from datetime import date
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from reporting import (
|
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,
|
detect_events,
|
||||||
|
effective_basal_series,
|
||||||
|
glucose_min_max,
|
||||||
|
gmi_mmol_per_mol,
|
||||||
gmi_percent,
|
gmi_percent,
|
||||||
|
gmi_trend,
|
||||||
minutes_per_day,
|
minutes_per_day,
|
||||||
|
overnight_daytime_split,
|
||||||
percent_cv,
|
percent_cv,
|
||||||
sensor_active_percent,
|
sensor_active_percent,
|
||||||
|
site_interval_stats,
|
||||||
summarize_events,
|
summarize_events,
|
||||||
|
target_glucose_series,
|
||||||
tir_breakdown_5band,
|
tir_breakdown_5band,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -23,6 +41,63 @@ 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
|
||||||
@@ -88,6 +163,42 @@ def test_sensor_active_percent_handles_gaps():
|
|||||||
assert result == pytest.approx(50.0, abs=1.0)
|
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():
|
def test_detect_events_ignores_dip_shorter_than_minimum_duration():
|
||||||
# dip van 10 minuten (< 15 min drempel) mag niet meetellen
|
# dip van 10 minuten (< 15 min drempel) mag niet meetellen
|
||||||
glucose = _series(
|
glucose = _series(
|
||||||
@@ -213,6 +324,411 @@ def test_summarize_events_computes_expected_stats():
|
|||||||
assert result["events_per_week"] == pytest.approx(2.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():
|
def test_summarize_events_handles_empty_input():
|
||||||
empty = pd.DataFrame(columns=["start", "end", "duration_minutes"])
|
empty = pd.DataFrame(columns=["start", "end", "duration_minutes"])
|
||||||
result = summarize_events(empty, period_days=14)
|
result = summarize_events(empty, period_days=14)
|
||||||
|
|||||||
@@ -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
|
||||||
+411
@@ -8,10 +8,37 @@ worden per pagina.
|
|||||||
|
|
||||||
from __future__ import annotations
|
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
|
import streamlit as st
|
||||||
|
|
||||||
|
from nightscout_client import (
|
||||||
|
fetch_entries_for_day,
|
||||||
|
fetch_entries_range,
|
||||||
|
fetch_profile,
|
||||||
|
fetch_treatments_for_day,
|
||||||
|
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>"
|
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
|
# Kleuren per rol, licht/donker — categorale kleuren voor identiteit
|
||||||
# (glucose/insuline/carbs), status-kleuren (vast, nooit hergebruikt) voor
|
# (glucose/insuline/carbs), status-kleuren (vast, nooit hergebruikt) voor
|
||||||
# te laag/te hoog.
|
# te laag/te hoog.
|
||||||
@@ -29,6 +56,19 @@ PALETTE = {
|
|||||||
"muted": "#898781",
|
"muted": "#898781",
|
||||||
"text": "#52514e",
|
"text": "#52514e",
|
||||||
"good": "#0ca30c",
|
"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": {
|
"dark": {
|
||||||
"glucose": "#3987e5",
|
"glucose": "#3987e5",
|
||||||
@@ -43,9 +83,36 @@ PALETTE = {
|
|||||||
"muted": "#898781",
|
"muted": "#898781",
|
||||||
"text": "#c3c2b7",
|
"text": "#c3c2b7",
|
||||||
"good": "#0ca30c",
|
"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:
|
def get_colors() -> dict:
|
||||||
"""Geef de kleurenset terug die past bij het actieve Streamlit-thema."""
|
"""Geef de kleurenset terug die past bij het actieve Streamlit-thema."""
|
||||||
@@ -55,3 +122,347 @@ def get_colors() -> dict:
|
|||||||
except AttributeError:
|
except AttributeError:
|
||||||
pass
|
pass
|
||||||
return PALETTE["dark" if theme_type == "dark" else "light"]
|
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=300, show_spinner="Data ophalen van Nightscout...")
|
||||||
|
def load_day_data(day: date): # pragma: no cover
|
||||||
|
"""Gecachete Nightscout-fetch voor precies één kalenderdag (Dagoverzicht-navigatie).
|
||||||
|
|
||||||
|
Kortere TTL dan load_range_data (5 min i.p.v. 1 uur): in tegenstelling tot
|
||||||
|
een afgeronde periode kan de geselecteerde dag "vandaag" zijn, waar
|
||||||
|
nieuwe metingen blijven binnenkomen. fetch_treatments_for_day() haalt
|
||||||
|
zelf een lookback-marge vóór middernacht op zodat effective_basal_series()
|
||||||
|
de vroege ochtenduren correct kan berekenen.
|
||||||
|
|
||||||
|
Dunne st.cache_data-wrapper rond al-geteste fetch_entries_for_day()/
|
||||||
|
fetch_treatments_for_day() — buiten scope van de unit-testdekking net als
|
||||||
|
pages/*.py, zie pyproject.toml se coverage-omit-lijst.
|
||||||
|
"""
|
||||||
|
glucose = fetch_entries_for_day(day)
|
||||||
|
treatments = fetch_treatments_for_day(day)
|
||||||
|
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