def run_parameter_scan(parallel=False): """Perform a parameter scan""" # [2] value scan scan_changeset = ChangeSet.scan_changeset('n', values=np.linspace(start=2, stop=10, num=8)) tcsims = ensemble(sim=TimecourseSim([ Timecourse(start=0, end=100, steps=100, changes={}), Timecourse(start=0, end=60, steps=100, changes={'[X]': 10}), Timecourse(start=0, end=60, steps=100, changes={'X': 10}), ]), changeset=scan_changeset) print(tcsims[0]) if parallel: simulator = SimulatorParallel(path=MODEL_REPRESSILATOR) results = simulator.timecourses(tcsims) assert isinstance(results, Result) else: simulator = SimulatorSerial(path=MODEL_REPRESSILATOR) results = simulator.timecourses(tcsims) assert isinstance(results, Result) return results
def stepped_clamp(simulator, r): changes_init = pkpd.init_concentrations_changes(r, 'som', 0E-6) # [0 nmol/L] tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=60, steps=120, changes=changes_init), Timecourse(start=0, end=60, steps=120, changes={'Ri_som': 10.0E-6}), # [mg/min], Timecourse(start=0, end=60, steps=120, changes={'Ri_som': 20.0E-6}), # [mg/min], Timecourse(start=0, end=60, steps=120, changes={'Ri_som': 40.0E-6}), # [mg/min], Timecourse(start=0, end=60, steps=120, changes={'Ri_som': 80.0E-6}), # [mg/min], ]), ChangeSet.parameter_sensitivity_changeset(r, 0.1) ) return simulator.timecourses(tcsims)
def run_sensitivity(): """ Parameter sensitivity simulations. :return: """ simulator = Simulator(MODEL_REPRESSILATOR) # parameter sensitivity # FIXME: make work with parallel r = load_model(MODEL_REPRESSILATOR) changeset = ChangeSet.parameter_sensitivity_changeset(r) tc_sim = TimecourseSim([ Timecourse(start=0, end=100, steps=100), Timecourse(start=0, end=200, steps=100, model_changes={"boundary_condition": { "X": True }}), Timecourse(start=0, end=100, steps=100, model_changes={"boundary_condition": { "X": False }}), ]) tc_sims = ensemble(tc_sim, changeset=changeset) result = simulator.timecourses(tc_sims) # create figure fig, (ax1) = plt.subplots(nrows=1, ncols=1, figsize=(5, 5)) fig.subplots_adjust(wspace=0.3, hspace=0.3) add_line(ax=ax1, data=result, xid='time', yid="X", label="X") add_line(ax=ax1, data=result, xid='time', yid="Y", label="Y", color="darkblue") add_line(ax=ax1, data=result, xid='time', yid="Z", label="Z", color="darkorange") ax1.legend() plt.show()
def po_bolus(simulator, r): """ Oral bolus dose oral dose (single dose, at given start with given dose). Examples are the oral glucose tolerance test (OGTT) or the application of a drug orally, e.g., codeine, midazolam, caffeine or paracetamol. :return: """ # set initial concentration of somatostatin in all blood compartments changes_init = pkpd.init_concentrations_changes(r, 'som', 0E-6) # [0 nmol/L] # oral bolus dose # FIXME: dosing changesets changes_po_bolus = { 'PODOSE_som': 10.0E-6, # [mg] } # simulate tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=1200, steps=600, changes={ **changes_init, **changes_po_bolus} ) ]), changeset=ChangeSet.parameter_sensitivity_changeset(r, 0.1) ) return simulator.timecourses(tcsims)
def test_plotting(): r = load_model(MODEL_REPRESSILATOR) simulator = Simulator(MODEL_REPRESSILATOR) changeset = ChangeSet.parameter_sensitivity_changeset(r, sensitivity=0.5) tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=400, steps=400), ]), changeset) result = simulator.timecourses(tcsims) # create figure fig, (ax1) = plt.subplots(nrows=1, ncols=1, figsize=(5, 5)) fig.subplots_adjust(wspace=0.3, hspace=0.3) add_line(ax=ax1, data=result, xid='time', yid="X", label="X") add_line(ax=ax1, data=result, xid='time', yid="Y", label="Y", color="darkblue") ax1.legend() plt.show()
def mix(simulator, r): """ [5] combination experiments - somatostatin infusion + c-peptide bolus - hyperinsulinemic, euglycemic clamp """ changes_init = pkpd.init_concentrations_changes(r, 'som', 0E-6) # [0 nmol/L] tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=60, steps=120, changes=changes_init), Timecourse(start=0, end=60, steps=120, changes={'IVDOSE_som': 10.0E-6}), Timecourse(start=0, end=60, steps=240, changes={'Ri_som': 10.0E-6}), # [mg/min], Timecourse(start=0, end=60, steps=120, changes={'Ri_som': 10.0E-6, 'PODOSE_som': 10.0E-4}), Timecourse(start=0, end=120, steps=240, changes={'Ri_som': 0.0}), # [mg/min], ]), ChangeSet.parameter_sensitivity_changeset(r, 0.1)) return simulator.timecourses(tcsims)
def iv_infusion(simulator, r): """ [3] constant infusion (for given period, tstart, tend) - somatostatin infusion - insulin infusion - glucose infusion - glucagon infusion :return: """ changes_init = pkpd.init_concentrations_changes(r, 'som', 0E-6) # [0 nmol/L] tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=60, steps=120, changes=changes_init), Timecourse(start=0, end=120, steps=240, changes={'Ri_som': 10.0E-6}), # [mg/min], Timecourse(start=0, end=120, steps=240, changes={'Ri_som': 0.0}), # [mg/min], ]), ChangeSet.parameter_sensitivity_changeset(r, 0.1) ) return simulator.timecourses(tcsims)
def clamp(simulator, r): """ clamping of substance (e.g. glucose, tstart, tend) - glucose clamping (euglycemic clamp) - insulin clamping (insulin clamp) :return: """ changes_init = pkpd.init_concentrations_changes(r, 'som', 0E-6) # [0 nmol/L] # FIXME: some bug in the concentrations and assignments tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=60, steps=120, changes={**changes_init, **{'PODOSE_som': 1E-9}}), Timecourse(start=0, end=120, steps=240, model_changes={'boundary_condition': {"Ave_som": True}}), # clamp venous som Timecourse(start=0, end=120, steps=240, model_changes={'boundary_condition': {"Ave_som": False}}), # release venous som, ]), ChangeSet.parameter_sensitivity_changeset(r, 0.1) ) return simulator.timecourses(tcsims)
def test_timecourse_simulation(): simulator = Simulator(MODEL_REPRESSILATOR) s = simulator.timecourse(Timecourse(start=0, end=100, steps=100)) assert s is not None s = simulator.timecourse( Timecourse(start=0, end=100, steps=100, changes={"PX": 10.0})) assert s is not None assert isinstance(s, pd.DataFrame) assert "time" in s assert len(s.time) == 101 assert s.PX[0] == 10.0 s = simulator.timecourse( TimecourseSim(timecourses=[ Timecourse(start=0, end=100, steps=100, changes={"[X]": 10.0}) ])) assert s is not None
def run_clamp(): def plot_result(result: Result, title: str = None) -> None: # create figure fig, (ax1) = plt.subplots(nrows=1, ncols=1, figsize=(5, 5)) fig.subplots_adjust(wspace=0.3, hspace=0.3) plotting.add_line(ax=ax1, data=result, xid='time', yid="X", label="X") plotting.add_line(ax=ax1, data=result, xid='time', yid="Y", label="Y", color="darkblue") if title: ax1.set_title(title) ax1.legend() plt.show() # reference simulation simulator = Simulator(MODEL_REPRESSILATOR) tcsim = TimecourseSim([ Timecourse(start=0, end=400, steps=400, changes={"X": 10}), # clamp simulation Timecourse(start=0, end=200, steps=200, model_changes={'boundary_condition': { 'X': True }}), # free simulation Timecourse(start=0, end=400, steps=400, model_changes={'boundary_condition': { 'X': False }}), ]) result = simulator.timecourses(tcsim) assert isinstance(result, Result) plot_result(result, "clamp experiment (400-600)")
def example_multiple_actors(): """Multiple independent simulator actors. Actors should not be created manually, use the Simulator classes for simulations. """ # create ten Simulators. simulators = [SimulatorActor.remote(MODEL_REPRESSILATOR) for _ in range(16)] # define timecourse tcsim = TimecourseSim([ Timecourse(start=0, end=100, steps=100), Timecourse(start=0, end=100, steps=100, changes={"X": 10, "Y": 20}), ]) # run simulation on simulators tc_ids = [s.timecourse.remote(tcsim) for s in simulators] # collect results results = ray.get(tc_ids) return results
def test_timecourse_combined(): simulator = Simulator(MODEL_REPRESSILATOR) s = simulator.timecourse(simulation=TimecourseSim([ Timecourse(start=0, end=100, steps=100), Timecourse(start=0, end=50, steps=100, model_changes={"boundary_condition": { "X": True }}), Timecourse(start=0, end=100, steps=100, model_changes={"boundary_condition": { "X": False }}), ])) assert isinstance(s, pd.DataFrame) assert "time" in s assert s.time.values[-1] == 250.0
def example_single_actor(): """ Creates a single stateful simulator actor and executes timecourse. Normally multiple actors are created which execute the simulation load together. Actors should not be created manually, use the Simulator classes for simulations. :return: """ # Create single actor process sa = SimulatorActor.remote(MODEL_REPRESSILATOR) # run simulation tcsim = TimecourseSim([ Timecourse(start=0, end=100, steps=100), Timecourse(start=0, end=100, steps=100, changes={"X": 10, "Y": 20}), ]) tc_id = sa.timecourse.remote(tcsim) print("-" * 80) print(ray.get(tc_id)) print("-" * 80)
def test_timecourse_ensemble(): changeset = [ { "[X]": 10.0 }, { "[X]": 15.0 }, { "[X]": 20.0 }, { "[X]": 25.0 }, ] simulator = Simulator(MODEL_REPRESSILATOR) tcsims = ensemble(TimecourseSim([ Timecourse(start=0, end=400, steps=400), ]), changeset=changeset) result = simulator.timecourses(tcsims) assert isinstance(result, Result)
def iv_bolus(simulator, r): """ [2] bolus injection (at given time tstart, with given dose and given injection time, e.g. 5-10 min) - c-peptide bolus - ivGTT (glucose bolus) - insulin injection """ changes_init = pkpd.init_concentrations_changes(r, 'som', 0E-6) # [0 nmol/L] changes_iv_bolus = { 'IVDOSE_som': 10E-6, # [mg] } p_changeset = ChangeSet.parameter_sensitivity_changeset(r, 0.1) tcsims = ensemble( TimecourseSim([ Timecourse(start=0, end=1200, steps=600, changes={ **changes_init, **changes_iv_bolus} ) ]), p_changeset) return simulator.timecourses(tcsims)
def test_simulation_parallel(): tcsims = [] tc_sim = TimecourseSim([ Timecourse( start=0, end=100, steps=100, changes={ 'IVDOSE_som': 0.0, # [mg] 'PODOSE_som': 0.0, # [mg] 'Ri_som': 10.0E-6, # [mg/min] }) ]) # collect multiple simulation definitions (see also the ensemble functions) nsim = 100 for _ in range(nsim): tcsims.append(tc_sim) simulator = Simulator(path=MODEL_GLCWB, actor_count=15) results = simulator.timecourses(simulations=tcsims)
def run_timecourse_examples(): """ Run various timecourses. """ simulator = Simulator(MODEL_REPRESSILATOR) # 1. simple timecourse simulation print("*** simple timecourse ***") tc_sim = TimecourseSim(Timecourse(start=0, end=100, steps=100)) s1 = simulator.timecourses(tc_sim) print(tc_sim) # 2. timecourse with parameter changes print("*** parameter change ***") tc_sim = TimecourseSim( Timecourse(start=0, end=100, steps=100, changes={ "X": 10, "Y": 200 })) s2 = simulator.timecourses(tc_sim) print(tc_sim) # 3. combined timecourses print("*** combined timecourse ***") tc_sim = TimecourseSim([ Timecourse(start=0, end=100, steps=100), Timecourse(start=0, end=100, steps=100, changes={ "X": 10, "Y": 20 }), ]) s3 = simulator.timecourses(tc_sim) print(tc_sim) # 4. combined timecourses with model_change print("*** model change ***") tc_sim = TimecourseSim([ Timecourse(start=0, end=100, steps=100), Timecourse(start=0, end=50, steps=100, model_changes={"boundary_condition": { "X": True }}), Timecourse(start=0, end=100, steps=100, model_changes={"boundary_condition": { "X": False }}), ]) s4 = simulator.timecourses(tc_sim) print(tc_sim) # create figure fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=1, ncols=4, figsize=(20, 5)) fig.subplots_adjust(wspace=0.3, hspace=0.3) ax1.set_title("simple timecourse") ax2.set_title("parameter change") ax3.set_title("combined timecourse") ax4.set_title("model change") for s, ax in [(s1, ax1), (s2, ax2), (s3, ax3), (s4, ax4)]: df = s.frames[0] ax.plot(df.time, df.X, label="X") ax.plot(df.time, df.Y, label="Y") ax.plot(df.time, df.Z, label="Z") for ax in (ax1, ax2, ax3, ax4): ax.legend() ax.set_xlabel("time") ax.set_ylabel("concentration") plt.show()
def example_parallel_timecourse(nsim=40, actor_count=15): """Execute multiple simulations with model in parallel. :param nsim: number of simulations :return: """ tcsims = [] tc_sim = TimecourseSim([ Timecourse(start=0, end=100, steps=100, changes={ 'IVDOSE_som': 0.0, # [mg] 'PODOSE_som': 0.0, # [mg] 'Ri_som': 10.0E-6, # [mg/min] }) ]) # collect all simulation definitions (see also the ensemble functions) for _ in range(nsim): tcsims.append(tc_sim) def message(info, time): print(f"{info:<10}: {time:4.3f}") # load model once for caching (fair comparison) r = roadrunner.RoadRunner(MODEL_GLCWB) print("-" * 80) print(f"Run '{nsim}' simulations") print("-" * 80) simulator_defs = [ { "key": "parallel", 'simulator': SimulatorParallel, 'kwargs': {'actor_count': actor_count} }, { "key": "serial", 'simulator': SimulatorSerial, 'kwargs': {} }, ] sim_info = [] for sim_def in simulator_defs: key = sim_def['key'] print("***", key, "***") Simulator = sim_def['simulator'] kwargs = sim_def['kwargs'] # run simulation (with model reading) start_time = time.time() # create a simulator with 16 parallel actors simulator = Simulator(path=MODEL_GLCWB, **kwargs) load_time = time.time()-start_time message(f"load", load_time) start_time = time.time() results = simulator.timecourses(simulations=tcsims) sim_time = time.time()-start_time total_time = load_time + sim_time message("simulate", sim_time) message("total", total_time) assert(len(results) == len(tcsims)) time.sleep(3) # run parallel simulation (without model reading) start_time = time.time() results = simulator.timecourses(simulations=tcsims) repeat_time = time.time()-start_time message(f"repeat", repeat_time) assert (len(results) == len(tcsims)) actor_count = kwargs.get('actor_count', 1) times = { "load": load_time, "simulate": sim_time, "total": total_time, "repeat": repeat_time, } sim_info.extend([{ "key": key, "nsim": nsim, "actor_count": actor_count, "time_type": k, "time": v, } for (k, v) in times.items()]) print("-" * 80) return sim_info