Exemplo n.º 1
0
def create_sim_instance(sim_time=None,
                        scenario=None,
                        controller=None,
                        start_time=None,
                        save_path=None,
                        animate=True):
    if sim_time is None:
        #입력받은 시간을 시간값으로 할당
        sim_time = timedelta(
            hours=float(input('Input simulation time (hr): ')))

    if scenario is None:
        scenario = pick_scenario()

    envs = build_envs(scenario, start_time)

    if controller is None:
        controller = pick_controller()

    ctrllers = [copy.deepcopy(controller) for _ in range(len(envs))]

    sim_instances = [
        SimObj(e, c, sim_time, animate=animate, path=save_path)
        for (e, c) in zip(envs, ctrllers)
    ]
    return sim_instances
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)
Exemplo n.º 3
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)
Exemplo n.º 4
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.º 5
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)
Exemplo n.º 6
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!')
Exemplo n.º 7
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!')
Exemplo n.º 8
0
        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
        
Exemplo n.º 9
0
def simulate(sim_time=None,
             scenario=None,
             controller=None,
             patient_names=[],
             cgm_name=None,
             cgm_seed=None,
             insulin_pump_name=None,
             start_time=None,
             save_path=None,
             animate=None,
             parallel=None):
    '''
    Main user interface.
    ----
    Inputs:
    sim_time   - a datetime.timedelta object specifying the simulation time.
    scenario   - a simglucose.scenario.Scenario object. Use
                 simglucose.scenario_gen.RandomScenario or
                 simglucose.scenario.CustomScenario to create a scenario object.
    controller - a simglucose.controller.Controller object.
    start_time - a datetime.datetime object specifying the simulation start time.
    save_path  - a string representing the directory to save simulation results.
    animate    - switch for animation. True/False.
    parallel   - switch for parallel computing. True/False.
    '''
    if animate is None:
        animate = pick_animate()

    if parallel is None:
        parallel = pick_parallel()

    if platform.system() == 'Darwin' and (animate and parallel):
        raise ValueError(
            """animate and parallel cannot be turned on at the same time in macOS."""
        )

    if save_path is None:
        save_path = pick_save_path()

    if sim_time is None:
        sim_time = timedelta(
            hours=float(input('Input simulation time (hr): ')))

    if scenario is None:
        scenario = pick_scenario(start_time=start_time)

    if not patient_names:
        patient_names = pick_patients()

    if cgm_name is None:
        cgm_name = pick_cgm_sensor()

    if cgm_seed is None:
        cgm_seed = pick_cgm_seed()

    if insulin_pump_name is None:
        insulin_pump_name = pick_insulin_pump()

    if controller is None:
        controller = pick_controller()

    def local_build_env(pname):
        patient = T1DPatient.withName(pname)
        cgm_sensor = CGMSensor.withName(cgm_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

    envs = [local_build_env(p) for p in patient_names]

    ctrllers = [copy.deepcopy(controller) for _ in range(len(envs))]
    sim_instances = [
        SimObj(e, c, sim_time, animate=animate, path=save_path)
        for (e, c) in zip(envs, ctrllers)
    ]

    results = batch_sim(sim_instances, parallel=parallel)

    df = pd.concat(results, keys=[s.env.patient.name for s in sim_instances])
    results, ri_per_hour, zone_stats, figs, axes = report(df, save_path)

    return results
# --------- 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)
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()
    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.º 12
0
# --------- 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)
# 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
Exemplo n.º 13
0
        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)