def test_batch_sim(self): # specify start_time as the beginning of today now = datetime.now() start_time = datetime.combine(now.date(), datetime.min.time()) # --------- Create Random Scenario -------------- # Create a simulation environment patient = T1DPatient.withName('adolescent#001') sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') scenario = RandomScenario(start_time=start_time, seed=1) env = T1DSimEnv(patient, sensor, pump, scenario) # Create a controller controller = BBController() # Put them together to create a simulation object s1 = SimObj(env, controller, timedelta( days=2), animate=True, path=save_folder) results1 = sim(s1) # --------- Create Custom Scenario -------------- # Create a simulation environment patient = T1DPatient.withName('adolescent#001') sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') # custom scenario is a list of tuples (time, meal_size) scen = [(7, 45), (12, 70), (16, 15), (18, 80), (23, 10)] scenario = CustomScenario(start_time=start_time, scenario=scen) env = T1DSimEnv(patient, sensor, pump, scenario) # Create a controller controller = BBController() # Put them together to create a simulation object s2 = SimObj(env, controller, timedelta( days=2), animate=False, path=save_folder) results2 = sim(s2) # --------- batch simulation -------------- s1.reset() s2.reset() s1.animate = False s = [s1, s2] results_para = batch_sim(s, parallel=True) s1.reset() s2.reset() s = [s1, s2] results_serial = batch_sim(s, parallel=False) assert_frame_equal(results_para[0], results1) assert_frame_equal(results_para[1], results2) for r1, r2 in zip(results_para, results_serial): assert_frame_equal(r1, r2)
def local_build_env(pname): patient = T1DPatient.withName(pname) cgm_sensor = CGMSensor.withName(cgm_sensor_name, seed=cgm_seed) insulin_pump = InsulinPump.withName(insulin_pump_name) scen = copy.deepcopy(scenario) env = T1DSimEnv(patient, cgm_sensor, insulin_pump, scen) return env
def run_sim_PID_once(pname, runtime, meals, controller_params): ''' Run the simulation a single time on a single patient with the PID controller. Parameters ---------- pname: str patient name runtime: int simulation time, in hours. meals: (timedelta, int) a tuple containing the time of meal (as referenced from simulation start) and the meal size, in grams. targetBG: int the target blood glucose for the controller, in mg/dl lowBG: int the pump suspension glucose for the controller, in mg/dl Returns ------- A pandas dataframe containing the simulation results. axis=0: time, type datetime.datetime axis=1: data category, type str ''' sensor = CGMSensor.withName('Dexcom') pump = InsulinPump.withName('Insulet') scenario = CustomScenario(start_time = datetime(2020, 1, 1, 0,0,0), scenario=meals) obj = SimObj(T1DSimEnv(T1DPatient.withName(pname), sensor, pump, scenario), controller.PIDController(controller_params, pname), timedelta(hours=runtime), animate=False, path=None) return sim(obj)
def build_env(pname): patient = T1DPatient.withName(pname) sensor = CGMSensor.withName('Dexcom') pump = InsulinPump.withName('Insulet') copied_scenario = copy.deepcopy(scenario) env = T1DSimEnv(patient, sensor, pump, copied_scenario) return env
def test_results_consistency(self): # Test data results_exp = pd.read_csv(TESTDATA_FILENAME, index_col=0) results_exp.index = pd.to_datetime(results_exp.index) # specify start_time as the beginning of today start_time = datetime(2018, 1, 1, 0, 0, 0) # --------- Create Random Scenario -------------- # Create a simulation environment patient = T1DPatient.withName('adolescent#001') sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') scenario = RandomScenario(start_time=start_time, seed=1) env = T1DSimEnv(patient, sensor, pump, scenario) # Create a controller controller = BBController() # Put them together to create a simulation object s = SimObj(env, controller, timedelta(days=2), animate=False, path=save_folder) results = sim(s) assert_frame_equal(results, results_exp)
def run_sim_PID(no_runs, patients, runtime, meals, controller_params): ''' Run the simulation a single time on a list of patients with the PID controller. Parameters ---------- no_runs: int the number of separate simulation runs. patients: list of str a list of patient name strings. Patient name strings can be found in the params/Quest.csv file inside simGlucose. runtime: int simulation time, in hours. meals: (timedelta, int) a tuple containing the time of meal (as referenced from simulation start) and the meal size, in grams. targetBG: int the target blood glucose for the controller, in mg/dl lowBG: int the pump suspension glucose for the controller, in mg/dl Returns ------- A pandas dataframe containing the simulation results. axis=0: time, type datetime.datetime axis=1: MultiIndex level 0: data category, type str level 1: patient id, type str level 2: run number, type int (starts at 1) ''' sensor = CGMSensor.withName('Dexcom') pump = InsulinPump.withName('Insulet') scenario = CustomScenario(start_time = datetime(2020, 1, 1, 0,0,0), scenario=meals) sim_objs = [] keys = [] for run in range(0, no_runs): for pname in patients: sim_objs.append(SimObj(T1DSimEnv(T1DPatient.withName(pname), sensor, pump, copy.deepcopy(scenario)), # because random numbers. controller.PIDController(controller_params, pname), timedelta(hours=runtime), animate=False, path=None)) keys.append((run + 1, pname)) p_start = time.time() print('Running batch simulation of {} items...'.format(len(patients * no_runs))) p = pathos.pools.ProcessPool() results = p.map(sim, sim_objs) print('Simulation took {} seconds.'.format(time.time() - p_start)) return pd.concat(results, axis=1, keys=keys)
def pidsim(): for idx,patient in enumerate(patients): patient = T1DPatient.withName(patient) sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') p,i,d = pidparams[idx] for seed in range (10,20): scenario = RandomScenario(start_time=start_time, seed=randint(10, 99999)) env = T1DSimEnv(patient, sensor, pump, scenario) # Create a controller controller = FoxPIDController(112.517,kp=p, ki=i, kd=d) # Put them together to create a simulation object s1 = SimObj(env, controller, timedelta(days=10), animate=False, path=path+str(seed)) results1 = sim(s1) print('Complete:',patient.name,'-',seed) print('All done!')
def bbsim(): for patient in patients: patient = T1DPatient.withName(patient) sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') for seed in range(10, 20): scenario = RandomScenario(start_time=start_time, seed=randint(10, 99999)) env = T1DSimEnv(patient, sensor, pump, scenario) # Create a controller controller = BBController() # Put them together to create a simulation object s1 = SimObj(env, controller, timedelta(days=10), animate=False, path=path + str(seed)) results1 = sim(s1) print('Complete:', patient.name, '-', seed) print('All done!')
filename = 'dfs/' + 'p_' + str(PIDparams[0]) + ' i_' + str(PIDparams[1]) + ' d_' + str(PIDparams[2]) + ' target_' + str(PIDparams[3]) + '.bz2' dfs.to_pickle(filename) ======= pname = "adult#001" t = 9 meals = [(timedelta(hours=2), 50)] sensor = CGMSensor.withName('Dexcom') pump = InsulinPump.withName('Insulet') scenario = CustomScenario(start_time = datetime(2020, 1, 1, 0,0,0), scenario=meals) keys = [] # forward horizon horizon = 50 controller_params = (140, 80, horizon) obj= SimObj(T1DSimEnv(T1DPatient.withName(pname), sensor, pump, copy.deepcopy(scenario)), # because random numbers. controller.MPCNaive(controller_params, pname), timedelta(hours=t), animate=False, path=None) keys.append((1, pname)) p_start = time.time() results = sim(obj) print('Simulation took {} seconds.'.format(time.time() - p_start)) dfs = results filename = 'mpc_test.bz2' dfs.to_pickle(filename) >>>>>>> MPC-exploration
from datetime import datetime # specify start_time as the beginning of today now = datetime.now() start_time = datetime.combine(now.date(), datetime.min.time()) # --------- Create Random Scenario -------------- # Specify results saving path path = './results' # Create a simulation environment patient = T1DPatient.withName('adolescent#001') sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') scenario = RandomScenario(start_time=start_time, seed=1) env = T1DSimEnv(patient, sensor, pump, scenario) # Create a controller controller = BBController() # Put them together to create a simulation object s1 = SimObj(env, controller, timedelta(days=1), animate=False, path=path) results1 = sim(s1) print(results1) # --------- Create Custom Scenario -------------- # Create a simulation environment patient = T1DPatient.withName('adolescent#001') sensor = CGMSensor.withName('Dexcom', seed=1) pump = InsulinPump.withName('Insulet') # custom scenario is a list of tuples (time, meal_size)
self.state = init_state def policy(self, observation, reward, done, **info): self.state = observation action = Action(basal=.0, bolus=0) return action def reset(self): self.state = self.init_state # patient setup patientID = 12 patient = T1DPatient.withID(12) sim_sensor = CGMSensor.withName('Dexcom') sim_pump = InsulinPump.withName('Insulet') # env setup RANDOM_SEED = 25 sim_start_time = datetime.now() sim_run_time = timedelta(hours=24) sim_scenario = RandomScenario(start_time = sim_start_time, seed = RANDOM_SEED) environment = T1DSimEnv(patient, sim_sensor, sim_pump, sim_scenario) controller = blankController(0) # script saves csv(s) into this path results_path = './results/' simulator = SimObj( environment, controller, sim_run_time, animate=False, path = results_path sim(simulator)
# env setup RANDOM_SEED = 5550 RUN_TIME = 48 sim_start_time = datetime(2020, 1, 1, 0, 0, 0) sim_run_time = timedelta(hours=RUN_TIME) # random scenario random_scen = RandomScenario(start_time=sim_start_time, seed=RANDOM_SEED) # custom scenario # meals is a list of tuples, each tuple containing a timedelta (time after start of sim) and a meal size, in g CHO. meals = [(timedelta(hours=12), 100)] # generate the custom scenario with the list of meals custom_scen = CustomScenario(start_time=sim_start_time, scenario=meals) # choose scenario environment = T1DSimEnv(patient, sim_sensor, sim_pump, custom_scen) # choose controller controller = PController(gain=0.04, dweight=.5, pweight=1, target=120) # script saves csv(s) into this path results_path = './results/' simulator = SimObj(environment, controller, sim_run_time, animate=False, path=results_path) results = sim(simulator) plotBG.group_plot(results, savedir='./results')