def run(n_sim, model, tspan, simulator='cuda'): v = False if 'cl' in simulator: sim = OpenCLSSASimulator(model, tspan=tspan, verbose=v, precision=np.float64) elif simulator == 'cuda': sim = CudaSSASimulator(model, tspan=tspan, verbose=v, precision=np.float64) elif simulator == 'bng': sim = BngSimulator(model, tspan=tspan, verbose=v) elif simulator == 'stochkit': sim = StochKitSimulator(model, tspan=tspan, verbose=v) else: return st = time.time() if simulator in ('bng', 'stochkit'): sim.run(tspan, n_runs=n_sim) else: # sim.run(tspan, number_sim=n_sim) traj = sim.run(tspan, number_sim=n_sim) # print(traj.dataframe.min()) # quit() total_time = time.time() - st return total_time, sim._time
def main(self): observables = self.make_model() write_columns(observables) write_model_attributes(self.model.rules, "rules") write_model_attributes(self.model.parameters, "parameters") write_model_attributes(self.model.observables, "observables") np.savetxt("time", self.tspan, fmt='%f') self.model.parameters['Ls_0'].value = self.ls sim = BngSimulator(self.model, tspan=self.tspan, cleanup=False) simulation_results = sim.run(n_runs=self.runs, method='ssa', cleanup=False, output_dir=os.getcwd()) # sim = StochKitSimulator(model, tspan=self.tspan) # simulation_results = sim.run(n_runs=self.runs) if len(observables) > 1: ls_results = [] lf_results = [] for i in range(self.runs): ls_results.append( simulation_results.observables[i][observables[0]]) lf_results.append( simulation_results.observables[i][observables[1]]) output = np.mean(ls_results, axis=0) + np.mean(lf_results, axis=0) else: results = [] for i in range(self.runs): results.append( simulation_results.observables[i][observables[0]]) output = np.mean(results, axis=0) print(results) print(output) np.savetxt("output", [output[-1]], fmt='%f')
def bngNF(model, start=0, finish=10, points=10, n_runs=20, path='/opt/conda/bin/'): set_path('bng', path) sims = BngSimulator(model, linspace(start, finish, points + 1)).run(method='nf', n_runs=n_runs).dataframe sims = modes(sims, n_runs) return {'sims': sims['sims'], 'avrg': sims['avrg'], 'stdv': sims['stdv']}
def produceGraph(model, filename, methods, observe, parameters): # make a graph # parameters is list will run multiple times and put them on the same graph model=model.reload() for graph in observe: for name, monomer in graph.items(): model.add_component(Observable(f'obs{name}', monomer)) t = np.linspace(0, 100) graphs = len(observe) fig, axs = plt.subplots(2, 2, constrained_layout=True, figsize=(10,6)) fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.6, hspace=0.3) # fig.tight_layout(pad=5.0) # hack for when there is only one subplot if graphs == 1: axs = [axs] for i, parameter_set in enumerate(parameters): for method in methods: # test without glutathionine and sHSP enabled simulationResult = BngSimulator(model).run( tspan=t, method=method, param_values=parameter_set ) for i, name in enumerate(simulationResult.observables.dtype.names): num = getGraph(observe, name) if (num == 0): axs[0][0].plot(t, simulationResult.all[name], label=f'{method.upper()} {name} High Temp') elif (num == 1): axs[0][1].plot(t, simulationResult.all[name], label=f'{method.upper()} {name} High Temp') elif (num == 2): axs[1][0].plot(t, simulationResult.all[name], label=f'{method.upper()} {name} High Temp') else: axs[1][1].plot(t, simulationResult.all[name], label=f'{method.upper()} {name} High Temp') for i in range(0, 2): for j in range(0,2): axs[i][j].set_xlabel('Time in seconds') axs[i][j].set_ylabel('Number of molecules') axs[i][j].legend() axs[i][j].set_ylim(bottom=0) axs[0][0].set_ylim(ymin=0, ymax=10**7) fig.savefig(f'export/{filename}.png')
n_runs = n_genes len_tspan = len(tspan) HO_tot = np.array(len_tspan * [0]) skew = np.empty((len_tspan, n_runs), dtype=float) color = np.empty((len_tspan, n_runs), dtype=str) # batch_size = int(n_runs/n_levels) np.random.seed(44) # for batch in range(n_levels): start = 0 for batch in range(len(N_GENES)): # size = batch_size if batch < n_levels-1 else n_runs-(n_levels-1)*batch_size size = N_GENES[batch] model = create_model(N_STATES[batch], K_SKEW[batch]) sim = BngSimulator(model, tspan, verbose=True) x = sim.run( n_runs=size, netgen_args={'max_iter': 1000000}, seed=np.random.choice(int(1e6), size=size, replace=False) #, # param_values={ k.name : 0 for k in kf_skew[len(kf_skew)-k_remove[batch]:] } # if k_remove[batch] > 0 else None ) observables = [x.observables] if size == 1 else x.observables species = [x.species] if size == 1 else x.species for t in range(len_tspan): for n in range(size): # Total HO genes HO_tot[t] += observables[n][t][0] # Skew and color idx = np.where(species[n][t] == species[n][t].max())[0][0]
def test_save_load(): tspan = np.linspace(0, 100, 101) model = tyson_oscillator.model test_unicode_name = u'Hello \u2603 and \U0001f4a9!' model.name = test_unicode_name sim = ScipyOdeSimulator(model, integrator='lsoda') simres = sim.run(tspan=tspan, param_values={'k6': 1.0}) sim_rob = ScipyOdeSimulator(robertson.model, integrator='lsoda') simres_rob = sim_rob.run(tspan=tspan) # Reset equations from any previous network generation robertson.model.reset_equations() A = robertson.model.monomers['A'] # NFsim without expressions nfsim1 = BngSimulator(robertson.model) nfres1 = nfsim1.run(n_runs=2, method='nf', tspan=np.linspace(0, 1)) # Test attribute saving (text, float, list) nfres1.custom_attrs['note'] = 'NFsim without expressions' nfres1.custom_attrs['pi'] = 3.14 nfres1.custom_attrs['some_list'] = [1, 2, 3] # NFsim with expressions nfsim2 = BngSimulator(expression_observables.model) nfres2 = nfsim2.run(n_runs=1, method='nf', tspan=np.linspace(0, 100, 11)) with tempfile.NamedTemporaryFile() as tf: # Cannot have two file handles on Windows tf.close() simres.save(tf.name, dataset_name='test', append=True) # Try to reload when file contains only one dataset and group SimulationResult.load(tf.name) simres.save(tf.name, append=True) # Trying to overwrite an existing dataset gives a ValueError assert_raises(ValueError, simres.save, tf.name, append=True) # Trying to write to an existing file without append gives an IOError assert_raises(IOError, simres.save, tf.name) # Trying to write a SimulationResult to the same group with a # different model name results in a ValueError assert_raises(ValueError, simres_rob.save, tf.name, dataset_name='robertson', group_name=model.name, append=True) simres_rob.save(tf.name, append=True) # Trying to load from a file with more than one group without # specifying group_name should raise a ValueError assert_raises(ValueError, SimulationResult.load, tf.name) # Trying to load from a group with more than one dataset without # specifying a dataset_name should raise a ValueError assert_raises(ValueError, SimulationResult.load, tf.name, group_name=model.name) # Load should succeed when specifying group_name and dataset_name simres_load = SimulationResult.load(tf.name, group_name=model.name, dataset_name='test') assert simres_load._model.name == test_unicode_name # Saving network free results requires include_obs_exprs=True, # otherwise a warning should be raised with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") nfres1.save(tf.name, dataset_name='nfsim_no_obs', append=True) assert len(w) == 1 assert issubclass(w[-1].category, UserWarning) nfres1.save(tf.name, include_obs_exprs=True, dataset_name='nfsim test', append=True) # NFsim load nfres1_load = SimulationResult.load(tf.name, group_name=nfres1._model.name, dataset_name='nfsim test') # NFsim with expression nfres2.save(tf.name, include_obs_exprs=True, append=True) nfres2_load = SimulationResult.load(tf.name, group_name=nfres2._model.name) _check_resultsets_equal(simres, simres_load) _check_resultsets_equal(nfres1, nfres1_load) _check_resultsets_equal(nfres2, nfres2_load)
# make a graph without any text to display on the wiki from pysb import * from pysb.simulator import BngSimulator import matplotlib.pyplot as plt import numpy as np from base_model import * t = np.linspace(0, 100) fig, axs = plt.subplots(1, 1) model.add_component(Observable(f'obsATP', ATP())) model.add_component(Observable(f'obsADP', ADP())) simulationResult = BngSimulator(model).run( tspan=t, method='ssa', param_values={**tempValues(1), **{'ROS'} ) for name in simulationResult.observables.dtype.names: axs.plot(t, simulationResult.all[name]) ax fig.savefig(f'export/blank_graph.png')
def bngODE(model, start=0, finish=10, points=10, path='/opt/conda/bin/'): set_path('bng', path) return BngSimulator(model, linspace(start, finish, points + 1)).run(method='ode').dataframe
def test_save_load(): tspan = np.linspace(0, 100, 101) # Make a copy of model so other tests etc. don't see the changed name. model = copy.deepcopy(tyson_oscillator.model) test_unicode_name = u'Hello \u2603 and \U0001f4a9!' model.name = test_unicode_name sim = ScipyOdeSimulator(model, integrator='lsoda') simres = sim.run(tspan=tspan, param_values={'k6': 1.0}) sim_rob = ScipyOdeSimulator(robertson.model, integrator='lsoda') simres_rob = sim_rob.run(tspan=tspan) # Reset equations from any previous network generation robertson.model.reset_equations() A = robertson.model.monomers['A'] # NFsim without expressions nfsim1 = BngSimulator(robertson.model) nfres1 = nfsim1.run(n_runs=2, method='nf', tspan=np.linspace(0, 1)) # Test attribute saving (text, float, list) nfres1.custom_attrs['note'] = 'NFsim without expressions' nfres1.custom_attrs['pi'] = 3.14 nfres1.custom_attrs['some_list'] = [1, 2, 3] # NFsim with expressions nfsim2 = BngSimulator(expression_observables.model) nfres2 = nfsim2.run(n_runs=1, method='nf', tspan=np.linspace(0, 100, 11)) with tempfile.NamedTemporaryFile() as tf: # Cannot have two file handles on Windows tf.close() simres.save(tf.name, dataset_name='test', append=True) # Try to reload when file contains only one dataset and group SimulationResult.load(tf.name) simres.save(tf.name, append=True) # Trying to overwrite an existing dataset gives a ValueError assert_raises(ValueError, simres.save, tf.name, append=True) # Trying to write to an existing file without append gives an IOError assert_raises(IOError, simres.save, tf.name) # Trying to write a SimulationResult to the same group with a # different model name results in a ValueError assert_raises(ValueError, simres_rob.save, tf.name, dataset_name='robertson', group_name=model.name, append=True) simres_rob.save(tf.name, append=True) # Trying to load from a file with more than one group without # specifying group_name should raise a ValueError assert_raises(ValueError, SimulationResult.load, tf.name) # Trying to load from a group with more than one dataset without # specifying a dataset_name should raise a ValueError assert_raises(ValueError, SimulationResult.load, tf.name, group_name=model.name) # Load should succeed when specifying group_name and dataset_name simres_load = SimulationResult.load(tf.name, group_name=model.name, dataset_name='test') assert simres_load._model.name == test_unicode_name # Saving network free results requires include_obs_exprs=True, # otherwise a warning should be raised with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") nfres1.save(tf.name, dataset_name='nfsim_no_obs', append=True) assert len(w) == 1 assert issubclass(w[-1].category, UserWarning) nfres1.save(tf.name, include_obs_exprs=True, dataset_name='nfsim test', append=True) # NFsim load nfres1_load = SimulationResult.load(tf.name, group_name=nfres1._model.name, dataset_name='nfsim test') # NFsim with expression nfres2.save(tf.name, include_obs_exprs=True, append=True) nfres2_load = SimulationResult.load(tf.name, group_name=nfres2._model.name) _check_resultsets_equal(simres, simres_load) _check_resultsets_equal(nfres1, nfres1_load) _check_resultsets_equal(nfres2, nfres2_load)
plt.ylabel('Population of %s' % name) PARP, CPARP, Mito, mCytoC = [ model.monomers[x] for x in ['PARP', 'CPARP', 'Mito', 'mCytoC'] ] klump = Parameter('klump', 10000, _export=False) model.add_component(klump) population_maps = [ PopulationMap(PARP(b=None), klump), PopulationMap(CPARP(b=None), klump), PopulationMap(Mito(b=None), klump), PopulationMap(mCytoC(b=None), klump) ] sim = BngSimulator(model, tspan=np.linspace(0, 20000, 101)) simres = sim.run(n_runs=20, method='nf', population_maps=population_maps) trajectories = simres.all tout = simres.tout plot_mean_min_max('Bid_unbound') plot_mean_min_max('PARP_unbound') plot_mean_min_max('mSmac_unbound') plot_mean_min_max('tBid_total') plot_mean_min_max('CPARP_total') plot_mean_min_max('cSmac_total') plt.show()
plt.legend(loc=0) plt.xlabel('Time') plt.ylabel('Population of %s' % name) PARP, CPARP, Mito, mCytoC = [model.monomers[x] for x in ['PARP', 'CPARP', 'Mito', 'mCytoC']] klump = Parameter('klump', 10000, _export=False) model.add_component(klump) population_maps = [ PopulationMap(PARP(b=None), klump), PopulationMap(CPARP(b=None), klump), PopulationMap(Mito(b=None), klump), PopulationMap(mCytoC(b=None), klump) ] sim = BngSimulator(model, tspan=np.linspace(0, 20000, 101)) simres = sim.run(n_runs=20, method='nf', population_maps=population_maps) trajectories = simres.all tout = simres.tout plot_mean_min_max('Bid_unbound') plot_mean_min_max('PARP_unbound') plot_mean_min_max('mSmac_unbound') plot_mean_min_max('tBid_total') plot_mean_min_max('CPARP_total') plot_mean_min_max('cSmac_total') plt.show()