def GetModel(numberOfGenes, modelName, folderPath, Probabilities, rSeed=0, ParamRange=[], MAX_TRIES=100, InducedGenes=[]): if len(InducedGenes) > 0: for i in range(len(InducedGenes)): InducedGenes[i] -= 1 if rSeed != 0: np.random.seed(rSeed) # Percent /= 100 tries = 0 antStr = '' while tries < MAX_TRIES: try: Regulations, antStr = RandomGRN(numberOfGenes, Probabilities, ParamRange, InducedGenes) # print "AntString = ", antStr r = te.loadAntimonyModel(antStr) r.steadyState() print('Success! A random GRN was generated after ' + str(tries + 1) + ' tries') Output(modelName, folderPath, rSeed, r, antStr, Regulations) break except: tries = tries + 1 print "Failed to find steady state, generating a new GRN" return antStr
def test_latex_export2(self): """Test latex export. """ temp_dir = tempfile.mkdtemp() # export is writing files which have to be handeled in temp_dir try: tmp_f = tempfile.NamedTemporaryFile() import tellurium as te newModel = ''' $Xo -> S1; k1*Xo; S1 -> S2; k2*S1; S2 -> $X1; k3*S2; Xo = 50; X1=0.0; S1 = 0; S2 = 0; k1 = 0.2; k2 = 0.4; k3 = 2; ''' rr = te.loadAntimonyModel(newModel) result = rr.simulate(0, 30) p = te.LatexExport(rr, color=['blue', 'green'], legend=['S1', 'S2'], xlabel='Time', ylabel='Concentration', exportComplete=True, saveto=temp_dir, fileName='Model') p.saveToOneFile(result) # test that file was written self.assertTrue(os.path.isfile(os.path.join(temp_dir, 'Model.txt'))) finally: shutil.rmtree(temp_dir)
def GetModel(genes, Probabilities, InitVals, Name): tries = 0 while tries < 10: try: antStr = RandomGRN(genes, Probabilities, InitVals, {'Tra1': [10]}) r = te.loadAntimonyModel(antStr) print r.steadyState() break except: tries = tries + 1 print "Failed to find steady state" return ((r, antStr))
def spark_sensitivity_analysis(model_with_parameters): import tellurium as te sa_model = model_with_parameters[0] parameters = model_with_parameters[1] class_name = importlib.import_module(sa_model.filename) user_defined_simulator = getattr(class_name, dir(class_name)[0]) sa_model.simulation = user_defined_simulator() if (sa_model.sbml): model_roadrunner = te.loadAntimonyModel( te.sbmlToAntimony(sa_model.model)) else: model_roadrunner = te.loadAntimonyModel(sa_model.model) model_roadrunner.conservedMoietyAnalysis = sa_model.conservedMoietyAnalysis #Running PreSimulation model_roadrunner = sa_model.simulation.presimulator(model_roadrunner) #Running Analysis computations = {} model_roadrunner = sa_model.simulation.simulator( model_roadrunner, computations) _analysis = [None, None] #Setting the Parameter Variables _analysis[0] = {} for i_param, param_names in enumerate(sa_model.bounds.keys()): _analysis[0][param_names] = parameters[i_param] setattr(model_roadrunner, param_names, parameters[i_param]) _analysis[1] = computations return _analysis
def __init__(self, n_times, real_time): ContinuousSimulation.__init__(self, n_times=n_times, u_tracks_from_knots=self.step_u_tracks, real_time=real_time, output_vars=['OCT4', 'SOX2', 'NANOG', 'OCT4_SOX2', 'Protein'], u_type="step") file_name = \ get_file_name('biomodels/oct4_reversible_0203_template.ant') with open(file_name, 'r') as myfile: data = myfile.read() r = te.loadAntimonyModel(data) self.model_str = r.getCurrentAntimony()
def spark_sensitivity_analysis(model_with_parameters): import tellurium as te sa_model = model_with_parameters[0] parameters = model_with_parameters[1] class_name = importlib.import_module(sa_model.filename) user_defined_simulator = getattr(class_name, dir(class_name)[0]) sa_model.simulation = user_defined_simulator() if(sa_model.sbml): model_roadrunner = te.loadAntimonyModel(te.sbmlToAntimony(sa_model.model)) else: model_roadrunner = te.loadAntimonyModel(sa_model.model) model_roadrunner.conservedMoietyAnalysis = sa_model.conservedMoietyAnalysis #Running PreSimulation model_roadrunner = sa_model.simulation.presimulator(model_roadrunner) #Running Analysis computations = {} model_roadrunner = sa_model.simulation.simulator(model_roadrunner,computations) _analysis = [None,None] #Setting the Parameter Variables _analysis[0] = {} for i_param,param_names in enumerate(sa_model.bounds.keys()): _analysis[0][param_names] = parameters[i_param] setattr(model_roadrunner, param_names, parameters[i_param]) _analysis[1] = computations return _analysis
def GetModel(tries,numGenes,regProb, InitParams, Name): print 'Model simulation tries = ' + str(tries) #Set Lists and Empty Dictionaries Interactions = ["SingleAct", "SingleRep", "and", "or", "Nand", "Nor", "Counter"] GRN = {'Rate': [], 'mRNA':[], 'Prot': [],'PDeg':[],'mDeg': [],'Leak': [],'Vm':[], 'a_p':[], 'DualDissoc':[], 'Dissoc':[], 'HillCoeff': []} GRNInt = {'TF':[],'TFs':[]} #Perturbation = {'TRa1':[10]} StringList=[] modelCreationTries = 0 while modelCreationTries < 3: try: ModelInitNames(GRN) print 'ModelInitNames done.' AssignRegulation(numGenes,GRN,GRNInt,Interactions) print 'AssignRegulation done.' DetermineInteractors(GRN,GRNInt,regProb) print 'DetermineInteractors done.' ChooseProtein(GRNInt) print 'ChooseProtein done.' Rates = GetReactionRates(GRN,GRNInt) print 'GetReactionRates done.' GetReactions(GRN,StringList,Rates) print 'GetReactions done.' ValueGeneration(InitParams,StringList) #GetEvents(Perturbation,StringList) print 'ValueGeneration done.' antStr = GetModelString(StringList) print('Loading model into Antimony...\n') #print StringList except Exception as error: print "Something went wrong when constructing Model (GetModel method)!" ErrorPrinting(error) return(0,0,0) try: model = te.loadAntimonyModel(antStr) print('Success!') break except: modelCreationTries = modelCreationTries + 1 print "Failed to load model code into Antimony." if antStr == '': return(0,StringList.join('This is a pre-loaded string into Antimony that failed.\n'),GRN) return(0,antStr,GRNInt) return (model, antStr,GRNInt)
# -*- coding: utf-8 -*- """ Created on Wed May 30 16:39:36 2018 @author: Joshua Ip - Work """ import tellurium as te import numpy as np import CIDmodelAdvanced as model r = te.loadAntimonyModel(antimonyString); r.integrator = 'gillespie';/ r.integrator.seed = 1234; r.integrator.variable_step_size = False; # selections specifies the output variables in a simulation selections = ['time'] + r.getBoundarySpeciesIds() + r.getFloatingSpeciesIds() numberOfOutputs = len(selections) timesToSimulate = 10; pointsToSimulate = 101; sumOfSimulations = np.zeros(shape = [pointsToSimulate, numberOfOutputs]) for k in range(timesToSimulate): r.resetToOrigin() currentSim = r.simulate(0, 24, pointsToSimulate, selections) # we record the sum of the simulations to calculate the average later sumOfSimulations += currentSim
def run_model2(antStr, noiseLevel, species_type, species_nums, timepoints, exportData=False, input_conc=1, perturbs=[], perbParam=[.20, .50], bioTap='', save_path=os.getcwd(), filename="results", showTimePlots=False, seed=0, runAttempts=5): """Checks if Antimony models will reach steady-state, generates visualizations, and exports data. Arguments antStr = antimony string for the given model noiseLevel = (float) level of noise as a decimal. Ex: 0.05 = 5% species_type = 'P' for protein, or 'M' for mRNA species_nums = The gene numbers for associated to the species you are interested in. i.e. species_type = 'P' and species_nums =[1,2,3,4] will return the data for P1, P2, P3, and P4 timepoints = specifies length and resolution of simulation/experimental data -> [max time value, resolution (i.e. stepsize)]: exportData = whether or not to include additional files in the output. These files include the antimony string and the SBML Model NOTE: should probably stay at FALSE for student usage input_conc = what the value INPUT should be set to before running model perturbs = Perturbations to apply -> [(perturbation type, [target1, target2, ...]), (<next perturbation)>)] i.e. perturbs =[ ("UP", [1, 2, ...]), ("DOWN", [4,5,6])] perbParam = For Up/down regulation, this specifies the min/max amount you want to change regulation -> perbParm = (min percent change, max percent change) i.e. perbParam = (0.20, 0.50) specifies that you want the up/down regulation to change transcription between 20 and 50 percent. NOTE: percents are chosen uniformally between the min and max bioTap: (str) If this is not empty, a csv file to use for BioTapestry will be exported. save_path = directory to save output folder to filename = file to save the experimental data to showTimePlots: whether or not to output timeplots of the data (as png) in the output file seed: random number generator seed runAttempts: number of attempts to load/run model before exiting and suggesting to rebuild the model Outputs: model: roadrunner model for the full working GRN result: experimental data without noise resultNoisy: experimental data with noise """ # Attempt to execute run_model up to runAttempts times with different generated models. for retry in range(runAttempts): # Load the Antimony string as a model try: model = te.loadAntimonyModel(antStr) print('Successfully loaded in Antimony string as a model.') except Exception as error: ErrorPrinting(error) raise RuntimeError( "Failed to load antimony string due to parsing error. Check that your antStr is correct." ) # Check that the model reaches steady-state. If the model has any issues running, it will raise an Exception. The user should run get_model again. plt.close('all') model.resetToOrigin() tStep = int(math.ceil(timepoints[0] / timepoints[1])) try: model.steadyState() except Exception: try: model.conservedMoietyAnalysis = True model.steadyState() except Exception as error: print( "Failed to reach steady-state or there is an Integrator error. Check your model or run get_model again." ) ErrorPrinting(error) raise error model.resetToOrigin() #Specify input model.INPUT = input_conc # set seed if seed != 0: np.random.seed(seed) if len(perturbs) > 0: #specify perturbations for next_type, targets in perturbs: for gene in targets: currVm = eval("model.Vm" + str(gene)) if next_type == 'UP': newVm = currVm + np.random.uniform( perbParam[0] * currVm, perbParam[1] * currVm) exec("model.Vm" + str(gene) + " = " + str(newVm)) elif next_type == 'DOWN': newVm = currVm - np.random.uniform( perbParam[0] * currVm, perbParam[1] * currVm) exec("model.Vm" + str(gene) + " = " + str(newVm)) elif next_type == 'KO': exec("model.L" + str(gene) + " = 0") exec('model.Vm' + str(gene) + ' = 0') exec('model.d_mRNA' + str(gene) + ' = 0') exec('model.d_protein' + str(gene) + ' = 0') exec('model.mRNA' + str(gene) + ' = 1E-9') exec('model.P' + str(gene) + ' = 1E-9') #change initVals to 1E-9 instead of 0 to prevent possible solver hanging bug else: raise ValueError( "Perturbation type is not recognized; expected UP, DOWN, or KO" ) # Run a simulation for time-course data if species_type == 'P': selections = ["P" + str(i) for i in species_nums] elif species_type == 'M': selections = ["mRNA" + str(i) for i in species_nums] else: raise ValueError( "Output data type not recognized (must be P or M)") selections = ['time'] + selections result = model.simulate(0, timepoints[0], tStep + 1, selections=selections) model_name = model.getInfo().split("'modelName' : ")[1].split("\n")[0] # Specify (and make if necessary) a folder to save outputs to filesPath = save_path + "/experimental_data_" + model_name + '/' if os.path.exists(filesPath) == False: os.mkdir(filesPath) print('\nFolder created: ' + filesPath) # Create results with artificial noise noise = np.random.normal(1, noiseLevel, size=result.shape) noise[:, 0] = 1 # we dont want there to be noise in the time resultNoisy = np.multiply(result, noise) # Create graphs if showTimePlots == True: data = { next_name: resultNoisy[:, i] for i, next_name in enumerate(selections) } df = pd.DataFrame.from_dict(data) df.set_index('time', inplace=True) df.plot() plt.title("Noisy Data") plt.xlabel("time") plt.savefig(filesPath + 'Simulation_Noisy_Plot2.png', dpi=400) # do not want to give students the clean data #data = {next_name:result[:,i] for i,next_name in enumerate(selections)} #df = pd.DataFrame.from_dict(data) #df.set_index('time', inplace=True) #df.plot() #plt.title("Normal Data") #plt.xlabel("time") #plt.savefig(filesPath + 'Simulation_Clean_Plot2.png', dpi=400) plt.show() # Export datasets Output(exportData, model, seed, result, noiseLevel, resultNoisy, filesPath, antStr, bioTap, selections, filename) #returns the model, and result and/or resultNoisy arrays return (model, result, resultNoisy) raise RuntimeError('Could not create a working model for ' + str(runAttempts) + ' tries.')
def RunModel(numberOfGenes, modelName, filePath, rSeed, NLevel, tMax, Steps, DataExport, ModelString ='', ExternalModel = ''): if ModelString =='' and os.path.isfile(ExternalModel): AntImport = open(ExternalModel, 'r') ModelString = AntImport.read() if rSeed != 0: np.random.seed (rSeed) NLevel /= 100 # Values = {'M':[InitVals[0]], 'P':[InitVals[1]],'Dp':[InitVals[2]],'Dm':[InitVals[3]],'L':[InitVals[4]],'TRa':[InitVals[5]], 'TRb':[InitVals[6]],'Kd':[InitVals[7]], 'K':[InitVals[8]], 'H': [InitVals[9]]} # InitParams = [0,0,0.5,0.9,0.8,30,30,0.2,0.5,1] r = te.loadAntimonyModel(ModelString) # Regulations,r,antStr = Syn.GetModel(numberOfGenes, InitProb, InitParams) tries = 0 while tries < 10: try: plt.close('all') r.reset() result = r.simulate(0,tMax, Steps) NoisyResult = np.zeros([len(result[:,0]), len(result[0,:])]) if numberOfGenes<11: vars = {'P':[],'M':[]} for e in vars.keys(): plt.figure(1) for k in np.arange(1,numberOfGenes+1): vars[e].append(e + str(k)) tStep = int(math.ceil(tMax)/20) if tMax < 20: tStep = int(math.ceil(tMax)/(tMax/2)) tRange = np.arange(0,(int(math.ceil(tMax)))+ tStep,tStep) if e=='P': plt.subplot(2,1,1) plt.title('Protein Vs. Time', fontsize=8) plt.grid(color='k', linestyle='-', linewidth=.4) plt.ylabel('count',fontsize=6) plt.yticks(fontsize=6) if tMax > 999: plt.loglog(result[:,0],result[:,(k-1)+1], label = vars[e][k-1]) plt.xticks(fontsize=6) else: plt.semilogy(result[:,0],result[:,(k-1)+1], label = vars[e][k-1]) plt.xticks(tRange, fontsize=6) plt.xlim(0,tMax) plt.legend(loc='upper right', bbox_to_anchor=(1.13, 1.035), fontsize=6) else: plt.subplot(2,1,2) plt.title('mRNA Vs. Time', fontsize=8) plt.grid(color='k', linestyle='-', linewidth=.4) plt.xlabel('time(s)',fontsize=6) plt.ylabel('count',fontsize=6) plt.yticks(fontsize=6) if tMax > 999: plt.loglog(result[:,0],result[:,(k-1)+numberOfGenes+1], label = vars[e][k-1]) plt.xticks(fontsize=6) else: plt.semilogy(result[:,0],result[:,(k-1)+numberOfGenes+1], label = vars[e][k-1]) plt.xticks(tRange, fontsize=6) plt.xlim(0,tMax) plt.legend(vars[e],loc='upper right', bbox_to_anchor=(1.13, 1.035), fontsize=6) manager = plt.get_current_fig_manager() manager.window.showMaximized() plt.savefig(filePath + modelName + ' Simulation Plot.png', dpi=400) plt.close('all') if NLevel != 0: for k in range(len(result[:,0])): for i in range(len(result[0])): if i == 0: NoisyResult[k,i] = result[k,i] else: CurrVal = -1 while CurrVal < 0: CurrVal = result[k,i] + np.random.normal(0,NLevel*result[k,i]) NoisyResult[k,i] = CurrVal if numberOfGenes<11: for e in vars.keys(): plt.figure(2) for k in np.arange(1,numberOfGenes+1): vars[e].append(e + str(k)) if e=='P': plt.subplot(2,1,1) plt.title('Protein Vs. Time (Noisy)', fontsize=8) plt.grid(color='k', linestyle='-', linewidth=.4) plt.ylabel('count',fontsize=6) plt.yticks(fontsize=6) plt.legend(vars[e]) if tMax > 999: plt.loglog(NoisyResult[:,0],NoisyResult[:,(k-1)+1], label = vars[e][k-1]) plt.xticks(fontsize=6) else: plt.semilogy(NoisyResult[:,0],NoisyResult[:,(k-1)+1], label = vars[e][k-1]) plt.xticks(tRange, fontsize=6) plt.xlim(0,tMax) plt.legend(loc='upper right', bbox_to_anchor=(1.13, 1.035), fontsize=6) else: plt.subplot(2,1,2) plt.title('mRNA Vs. Time (Noisy)', fontsize=8) plt.grid(color='k', linestyle='-', linewidth=.4) plt.yticks(fontsize=6) plt.xlabel('time(s)',fontsize=6) plt.ylabel('count',fontsize=6) plt.legend(vars[e]) if tMax > 999: plt.loglog(NoisyResult[:,0],NoisyResult[:,(k-1)+numberOfGenes+1], label = vars[e][k-1]) plt.xticks(fontsize=6) else: plt.semilogy(NoisyResult[:,0],NoisyResult[:,(k-1)+numberOfGenes+1], label = vars[e][k-1]) plt.xticks(tRange, fontsize=6) plt.xlim(0,tMax) plt.legend(loc='upper right', bbox_to_anchor=(1.13, 1.035), fontsize=6) manager = plt.get_current_fig_manager() manager.window.showMaximized() plt.savefig(filePath + modelName + ' Noisy Simulation Plot.png', dpi=400) plt.close('all') break except: tries = tries + 1 print "Failed to simulate your model, generating a new GRN." if tries ==10: print('Sorry you network was not able to be simulated, please try again, or read the documentation') Output(DataExport, modelName, r, result, NLevel, NoisyResult, filePath)
timePoints = [ 1.0, 2.0, 3.0 ] #zu welchen Zeitpunkten soll die Konfiguration gespeichert werden? tStart = 0 #Start- und Endzeit der Simulation tEnd = 3.01 doplot = True #plotten? plotlegend = True #Legende plotten? verbose = 2 #Verbose level: 0 = garnicht, 1 = Statistik 1x je outerLoop, 2 = Statistik nach jedem N, 3 = +Schleifenzaehler (Haengt sich die Simulation auf?) Nscale = 100 #Produkt der naechsten 3 Variablen ist die Anzahl der insg. simulierten Pfade outerLoop = 1 #Anzahl Wiederholungen festlegen (multipliziert sich mit AnzahlPfade zur Anzahl der simulierten Pfade je N) Nrange = range( 3 ) #Bereich von N festlegen. range(5) == 0,1,2,3,4. Daher Multiplikator N = (N+1)*Nscale AnzahlPfade = 40 #Anzahl Wiederholungen festlegen (multipliziert sich mit outerLoop). Fuer schoene Plots hier Wert 40-100. Fuer grosse N: doplot=False, hier 1, dafuer bei outerLoop gewuenschte Werte eintragen. r = te.loadAntimonyModel( antStr) #Modell laden, kann auch URL sein z.B. von www.biomodels.net r.setIntegrator( 'gillespie') #Integrator auswaehlen. Andere unterstuetzen z.B. ODEs r.getIntegrator().setValue( 'variable_step_size', True ) #Parameter fuer Integrator setzen, anderer Integrator unterstuetzt andere Parameter Config.setValue(Config.MAX_OUTPUT_ROWS, pow( 10, 7)) #bei 64-bit pow(10,11) oder weniger bei wenig Arbeitsspeicher #---------------------------- Reactions = 0 start_time = time.time() selectToSave = ['N'] + selectToPlot form = (1, len(selectToSave)) r.selections = selectToSave simuliertePfade = 0 PfadeGesamt = outerLoop * AnzahlPfade * len(Nrange)
def test_loadAntimonyModel_file(self): r = te.loadAntimonyModel(self.ant_file) self.assertIsNotNone(r)
# -*- coding: utf-8 -*- """ Created on Tue Mar 11 15:06:33 2014 @author: mgaldzic """ import tellurium as te from roadrunner import Config Config.setValue(Config.LOADSBMLOPTIONS_CONSERVED_MOIETIES, True) model = ''' model pathway() $Xo -> S1; k1*Xo - k2*S1 S1 -> S2; k3*S2 S2 -> $X1; k4*S2 Xo = 1; X1 = 0 S1 = 0; S2 = 0 k1 = 0.1; k2 = 0.56 k3 = 1.2; k4 = 0.9 end ''' r = te.loadAntimonyModel(model) # Compute the steady state r.getSteadyStateValues() Config.setValue(Config.LOADSBMLOPTIONS_CONSERVED_MOIETIES, False) print "S1 =", r.S1, ", S2 =", r.S2
""" Created on Thu Feb 27 18:56:59 2014 @author: mgaldzic """ import tellurium as te import roadrunner import libantimony antStr = ''' 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''' rr = te.loadAntimonyModel(antStr) result = rr.simulate(0, 40, 500) rr.plot(rr, result)
def test_loadAntimonyModel_str(self): r = te.loadAntimonyModel(self.ant_str) self.assertIsNotNone(r)
# -*- coding: utf-8 -*- """ Setting boundary species in a model """ from __future__ import print_function import tellurium as te model = ''' model cell() # The $ character is used to indicate that a particular species is FIXED $S1 -> S2; k1*S1 S2 -> S3; k2*S2 - k3*S3 S3 -> $S4; Vm*S3/(Km + S3) # Initialize values S1 = 1.0; S2 = 0; S3 = 0; S4 = 0.0 k1 = 0.2; k2 = 0.67; k3 = 0.04 Vm = 5.6; Km = 0.5 end ''' r = te.loadAntimonyModel(model) result = r.simulate(0, 50, 201) r.plot(result)
eV=0.00018; ////////////////// Initial Conditions ///////////////////// E = 5.0*10^5; // Uninfected epithelial cells Ev = 10.0; // Virus-infected epithelial cells V = 1000.0; // Da = 0.0; // Infected-activated dendtritic cells in Tissue Dm = 0.0; // Migrated dendritic cells in Lymph Tc = 1.0; // Effector cytotoxic T-cells in Lymph Tct = 0.0; // Effector cytotoxic T-cells in Tissue Th1 = 1.0; // Type I helper T-cells Th2 = 1.0; // Type II helper T-cells B = 1.0; // Activated B-cells pSs = 0.0; // SP-RBD-specific Short-living plasma cells pLs = 0.0; // SP-RBD-specific Long-living plasma cells pSn = 0.0; // NP-specific Short-living plasma cells pLn = 0.0; // NP-specific Long-living plasma cells sIgM = 0.0; // SP-RBD-specific IgM sIgG = 0.0; // SP-RBD-specific IgG nIgM = 0.0; // NP-specific IgM nIgG = 0.0; // NP-specific IgG ''' rr = te.loadAntimonyModel(model_string) n = rr.simulate(0, 30, 10000, ['time', 'Tc', 'Tct', 'Da', 'Dm']) rr.plot()
r.k_off_anchor_binder = r.K_d_dimerization_binder * r.k_on_dimerization_binder arrayOfRates = r.simulate(0, secondsToSimulate, secondsToSimulate / 30 + timeshiftToStopWeirdODEIntegratorErrors) measuredReporter = np.amax(column(arrayOfRates, 16)) if debug: print(" Molecule added: " + str(r.MoleculeAdded)) print(" Measured reporter of: " + str(measuredReporter)) r.plot(show = False) #input("Press Enter to continue...") return measuredReporter; except: if debug: print("Threw CVODE error! Attempting timeshift of " + str(timeshiftToStopWeirdODEIntegratorErrors + 1)) continue; raise RuntimeError('Unable to resolve ODE integrator errors despite timeshift of 20 steps') r = te.loadAntimonyModel(model.antimonyString); # This is the range of anchor and dimerization binder binding affinities we will scan through ancArray = np.arange(-12.0, -5.0, 1.00) dimArray = np.arange(-9.0, -3.0, 1.00) # These parameters inform how the simulation is run each time SECONDS_TO_SIMULATE = 14 * 60 * 60 # 14 hours PERCENT_CHANGE_PER_STEP = 0.03 INITIAL_MOLECULE_ADDED = 0.0001 # If DEBUG is True, the script outputs some debug information to the console. A lot of debug information. # It also plots the curve, but that's not really working right. One thing to fix. DEBUG = True
import tellurium as te newModel = """ $Xo -> S1; k1*Xo; S1 -> S2; k2*S1; S2 -> $X1; k3*S2; Xo = 50; S1 = 0; S2 = 0; k1 = 0.2; k2 = 0.4; k3 = 2; """ rr = te.loadAntimonyModel(newModel) result = rr.simulate(0, 30) p = te.Export.export(rr) p.color = ["blue", "green"] p.legend = ["S1", "S2"] p.xlabel = "Time" p.ylabel = "Concentration" p.exportComplete = True p.location = "./" p.filename = "newModel" p.saveToFile(result) p.getString()
import tellurium as te # convert to eliminate rate rules model = te.loadAntimonyModel(te.sbmlToAntimony('huang-ferrell-96.xml')) model.conservedMoietyAnalysis = True print(model.steadyStateNamedArray()) # need to pre-simulate to converge in COPASI's solution model.simulate(0,1000,5000) # the output variable is PP_K (which represents doubly phosphorylated MAPK) # parameter 2: r1b_k2 (original: MAPKKK activation.k1) fig1a_local = model.getCC('PP_K', 'r1b_k2') print('Figure 1A: local value = {}'.format(fig1a_local)) # parameter 5: r8a_a8 (original: binding MAPK—Pase and P-MAPK.k1) fig1b_local = model.getCC('PP_K', 'r8a_a8') print('Figure 1B: local value = {}'.format(fig1b_local)) # parameter 7: r10a_a10 (original: binding MAPK—Pase and PP—MAPK.k1) fig1c_local = model.getCC('PP_K', 'r10a_a10') print('Figure 1C: local value = {}'.format(fig1c_local))
k2 = 0.018 k3 = 1.6 A = 5. AE = 0. E = 3. B = 0. """ """ # Create exact results result = opt.model.simulate(0,15,300) result = np.asarray([[y for y in x] for x in result]) entities = [x.replace('[','').replace(']','') for x in opt.model.selections] opt.model.plot() print('{}\t{}\t{}\t{}\t'.format(*entities)) for i in range(len(result)): print('{}\t{}\t{}\t{}\t'.format(*result[i])) """ opt = Optimization(model=te.loadAntimonyModel(soe)) opt.LoadMeasurements('data2.txt') opt.CreateParameterMap() #opt.FixParameter('k1') #m = opt.CreateRandomMember() opt.Run() print('\n') for k in opt.parameter_map: print('{}={}'.format(k,opt.model.__getattr__(k)))
def run_model(antStr,noiseLevel,inputData=None,genesToExport=None,perturb=None,exportData=None,bioTap='', savePath='results',fileName = '',showTimePlots=False,seed=0,drawModel=None): """ Checks if Antimony models will reach steady-state, generates visualizations, and exports data. Arguments: antStr (str) : - The Antimony model. noiseLevel (float): - level of noise as a decimal. Ex: `0.05` = 5% inputData (list: [inputVal,maxTime,resolution]) : - **inputVal** (float) : The initial concentration of the input species (name in model: INPUT). Default: 1 - **maxTime** (int) : Duration of minutes to simulate model. Default: 100 - **resolution** (int) : The resolution of datapoints. Eg: If resolution = 5, the data will include data every 5 minutes. Default: 1 perturb (list: [pertSpecies, pertType, mean, stdev]) : - **pertSpecies** (int list) : Which species to perturb, if perturbation is necessary. Default: 0 - The following are parameters needed for perturbation of species. They are **optional** inputs. You can just supply pertSpecies, or pertSpecies and pertType, and the rest will use default parameters. - **pertType** (str) : either `UP` or `DOWN` or `KO` used as a flag for upregulation, repression, or knockout, respectively. Default: 'UP' - **mean** (int list) [mean,accuracy]: The mean value used in `np.random.normal` to generate a random perturbation, along with an accuracy value (in ##%) Default: [35,15] - **stdev** (float) : The stdev value used in `np.random.normal` to generate a random pertrubation. Default: 4 genesToExport (list: [genesToExport,speciesType]) : - **genesToExport** (int list): Which genes you want to export. Pass in [0] to export all proteins or mRNA. Default: [0] - **speciesType** (str) : `P`rotein or `M`rNA. Default: 'P' exportData (list: [sbml, antimony]) : - **antimony** (bool) : This is a flag for the export of the Antimony model as a txt. Default:True - **sbml** (bool) : This is a flag for the export of the model in SBML format (version based on Tellurium). Default:False bioTap (str): - If this is not empty, a csv file to use for BioTapestry will be exported. Default: '' savePath (str): - All output files will be saved to `current_working_directory\savePath\modelName\` . Default: 'results' fileName (str): - A name that will prefix all filenames generated by the script. Default: Name of model taken from antStr showTimePlots (bool): - Flag for if you want plots to be generated and saved. Default: False seed (int): - Seed for reproducibility purposes when generating random data. Default: 0 drawModel (bool): - Generates a graph with PyGraphViz. Requires pygraphviz and graphviz installed Default: False Outputs: - model (model object): Roadrunner instance of the model. - result (np.array): Numpy matrix of the result data - resultNoisy (np.array): Numpy matrix of the result data (Noisy) """ # Creating default lists if inputData is None: inputData = [1,100,1] if exportData is None: exportData = [True,False] if drawModel is None: drawModel = [False,'fdp'] if genesToExport is None: genesToExport = [[0],'P'] if perturb is None: perturb = [0] if len(perturb) == 1: perturb = [perturb,'UP',[0,0],0] if len(perturb) == 2: perturb = [perturb, [35,15], 4] #error catching if genesToExport[1] not in ['P','M']: raise ValueError("Output data type not recognized (must be P or M)") # Load the Antimony string as a model try: model = te.loadAntimonyModel(antStr) print('Successfully loaded in Antimony string as a model.') except Exception as error: ErrorPrinting(error) raise RuntimeError("Failed to load antimony string due to parsing error. Check that your antStr is correct.") # Check that the model reaches steady-state. If the model has any issues running, it will raise an Exception. # If an exception is reached, the user should run get_model again. plt.close('all') model.resetToOrigin() tStep = int(math.ceil(inputData[1]/inputData[2])) try: model.steadyState() except Exception: try: model.conservedMoietyAnalysis = True model.steadyState() except Exception as error: print ("Failed to reach steady-state or there is an Integrator error. Check your model or run get_model again.") ErrorPrinting(error) raise error # reset model model.resetToOrigin() # specify input model.INPUT = inputData[0]; # specify perturbations if perturb != 0 and not 0 in perturb[0]: #i.e. not wild-type pertSpecies = perturb[0] pertType = perturb[1] mean = perturb[2] stdev = perturb[3] for species in pertSpecies: if pertType == 'KO': exec('model.Vm' + str(species) + ' = 0') in locals(), globals() exec('model.d_mRNA' + str(species) + ' = 0') in locals(), globals() exec('model.d_protein' + str(species) + ' = 0') in locals(), globals() exec('model.mRNA' + str(species) + ' = 1E-9') in locals(), globals() exec('model.P' + str(species) + ' = 1E-9') in locals(), globals() exec('model.L' + str(species) + ' = 0') in locals(), globals() #change initVals to 1E-9 instead of 0 to prevent possible solver hanging bug else: currVm = eval('model.Vm' + str(species)) randPert = mean[0] if mean[1]!=0: randPert = np.random.normal(mean[0],stdev) while mean[0] - mean[1] > randPert or randPert > mean[0] + mean[1]: randPert = np.random.normal(mean[0],stdev) while randPert >= 0: randPert = np.random.normal(mean[0],stdev) randPert /= 100.0 if pertType == 'UP': newVal = currVm * (1 + randPert) exec('model.Vm' + str(species) + ' = ' + str(newVal)) in locals(), globals() if pertType == 'DOWN': newVal = currVm * (1 - randPert) exec('model.Vm' + str(species) + ' = ' + str(newVal)) in locals(), globals() # Construct the selection arguments for simulation exportSpecies = genesToExport[0] species_type = genesToExport[1] if exportSpecies==0: allGenes = int((model.getNumFloatingSpecies() - 1)/2) if species_type == 'P': selections = ["P" + str(i+1) for i in range(allGenes)] elif species_type == 'M': selections = ["mRNA" + str(i+1) for i in range(allGenes)] else: if species_type == 'P': selections = ["P" + str(i) for i in exportSpecies] elif species_type == 'M': selections = ["mRNA" + str(i) for i in exportSpecies] selections = ['time'] + selections # Run a simulation for time-course data result = model.simulate(0,inputData[1],tStep+1,selections=selections) # Retrieve model name if fileName == '': fileName = model.getInfo().split("'modelName' : ")[1].split("\n")[0] # Specify (and make if necessary) a folder to save outputs to folderPath = Path(os.getcwd()) / savePath if not os.path.exists(folderPath): os.mkdir(folderPath) print('\nFolder created: ' + folderPath.name) #fileName = fileName + '_' # Create results with artificial noise if noiseLevel != '0': resultNoisy = np.zeros([len(result[:,0]), len(result[0,:])]) for k in range(len(result[:,0])): for i in range(len(result[0])): if i == 0: resultNoisy[k,i] = result[k,i] else: CurrVal = -1 while CurrVal < 0: CurrVal = result[k,i] + np.random.normal(0,noiseLevel*result[k,i]) resultNoisy[k,i] = CurrVal # Export datasets Output(exportData,model,seed,selections,result,noiseLevel,resultNoisy, folderPath, fileName, antStr,bioTap) # Create graphs if showTimePlots: data = {next_name:resultNoisy[:,i] for i,next_name in enumerate(selections)} df = pd.DataFrame.from_dict(data) df.set_index('time', inplace=True) df.plot() plt.title("Noisy Data") plt.xlabel("time") plt.savefig(folderPath / (fileName +'_Simulation_Noisy_Plot.png'), dpi=400) data = {next_name:result[:,i] for i,next_name in enumerate(selections)} df = pd.DataFrame.from_dict(data) df.set_index('time', inplace=True) df.plot() plt.title("Clean Data") plt.xlabel("time") plt.savefig(folderPath / (fileName +'_Simulation_Plot.png'), dpi=400) # Draw the model (requires pygraphviz module) if drawModel[0]: try: imp.find_module('pygraphviz') model.draw(layout=str(drawModel[1])) except ImportError: print('pygraphviz is not installed!') #returns the model, and result and/or resultNoisy arrays return(model,result,resultNoisy)
from __future__ import print_function import tellurium as te # Load an antimony model ant_model = ''' S1 -> S2; k1*S1; S2 -> S3; k2*S2; k1= 0.1; k2 = 0.2; S1 = 10; S2 = 0; S3 = 0; ''' # At the most basic level one can load the SBML model directly using libRoadRunner print('--- load roadrunner ---') import roadrunner # convert to SBML model sbml_model = te.antimonyToSBML(ant_model) r = roadrunner.RoadRunner(sbml_model) result = r.simulate(0, 10, 100) r.plot(result) # The method loada is simply a shortcut to loadAntimonyModel print('--- load tellurium ---') r = te.loada(ant_model) result = r.simulate(0, 10, 100) r.plot(result) # same like r = te.loadAntimonyModel(ant_model) # In[2]:
import seaborn as sns sns.set_style("ticks") import matplotlib.gridspec as gridspec import FigureTools as FT def apply_param_dict_to_model(model, param_dict): for param in param_dict.keys(): if param_dict[ param] is not None: # do not change parameters marked with value==None. #print param_dict[param] model[param] = param_dict[param] return model volume_and_hog_model = te.loadAntimonyModel("volume_and_hog.txt") volume_model = te.loadAntimonyModel("volume_reference_radius.txt") volume_and_hog_model.integrator.relative_tolerance = 1e-10 volume_model.integrator.relative_tolerance = 1e-10 volume_and_hog_model_species = [ 'time', 'vol_V_tot_fl', '[hog_Glyc_in]', '[vol_c_i]', 'hog_Glyc_in', 'vol_c_i', 'hog_totalHog1PP', 'hog_n_totalHog1', 'hog_Hog1PPn', 'hog_Hog1PPc', 'hog_Hog1n', 'hog_Hog1c', '[hog_Hog1PPn]', '[hog_Hog1PPc]', '[hog_Hog1n]', '[hog_Hog1c]', 'vol_pi_t', 'vol_pi_i' ] volume_model_species = [ 'time', 'V_tot_fl', 'V_ref', 'r_os', 'r_b', '[c_e]', '[c_i]', 'c_i', 'pi_t', 'pi_i' ]
# -*- coding: utf-8 -*- """ Created on Thu Jul 05 12:28:35 2018 @author: Yoshi """ import os import tellurium as te import matplotlib.pyplot as plt import numpy as np np.set_printoptions(linewidth=160) #%% Visualize the models used in DREAM7 r = te.loadAntimonyModel( 'C:\Users\Yoshi\Documents\GitHub\DREAM-work\model1_0\model_without_parameters\model1_antimony.txt' ) r.draw()
import tellurium as te cell = ''' $Xo -> S1; vo; S1 -> S2; k1*S1 - k2*S2; S2 -> $X1; k3*S2; vo = 1 k1 = 2; k2 = 0; k3 = 3; ''' rr = te.loadAntimonyModel(cell) p = te.ParameterScan.ParameterScan(rr) p.endTime = 3 p.colormap = p.createColormap([.86,.08,.23], [.12,.56,1]) p.createColorPoints() p.plotSurface()
ant_model = ''' S1 -> S2; k1*S1; S2 -> S3; k2*S2; k1= 0.1; k2 = 0.2; S1 = 10; S2 = 0; S3 = 0; ''' # At the most basic level one can load the SBML model directly using libRoadRunner print('--- load roadrunner ---') import roadrunner # convert to SBML model sbml_model = te.antimonyToSBML(ant_model) r = roadrunner.RoadRunner(sbml_model) result = r.simulate(0, 10, 100) r.plot(result) # The method loada is simply a shortcut to loadAntimonyModel print('--- load tellurium ---') r = te.loada(ant_model) result = r.simulate (0, 10, 100) r.plot(result) # same like r = te.loadAntimonyModel(ant_model) # In[2]: