Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/api/datasets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,11 @@ PyHealth does not ship any data: you download each dataset from its source and p
- `HL7 <https://www.hl7.org/fhir/>`__
- —
- `MIMIC-IV FHIR demo <https://physionet.org/content/mimic-iv-fhir-demo/2.1.0/>`__
* - :doc:`SimGlucose <datasets/pyhealth.datasets.SimGlucoseDataset>`
- Open (synthetic)
- `GitHub <https://github.com/MLD3/RL4BG>`__
- No (setup script)
- —

Available Datasets
------------------
Expand Down Expand Up @@ -721,3 +726,4 @@ Available Datasets
datasets/pyhealth.datasets.GoldTestSplit
datasets/pyhealth.datasets.utils
datasets/pyhealth.datasets.TCGARNASeqDataset
datasets/pyhealth.datasets.SimGlucoseDataset
44 changes: 44 additions & 0 deletions docs/api/datasets/pyhealth.datasets.SimGlucoseDataset.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
pyhealth.datasets.SimGlucoseDataset
==================================

Overview
--------

The SimGlucose dataset contains physiological and insulin controller
parameters for 30 virtual patients with type 1 diabetes, consisting
of 10 adults, 10 adolescents, and 10 children.

The dataset contains three source tables:

- ``vpatient_params.csv``: Virtual patient physiological parameters.
- ``Quest2.csv``: Basal-bolus controller parameters.
- ``pid_params.csv``: Proportional-integral-derivative controller parameters.

Each virtual patient is represented by static parameter records.
Blood glucose and insulin trajectories can be generated using
``GlucoseControlTask``.

Getting the Data
----------------

The parameter files are available from the RL4BG repository.
From the PyHealth repository root, run:

.. code-block:: bash

python examples/glucose_control/setup_rl4bg.py --target .

Set ``root`` to ``bgp/simglucose/params`` when initializing the dataset.

Source: `RL4BG GitHub Repository <https://github.com/MLD3/RL4BG>`_

Reference: `Deep Reinforcement Learning for Closed-Loop Blood Glucose Control
<https://proceedings.mlr.press/v126/fox20a.html>`_ (Fox et al., 2020).

API Reference
-------------

.. autoclass:: pyhealth.datasets.SimGlucoseDataset
:members:
:undoc-members:
:show-inheritance:
11 changes: 11 additions & 0 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ routes each feature type automatically.
* - :doc:`models/pyhealth.models.td_cnn_lstm`
- You want real-time ICU mortality risk for each measurement-time state of irregular event streams
- Temporal-difference training needs paired ``next_*`` successor states and a custom loop that calls ``model.update_target()`` after each optimizer step
* - :doc:`models/pyhealth.models.SACGRU`
- You want closed-loop blood glucose control using reinforcement learning
- GRU-based Soft Actor-Critic with continuous actions, experience replay and a custom training loop
* - :doc:`models/pyhealth.models.HiCu`
- You predict ICD codes from clinical notes (e.g. ``MIMIC3ICD9Coding``) and many codes are rare
- MultiResCNN with label attention, trained level by level down the ICD tree; call ``set_level`` between training stages
Expand Down Expand Up @@ -105,6 +108,13 @@ key.
The ``forward()`` method is expected to return a dictionary with four keys:
``loss``, ``y_prob``, ``y_true``, and ``logit``. The Trainer reads all four.

Reinforcement learning models such as
:doc:`models/pyhealth.models.SACGRU` use a custom training loop.
SACGRU exposes policy parameters through ``forward()``,
selects actions through ``select_action()``, and performs
optimization through ``training_step()`` rather than using
the standard supervised ``Trainer``.

EmbeddingModel
--------------

Expand Down Expand Up @@ -419,6 +429,7 @@ API Reference
models/pyhealth.models.MedTsLLMAnomaly
models/pyhealth.models.CHET
models/pyhealth.models.GAME
models/pyhealth.models.SACGRU
models/pyhealth.models.MedTok
models/pyhealth.models.EviCare
models/pyhealth.models.QueryFocusedEHRModel
Expand Down
84 changes: 84 additions & 0 deletions docs/api/models/pyhealth.models.SACGRU.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
SACGRU
======

SACGRU is a recurrent soft actor-critic model for simulated closed-loop
blood glucose control, based on the study by Fox et al. (2020),
`Deep Reinforcement Learning for Closed-Loop Blood Glucose Control
<https://proceedings.mlr.press/v126/fox20a.html>`_.

The model uses GRU encoders for the Gaussian actor, a single Q-network,
a value network, and a target value network. The entropy temperature is
learned automatically.

Inputs and outputs
------------------

The state represents a four-hour history sampled at five-minute intervals.
A flattened observation contains 48 glucose values followed by 48 insulin
values. The model converts observations to recurrent tensors of shape
``(batch, 48, 2)``.

The following state shapes are accepted by ``prepare_state``, ``forward``,
``select_action`` and ``training_step``:

* ``(96,)``: a single flattened observation.
* ``(batch, 96)``: a batch of flattened observations.
* ``(48, 2)``: a single recurrent observation.
* ``(batch, 48, 2)``: a batch of recurrent observations.

The ``forward`` method returns the Gaussian policy parameters
``action_mean``, ``action_std`` and ``action_log_std``. The ``select_action``
method returns a tensor of shape ``(batch, 1)`` with actions squashed to
``[-1, 1]``. These are normalized policy actions, not physical insulin doses;
the simulator handles action scaling.

Training
--------

SACGRU uses its own ``training_step`` method rather than a standard
supervised PyHealth trainer. A replay transition contains the current state,
action, reward, next state and terminal indicator. For a batch of transitions,
action, reward and done must be tensors of shape ``(batch, 1)`` on the model
device. True terminal transitions disable bootstrapping; time-limit
truncations can retain bootstrapping by using ``done=0``.

The training step updates the entropy temperature, Q-network, value network,
actor and target value network. It returns a dictionary of scalar loss values
and the updated entropy temperature.

Example
-------

The following example runs a single optimization step using synthetic
transitions. It does not require the glucose simulator or patient data.

.. code-block:: python

import torch
from pyhealth.models import SACGRU

model = SACGRU(hidden_size=8, num_layers=1, device="cpu")
state = torch.zeros(2, 96)
next_state = torch.ones(2, 96)
action = torch.tensor([[0.2], [0.7]])
reward = torch.tensor([[-2.0], [-4.0]])
done = torch.tensor([[0.0], [1.0]])

losses = model.training_step(state, action, reward, next_state, done)
print(losses)

model.eval()
action = model.select_action(state, deterministic=True)
print(action.shape) # torch.Size([2, 1])

For simulated expert transitions, see :class:`~pyhealth.datasets.SimGlucoseDataset`
and :class:`~pyhealth.tasks.GlucoseControlTask`. The example training scripts
are located in ``examples/glucose_control/``.

API reference
-------------

.. autoclass:: pyhealth.models.SACGRU
:members:
:undoc-members:
:show-inheritance:
1 change: 1 addition & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ Available Tasks
Value Set Pair Classification (VSAC) <tasks/pyhealth.tasks.ValueSetPairClassification>
Time-to-event survival (GBSG and SUPPORT) <tasks/pyhealth.tasks.survival_time_to_event>
TCGA RNA-seq Survival Prediction <tasks/pyhealth.tasks.TCGASurvivalPrediction>
Glucose Control (SimGlucose) <tasks/pyhealth.tasks.GlucoseControlTask>
Hourly remaining ICU LOS <tasks/pyhealth.tasks.tpc_eicu>
Query-Focused EHR Summarization (MIMIC-III) <tasks/pyhealth.tasks.QueryFocusedEHRTask>
Multi-event survival (Rotterdam) <tasks/pyhealth.tasks.multi_event_survival_rotterdam>
Expand Down
107 changes: 107 additions & 0 deletions docs/api/tasks/pyhealth.tasks.GlucoseControlTask.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
Glucose Control (SimGlucose)
===========================

Overview
--------

The ``GlucoseControlTask`` generates expert demonstration trajectories
for closed-loop blood glucose control using the RL4BG simulator and a
rule-based basal-bolus insulin controller.

The task uses physiological and controller parameters from
:doc:`../datasets/pyhealth.datasets.SimGlucoseDataset` to simulate
virtual patients with type 1 diabetes.

The generated transitions can be used to initialize a replay buffer
for reinforcement learning algorithms.

Task Inputs and Outputs
-----------------------

Each sample represents one simulation transition.

.. list-table::
:header-rows: 1
:widths: 25 20 55

* - Field
- Default shape
- Description
* - ``state``
- (96,)
- Current glucose and insulin history.
* - ``action``
- (1,)
- Normalized insulin action between 0 and 1.
* - ``reward``
- (1,)
- Magni risk-based reward by default.
* - ``next_state``
- (96,)
- Glucose and insulin history after the action.
* - ``done``
- (1,)
- Simulator termination indicator.
* - ``truncated``
- (1,)
- Simulation time-limit indicator.

The default state contains four hours of glucose and insulin
history sampled at five-minute intervals.

All six transition fields use the ``tensor`` input processor.
The output schema is empty because reinforcement learning does
not require supervised target labels.

Example
-------

First, install the RL4BG simulator from the PyHealth repository root:

.. code-block:: bash

python examples/glucose_control/setup_rl4bg.py --target .

Generate expert demonstrations for a single virtual patient:

.. code-block:: python

from pyhealth.datasets import SimGlucoseDataset, get_dataloader
from pyhealth.tasks import GlucoseControlTask

dataset = SimGlucoseDataset()

task = GlucoseControlTask(
duration_hrs=24,
history_hrs=4,
seed=1,
patient_id="adult#001",
)

sample_dataset = dataset.set_task(task, num_workers=1)

loader = get_dataloader(
sample_dataset,
batch_size=32,
shuffle=False,
)

batch = next(iter(loader))
print(batch["state"].shape)
print(batch["action"].shape)

References
----------

- Paper: `Deep Reinforcement Learning for Closed-Loop Blood Glucose Control
<https://proceedings.mlr.press/v126/fox20a.html>`_
- Original implementation: https://github.com/MLD3/RL4BG


API Reference
-------------

.. autoclass:: pyhealth.tasks.GlucoseControlTask
:members:
:undoc-members:
:show-inheritance:
Loading
Loading