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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@
# Python egg metadata, regenerated from source files by setuptools.
/*.egg-info
/*.egg

/.claude/
/.venv/
36 changes: 36 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[project]
name = "simglucose"
version = "0.2.11"
description = "A Type-1 Diabetes Simulator as a Reinforcement Learning Environment in OpenAI gym or rllab"
readme = "README.md"
license = {text = "MIT"}
authors = [{name = "Jinyu Xie", email = "xjygr08@gmail.com"}]
requires-python = ">=3.9"
dependencies = [
"gym==0.9.4",
"gymnasium~=0.29.1",
"pathos>=0.3.1",
"scipy>=1.11.0",
"matplotlib>=3.7.2",
"numpy>=1.25.0",
"pandas>=2.0.3",
]

[project.optional-dependencies]
gpu = ["torch>=2.0"]

[project.urls]
Homepage = "https://github.com/jxx123/simglucose"

[build-system]
requires = ["setuptools>=64"]
build-backend = "setuptools.build_meta"

[tool.setuptools.packages.find]
include = ["simglucose*"]

[tool.setuptools.package-data]
simglucose = ["params/*.csv"]

[tool.pytest.ini_options]
testpaths = ["tests"]
24 changes: 1 addition & 23 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,3 @@
from setuptools import setup

setup(
name="simglucose",
version="0.2.11",
description="A Type-1 Diabetes Simulator as a Reinforcement Learning Environment in OpenAI gym or rllab (python implementation of UVa/Padova Simulator)",
url="https://github.com/jxx123/simglucose",
author="Jinyu Xie",
author_email="xjygr08@gmail.com",
license="MIT",
packages=["simglucose"],
install_requires=[
"gym==0.9.4",
"gymnasium~=0.29.1",
"pathos>=0.3.1",
"scipy>=1.11.0",
"matplotlib>=3.7.2",
"numpy>=1.25.0",
"pandas>=2.0.3",
],
include_package_data=True,
zip_safe=False,
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
)
setup()
4 changes: 2 additions & 2 deletions simglucose/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from gym.envs.registration import register
from gymnasium.envs.registration import register

register(
id='simglucose-v0',
entry_point='simglucose.envs:T1DSimEnv',
entry_point='simglucose.envs:T1DSimGymnaisumEnv',
)
17 changes: 17 additions & 0 deletions simglucose/_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""Centralized path resolution for simglucose data files.

Uses __file__-relative paths so editable installs work correctly.
"""

import os

_PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))


def resource_path(*parts: str) -> str:
"""Resolve a path relative to the simglucose package root.

Usage:
resource_path("params", "vpatient_params.csv")
"""
return os.path.join(_PACKAGE_DIR, *parts)
5 changes: 2 additions & 3 deletions simglucose/actuator/pump.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import pandas as pd
import pkg_resources
import logging
import numpy as np
from simglucose.utils import _get_resource_path

INSULIN_PUMP_PARA_FILE = pkg_resources.resource_filename(
'simglucose', 'params/pump_params.csv')
INSULIN_PUMP_PARA_FILE = _get_resource_path("simglucose", "params/pump_params.csv")
logger = logging.getLogger(__name__)


Expand Down
55 changes: 55 additions & 0 deletions simglucose/analysis/risk.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np


def risk_index(BG, horizon):
# BG is in mg/dL
BG_to_compute = BG[-horizon:]
Expand Down Expand Up @@ -38,3 +39,57 @@ def risk(BG):
if U >= 0:
rh = ri
return (rl, rh, ri)


# ---------------------------------------------------------------------------
# Vectorised batch variants (PyTorch) — used by the GPU batch environment
# ---------------------------------------------------------------------------

def risk_batch(BG):
"""
Vectorised risk score for a (N,) BG tensor.

Mirrors the scalar ``risk()`` function but operates on a full batch.

Returns
-------
ri : Tensor, shape (N,) — total risk index per patient
rl : Tensor, shape (N,) — low-BG component
rh : Tensor, shape (N,) — high-BG component
"""
import torch
MIN_BG = 20.0
MAX_BG = 600.0

BG_safe = BG.clamp(min=MIN_BG + 1e-8, max=MAX_BG - 1e-8)
U = 1.509 * (torch.log(BG_safe) ** 1.084 - 5.381)
ri = 10.0 * U ** 2

# Boundary overrides
ri = torch.where(BG <= MIN_BG, torch.full_like(ri, 100.0), ri)
ri = torch.where(BG >= MAX_BG, torch.full_like(ri, 100.0), ri)

rl = torch.where((U <= 0) & (BG > MIN_BG) & (BG < MAX_BG), ri, torch.zeros_like(ri))
rl = torch.where(BG <= MIN_BG, torch.full_like(rl, 100.0), rl)

rh = torch.where((U >= 0) & (BG > MIN_BG) & (BG < MAX_BG), ri, torch.zeros_like(ri))
rh = torch.where(BG >= MAX_BG, torch.full_like(rh, 100.0), rh)

return ri, rl, rh


def risk_diff_batch(cgm_hist):
"""
Batch reward = risk[t-1] - risk[t] (risk reduction is positive).

Parameters
----------
cgm_hist : Tensor shape (N, W), W >= 2 — rolling CGM window, newest last.

Returns
-------
reward : Tensor shape (N,)
"""
ri_prev, _, _ = risk_batch(cgm_hist[:, -2])
ri_curr, _, _ = risk_batch(cgm_hist[:, -1])
return ri_prev - ri_curr
8 changes: 3 additions & 5 deletions simglucose/controller/basal_bolus_ctrller.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@
from .base import Action
import numpy as np
import pandas as pd
import pkg_resources
import logging
from simglucose.utils import _get_resource_path

logger = logging.getLogger(__name__)
CONTROL_QUEST = pkg_resources.resource_filename('simglucose',
'params/Quest.csv')
PATIENT_PARA_FILE = pkg_resources.resource_filename(
'simglucose', 'params/vpatient_params.csv')
CONTROL_QUEST = _get_resource_path("simglucose", "params/Quest.csv")
PATIENT_PARA_FILE = _get_resource_path("simglucose", "params/vpatient_params.csv")


class BBController(Controller):
Expand Down
4 changes: 4 additions & 0 deletions simglucose/envs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
from simglucose.envs.simglucose_gym_env import T1DSimEnv
from simglucose.envs.simglucose_gym_env import T1DSimGymnaisumEnv
try:
from simglucose.envs.batch_env import T1DSimVectorEnv
except Exception:
pass
Loading
Loading