def test_unicode_obsname_nonascii(): """Ensure non-ascii unicode observable names error in python 2.""" t = np.linspace(0, 100) rob_copy = copy.deepcopy(robertson.model) rob_copy.observables[0].name = u'A_total\u1234' sim = ScipyOdeSimulator(rob_copy) simres = sim.run(tspan=t)
def test_lsoda_jac_solver_run(self): """Test lsoda and analytic jacobian.""" solver_lsoda_jac = ScipyOdeSimulator(self.model, tspan=self.time, integrator='lsoda', use_analytic_jacobian=True) solver_lsoda_jac.run()
def setUp(self): Monomer('A', ['a']) Monomer('B', ['b']) Parameter('ksynthA', 100) Parameter('ksynthB', 100) Parameter('kbindAB', 100) Parameter('A_init', 0) Parameter('B_init', 0) Initial(A(a=None), A_init) Initial(B(b=None), B_init) Observable("A_free", A(a=None)) Observable("B_free", B(b=None)) Observable("AB_complex", A(a=1) % B(b=1)) Rule('A_synth', None >> A(a=None), ksynthA) Rule('B_synth', None >> B(b=None), ksynthB) Rule('AB_bind', A(a=None) + B(b=None) >> A(a=1) % B(b=1), kbindAB) self.model = model # Convenience shortcut for accessing model monomer objects self.mon = lambda m: self.model.monomers[m] # This timespan is chosen to be enough to trigger a Jacobian evaluation # on the various solvers. self.time = np.linspace(0, 1) self.sim = ScipyOdeSimulator(self.model, tspan=self.time, integrator='vode')
def fig_4b(): print("Simulating model for figure 4B...") t = linspace(0, 6 * 3600, 6 * 60 + 1) # 6 hours x = ScipyOdeSimulator(model).run(tspan=t).all x_norm = c_[x['Bid_unbound'], x['PARP_unbound'], x['mSmac_unbound']] x_norm = 1 - x_norm / x_norm[ 0, :] # gets away without max() since first values are largest # this is what I originally thought 4B was plotting. it's actually very close. -JLM #x_norm = array([x['tBid_total'], x['CPARP_total'], x['cSmac_total']]).T #x_norm /= x_norm.max(0) tp = t / 3600 # x axis as hours plt.figure("Figure 4B") plt.plot(tp, x_norm[:, 0], 'b', label='IC substrate (tBid)') plt.plot(tp, x_norm[:, 1], 'y', label='EC substrate (cPARP)') plt.plot(tp, x_norm[:, 2], 'r', label='MOMP (cytosolic Smac)') plt.legend(loc='upper left', bbox_to_anchor=(0, 1)).draw_frame(False) plt.xlabel('Time (hr)') plt.ylabel('fraction') a = plt.gca() a.set_ylim((-.05, 1.05))
def test_integrate_with_expression(): """Ensure a model with Expressions simulates.""" Monomer('s1') Monomer('s9') Monomer('s16') Monomer('s20') # Parameters should be able to contain s(\d+) without error Parameter('ks0',2e-5) Parameter('ka20', 1e5) Initial(s9(), Parameter('s9_0', 10000)) Observable('s1_obs', s1()) Observable('s9_obs', s9()) Observable('s16_obs', s16()) Observable('s20_obs', s20()) Expression('keff', (ks0*ka20)/(ka20+s9_obs)) Rule('R1', None >> s16(), ks0) Rule('R2', None >> s20(), ks0) Rule('R3', s16() + s20() >> s16() + s1(), keff) time = np.linspace(0, 40) sim = ScipyOdeSimulator(model, tspan=time) simres = sim.run() keff_vals = simres.expressions['keff'] assert len(keff_vals) == len(time) assert np.allclose(keff_vals, 1.8181818181818182e-05)
def param_sweep(param, low, high, outputs): sim = ScipyOdeSimulator(m.model, te) results = [] params = {'k1': 0.03, 'k2': 10000} for k in np.linspace(low, high, 10): params['k3'] = k3 result = sim.run(param_values=params) results.append(result)
def test_multiprocessing_lambdify(): model = tyson_oscillator.model pars = [p.value for p in model.parameters] tspan = np.linspace(0, 100, 100) ScipyOdeSimulator( model, tspan=tspan, compiler='python', use_analytic_jacobian=True ).run(param_values=[pars, pars], num_processors=2)
def simulation(): pars = [[3.42477815e-02, 3.52565624e+02, 1.04957728e+01, 6.35198054e-02, 3.14044789e+02, 5.28598128e+01, 1.00000000e+01, 1.00000000e+02, 1.00000000e+02], [9.13676502e-03, 2.07253754e+00, 1.37740528e+02, 2.19960625e-01, 1.15007005e+04, 5.16232342e+01, 1.00000000e+01, 1.00000000e+02, 1.00000000e+02]] tspan = np.linspace(0, 50, 101) sims = ScipyOdeSimulator(model, tspan=tspan, param_values=pars).run() return sims
def test_unicode_obsname_ascii(): """Ensure ascii-convetible unicode observable names are handled.""" t = np.linspace(0, 100) rob_copy = copy.deepcopy(robertson.model) rob_copy.observables[0].name = u'A_total' sim = ScipyOdeSimulator(rob_copy) simres = sim.run(tspan=t) simres.all simres.dataframe
def test_unicode_exprname_nonascii(): """Ensure non-ascii unicode expression names error in python 2.""" t = np.linspace(0, 100) rob_copy = copy.deepcopy(robertson.model) ab = rob_copy.observables['A_total'] + rob_copy.observables['B_total'] expr = Expression(u'A_plus_B\u1234', ab, _export=False) rob_copy.add_component(expr) sim = ScipyOdeSimulator(rob_copy) simres = sim.run(tspan=t)
def setUp(self): super(TestScipyOdeCompilerTests, self).setUp() self.args = {'model': self.model, 'tspan': self.time, 'integrator': 'vode', 'use_analytic_jacobian': True} self.python_sim = ScipyOdeSimulator(compiler='python', **self.args) self.python_res = self.python_sim.run()
def _check_parallel(self, integrator, use_analytic_jacobian): initials = [[10, 20, 30], [50, 60, 70]] sim = ScipyOdeSimulator(self.model, self.sim.tspan, initials=initials, integrator=integrator, use_analytic_jacobian=use_analytic_jacobian) base_res = sim.run(initials=initials) res = sim.run(initials=initials, num_processors=2) assert np.allclose(res.species, base_res.species)
def visualize(): pars = [[3.42477815e-02, 3.52565624e+02, 1.04957728e+01, 6.35198054e-02, 3.14044789e+02, 5.28598128e+01, 1.00000000e+01, 1.00000000e+02, 1.00000000e+02], [9.13676502e-03, 2.07253754e+00, 1.37740528e+02, 2.19960625e-01, 1.15007005e+04, 5.16232342e+01, 1.00000000e+01, 1.00000000e+02, 1.00000000e+02]] tspan = np.linspace(0, 50, 101) labels = [1, 0] sims = ScipyOdeSimulator(model, tspan=tspan, param_values=pars).run() clus = VisualizeSimulations(model, clusters=labels, sim_results=sims) return clus
def get_pSTAT(kd4): mod = IFNaModelfile.model simres = ScipyOdeSimulator(mod, tspan=[0, 5, 15, 30, 60], param_values={ 'kd4': kd4.random(size=1) }, compiler='python').run() timecourse = simres.all return timecourse['TotalpSTAT']
def test_save_load_observables_expressions(): buff = io.BytesIO() tspan = np.linspace(0, 100, 100) sim = ScipyOdeSimulator(tyson_oscillator.model, tspan).run() sim.save(buff, include_obs_exprs=True) sim2 = SimulationResult.load(buff) assert len(sim2.observables) == len(tspan) # Tyson oscillator doesn't have expressions assert_raises(ValueError, lambda: sim2.expressions)
def trajectories_signature_2_txt(model, tspan, sp_to_analyze=None, parameters=None, file_path=''): """ Parameters ---------- model : pysb.Model PySB model to use tspan : vector-like Time values over which to simulate. sp_to_analyze: vector-like Species whose dynamic signature is going to be obtained parameters : vector-like or dict, optional Values to use for every parameter in the model. Ordering is determined by the order of model.parameters. If passed as a dictionary, keys must be parameter names. If not specified, parameter values will be taken directly from model.parameters. file_path : str Path for saving the file Returns ------- """ # TODO: make sure this functions works sim_result = ScipyOdeSimulator(model, tspan=tspan, param_values=parameters).run() y = sim_result.dataframe observables = [obs.name for obs in model.observables] y.drop(observables, axis=1, inplace=True) sp_short_names = [hf.parse_name(sp) for sp in model.species] y.columns = sp_short_names disc = Discretize(model, sim_result, diff_par=1) signatures = disc.get_signatures() # FIXME: This is not working. The signature data structure now uses pandas for sp in sp_to_analyze: y[hf.parse_name(model.species[sp]) + '_truncated'] = signatures[sp][0] y.to_csv(file_path + 'tr_sig.txt') if parameters is not None: initials = np.zeros([1, len(model.species)]) initials_df = pd.DataFrame(data=initials, columns=sp_short_names) initial_pars = [ic[1] for ic in model.initial_conditions] for i, par in enumerate(model.parameters): if par in initial_pars: idx = initial_pars.index(par) ic_name = hf.parse_name(model.initial_conditions[idx][0]) ic_value = parameters[i] initials_df[ic_name] = ic_value initials_df.to_csv(file_path + 'initials.txt', index=False) return
def test_unicode_exprname_ascii(): """Ensure ascii-convetible unicode expression names are handled.""" t = np.linspace(0, 100) rob_copy = copy.deepcopy(robertson.model) ab = rob_copy.observables['A_total'] + rob_copy.observables['B_total'] expr = Expression(u'A_plus_B', ab, _export=False) rob_copy.add_component(expr) sim = ScipyOdeSimulator(rob_copy) simres = sim.run(tspan=t) simres.all simres.dataframe
def __init__(self, model, tspan, use_analytic_jacobian=False, integrator='vode', cleanup=True, verbose=False, **integrator_options): self._sim = ScipyOdeSimulator(model, verbose=verbose, tspan=tspan, use_analytic_jacobian= use_analytic_jacobian, integrator=integrator, cleanup=cleanup, **integrator_options) self.result = None self._yexpr_view = None self._yobs_view = None
def initialize(self, cfg_file=None, mode=None): """Initialize the model for simulation, possibly given a config file. Parameters ---------- cfg_file : Optional[str] The name of the configuration file to load, optional. """ self.sim = ScipyOdeSimulator(self.model) self.state = numpy.array(copy.copy(self.sim.initials)[0]) self.time = numpy.array(0.0) self.status = 'initialized'
def setup(self): self.nsims = 100 self.timer = timeit.default_timer self.model = earm_1_0.model self.model.reset_equations() self.parameter_set = np.repeat( [[p.value for p in self.model.parameters]], self.nsims, axis=0) integrator_options_common = { 'model': self.model, 'tspan': np.linspace(0, 20000, 101), 'param_values': self.parameter_set } self.sim_lsoda = ScipyOdeSimulator(integrator='lsoda', compiler='cython', integrator_options={ 'atol': 1e-6, 'rtol': 1e-6, 'mxstep': 20000 }, **integrator_options_common) self.sim_lsoda_no_compiler_directives = ScipyOdeSimulator( integrator='lsoda', compiler='cython', cython_directives={}, integrator_options={ 'atol': 1e-6, 'rtol': 1e-6, 'mxstep': 20000 }, **integrator_options_common) self.sim_cupsoda = CupSodaSimulator(integrator_options={ 'atol': 1e-6, 'rtol': 1e-6, 'max_steps': 20000 }, **integrator_options_common)
def test_vode_jac_solver_run(self): """Test vode and analytic jacobian.""" args = { 'model': self.model, 'tspan': self.time, 'integrator': 'vode', 'use_analytic_jacobian': True } solver_vode_jac = ScipyOdeSimulator(**args) res1 = solver_vode_jac.run() # Test again with analytic jacobian if ScipyOdeSimulator._use_inline: ScipyOdeSimulator._use_inline = False sim = ScipyOdeSimulator(**args) simres = sim.run() assert simres.species.shape[0] == args['tspan'].shape[0] assert np.allclose(res1.dataframe, simres.dataframe) ScipyOdeSimulator._use_inline = True # Test again using theano solver = ScipyOdeSimulator(use_theano=True, **args) simres = solver.run() assert np.allclose(res1.dataframe, simres.dataframe)
def test_simres_dataframe(): """ Test SimulationResult.dataframe() """ tspan1 = np.linspace(0, 100, 100) tspan2 = np.linspace(50, 100, 50) tspan3 = np.linspace(100, 150, 100) model = tyson_oscillator.model sim = ScipyOdeSimulator(model, integrator='lsoda') simres1 = sim.run(tspan=tspan1) # Check retrieving a single simulation dataframe df_single = simres1.dataframe # Generate multiple trajectories trajectories1 = simres1.species trajectories2 = sim.run(tspan=tspan2).species trajectories3 = sim.run(tspan=tspan3).species # Try a simulation result with two different tspan lengths sim = ScipyOdeSimulator(model, param_values={'k6': [1., 1.]}, integrator='lsoda') simres = SimulationResult(sim, [tspan1, tspan2], [trajectories1, trajectories2]) df = simres.dataframe assert df.shape == (len(tspan1) + len(tspan2), len(model.species) + len(model.observables)) # Next try a simulation result with two identical tspan lengths, stacked # into a single 3D array of trajectories simres2 = SimulationResult(sim, [tspan1, tspan3], np.stack([trajectories1, trajectories3])) df2 = simres2.dataframe assert df2.shape == (len(tspan1) + len(tspan3), len(model.species) + len(model.observables))
def equil_NFkB(init_IKK = 100000.0, init_NFkB = 124781, sim_vals, run = False): equil_vals = {'IKK_act':0.001, 'neut_IKK_0':init_IKK, 'act_IKK_0':0, 'inact_IKK_0':0, 'NFkB_0':init_NFkB} e_out = sim.run(param_values = equil_vals).dataframe for k, value in equil_vals: init_param = m. kB_monomer = [] for i in kB_initial: chg_val(i, 0) kB_monomer.append(i.name[:-2]) chg_val(m.IKK_act, 0.001) chg_val(m.neut_IKK_0, init_IKK) chg_val(m.NFkB_0, init_NFkB) e_out = ScipyOdeSimulator(m.model, tspan=te).run().dataframe for i, initial in enumerate(kB_initial): chg_val(initial, e_out['o_' + kB_monomer[i]].iloc[-1]) chg_val(m.IKK_act, 0.001) if run: simres = ScipyOdeSimulator(m.model, tspan=t).run() y_out = simres.dataframe
def plot_arrestin_noarrestin_ppjnk3(): """ Plot ppJNK3 activation with and withou arrestin Returns ------- """ # Pre-equilibration exp_data = pd.read_csv('../data/exp_data_3min.csv') tspan = np.linspace(0, exp_data['Time (secs)'].values[-1], 181) solver = ScipyOdeSimulator(model, tspan=tspan) pars_arr = np.copy(par_set_calibrated) pars_noarr = np.copy(par_set_calibrated) # Pre-equilibration time_eq = np.linspace(0, 100, 100) pars_arr_eq = np.copy(par_set_calibrated) pars_noarr_eq = np.copy(par_set_calibrated) pars_noarr_eq[arrestin_idx] = 0 pars_noarr_eq[jnk3_initial_idxs] = [0.5958, 0, 0.0042] all_pars = np.stack((pars_arr_eq, pars_noarr_eq)) all_pars[:, kcat_idx] = 0 # Setting catalytic reactions to zero for pre-equilibration eq_conc = pre_equilibration(model, time_eq, all_pars)[1] # Simulating models with initials from pre-equilibration and parameters for condition with/without arrestin sim = solver.run(param_values=[pars_arr, pars_noarr], initials=eq_conc).all print((sim[0]['all_jnk3'][-1]) / (sim[1]['all_jnk3'][-1])) print(sim[0]['all_jnk3'][-1], sim[1]['all_jnk3'][-1]) plt.plot(tspan, sim[0]['all_jnk3'], color='r', label='ppJNK3 with Arrestin-3') plt.plot(tspan, sim[1]['all_jnk3'], color='k', label='ppJNK3 no Arrestin-3') plt.xlabel('Time (s)') plt.ylabel(r' Normalized Concentration') plt.legend() plt.savefig('arrestin_noarrestin_ppjnk3.pdf', format='pdf', bbox_inches='tight')
def sim_model_dyn_view(model, tspan, param_values=None, type_of_viz='dynamic_view', process='consumption', cmap='RdBu_r', layout_name='cose-bilkent'): """ Render a dynamic visualization of the model using the tspan and param_values passed to the function Parameters ---------- model: pysb.model or str Model to visualize. It can be a pysb model, or the file path to an an SBML or BNGL model tspan : vector-like, optional Time values over which to simulate. The first and last values define the time range. param_values : vector-like or dict, optional Values to use for every parameter in the model. Ordering is determined by the order of model.parameters. If passed as a dictionary, keys must be parameter names. If not specified, parameter values will be taken directly from model.parameters. type_of_viz: str Type of visualization. It can only be `sp_dyn_view`, `sp_comp_dyn_view` or `sp_comm_dyn_view` process : str Type of the dynamic visualization, it can be 'consumption' or 'production' cmap : str or Colormap instance The colormap used to map the reaction rate values to RGBA colors. For more information visit: https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html layout_name : str Layout name to use """ from pysb.simulator import ScipyOdeSimulator from pyvipr.util import dispatch_pysb_files model = dispatch_pysb_files(model) sim = ScipyOdeSimulator(model, tspan=tspan).run(param_values=param_values) return Viz(data=sim, type_of_viz=type_of_viz, process=process, layout_name=layout_name, cmap=cmap)
def fig_4a(): print("Simulating model for figure 4A...") t = linspace(0, 20 * 3600, 20 * 60 + 1) # 20 hours, in seconds, 1 min sampling dt = t[1] - t[0] Ls_exp = Lsat / array([1, 4, 20, 100, 500]) Td_exp = [144.2, 178.7, 236, 362.5, 656.5] Td_std = [32.5, 32.2, 36.4, 78.6, 171.6] Ts_exp = [21.6, 23.8, 27.2, 22.0, 19.0] Ts_std = [9.5, 9.5, 12.9, 7.7, 10.5] CVenv = 0.2 # num steps was originally 40, but 15 is plenty smooth enough for screen display Ls = floor(logspace(1, 5, 15)) fs = empty_like(Ls) Ts = empty_like(Ls) Td = empty_like(Ls) print("Scanning over %d values of L_0" % len(Ls)) for i in range(len(Ls)): model.parameters['L_0'].value = Ls[i] print(" L_0 = %g" % Ls[i]) x = ScipyOdeSimulator(model).run(tspan=t).all fs[i] = (x['PARP_unbound'][0] - x['PARP_unbound'][-1]) / x['PARP_unbound'][0] dP = 60 * (x['PARP_unbound'][:-1] - x['PARP_unbound'][1:]) / ( dt * x['PARP_unbound'][0]) # in minutes ttn = argmax(dP) dPmax = dP[ttn] Ts[i] = 1 / dPmax # minutes Td[i] = t[ttn] / 60 # minutes plt.figure("Figure 4A") plt.plot(Ls / Lfactor, Td, 'g-', Ls / Lfactor, (1 - CVenv) * Td, 'g--', Ls / Lfactor, (1 + CVenv) * Td, 'g--') plt.errorbar(Ls_exp / Lfactor, Td_exp, Td_std, None, 'go', capsize=0), plt.ylabel('Td (min)'), plt.xlabel('TRAIL (ng/ml)'), a = plt.gca() a.set_xscale('log') a.set_xlim((min(Ls) / Lfactor, max(Ls) / Lfactor)) a.set_ylim((0, 1000)) model.parameters['L_0'].value = L_0_baseline
def test_sequential_initials_dict_then_list(self): A, B = self.model.monomers base_sim = ScipyOdeSimulator( self.model, initials={A(a=None): 10, B(b=None): 20}) assert np.allclose(base_sim.initials, [10, 20, 0]) assert len(base_sim.initials_dict) == 2 # Now set initials using a list, which should overwrite the dict base_sim.initials = [30, 40, 50] assert np.allclose(base_sim.initials, [30, 40, 50]) assert np.allclose( sorted([x[0] for x in base_sim.initials_dict.values()]), base_sim.initials)
def test_model(simbio_model, pysb_model): """Run models with SimBio and PySB, and compare results at each timepoint.""" t = np.linspace(0, 20_000, 1_000) solver_options = {"atol": 1e-6, "rtol": 1e-6} # SimBio sim = Simulator( simbio_model, builder="numpy", solver=ODEint, solver_kwargs=solver_options ) _, df_simbio = sim.run(t) # PySB sim_pysb = ScipyOdeSimulator( pysb_model, integrator="lsoda", integrator_options=solver_options ) df_pysb = pysb_dataframe(sim_pysb.run(t), pysb_model) assert np.allclose(df_pysb, df_simbio[df_pysb.columns], rtol=1e-2, atol=1e-2)
def compare_to_pysb_simulation(self): examples = [ tyson_oscillator.model, robertson.model, expression_observables.model, bax_pore_sequential.model, bax_pore.model, bngwiki_egfr_simple.model ] for example in examples: example.name = example.name.replace('pysb.examples.', '') with self.subTest(example=example.name): ## pysb part tspan = np.linspace(0, 100, 101) sim = ScipyOdeSimulator(example, tspan=tspan, integrator_options={ 'rtol': 1e-8, 'atol': 1e-8 }, compiler='python') pysb_simres = sim.run() ## amici part amici.pysb2amici(example, example.name, verbose=False) sys.path.insert(0, example.name) amici_model_module = importlib.import_module(example.name) model_pysb = amici_model_module.getModel() model_pysb.setTimepoints(tspan) solver = model_pysb.getSolver() rdata = amici.runAmiciSimulation(model_pysb, solver) # check agreement of species simulation self.assertTrue( np.isclose(rdata['x'], pysb_simres.species, 1e-4, 1e-4).all())
from pydream.convergence import Gelman_Rubin from pydream.core import run_dream # load experimental data exp_data = pd.read_csv('EC-RP_IMS-RP_IC-RP_data_for_models.csv', index_col=False) # timepoints for simulation. These must match the experimental data. tspan = exp_data['# Time'].values.copy() rate_params = model.parameters_rules() param_values = np.array([p.value for p in model.parameters]) rate_mask = np.array([p in rate_params for p in model.parameters]) starting_position = np.log10(param_values[rate_mask]) solver = ScipyOdeSimulator(model, tspan) # Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and # yfinal (the last value of the IMS-RP trajectory) momp_data = np.array([9810.0, 180.0, model.parameters['Smac_0'].value]) momp_var = np.array([7245000.0, 3600.0, 1e4]) # Mean and variance of Td (delay time) and Ts (switching time) of MOMP, and # yfinal (the last value of the IMS-RP trajectory) momp_data = np.array([9810.0, 180.0, model.parameters['Smac_0'].value]) momp_var = np.array([7245000.0, 3600.0, 1e4]) like_mbid = norm(loc=exp_data['norm_IC-RP'], scale=exp_data['nrm_var_IC-RP']) like_momp = norm(loc=momp_data, scale=momp_var) sampled_parameter_names = [