Repository navigation
Add SimGlucose Dataset, GlucoseControlTask and SACGRU for Closed-Loop Blood Glucose Control - #1773
sushmit1990 wants to merge 13 commits into
Conversation
Test CoverageTotal: 88.81% (61716 / 69491 lines)
|
|
Why this PR has To make it eligible for automatic review: split it into smaller PRs, each well under the limit:
Keep the |
Hello, We are happy to split the contribution into the three smaller PRs as suggested. Would it be acceptable to preserve this original PR for course grading evaluation and create the smaller PRs separately for upstream review? Thank you again for your guidance. |
|
/review |
AI Reviewsuggestion: not available This PR is too large for AI review (over 300 files or 200000 diff characters). The label stays as it is: you can make the PR smaller, for example by clearing notebook outputs or splitting it, and comment |
Contributors
Team G1 — Georgia Tech CSE6250: Big Data Analytics for Healthcare, Fall 2026
smallik3, email: smallik3@gatech.edujsharma66, email: jsharma66@gatech.eduContribution Type
Full Pipeline (Dataset + Task + Model)
This contribution includes a complete reinforcement learning pipeline, paper reproduction experiments, two extension/ablation studies, an executed end-to-end demonstration notebook, a runnable ablation script, API documentation, and unit tests.
Paper
Fox, I., Lee, J., Pop-Busui, R., & Wiens, J. (2020).
Deep Reinforcement Learning for Closed-Loop Blood Glucose Control.
Machine Learning for Healthcare (MLHC), Proceedings of Machine Learning Research, Volume 126.
Quick Links
1. Background and Motivation
Type 1 diabetes requires frequent blood glucose monitoring and insulin administration. Conventional basal-bolus controllers rely on patient-specific parameters, glucose measurements, and meal announcements to determine insulin dosages.
The selected paper investigates whether deep reinforcement learning can automate insulin delivery using historical continuous glucose monitoring (CGM) measurements and insulin delivery history, without requiring meal announcements as policy inputs.
We reproduce the paper's recurrent Soft Actor-Critic (SAC) approach using the authors' RL4BG simulator and integrate the complete Dataset, Task, Model, training, and evaluation pipeline into PyHealth.
We additionally investigate whether initializing the experience replay buffer with basal-bolus expert experience improves glycemic control, training stability, and online learning efficiency.
2. Implementation
The contributed pipeline follows the workflow:
SimGlucoseDataset → GlucoseControlTask → PyHealth DataLoader → Experience Replay → SACGRU Training → Policy Evaluation
2.1 Dataset: SimGlucoseDataset
SimGlucoseDatasetinherits from PyHealth'sBaseDatasetand provides access to 30 virtual patients from the UVA/Padova Type 1 diabetes simulator:Virtual patient characteristics are represented using PyHealth's Patient and Event abstractions. Unlike conventional static healthcare datasets, glucose and insulin trajectories are generated dynamically through simulator interactions.
No protected clinical datasets or additional data-access permissions are required.
2.2 Task: GlucoseControlTask
GlucoseControlTaskinherits from PyHealth'sBaseTaskand generates reinforcement learning transitions using a basal-bolus (BB) expert controller.stateactionrewardnext_statedonetruncatedFollowing the paper, the default observation contains four hours of CGM and insulin delivery history sampled at five-minute intervals.
The task supports configurable patient selection, simulation duration, observation history, random seed, reward function, and simulator history initialization.
Expert transitions are processed through PyHealth's existing DataLoader interface and transferred into an experience replay buffer.
2.3 Model: SACGRU
SACGRUinherits from PyHealth'sBaseModeland implements the recurrent Soft Actor-Critic architecture described in the selected paper.The implementation includes:
training_step()method.The default architecture uses two GRU layers with 128 hidden units per layer. Model hyperparameters, including hidden dimensions, GRU layers, learning rates, discount factor, and target network update coefficient, are configurable.
The learned policy uses historical CGM and insulin delivery observations without requiring meal announcements during execution.
2.4 Reinforcement Learning Integration Challenges
PyHealth's standard training workflow is primarily designed around static samples, feature-label pairs, and supervised optimization. In contrast, reinforcement learning generates experience dynamically through interactions between an agent and its environment.
To accommodate this difference, we use the Dataset and Task abstractions to generate expert transitions, a replay buffer to combine expert and online experience, and a custom SAC training loop with multiple optimizers, entropy tuning, and target network updates. Evaluation uses independent closed-loop simulator rollouts rather than static labeled test samples.
This design integrates reinforcement learning without modifying PyHealth's underlying BaseDataset, BaseTask, BaseModel, or Trainer implementations, providing a reference example for future simulator-based healthcare reinforcement learning contributions.
3. End-to-End Demonstration Notebook
[Glucose Control End-to-End Demo Notebook](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/glucose_control/glucose_control_end_to_end_demo.ipynb)
The executed Jupyter notebook demonstrates the complete integration of the three contributed PyHealth components, with explanatory text, saved execution outputs, and visualizations.
The notebook covers:
SimGlucoseDataset.GlucoseControlTask.SACGRUthrough online simulator interactions and replay-based optimization.The CPU-friendly notebook uses
adult#001, 288 expert transitions, 288 online training steps, 257 gradient updates, and a one-day independent evaluation.The notebook successfully completed the entire pipeline using the actual RL4BG simulator. Its purpose is to demonstrate functional integration and explain the reinforcement learning workflow rather than train a converged glucose control policy.
4. Reproduction Experimental Setup
We reproduce the paper's RL-Scratch controller for two virtual patients,
adult#001andchild#001, selected from the authors' hyperparameter tuning subset.Due to computational and time constraints, we use one training seed per configuration while retaining the original online training budget.
Checkpoint Selection and Evaluation
After each training epoch, the policy is evaluated deterministically using a separate validation environment.
The checkpoint with the lowest mean validation Magni risk is retained among checkpoints satisfying both conditions:
Final evaluation uses 100 independent ten-day rollouts with test seeds 2000001–2000100, matched across configurations and excluded from checkpoint selection.
5. Reproduction Results
We compare patient-specific median Magni risk against approximate values visually extracted from the original paper's figures.
Lower Magni risk is better.
The reproduction captures the substantially poorer BB performance for the selected child patient and the improvement obtained through reinforcement learning for that patient.
The adult RL-Scratch controller underperforms the approximate published result, while the child RL-Scratch controller achieves a broadly comparable median risk.
Differences may arise from the limited number of training seeds, implementation differences, and the BB evaluation protocol.
We restrict the direct paper comparison to patient-specific median Magni risk because the paper's aggregate glycemic range statistics across 30 patients are not directly comparable to our patient-specific results.
6. Extension and Ablation Studies
Our extension investigates whether initializing the experience replay buffer with expert-generated transitions improves reinforcement learning performance.
The extension changes the initial replay data rather than introducing supervised weight pretraining or imitation learning. Model parameters remain randomly initialized, and the SAC algorithm is retained.
Expert experience is generated using the contributed Dataset and Task and processed through PyHealth's DataLoader.
6.1 Ablation I: Expert Replay Initialization
Both adult and child patients are evaluated under two configurations:
The 5,760 expert transitions correspond to 20 simulated days of basal-bolus controller experience.
Both configurations receive the same online training budget, gradient-update budget, replay capacity, and model architecture.
6.2 Ablation II: Expert Replay Quantity
For the adult patient, we additionally investigate filling the entire replay buffer before online training.
The full replay buffer is initialized using 35 bounded expert simulation trajectories.
This experiment investigates whether increasing the quantity of initial expert experience improves online learning efficiency and final policy performance while retaining the same online interaction and gradient-update budgets.
7. Full Experimental Results
The following metrics are arithmetic means across 100 independent ten-day test rollouts per configuration.
7.1 Independent Test Performance
All seven configurations completed 100 independent test rollouts. No catastrophic failures, defined as simulated blood glucose below 5 mg/dL, were observed under this evaluation protocol.
7.2 Training Performance and Stability
7.3 Findings: Expert Replay Initialization
For the adult patient, RL-Expert relative to RL-Scratch achieved:
For the child patient, RL-Expert achieved:
The results suggest a patient-specific trade-off: expert replay initialization can reduce hypoglycemia without necessarily improving overall glucose control.
7.4 Findings: Expert Replay Quantity
For the adult patient, full-buffer initialization reached an eligible validation Magni risk of 6.5 or lower substantially earlier than standard expert initialization.
Full-buffer initialization required approximately 58% fewer online interactions to reach this threshold.
However, it required substantially more expert-generated data and produced approximately 19.6% higher final mean test Magni risk than standard expert initialization.
Increasing initial expert experience therefore improved early online learning efficiency for the selected threshold but did not improve final held-out policy performance.
This improvement should not be interpreted as improved total sample efficiency because expert generation introduces substantial additional simulation cost.
7.5 Experimental Scope
The complete experimental study comprises:
Detailed experimental configurations, results, and limitations are available in:
[RESULTS.md](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/glucose_control/RESULTS.md)
8. Runnable Python Ablation Example
[simglucose_glucose_control_sacgru.py](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/simglucose_glucose_control_sacgru.py)
The CPU-friendly example demonstrates the complete pipeline and compares three replay initialization configurations.
All configurations use the same online training budget, gradient-update budget, model initialization seed, and independent evaluation seed.
Demonstration Results
All three configurations successfully completed training and evaluation using the actual RL4BG simulator.
The short demonstration produces identical glycemic metrics across configurations. These results validate functional execution of the ablation pipeline rather than demonstrate converged policy performance.
The substantive scientific comparisons are obtained from the full-scale experiments in Section 7.
The notebook and Python script serve complementary purposes: the notebook explains the complete workflow with visualizations, while the script systematically executes and compares multiple replay initialization configurations.
9. Installation and Quick Start
Complete installation, training, evaluation, and visualization instructions are available in:
[Installation and Reproduction README](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/glucose_control/README.md)
The simulator setup helper downloads a pinned version of the authors' RL4BG repository and automatically applies the required NumPy compatibility patches.
Pinned RL4BG commit:
c9e2189d44566d195bacb2e2d3b6d3a9aed1faedThe external simulator is not redistributed in this PR.
Step 1: Obtain the contribution
git clone -b glucose-control https://github.com/sushmit1990/PyHealth.git cd PyHealthStep 2: Create a Python environment
Step 3: Install dependencies and the simulator
Install the compatible CPU PyTorch and torchvision versions specified in the README, then execute the following commands from the repository root:
The setup helper installs the pinned external simulator and applies compatibility fixes.
No protected clinical data or manual simulator modifications are required.
Step 4: Run the CPU ablation example
The script trains and evaluates Scratch, Expert, and Full Buffer configurations and prints a comparative table of glucose control metrics.
Step 5: Run the end-to-end notebook
Open:
examples/glucose_control/glucose_control_end_to_end_demo.ipynbSelect the
pyhealth-glucoseenvironment as the notebook kernel in VS Code or Jupyter and execute all cells sequentially.Full Reproduction Experiments
Example commands for adult patient training:
The README provides the complete commands for both virtual patients, independent checkpoint evaluation, BB baseline evaluation, plotting, dependency installation, and descriptions of the generated output files.
The full experiments require substantially more computation and storage than the lightweight CPU demonstration.
10. Files for Review
Primary Implementation
pyhealth/datasets/simglucose_data.pypyhealth/datasets/configs/simglucose.yamlpyhealth/tasks/glucose_control.pypyhealth/models/sac_gru.pyAPI Documentation
docs/api/datasets/pyhealth.datasets.SimGlucoseDataset.rstdocs/api/tasks/pyhealth.tasks.GlucoseControlTask.rstdocs/api/models/pyhealth.models.SACGRU.rstThe corresponding documentation indices and package exports have also been updated.
Unit Tests
tests/core/test_simglucose_data.pytests/core/test_glucose_control_task.pytests/core/test_sac_gru.pyExamples and Experimental Documentation
examples/simglucose_glucose_control_sacgru.pyexamples/glucose_control/glucose_control_end_to_end_demo.ipynbexamples/glucose_control/README.mdexamples/glucose_control/RESULTS.mdTraining, Evaluation, and Supporting Utilities
All files below are located under
examples/glucose_control/.train_epochs.pytrain_epochs_full_expert.pyevaluate_checkpoint.pyevaluate_bb.pyplot_results.pyexpert_replay.pyreplay_buffer.pyevaluate.pyutils.pysetup_rl4bg.pyrequirements_glucose_control.txt11. Testing and Validation
All three contributed components include dedicated unit tests using synthetic patient data, mocked simulator components, and synthetic tensors.
Unit Test Coverage
All 29 unit tests and five subtests passed after integrating upstream master. The local coverage report showed 278/278 executable statements covered across the three contributed implementation files.
The tests cover patient loading and parameter parsing, task configuration and transition generation, termination and truncation behavior, model initialization, observation shapes, action selection, SAC losses, target network updates, and the complete optimization step.
Additional Validation
The notebook was executed before upstream integration. The Python ablation script was executed both before and after integration, with the post-merge execution reusing cached expert transitions.
Test Command
Component-specific coverage report:
python -m coverage report --include="*simglucose_data.py,*glucose_control.py,*sac_gru.py" -mPR compliance verification:
Result:
All PR contribution rules passed.
These results reflect local validation. Repository CI and maintainer review remain separate from the local checks.
12. Limitations and Differences from the Original Paper
The implemented pipeline can be reviewed and executed without requiring access to protected patient datasets.