def pick_scenario():
    while True:
        print('Select scnenario:')
        print('[1] Random Scnenario')
        print('[2] Custom Scnenario')
        input_value = input('>>>')
        try:
            selection = int(input_value)
        except ValueError:
            print('Please input an integer!')
            continue
        if selection < 1 or selection > 2:
            print('Please input a number from the list!')
        else:
            break
    if selection == 1:
        while True:
            input_value = input(
                'Select random seed for random scenario [None]: ')
            try:
                seed = int(input_value)
                break
            except ValueError:
                if input_value == '' or input_value == 'None':
                    seed = None
                    break
                else:
                    print('Please input an integer!')
                    continue
        scenario = RandomScenario(seed=seed)
    elif selection == 2:
        scenario = CustomScenario()

    return scenario
Exemplo n.º 2
0
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 __init__(self, patient_name=None, reward_fun=None):
        '''
        patient_name must be 'adolescent#001' to 'adolescent#010',
        or 'adult#001' to 'adult#010', or 'child#001' to 'child#010'
        '''
        seeds = self._seed()
        # have to hard code the patient_name, gym has some interesting
        # error when choosing the patient
        if patient_name is None:
            patient_name = 'adolescent#001'
        patient = T1DPatient.withName(patient_name)
        sensor = CGMSensor.withName('Dexcom', seed=seeds[1])
        hour = self.np_random.randint(low=0.0, high=24.0)
        start_time = datetime(2018, 1, 1, hour, 0, 0)
        # scenario = RandomScenario(start_time=start_time, seed=seeds[2])

        # Added a custom scenario with no meals
        # scen = [(7, 45), (12, 70), (16, 15), (18, 80), (23, 10)]
        scen = [(0, 0)]
        scenario = CustomScenario(start_time=start_time, scenario=scen)
        pump = InsulinPump.withName('Insulet')
        self.env = _T1DSimEnv(patient, sensor, pump, scenario)
        self.reward_fun = reward_fun

        # Added by Jonas -- state space is now 10 * sample_time = 30 minutes long
        self.state_space_length = 10
        self.insulin_history = np.zeros(4)
    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)
Exemplo n.º 5
0
def run_sim_once(simtime, meals, controller, patients):
    # times
    run_time = timedelta(hours=simtime)
    start_time = datetime(2020, 1, 1, 0,0,0)
    scenario = CustomScenario(start_time = start_time, scenario=meals)
    envs = build_envs(scenario, start_time, patients)
    # must deepcopy controllers because they're dynamic
    controllers = [copy.deepcopy(controller) for _ in range(len(envs))]
    sim_instances = [SimObj(env, ctr, run_time, animate=False, path='./results') for (env, ctr) in zip(envs, controllers)]
    # run simulations
    results = batch_sim(sim_instances, parallel=False)
    # create dataframe with results from 1 sim
    return pd.concat(results, keys=[s.env.patient.name for s in sim_instances])
Exemplo n.º 6
0
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 __init__(self,
                 patient_name=None,
                 reward_fun=None,
                 scen=None,
                 start_time=None,
                 sensor_name=None,
                 pump_name=None):  #, scenario_tup=None, startTime=None
        '''
        patient_name must be 'adolescent#001' to 'adolescent#010',
        or 'adult#001' to 'adult#010', or 'child#001' to 'child#010'
        '''
        seeds = self._seed()
        # have to hard code the patient_name, gym has some interesting
        # error when choosing the patient
        if patient_name is None:
            patient_name = 'adolescent#001'

        if sensor_name is None:
            sensor_name = 'Dexcom'

        if pump_name is None:
            pump_name = 'Insulet'

        print(patient_name)
        print(sensor_name)
        print(pump_name)
        print(scen)

        patient = T1DPatient.withName(patient_name)
        sensor = CGMSensor.withName(sensor_name, seed=seeds[1])
        #hour = self.np_random.randint(low=0.0, high=24.0)
        #start_time = datetime(2018, 1, 1, hour, 0, 0)

        scenario = CustomScenario(
            start_time=start_time, scenario=scen
        )  #RandomScenario(start_time=start_time, seed=seeds[2])
        pump = InsulinPump.withName(pump_name)
        self.env = _T1DSimEnv(patient, sensor, pump, scenario)
        self.reward_fun = reward_fun
Exemplo n.º 8
0
def pick_scenario(start_time=None):
    while True:
        print('Select scnenario:')
        print('[1] Random Scnenario')
        print('[2] Custom Scnenario')
        input_value = input('>>>')
        try:
            selection = int(input_value)
        except ValueError:
            print('Please input an integer!')
            continue
        if selection < 1 or selection > 2:
            print('Please input a number from the list!')
        else:
            break

    if start_time is None:
        start_time = pick_start_time()

    if selection == 1:
        while True:
            input_value = input(
                'Select random seed for random scenario [None]: ')
            try:
                seed = int(input_value)
                break
            except ValueError:
                if input_value in ('', 'None'):
                    seed = None
                    break
                print('Please input an integer!')
                continue
        scenario = RandomScenario(start_time, seed=seed)
    else:
        custom_scenario = input_custom_scenario()
        scenario = CustomScenario(start_time, custom_scenario)

    return scenario
    def __init__(self, patient_name=None, reward_fun=None, Initial_Bg=0):
        '''
        patient_name must be 'adolescent#001' to 'adolescent#010',
        or 'adult#001' to 'adult#010', or 'child#001' to 'child#010'
        '''
        seeds = self._seed()
        # have to hard code the patient_name, gym has some interesting
        # error when choosing the patient
        if patient_name is None:
            patient_name = 'adolescent#001'
        patient = T1DPatient.withName(patient_name, Initial_Bg)
        sensor = CGMSensor.withName('GuardianRT', seed=seeds[1])  #Dexcom
        hour = 20  #self.np_random.randint(low=0.0, high=24.0)
        start_time = datetime(2018, 1, 1, hour, 0, 0)
        # scenario = RandomScenario(start_time=start_time, seed=seeds[2])
        # custom scenario is a list of tuples (time, meal_size)
        # scen = [(0,float(Initial_Bg)),(13, 45), (16, 10), (18, 35), (22, 10)]#, (23, 10)]
        scen = [(13, 45), (16, 10), (18, 35), (22, 10)]  #, (23, 10)]
        scenario = CustomScenario(start_time=start_time, scenario=scen)

        pump = InsulinPump.withName('Insulet')
        self.env = _T1DSimEnv(patient, sensor, pump, scenario)
        self.reward_fun = reward_fun
Exemplo n.º 10
0
        ki +=.000001
        print('kp=' + str(ki))
        #           (kp, ki, kd, target, low)
        PIDparams = (0.00025, round(ki, 7), 0, 120, 70)

        dfs = run_sim_PID(n, adults, t, meals, PIDparams)

        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)
# 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()

# Put them together to create a simulation object
s2 = SimObj(env, controller, timedelta(days=1), animate=False, path=path)
results2 = sim(s2)
print(results2)


# --------- batch simulation --------------
# Re-initialize simulation objects
s1.reset()
s2.reset()
Exemplo n.º 12
0
sim_pump = InsulinPump.withName('Insulet')

# 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)