def ensembleTimeCourse(model_col): """ """ r = te.loada(model_col[0]) T = np.empty((len(model_col), 100, r.getNumFloatingSpecies())) for i in range(len(model_col)): r = te.loada(model_col[i]) T[i] = r.simulate(0, 100, 100)[:, 1:] return T
def ensembleReactionRates(model_col): """ """ r = te.loada(model_col[0]) J = np.empty((len(model_col), r.getNumReactions())) for i in range(len(model_col)): r = te.loada(model_col[i]) r.steadyState() J[i] = r.getReactionRates() return J
def ensembleSteadyState(model_col): """ """ r = te.loada(model_col[0]) SS = np.empty((len(model_col), r.getNumFloatingSpecies())) for i in range(len(model_col)): r = te.loada(model_col[i]) r.steadyState() SS[i] = r.getFloatingSpeciesConcentrations() return SS
def ensembleFluxControlCoefficient(model_col): """ """ r = te.loada(model_col[0]) F = np.empty((len(model_col), r.getNumReactions(), r.getNumReactions())) for i in range(len(model_col)): r = te.loada(model_col[i]) r.steadyState() F[i] = r.getScaledFluxControlCoefficientMatrix() return F
def simulate_pscan(param, param_range: np.ndarray, ini_volume, selections, ss_param_dict: dict): mod = te.loada(cf.MECHANICAL_SIZE_CONTROL_MOD) ss_finder = SteadyStateFinder(cf.SIZE_REGULATION_MOD) ia_dict, rules_dict = mrt.get_ia_and_rules(mod) return p_scan(param, param_range, ss_finder, ia_dict, rules_dict, ss_param_dict, selections, mod, ini_volume)
def identifiability(best_estimated_parameters: Dict[str, float], num_points: int = 10): # we reload roadrunner here to prevent potential unintended consequences of modifying r inplace r = te.loada(ANTIMONY_STRING) # We make a copy of the original free parameters here # since we'll need to modify which parameters are estimated later # and put the original values back before each parameter original_free_parameters = r.freeParameters() # somewhere to store the results results = dict() for parameter in r.freeParameters(): print("Running profile likelihood for parameter ", parameter) # get best estimated value for parameter if parameter not in best_estimated_parameters.keys(): raise ValueError(f"Parameter {parameter} not in best estimated parameters: {best_estimated_parameters}") # reset our model back to the best parameter set for k, v in best_estimated_parameters.items(): setattr(r, k, v) # we can use the interface from above but we need to update the # freeParameters method to contain only 'parameter'. In profile # likelihood, many parameter estimations are conducted, staring # from the best estimated parameter set. The difference is that # we fix 1 parameter (say k1) to a calculated value and reoptimize # all the others. Then we repeat, but with a different value of k1. def freeParameters(self): return [p for p in original_free_parameters if p != parameter] # tell roadrunner which parameters to estimate during reoptimization r.freeParameters = freeParameters # calculate the boundaries of the proile likelihood in logspace best_estimated_value = best_estimated_parameters[parameter] lb = best_estimated_value / 1000 ub = best_estimated_value * 1000 # these are the values that we will set fix parameter to x = np.logspace(np.log10(lb), np.log10(ub), num_points) best_rss_for_parameter_fixed_at_x = [] # for collecting the best rss values for each run list_of_best_params = [] # collect the best parameters for each run for fixed_parameter_value in x: print("scanning parameter value of: ", fixed_parameter_value) # 1) set the fixed parameter value setattr(r, parameter, fixed_parameter_value) # 2) repeat the parameter estimation. objective_values_for_this_run, x_sim, y_sim, sel, best_parameters = do_estimation(ngen=50) best_rss_for_parameter_fixed_at_x.append(objective_values_for_this_run[-1]) list_of_best_params.append(best_parameters) results[parameter] = dict( x=x, list_of_best_params=list_of_best_params, best_rss_for_parameter_fixed_at_x=best_rss_for_parameter_fixed_at_x ) return results
def testCombMotif(flatComb, motifList): try: combMotif = te.loada( flatComb ) # If it fails here, the combined model is not formatted correctly SS = combMotif.steadyState() except: raise AssertionError('Failed to create a combined model! Check code.') try: SS = combMotif.steadyState() print('Model reaches Steady-State!') except: print( 'Model Fails to reach Steady-state. Retrying with new parameter values.' ) global SSFAILED SSFAILED = True motifList = [] motifListDir = motifsFromScratch() motifList = chooseDupMotif(motifListDir) combined = combineMotifs() flatComb = flattenMotif(combined) testCombMotif(flatComb, motifList) if SS == 0: print('Steady-state = 0. Retrying with new parameter values.') global SSFAILED SSFAILED = True motifList = [] motifListDir = motifsFromScratch() chooseDupMotif(motifListDir) combined = combineMotifs() flatComb = flattenMotif(combined) testCombMotif(flatComb, motifList) return (combMotif, SSFAILED)
def test_truth_table(testmodel, input_ids, output_ids, truth_table, ht=0.8, lt=0.2, delay=99, plot=False): import tellurium as te r = te.loada(testmodel) sims = [] for row in truth_table: message = ['When'] for i, input_val in enumerate(row[0]): message.append(input_ids[i] + ':' + str(input_val)) r[input_ids[i]] = input_val sim = r.simulate(0, delay + 1, delay + 1, ['time'] + input_ids + output_ids) sims.append(sim) for i, output_val in enumerate(row[1]): offset = len(input_ids) + 1 # Time + length of inputs ind = i + offset full_message = ' '.join(message + [ 'then', output_ids[i] + ':' + str(output_val), '; Found %s = %f' % (output_ids[i], sim[delay][ind]) ]) print full_message if output_val == 0: assert sim[delay][ind] < lt, full_message else: assert sim[delay][ind] > ht, full_message return r, sims
def exportAsCombine(self, outputPath, execute=False): """ Creates COMBINE archive for given antimony and phrasedml files. If execute=True all phrasedml are executed and the results written :param exportPath: full path of the combine zip file to create :type exportPath: str """ # Create empty archive m = tecombine.CombineArchive() # Add antimony models to archive for aStr in self.antimonyList: r = te.loada(aStr) name = r.getModel().getModelName() m.addAntimonyStr(aStr, "{}.xml".format(name)) # Add phrasedml models to archive for k, phrasedmlStr in enumerate(self.phrasedmlList): phrasedml.clearReferencedSBML() self._setReferencedSBML(phrasedmlStr) m.addPhraSEDMLStr(phrasedmlStr, self._phrasedmlFileName(k), master=True) phrasedml.clearReferencedSBML() # Add README.md to archive readmeStr = self.createReadmeString(outputPath) m.addStr(readmeStr, location='README.md', filetype='md') # add output files to archive if execute: for phrasedmlStr in self.phrasedmlList: # execute in temporary directory workingDir = tempfile.mkdtemp(suffix="_sedml") execStr = self._toPython(phrasedmlStr, workingDir=workingDir) exec execStr # Add output files to archive files = [f for f in os.listdir(workingDir)] for f in files: filepath = os.path.join(workingDir, f) if f.endswith('.xml'): # SBML or SEDML resulting from antimony/phrasedml (already in archive) pass elif f.endswith('.md'): # README.md (already in archive) pass elif f.endswith('.png'): # outputPlot2D | outputPlot3D m.addFile(filepath, filetype="png") elif f.endswith('.csv'): # outputReport m.addFile(filepath, filetype="csv") else: warnings.warn('Unsupported file type not written in COMBINE archive: {}'.format(filepath)) # remove temporary workingDir shutil.rmtree(workingDir) # Write archive m.write(outputPath)
def test_getSeed(self): r = te.loada(""" S1 -> S2; k1*S1; k1 = 0.1; S1 = 40; S2 = 0.0; """) seed = r.getSeed() self.assertIsNotNone(seed)
def test_setSeed(self): r = te.loada(""" S1 -> S2; k1*S1; k1 = 0.1; S1 = 40; S2 = 0.0; """) r.setSeed(123) self.assertEqual(123, r.getSeed())
def fed_batch_model_mu(): mu_model = ''' model *IDModel() ######## Set the compartment to 1, otherwise it will be multiplied by the compounds. compartment comp1; comp1 =1; ######## Specify the species in the compartment glucose in comp1; biomass in comp1; serine in comp1; #acetate in comp1 ######## Constants mu_max = 0.2477 # [1/h] Ks = 1.4344 # [g/L] Ks_qs = 2.6784 # [g/L] Ki = 688309 # [g/L] qs_max = 1.4075 # (g/(g*h)) F0 = 0.3 mu_set = 0.02 alpha = 1.5007 beta = 2.7714 ######## Initial conditions V = 0.1021 glucose = 0 # 0.149770*V # [g] biomass = 0.209504 #5.092*V # [g] serine = 0 # [g] ######## Feed function Fin := F0*exp(mu_set*time)/1000 # [L/h] ######## Function for volume in fed-batch EqVolume: -> V; Fin # [L/h] ######## Initial concentrations c_glucose := glucose/V # [g/L] c_glufeed = 415 # [g/L] c_biomass := biomass/V ######## Functions mu = 0 qs := qs_max*c_glucose/(Ks_qs+c_glucose) # [g_substrate/g_biomass h] qp := alpha*mu/(mu+beta) ######## Mass Balances eq_biomass: -> biomass; mu*biomass # [g/h] eq_glucose: -> glucose; -qs*biomass + Fin*c_glufeed # [g/h] eq_serine: -> serine; qp*biomass # [g/h] end ''' r = te.loada(mu_model) return r
def run(self,func=None): """Allows the user to set the data from a File This data is to be compared with the simulated data in the process of parameter estimation Args: func: An Optional Variable with default value (None) which by default run differential evolution which is from scipy function. Users can provide reference to their defined function as argument. Returns: The Value of the parameter(s) which are estimated by the function provided. .. sectionauthor:: Shaik Asifullah <*****@*****.**> """ self._parameter_names = self.bounds.keys() self._parameter_bounds = self.bounds.values() self._model_roadrunner = te.loada(self.model.model) x_data = self.data[:,0] y_data = self.data[:,1:] arguments = (x_data,y_data) if(func is not None): result = differential_evolution(self._SSE, self._parameter_bounds, args=arguments) return(result.x) else: result = func(self._SSE,self._parameter_bounds,args=arguments) return(result.x)
def simulationSandbox(setup, ant_str, r_comb): ''' Function to parallelize simulations due to memory leak issue. Sandbox anything that has to do with antimony and kill it off after an iteration ''' antimony.clearPreviousLoads() rr = te.loada(ant_str) rr.resetAll() # ALWAYS RESET rr.conservedMoietyAnalysis = True pert_i = rr.steadyStateNamedArray() # Initial steady state # Put initial steady state and species ids #pert_init.append(pert_i[0]) # Pertubation for rate constants k_pert_output_i = np.empty([len(r_comb), setup.num_float]) for i in range(len(r_comb)): k_pert_output_i[i] = util.perturbRate(rr, r_comb[i], setup.k_pert) antimony.clearPreviousLoads() return pert_i.tolist(), k_pert_output_i.tolist()
def test_plot(self): """ Regression tests for plotting. The following calls should work. """ r = te.loada(""" S1 -> S2; k1*S1; k1 = 0.1; S1 = 40; S2 = 0.0; """) s = r.simulate(0, 100, 21) # no argument version r.plot() # plot with data r.plot(s) # plot with named data r.plot(result=s) # plot without legend r.plot(s, loc=False) # plot without showing r.plot(s, show=False) r.plot(s, show=True) # no show # plot with label, title, axis and legend r.plot(s, xlabel="x", ylabel="y", xlim=[0, 10], ylim=[0, 10], grid=True) # plot with additional plot settings from matplotlib r.plot(s, color="blue", alpha=0.1, linestyle="-", marker="o")
def pathway(promoters, decay=True): antinom = modelHeader() if decay: antinom += modelTemplate(1, decay) antinom += modelTemplate(1) antinom += modelTemplate(None) antinom += "model *Big_Model()"+"\n" for i in np.arange(len(promoters)): p = promoters[i] if p is not None: if i == 0 and decay: antinom += "\t"+"m%d: Prom_Upstream_Model();" % (i+1,) else: antinom += "\t"+"m%d: Prom_Model();" % (i+1,) else: antinom += "\t"+"m%d: Noprom_Model();" % (i+1,) antinom += "\n" for i in np.arange(len(promoters)-1): antinom += "\t"+"m%d.Product is m%d.Substrate;" % (i+1, i+2) antinom += "\n" for i in np.arange(1,len(promoters)): p = promoters[i] if p is None: antinom += "\t"+"m%d.Activated_promoter is m%d.Activated_promoter" %(i+1,i) antinom += "\n" antinom += "end\n" return te.loada(antinom)
def runSSA(N, k, runs, std): # P, Ss. i_mean = np.array([20, 0]) i_std = np.array([5, 0]) # kb, kd, kout, kin. k_mean = np.array([1, 0.01, k, k]) k_std = np.array([std, 0.001, 0, 0]) s_stack = np.zeros(N+2) for i in range(runs): # Errors may be thrown out here if a negative value is drawn. initials = np.random.normal(i_mean,i_std, size = (N,len(i_mean))) rates = np.random.normal(k_mean,k_std, size = (N,len(k_mean))) # Rewrite Antimony file for N population cells. writeBirthDeath(initials.astype(int), rates, N) path = 'birthdeath.ant' r = te.loada(path) r.integrator = 'gillespie' selections = ['time'] + r.getFloatingSpeciesIds() r.integrator.variable_step_size = False r.resetToOrigin() s = r.simulate(0, 1000, 100, selections=selections) s_stack = np.vstack((s_stack, s)) s_stack = s_stack[1:] s_stack_df = pd.DataFrame(s_stack, columns = s.colnames) s_stack_df['N'] = np.repeat(N,runs*100) s_stack_df['k'] = np.repeat(k,runs*100) s_stack_df['std'] = np.repeat(std,runs*100) return s_stack_df
def test_plot(self): """ Regression tests for plotting. The following calls should work. """ r = te.loada(""" S1 -> S2; k1*S1; k1 = 0.1; S1 = 40; S2 = 0.0; """) print(type(r)) s = r.simulate(0, 100, 21) # no argument version r.plot() # plot with data r.plot(s) # plot with named data r.plot(result=s) # plot without legend r.plot(s) # plot without showing r.plot(s, show=False) r.plot(s, show=True) # no show # plot with label, title, axis and legend r.plot(s, xlabel="x", ylabel="y", xlim=[0, 10], ylim=[0, 10], grid=True) # plot with additional plot settings from matplotlib r.plot(s, alpha=0.1, color="blue", linestyle="-", marker="o")
def run(self, func=None): """Allows the user to set the data from a File This data is to be compared with the simulated data in the process of parameter estimation Args: func: An Optional Variable with default value (None) which by default run differential evolution which is from scipy function. Users can provide reference to their defined function as argument. Returns: The Value of the parameter(s) which are estimated by the function provided. .. sectionauthor:: Shaik Asifullah <*****@*****.**> """ self._parameter_names = self.bounds.keys() self._parameter_bounds = self.bounds.values() self._model_roadrunner = te.loada(self.model.model) x_data = self.data[:, 0] y_data = self.data[:, 1:] arguments = (x_data, y_data) if (func is not None): result = differential_evolution(self._SSE, self._parameter_bounds, args=arguments) return (result.x) else: result = func(self._SSE, self._parameter_bounds, args=arguments) return (result.x)
def runSimulation(sim_time=SIM_TIME, num_points=NUM_POINTS, parameters=None, road_runner=ROAD_RUNNER, model=MODEL): """ Runs the simulation model rr for the parameters. :param int sim_time: time to run the simulation :param int num_points: number of timepoints simulated :param lmfit.Parameters parameters: :param ExtendedRoadRunner road_runner: :param str model: :return named_array: """ if road_runner is None: road_runner = te.loada(model) else: road_runner.reset() if parameters is not None: parameter_dict = parameters.valuesdict() # Set the simulation constants for all parameters for constant in parameter_dict.keys(): stmt = "road_runner.%s = parameter_dict['%s']" % (constant, constant) exec(stmt) return road_runner.simulate(0, sim_time, num_points)
def _adjustNames(self, antimonyModel:str, observedTS:NamedTimeseries) \ ->typing.Tuple[NamedTimeseries, list]: """ Antimony exports can change the names of floating species by adding a "_" at the end. Check for this and adjust the names in observedTS. Return ------ NamedTimeseries: newObservedTS list: newSelectedColumns """ rr = te.loada(antimonyModel) dataNames = rr.simulate().colnames names = ["[%s]" % n for n in observedTS.colnames] missingNames = [n[1:-1] for n in set(names).difference(dataNames)] newSelectedColumns = list(self.selectedColumns) if len(missingNames) > 0: newObservedTS = observedTS.copy() self.logger.exception("Missing names in antimony export: %s" % str(missingNames)) for name in observedTS.colnames: missingName = "%s_" % name if name in missingNames: newObservedTS = newObservedTS.rename(name, missingName) newSelectedColumns.remove(name) newSelectedColumns.append(missingName) else: newObservedTS = observedTS return newObservedTS, newSelectedColumns
def testme(): """ Call this method to try out the methods in this module""" r = _te.loada(""" J1: $Xo -> S1; k1*Xo - k11*S1; J2: S1 -> S2; k2*S1 - k22*S2; J3: S2 -> S3; k3*S2 - k33*S3; J4: S3 -> S4; k3*S3 - k44*S4; J5: S4 -> S5; k4*S4 - k44*S5; J6: S5 -> S6; k5*S5 - k55*S6; J7: S6 -> S7; k4*S6 - k44*S7; J8: S7 -> S8; k3*S7 - k33*S8; J9: S8 -> ; k4*S8; k1 = 0.3; k11 = 0.26; k2 = 0.5; k22 = 0.41; k3 = 0.27; k33 = 0.12; k4 = 0.9; k44 = 0.56 k5 = 0.14; k55 = 0.02 Xo = 10; """) r.steadyState() plotting.plotFloatingSpecies(r, width=6, height=3) plotting.plotConcentrationControlIn3D(r) plotting.plotFluxControlIn3D(r, lowerLimit=0) plotting.plotConcentrationControlHeatMap(r) plotting.plotFluxControlHeatMap(r)
def generateNetworkWithSteadyState(num_node, num_bound, num_input, knownr=1): """ Generate network topology that has steady state solution :param num_node: total number of species :param num_bound: total number of boundary species :param num_input: number of input boundary species :rtype: array """ import antimony import tellurium as te i = 0 while i < 2: try: test_net = generateRandomNetwork(num_node, num_bound, num_input) k_count = np.count_nonzero(test_net) s_init = generateInitialSpecies(num_node, 5) k_init = generateInitialRateConstants(k_count, 1) ant_str = generateAntimony(test_net, s_init, k_init, num_node, num_bound) antimony.clearPreviousLoads() rr = te.loada(ant_str) rr.resetToOrigin() # ALWAYS RESET rr.steadyStateNamedArray() # Test steady state i += 1 except ValueError: pass except RuntimeError: pass antimony.clearPreviousLoads() return test_net, s_init, k_init
def __init__(self, model, trueParameterDct, startTime=0, endTime=None, numPoint=None): """ Parameters ---------- model: str/ExtendedAntimony parameter values are the true values trueParameterDct: dict True values of parameters for the model key: parameter name value: value of parameter Returns ------- """ self.startTime = startTime self.endTime = endTime self.numPoint = numPoint self.trueParameterDct = trueParameterDct if isinstance(model, str): self.antimonyModel = model self.roadrunnerModel = te.loada(self.antimonyModel) else: self.roadrunnerModel = model self.antimonyModel = self.roadrunnerModel.getAntimony() self.baseArr = self._getFlatValues(self.trueParameterDct) self.nrmseNrm = np.sqrt(np.sum(self.baseArr**2)) self.simDF = None # Results of last simulation experiments self.simTable = None # 2 parameter pivot table created in plot
def createSBML(antimony_str): """ :param str antimony_str: antimony model :return str SBML: """ rr = te.loada(antimony_str) sbmlstr = rr.getSBML() return sbmlstr
def load_model(model_file,parameter_dictionary): ''' Load a model and set its parameters ''' model = te.loada(model_file) update_model(model,parameter_dictionary) return model
def _initializeTests(title, modelStr): global _testCount global _failedTest _testCount = 0 _failedTest = [] r = _te.loada (modelStr) sbmlStr = r.getSBML() print ('\nBegin Report: ' + title) return _simplesbml.loadSBMLStr (sbmlStr)
def spark_work(model_with_parameters): import tellurium as te if(antimony == "antimony"): model_roadrunner = te.loada(model_with_parameters[0]) else: model_roadrunner = te.loadSBMLModel(model_with_parameters[0]) parameter_scan_initilisation = te.ParameterScan(model_roadrunner,**model_with_parameters[1]) simulator = getattr(parameter_scan_initilisation, function_name) return(simulator())
def to_roadrunner(self) -> rr.ExecutableModel: """ Construct a roadrunner model via the tellurium interface using the current antimony string Returns: """ return te.loada(self.to_antimony())
def _init(): global _known_parameters rr = _te.loada(_known_model_part) _known_parameters = dict( zip(rr.model.getGlobalParameterIds(), rr.model.getGlobalParameterValues())) global _all_regs _all_regs = _generate_all_regs()
def test_draw(self): r = te.loada(""" S1 -> S2; k1*S1; k1 = 0.1; S1 = 40; S2 = 0.0; """) try: import pygraphviz r.draw() except ImportError: pass
def test_loada(self): rr = te.loada(''' model example0 S1 -> S2; k1*S1 S1 = 10 S2 = 0 k1 = 0.1 end ''') self.assertIsNotNone(rr.getModel())
def dynamic_simulate(self): if self.model_str is None: print("Error simulation: Model definition missing") return None self.loada_str = self.preamble_str + self.model_str + self.input_str self.r = te.loada(self.loada_str) self.r.selections = self.output_vars self.result = self.r.simulate(0, self.real_time, self.n_times) self.X = np.array(self.result).T # time along shape[1] self.U = np.array(self.input_tracks)
def classify(setup, s_arr, c_arr): """ Ground truth classification. Returns initial perturbation response, perturbation response, classification, and reaction index :param g_truth: ground truth network matrix :param s_truth: ground truth species concentrations :param k_truth: ground truth rate constants :param num_node: ground truth numbder of nodes :param num_bound: ground truth numbder of boundary species :param k_pert: perturbation amount :param Thres: classification threshold :rtype: list """ antimony.clearPreviousLoads() # Strip and translate to string t_s = setup.t_s.astype('str') t_k = setup.t_k[setup.t_k != np.array(0)].astype('str') #t_k_count = np.count_nonzero(setup.t_net) t_ant = generate.generateAntimonyNew(setup.t_net, t_s, t_k, s_arr, c_arr) #r_ind = np.array(np.where(setup.t_net != np.array(0))).T r_ind = util.getPersistantOrder(setup.t_net, setup.p_net) rr = te.loada(t_ant) rr.reset() # ALWAYS RESET rr.conservedMoietyAnalysis = True pert_i = rr.steadyStateNamedArray() # Initial steady state r_comb = clustering.getListOfCombinations(r_ind) # Pertubation for rate constants k_pert_output_i = np.empty([len(r_comb), setup.num_float]) for i in range(len(r_comb)): k_pert_output_i[i] = util.perturbRate(rr, r_comb[i], setup.k_pert) # Classification for rate constants k_class_i = np.empty([len(r_comb), setup.num_float], dtype=int) for i in range(len(r_comb)): for j in range(setup.num_float): k_diff = (k_pert_output_i[i][j] - pert_i[0][j]) if (np.abs(k_diff) > setup.Thres): if k_diff < 0.: k_class_i[i][j] = 1 else: k_class_i[i][j] = 2 else: k_class_i[i][j] = 0 antimony.clearPreviousLoads() return pert_i[0], k_pert_output_i, k_class_i
def fromAntimony(cls, antimonyStr, location, master=None): """ Create SBMLAsset from antimonyStr :param antimonyStr: :type antimonyStr: :param location: :type location: :return: :rtype: """ r = te.loada(antimonyStr) raw = r.getSBML() return cls.fromRaw(raw=raw, location=location, filetype='sbml', master=master)
def fromAntimony(cls, antimonyStr, location, master=None): """ Create SBMLAsset from antimonyStr :param antimonyStr: :type antimonyStr: :param location: :type location: :return: :rtype: """ warnings.warn('Use inline_omex instead.', DeprecationWarning) r = te.loada(antimonyStr) raw = r.getSBML() return cls.fromRaw(raw=raw, location=location, filetype='sbml', master=master)
def test_README_example(self): """ Tests the source example in the main README.md. """ import tellurium as te rr = te.loada(''' model example0 S1 -> S2; k1*S1 S1 = 10 S2 = 0 k1 = 0.1 end ''') result = rr.simulate(0, 40, 500) te.plotArray(result)
def stochastic_work(model_object): import tellurium as te if model_type == "antimony": model_roadrunner = te.loada(model_object.model) else: model_roadrunner = te.loadSBMLModel(model_object.model) model_roadrunner.integrator = model_object.integrator # seed the randint method with the current time random.seed() # it is now safe to use random.randint model_roadrunner.setSeed(random.randint(1000, 99999)) model_roadrunner.integrator.variable_step_size = model_object.variable_step_size model_roadrunner.reset() simulated_data = model_roadrunner.simulate(model_object.from_time, model_object.to_time, model_object.step_points) return([simulated_data.colnames,np.array(simulated_data)])
def _setReferencedSBML(self, phrasedmlStr): """ Set phrasedml referenced SBML for given phrasedml String. """ modelNames = [] for aStr in self.antimonyList: r = te.loada(aStr) name = r.getModel().getModelName() modelNames.append(name) sources = self._modelsFromPhrasedml(phrasedmlStr) for source, name in sources.iteritems(): # not a antimony model if name not in modelNames: continue # set as referenced model aStr = self.antimonyList[modelNames.index(name)] phrasedml.setReferencedSBML(source, te.antimonyToSBML(aStr))
def test_seed(self): r = te.loada(''' S1 -> S2; k1*S1; k1 = 0.1; S1 = 40; S2 = 0; ''') # Simulate from time zero to 40 time units result = r.gillespie(0, 40, 11) # Simulate on a grid with 10 points from start 0 to end time 40 result = r.gillespie(0, 40, 10) # Simulate from time zero to 40 time units using the given selection list # This means that the first column will be time and the second column species S1 result = r.gillespie(0, 40, 11, ['time', 'S1']) # Simulate from time zero to 40 time units, on a grid with 20 points # using the give selection list result = r.gillespie(0, 40, 20, ['time', 'S1'])
def test_plot2DParameterScan(self): """Test plot2DParameterScan.""" import tellurium as te from tellurium.analysis.parameterscan import plot2DParameterScan r = te.loada(""" model test J0: S1 -> S2; Vmax * (S1/(Km+S1)) S1 = 10; S2 = 0; Vmax = 1; Km = 0.5; end """) s = r.simulate(0, 50, 101) # r.plot(s) import numpy as np plot2DParameterScan(r, p1='Vmax', p1Range=np.linspace(1, 10, num=5), p2='Vmax', p2Range=np.linspace(0.1, 1.0, num=5), start=0, end=50, points=101)
def test_complex_simulation(self): """ Test complex simulation. """ model = ''' model feedback() // Reactions: J0: $X0 -> S1; (VM1 * (X0 - S1/Keq1))/(1 + X0 + S1 + S4^h); J1: S1 -> S2; (10 * S1 - 2 * S2) / (1 + S1 + S2); J2: S2 -> S3; (10 * S2 - 2 * S3) / (1 + S2 + S3); J3: S3 -> S4; (10 * S3 - 2 * S4) / (1 + S3 + S4); J4: S4 -> $X1; (V4 * S4) / (KS4 + S4); // Species initializations: S1 = 0; S2 = 0; S3 = 0; S4 = 0; X0 = 10; X1 = 0; // Variable initialization: VM1 = 10; Keq1 = 10; h = 10; V4 = 2.5; KS4 = 0.5; end ''' r = te.loada(model) result = r.simulate(0, 40, 101) r.plot(result)
#Output requested: Amount of people in each state for years 1-10. # #This implementation uses a flattened model separated to M=Male and F=Female import tellurium as te r = te.loada (''' MJ00: MH -> MS; MH*0.2 MJ02: MH -> MD; MH*0.01 MJ10: MS -> MH; MS*0.1 MJ12: MS -> MD; MS*0.3 FJ00: FH -> FS; FH*0.1 FJ02: FH -> FD; FH*0.01 FJ10: FS -> FH; FS*0.1 FJ12: FS -> FD; FS*0.3 MH = 50 MS = 0 MD = 0 FH = 50 FS = 0 FD = 0 ''') # This will create the SBML XML file te.saveToFile ('Example3.xml', r.getSBML()) r.setIntegrator('gillespie') r.integrator.variable_step_size = True
""" Some testing with ndarrays for storage """ import numpy as np import tellurium as te r = te.loada(""" model test() J0: S1 -> S2; k1*S1; S1=10.0; S2=0.0; k1=0.1; end """) print(r) N1 = 3 N2 = 4 N3 = 5 test = np.empty(shape=(N1, N2, N3), dtype=object) for k in range(N1): r.reset() s = r.simulate(start=0, end=5, steps=5) test[k, 0, 0] = s
# -*- coding: utf-8 -*- """ Simple UniUni reaction with first-order mass-action kinetics. """ from __future__ import print_function import tellurium as te model = ''' model pathway() S1 -> S2; k1*S1 # Initialize values S1 = 10; S2 = 0 k1 = 1 end ''' # load model r = te.loada(model) # carry out a time course simulation # arguments are: start time, end time, number of points result = r.simulate(0, 10, 100) # plot results r.plotWithLegend(result)
# Sniffers, buzzers, toggles and blinkers. # Tyson Model 2c - Substrate-depletion oscillator import tellurium as te import matplotlib.pyplot as plt r = te.loada (''' J1: $src -> X; k1*S; J2: X -> R; (kop + ko*EP)*X; J3: R -> $waste; k2*R; J4: E -> EP; Vmax_1*R*E/(Km_1 + E); J5: EP -> E; Vmax_2*EP/(Km_2 + EP); src = 0; kop = 0.01; ko = 0.4; k1 = 1; k2 = 1; R = 1; EP = 1; S = 0.2; Km_1 = 0.05; Km_2 = 0.05; Vmax_2 = 0.3; Vmax_1 = 1; ''') m = r.simulate (0, 300, 1000, ["Time", "R", "X", "EP", "E"]); plt.plot(m[:,0], m[:,1], 'r-', label="R", linewidth=2) plt.plot(m[:,0], m[:,2], 'g-', label="X", linewidth=2) plt.legend(loc='upper right') plt.xlabel('Time', fontsize=16) plt.ylabel('Concentration', fontsize=16) plt.show()
r = te.loada (''' #J1: S1 -> S2; Activator*kcat1*S1/(Km1+S1); J1: S1 -> S2; SE2*kcat1*S1/(Km1+S1); J2: S2 -> S1; Vm2*S2/(Km2+S2); J3: T1 -> T2; S2*kcat3*T1/(Km3+T1); J4: T2 -> T1; Vm4*T2/(Km4+T2); J5: -> E2; Vf5/(Ks5+T2^h5); J6: -> E3; Vf6*T2^h6/(Ks6+T2^h6); #J7: -> E1; J8: -> S; kcat8*E1 J9: E2 -> ; k9*E2; J10:E3 -> ; k10*E3; J11: S -> SE2; E2*kcat11*S/(Km11+S); J12: S -> SE3; E3*kcat12*S/(Km12+S); J13: SE2 -> ; SE2*kcat13; J14: SE3 -> ; SE3*kcat14; Km1 = 0.01; Km2 = 0.01; Km3 = 0.01; Km4 = 0.01; Km11 = 1; Km12 = 0.1; S1 = 6; S2 =0.1; T1=6; T2 = 0.1; SE2 = 0; SE3=0; S=0; E2 = 0; E3 = 0; kcat1 = 0.1; kcat3 = 3; kcat8 =1; kcat11 = 1; kcat12 = 1; kcat13 = 0.1; kcat14=0.1; E1 = 1; k9 = 0.1; k10=0.1; Vf6 = 1; Vf5 = 3; Vm2 = 0.1; Vm4 = 2; h6 = 2; h5=2; Ks6 = 1; Ks5 = 1; Activator = 0; at (time > 100): Activator = 5; ''')
r = te.loada(""" model normalized_species() # conversion between active (SA) and inactive (SI) J1: SA -> SI; k1*SA - k2*SI; k1 = 0.1; k2 = 0.02; # species species SA, SI, ST; SA = 10.0; SI = 0.0; const ST := SA + SI; SA is "active state S"; SI is "inactive state S"; ST is "total state S"; # normalized species calculated via assignment rules species SA_f, SI_f; SA_f := SA/ST; SI_f := SI/ST; SA_f is "normalized active state S"; SI_f is "normalized inactive state S"; # parameters for your function P = 0.1; tau = 10.0; nA = 1.0; nI = 2.0; kA = 0.1; kI = 0.2; # now just use the normalized species in some math F := ( (1-(SI_f^nI)/(kI^nI+SI_f^nI)*(kI^nI+1) ) * ( (SA_f^nA)/(kA^nA+SA_f^nA)*(kA^nA+1) ) -P)*tau; end """)
# ### Consecutive UniUni reactions using first-order mass-action kinetics # Model creation and simulation of a simple irreversible chain of reactions S1 -> S2 -> S3 -> S4. # In[1]: #!!! DO NOT CHANGE !!! THIS FILE WAS CREATED AUTOMATICALLY FROM NOTEBOOKS !!! CHANGES WILL BE OVERWRITTEN !!! CHANGE CORRESPONDING NOTEBOOK FILE !!! from __future__ import print_function import tellurium as te r = te.loada(''' model pathway() S1 -> S2; k1*S1 S2 -> S3; k2*S2 S3 -> S4; k3*S3 # Initialize values S1 = 5; S2 = 0; S3 = 0; S4 = 0; k1 = 0.1; k2 = 0.55; k3 = 0.76 end ''') result = r.simulate(0, 20, 51) te.plotArray(result); # In[2]:
k10 = random.uniform(0.0001, 1) k11 = random.uniform(0.0001, 1) k12 = random.uniform(1.0 / 2500.0, 1.0 / 10000000.0) Km9 = random.uniform(0.0001, 0.01) Km10 = random.uniform(0.0001, 0.01) Km11 = random.uniform(0.0001, 0.01) inter = 0.0 S1 = 10.0 constants_ref = {'k1': str(k1), 'k2': str(k2), 'k3': str(k3), 'k4': str(k4), 'k5': str(k5), 'k6': str(k6), 'k7': str(k7), 'k9': str(k9), 'k10': str(k10), 'k11': str(k11), 'k12': str(k12), 'Km9' : str(Km9), 'Km10': str(Km10), 'Km11': str(Km11), 'inter': str(inter), 'k8': str(k8), 'S1': str(S1)} rr = te.loada(model.format(**constants)) rr.getSteadyStateValues() S4_ref = rr.S4 print 'S4_ref =', S4_ref inter = random.uniform(0.0000000001, 1.0) constants = {'k1': str(k1), 'k2': str(k2), 'k3': str(k3), 'k4': str(k4), 'k5': str(k5), 'k6': str(k6), 'k7': str(k7), 'k9': str(k9), 'k10': str(k10), 'k11': str(k11), 'k12': str(k12), 'Km9' : str(Km9), 'Km10': str(Km10), 'Km11': str(Km11), 'inter': str(inter), 'k8': str(k8), 'S1': str(S1)} rr = te.loada(model.format(**constants)) rr.getSteadyStateValues() S4 = rr.S4
def simulate(antModelStr, constants): rr = te.loada(antModelStr.format(**constants)) rr.simulate(0, 800000, 100) rr.plot() print "P =", rr.P
# Copyright (c) 2017 Kiri Choi import os, sys import tellurium as te import matplotlib import matplotlib.pyplot as plt import seaborn as sb import numpy as np workingDir = os.getcwd() f = open('ant_str.txt','r') ant_str = f.read() f.close() r = te.loada(ant_str) results = r.simulate(0, 30, 31) ind_1 = np.shape(results)[1]/2 #ind_2 = np.sqrt((np.shape(results)[1] - 2)/2) ind_2 = 38 grid = [] for i in range(len(results[:,1:-ind_1])): grid.append(results[:,1:-ind_1][i].reshape(-1, int(ind_2))) sb.set_style("white") plt.figure() cmap = matplotlib.colors.ListedColormap(['black','white'])
# In[1]: #!!! DO NOT CHANGE !!! THIS FILE WAS CREATED AUTOMATICALLY FROM NOTEBOOKS !!! CHANGES WILL BE OVERWRITTEN !!! CHANGE CORRESPONDING NOTEBOOK FILE !!! from __future__ import print_function import tellurium as te import matplotlib.pyplot as plt import tellurium as te import numpy as np from roadrunner import Config Config.setValue(Config.LOADSBMLOPTIONS_CONSERVED_MOIETIES, True) r = te.loada(''' $Xo -> S1; vo; S1 -> S2; k1*S1 - k2*S2; S2 -> $X1; k3*S2; vo = 1 k1 = 2; k2 = 0; k3 = 3; ''') p = te.SteadyStateScan(r, value = 'k3', startValue = 2, endValue = 3, numberOfPoints = 20, selection = ['S1', 'S2'] ) p.plotArray() Config.setValue(Config.LOADSBMLOPTIONS_CONSERVED_MOIETIES, False)
def simulate(antModelStr, constants): rr = te.loada(antModelStr.format(**constants)) rr.simulate(0, 800000, 1000) rr.plot() rr.getSteadyStateValues() return rr.P
# coding: utf-8 # Back to the main [Index](../index.ipynb) # ### Simple Example # In[1]: #!!! DO NOT CHANGE !!! THIS FILE WAS CREATED AUTOMATICALLY FROM NOTEBOOKS !!! CHANGES WILL BE OVERWRITTEN !!! CHANGE CORRESPONDING NOTEBOOK FILE !!! from __future__ import print_function import tellurium as te r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10') r.simulate(0, 50, 100) r.plot(); # ### More Complex Example # Stochastic simulation of a linear chain. # In[2]: import tellurium as te import numpy as np r = te.loada(''' J1: S1 -> S2; k1*S1; J2: S2 -> S3; k2*S2 - k3*S3 # J2_1: S2 -> S3; k2*S2 # J2_2: S3 -> S2; k3*S3; J3: S3 -> S4; k4*S3;