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 # This timespan is chosen to be enough to trigger a Jacobian evaluation # on the various solvers. self.time = np.linspace(0, 1) self.solver = Solver(self.model, self.time, integrator='vode')
def visualize(): for ACC_NO in ACC_NOs: dot_r = render_reactions.run(models[ACC_NO]) dotfile_r = open('model_reactions-' + ACC_NO + '.dot', 'w') dotfile_r.write(dot_r) dotfile_r.close() system('dot -T pdf model_reactions-' + ACC_NO + '.dot -o model_reactions-' + ACC_NO + '.pdf') dot_s = render_species.run(models[ACC_NO]) dotfile_s = open('model_species-' + ACC_NO + '.dot', 'w') dotfile_s.write(dot_s) dotfile_s.close() system('ccomps -x model_species-' + ACC_NO + '.dot | dot | gvpack -m0 | neato -n2 -T pdf -o model_species-' + ACC_NO + '.pdf') # Run the simulation solver = Solver(models[ACC_NO], t) solver.run() yout = solver.yobs # Plot simulation results for the observables in the model pl.ion() pl.figure() for observ in outputs[ACC_NO]: pl.plot(t, yout[observ], label=observ) pl.legend() pl.xlabel("Time (minutes)") pl.ylabel("Distribution of radioactive iron/body compartments") pl.savefig('model_results-' + ACC_NO + '.png') pl.clf()
def scatter_plot(): n = 100 mod = models['adequate'] for param in param_bounds.keys(): prob = { 'num_vars': 1, 'names': [param], 'bounds': [param_bounds[param]] } par_sets = [p[0] for p in sampling_method.sample(prob, n)] solver = Solver(mod, t) res_sets = {out: [] for out in outputs['adequate']} for par_set in par_sets: pars = {p.name: p.value for p in mod.parameters} pars[param] = par_set solver.run(pars) for out in outputs['adequate']: res_sets[out].append(solver.yobs[out][-1]) # last result # Plot simulation results for the observables in the model pl.ion() pl.figure(figsize=(8, 8)) for res in res_sets.keys(): pl.scatter(par_sets, res_sets[res], label=res) pl.legend() pl.xlabel(param) pl.ylabel("Outputs") pl.savefig('scatterplots/' + param + '.png', dpi=300) pl.clf()
def run_query(model, query): m = re.match('Is the amount of (.+) ([^ ]+) in time?', query) target_str = m.groups()[0] pattern_str = m.groups()[1] ts = numpy.linspace(0, 100, 10) solver = Solver(model, ts) solver.run() if target_str == 'A-B complex': target = 'AB' if target_str == 'A': target = 'A' for i, a in enumerate(solver.yobs[target]): solver.yobs[target][i] = 1 if a > 50 else 0 if pattern_str == 'sustained': fstr = sustained_formula(target) elif pattern_str == 'transient': fstr = transient_formula(target) elif pattern_str == 'unchanged': fstr = noact_formula(target) print '\n\n' print '-----------' print query print 'LTL formula: %s' % fstr mc = ModelChecker(fstr, solver.yobs) print solver.yobs[target] print 'Result:', mc.truth print '-----------'
def test_vode_jac_solver_run(self): """Test vode and analytic jacobian.""" solver_vode_jac = Solver(self.model, self.time, integrator='vode', use_analytic_jacobian=True) solver_vode_jac.run()
def test_lsoda_jac_solver_run(self): """Test lsoda and analytic jacobian.""" solver_lsoda_jac = Solver(self.model, self.time, integrator='lsoda', use_analytic_jacobian=True) solver_lsoda_jac.run()
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) solver = Solver(model, time) solver.run() assert solver.yexpr_view.shape == (len(time), len(model.expressions_dynamic())) assert solver.yobs_view.shape == (len(time), len(model.observables))
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) solver = Solver(model, time) solver.run() assert solver.yexpr_view.shape == (len(time), len(model.expressions_dynamic())) assert solver.yobs_view.shape == (len(time), len(model.observables))
def check_runtime(model, tspan, iterations, use_inline, use_analytic_jacobian): Solver._use_inline = use_inline sol = Solver(model, tspan, use_analytic_jacobian=use_analytic_jacobian) start_time = timeit.default_timer() for i in range(iterations): sol.run() elapsed = timeit.default_timer() - start_time print("use_inline=%s, use_analytic_jacobian=%s, %d iterations" % (use_inline, use_analytic_jacobian, iterations)) print("Time: %f sec\n" % elapsed)
def test_ic_expression_with_one_parameter(): Monomer('A') Parameter('k1', 1) Expression('e1', k1) Rule('A_deg', A() >> None, k1) Initial(A(), e1) generate_equations(model) t = np.linspace(0, 1000, 100) sol = Solver(model, t, use_analytic_jacobian=True) sol.run()
def simulate_vemurafenib_treatment(model, ts, y0): # New initial conditions for simulation post event y_init = y0 y_init[model.observables['Vem_free'].species[0]] = 2e5 # Continue model simulation with y_init as new initial condition solver = Solver(model, ts) solver.run(y0=y_init) # Concatenate the two simulations return solver.yobs, solver.y
def run_one_model(model, data, prior_vals, ns, pool=None): # Vector of estimated parameters pe = [p for p in model.parameters if p.name.startswith('k')] # Generate model equations generate_equations(model) Solver._use_inline = True sol = Solver(model, numpy.linspace(0, 10, 10)) sol.run() # Number of temperatures, dimensions and walkers ntemps = 20 ndim = len(pe) blocksize = 48 nwalkers = get_num_walkers(ndim, blocksize) print 'Running %d walkers at %d temperatures for %d steps.' %\ (nwalkers, ntemps, ns) sampler = emcee.PTSampler(ntemps, nwalkers, ndim, likelihood, prior, threads=1, pool=pool, betas=None, a=2.0, Tmax=None, loglargs=[model, data], logpargs=[model, prior_vals], loglkwargs={}, logpkwargs={}) # Random initial parameters for walkers p0 = numpy.ones((ntemps, nwalkers, ndim)) for i in range(ntemps): for j in range(nwalkers): for k, pp in enumerate(pe): p0[i, j, k] = prior_vals.vals[j][pp.name] print p0 # Run sampler fname = scratch_path + 'chain_%s.dat' % model.name step = 0 for result in sampler.sample(p0, iterations=ns, storechain=True): print '---' position = result[0] with open(fname, 'a') as fh: for w in range(nwalkers): for t in range(ntemps): pos_str = '\t'.join(['%f' % p for p in position[t][w]]) fh.write('%d\t%d\t%d\t%s\n' % (step, w, t, pos_str)) step += 1 return sampler
def sim_experiment(model, exp, pd=None): if pd is None: pd = {} pd['ERK_0'] = exp.ERKtot * exp.ERK[0] pd['ERKpT_0'] = exp.ERKtot * exp.ERKpT[0] pd['ERKpY_0'] = exp.ERKtot * exp.ERKpY[0] pd['ERKpTpY_0'] = exp.ERKtot * exp.ERKpTpY[0] pd['MEK_0'] = exp.MEKtot pd['MKP_0'] = exp.MKPtot solver = Solver(model, exp.ts, use_analytic_jacobian=True) solver.run(pd) return solver.yobs
def get_steady_state(model, y0): sim_hours = 1 t = np.linspace(0, sim_hours * 3600, sim_hours * 60) solver = Solver(model, t) ss = False y_init = y0 while not ss: solver.run(y0=y_init) ss = is_steady_state(solver.yobs) y_init = solver.y[-1] steady_state = solver.yobs[-1] timecourse = solver.yobs return steady_state, timecourse
def test_piecewise_expression(): Monomer('A') Observable('A_total', A()) Expression( 'A_deg_expr', Piecewise((0, A_total < 400.0), (0.001, A_total < 500.0), (0.01, True))) Initial(A(), Parameter('A_0', 1000)) Rule('A_deg', A() >> None, A_deg_expr) generate_equations(model) t = np.linspace(0, 1000, 100) sol = Solver(model, t, use_analytic_jacobian=True) sol.run()
def test_nested_expression(): Monomer('A') Monomer('B') Parameter('k1', 1) Observable('o1', B()) Expression('e1', o1 * 10) Expression('e2', e1 + 5) Initial(A(), Parameter('A_0', 1000)) Initial(B(), Parameter('B_0', 1)) Rule('A_deg', A() >> None, e2) generate_equations(model) t = np.linspace(0, 1000, 100) sol = Solver(model, t, use_analytic_jacobian=True) sol.run()
def _initiate_log(self): # retrieve time points from data for each in self.processed_data: self.time.append(float(each[0])) # set parameter values or prior ranges (log-space) for each in self.model.parameters: if each.name[-2:] == '_0': self.params.append(each.value) if each.name[-3:] == '1kf': self.params.append(self.prior_1kf) if each.name[-3:] == '2kf': self.params.append(self.prior_2kf) if each.name[-3:] == '1kr': self.params.append(self.prior_1kr) if each.name[-3:] == '1kc': self.params.append(self.prior_1kc) # create solver object self.model_solver = Solver(self.model, self.time, integrator='lsoda', integrator_options={ 'atol': 1e-12, 'rtol': 1e-12, 'mxstep': 20000 }) # construct the working population of N parameter sets k = 0 while k < self.N: # randomly choose points from parameter space point = [] for each in self.params: if isinstance(each, list): point.append(10**(np.random.uniform(each[0], each[1]))) else: point.append(each) objective = self._compute_objective(point) if not isnan(objective): self.working_set.append([objective, point]) print k, objective k += 1 self.working_set.sort()
def likelihood(p, model, data, plot=False): pd = parameter_dict(model, p) lh = 0 tstart = time.time() Solver._use_inline = True sol = Solver(model, data[0].ts, nsteps=1e5) for i, exp in enumerate(data): # Experiment 1 is a control that is not relevant for # model fitting. if i == 1: continue yobs = sim_experiment(model, exp, pd, sol) erk = yobs['ERKu'] / exp.ERKtot erkpt = yobs['ERKpT'] / exp.ERKtot erkpy = yobs['ERKpY'] / exp.ERKtot lh += gauss_lh(erk[1:], exp.ERK[1:], exp.ERK_std[1:]) lh += gauss_lh(erkpt[1:], exp.ERKpT[1:], exp.ERKpT_std[1:]) lh += gauss_lh(erkpy[1:], exp.ERKpY[1:], exp.ERKpY_std[1:]) tend = time.time() print lh, tend - tstart sys.stdout.flush() if numpy.isnan(lh): return -numpy.inf else: return lh
def plot_func(self, x=None): """Plots the timecourses with the parameter values given by x. Parameters ---------- x : np.array or list The parameters to use for the plot. These should be in the same order used by the objective function: globally fit parameters first, then a set of local parameters for each of the timecourses being fit. """ if x is None: if self.result is None: raise ValueError('x must be a vector of parameter values.') else: # If minimize was run, the parameters will be in the 'x' # attribute of the result object try: x = 10**self.result.x # If leastsq was run, the parameters will be the first entry # in the result tuple except AttributeError: x = 10**self.result[0] s = Solver(self.builder.model, self.time) # Iterate over each entry in the data array for data_ix, data in enumerate(self.data): # Set the parameters appropriately for the simulation: # Iterate over the globally fit parameters for g_ix, p in enumerate(self.builder.global_params): p.value = x[g_ix] # Iterate over the locally fit parameters for l_ix, p in enumerate(self.builder.local_params): ix_offset = len(self.builder.global_params) + \ data_ix * len(self.builder.local_params) p.value = x[l_ix + ix_offset] # Now fill in the initial condition parameters for p_name, values in self.params.iteritems(): p = self.builder.model.parameters[p_name] p.value = values[data_ix] # Now run the simulation s.run() # Plot the observable if self.use_expr: plt.plot(self.time, s.yexpr[self.obs_name], color='r') else: plt.plot(self.time, s.yobs[self.obs_name], color='r')
def test_earm_integration(): t = np.linspace(0, 1e4, 1000) # Run with and without inline Solver._use_inline = False sol = Solver(earm_1_0.model, t, use_analytic_jacobian=True) sol.run() Solver._use_inline = True sol = Solver(earm_1_0.model, t, use_analytic_jacobian=True) sol.run()
def simulate_model(self, model, target_entity): ''' Simulate a model and return the observed dynamics of a given target agent. ''' # TODO: where does the maximal time point come from? monomer = self.get_monomer(model, target_entity) obs_name = self.get_obs_name(model, monomer) ts = numpy.linspace(0, 100, 100) solver = Solver(model, ts) solver.run() yobs_target = solver.yobs[obs_name] plt.ion() plt.plot(ts, yobs_target, label=obs_name) plt.show() plt.legend() return yobs_target
def synthetic_data(model, tspan, obs_list=None, sigma=0.1): #from pysb.integrate import odesolve from pysb.integrate import Solver solver = Solver(model, tspan) solver.run() # Sample from a normal distribution with variance sigma and mean 1 # (randn generates a matrix of random numbers sampled from a normal # distribution with mean 0 and variance 1) # # Note: This modifies yobs_view (the view on yobs) so that the changes # are reflected in yobs (which is returned by the function). Since a new # Solver object is constructed for each function invocation this does not # cause problems in this case. solver.yobs_view *= ( (numpy.random.randn(*solver.yobs_view.shape) * sigma) + 1) return solver.yobs
def run_model(model): sim_hours = 200 ts = np.linspace(0, sim_hours * 3600, sim_hours * 60) solver = Solver(model, ts) solver.run() plt.figure(figsize=(2, 2), dpi=300) set_fig_params() plt.plot(ts, solver.yobs['p53_active'], 'r') #if model.name == 'p53_ATR': # plt.plot(ts, solver.yobs['atr_active'], 'b') #else: # plt.plot(ts, solver.yobs['atm_active'], 'b') plt.xticks([]) plt.xlabel('Time (a.u.)', fontsize=12) plt.ylabel('Active p53', fontsize=12) plt.yticks([]) plt.savefig(model.name + '.pdf') return ts, solver
def test_robertson_integration(): t = np.linspace(0, 100) # Run with and without inline Solver._use_inline = False sol = Solver(robertson.model, t, use_analytic_jacobian=True) sol.run() assert sol.y.shape[0] == t.shape[0] # Run with and without inline Solver._use_inline = True sol = Solver(robertson.model, t, use_analytic_jacobian=True) sol.run()
def test_earm_integration(): """Ensure earm_1_0 model simulates.""" t = np.linspace(0, 1e3) # Run with or without inline sol = Solver(earm_1_0.model, t) sol.run() if Solver._use_inline: # Also run without inline Solver._use_inline = False sol = Solver(earm_1_0.model, t) sol.run() Solver._use_inline = True
def run_model(model): sim_hours = 20 ts = np.linspace(0, sim_hours * 3600, sim_hours * 60) tst = time.time() solver = Solver(model, ts) solver.run() te = time.time() print('Simulation took %.2fs' % (te - tst)) plt.figure(figsize=(1.8, 1), dpi=300) set_fig_params() plt.plot(ts, solver.yobs['p53_active'], 'r') plt.xticks([]) plt.xlabel('Time (a.u.)', fontsize=7) plt.ylabel('Active p53', fontsize=7) plt.yticks([]) ax = plt.gca() format_axis(ax) #plt.subplots_adjust() plt.savefig(model.name + '.pdf') return ts, solver
def test_robertson_integration(): """Ensure robertson model simulates.""" t = np.linspace(0, 100) # Run with or without inline sol = Solver(robertson.model, t) sol.run() assert sol.y.shape[0] == t.shape[0] if Solver._use_inline: # Also run without inline Solver._use_inline = False sol = Solver(robertson.model, t) sol.run() assert sol.y.shape[0] == t.shape[0] Solver._use_inline = True
def sim_experiment(model, exp, pd=None, solver=None): if pd is None: pd = {} pd['ERK_0'] = exp.ERKtot * exp.ERK[0] pd['ERKpT_0'] = exp.ERKtot * exp.ERKpT[0] pd['ERKpY_0'] = exp.ERKtot * exp.ERKpY[0] pd['ERKpTpY_0'] = exp.ERKtot * exp.ERKpTpY[0] pd['MEK_0'] = exp.MEKtot pd['MKP_0'] = exp.MKPtot if solver is None: Solver._use_inline = True solver = Solver(model, exp.ts, use_analytic_jacobian=True) else: solver.set_tspan(exp.ts) solver.run(pd) return solver.yobs
# for s in sos_range: for r in Ras_range: wt_holder_row = [] v600e_holder_row = [] erk_holder_row = [] kras_holder_row = [] sos_holder_row = [] for v in Vemurafenib_range: model.parameters['KRAS_0'].value = r # model.parameters['SOS_0'].value = s model.parameters['Vem_0'].value = v ts = np.linspace(0, 1e5, 100) solver = Solver(model, ts) solver.run() wt_holder_row.append(solver.yobs['BRAF_WT_active'][-1]) v600e_holder_row.append(solver.yobs['BRAF_V600E_active'][-1]) erk_holder_row.append(solver.yobs['ERK_P'][-1]) kras_holder_row.append(solver.yobs['active_KRAS'][-1]) sos_holder_row.append(solver.yobs['active_SOS'][-1]) RAF_WT_level.append(wt_holder_row) RAF_V600E_level.append(v600e_holder_row) ERK_P_level.append(erk_holder_row) KRAS_level.append(kras_holder_row) SOS_level.append(sos_holder_row) wt = np.array(RAF_WT_level, dtype='float')
from pysb.integrate import Solver from pysb.sensitivity import Sensitivity import scipy.optimize from pyDOE import * from scipy.stats.distributions import norm import numdifftools as nd # Simulate the model # Create time vector using np.linspace function num_timepoints = 101 num_dim = 3 t = np.linspace(0, 200, num_timepoints) # Get instance of the Solver sol = Solver(model, t, use_analytic_jacobian=False) # Perform the integration sol.run() # Get instance of Sensitivity object sens = Sensitivity(model, t) # sol.y contains timecourses for all of the species # (model.species gives matched list of species) # sol.yobs contains timecourse only for the observables # Indexed by the name of the observable # Plot the timecourses for A, B, and C plt.ion()
from pydream.core import run_dream from pysb.integrate import Solver import numpy as np from pydream.parameters import SampledParam from pydream.convergence import Gelman_Rubin from scipy.stats import norm import inspect import os.path from .corm import model as cox2_model pydream_path = os.path.dirname(inspect.getfile(run_dream)) #Initialize PySB solver object for running simulations. Simulation timespan should match experimental data. tspan = np.linspace(0, 10, num=100) solver = Solver(cox2_model, tspan) solver.run() #Load experimental data to which CORM model will be fit here location = pydream_path + '/examples/corm/exp_data/' exp_data_PG = np.loadtxt(location + 'exp_data_pg.txt') exp_data_PGG = np.loadtxt(location + 'exp_data_pgg.txt') exp_data_sd_PG = np.loadtxt(location + 'exp_data_sd_pg.txt') exp_data_sd_PGG = np.loadtxt(location + 'exp_data_sd_pgg.txt') #Experimental starting values of AA and 2-AG species (all in microM). exp_cond_AA = [0, .5, 1, 2, 4, 8, 16] exp_cond_AG = [0, .5, 1, 2, 4, 8, 16] #Experimentally measured parameter values. These will not be sampled with DREAM.