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)
예제 #2
0
    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)
예제 #3
0
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!')
예제 #4
0
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!')
# 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)
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()
            analysis_path = P.join(current_summary_path, 'Analysis')
            # init simulation
            patient_names = get_patients([patient_number])
            pump_name = get_insulin_pump(selection=2)
            cgm_seed = 5
            cgm_sensor_name = get_cgm_sensor(selection=1)
            sim_time = datetime.timedelta(hours=8)  # datetime.time(23)
            control = input("Choose controller:\n[1]DDPG\n[2]BB\n")
            if control == '2':
                # Original Controller
                controller = BBController()
                envs = our_build_envs(scenario, start_time, patient_names, cgm_sensor_name, cgm_seed, pump_name,
                                      controller_name='BB Controller', results_path=analysis_path + '_BB')
                env_BB = envs[0]
                sim1 = SimObj(env_BB, controller, sim_time, animate=animate, path=analysis_path + '_BB')
                results1 = sim(sim1)
                report(results1, analysis_path + '_BB')
                env_BB.render()
                env_BB.viewer.close()

            # Our Controller
            else:
                state_dim = gym_env.observation_space.shape[0]
                action_dim = gym_env.action_space.shape[0]
                action_bound = gym_env.action_space.high
                actor = ActorNetwork(sess, state_dim, action_dim, action_bound,
                                     float(args['actor_lr']), float(args['tau']),
                                     int(args['minibatch_size']))
                sess.run(tf.global_variables_initializer())
                actor.restore(sess, P.join(args['Load_models_path'][0], f"actor_{args['Load_models_path'][1]}"))
                our_controller = DDPG_Controller(actor=actor)
예제 #7
0
# 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)
# 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()
예제 #8
0
파일: example1.py 프로젝트: kyadamos/uciAPC
    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)
예제 #9
0
    scenario = RandomScenario(start_time=start_time, seed=1)
    env = T1DSimEnv(patient, sensor, pump, scenario)
    # tr_model = PPO2.load("sim-adl-02")
    # in_state = env.reset()
    # ctrller = MyController(0, model = tr_model) #BBController() #
    controller = BBController()
    sim_i = [
        SimObj(env, controller, timedelta(days=1), animate=False, path=path)
    ]

    # sim_instances.simulate()
    # sim_instances.save_results()
    # result =  sim(sim_instances[0])
    # print('Simulation Completed!')
    # # df = pd.concat(result, keys=[s.env.patient.name for s in sim_instances])
    # results, ri_per_hour, zone_stats, figs, axes = report(path, df=result)
    results1 = sim(sim_i[0])
    # print(results1)
    pd_result = pd.DataFrame(results1)
    bg = list(pd_result['BG'])
    print(type(bg), bg[0], type(bg[0]))

    percent_time.append(
        (len([I for I in bg if 70 <= I <= 180]) / len(bg)) * 100)

final_result = pd.DataFrame(list(zip(person_options, percent_time)),
                            columns=['Paient_ID', 'Percent_Time'])
final_result.to_csv(path + '/Final Result.csv', index=False)

# simulate(controller=ctrller)
예제 #10
0
# 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')