def translate(combine, filename): sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] outputstr = '"End of code generated by Import Combine as PhrasedML plugin ' + time.strftime( "%m/%d/%Y") + '"\n"Extracted from ' + filename + '"\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(os.path.join(zipextloc, sbmlloclist[i])) try: transtext = te.sbmlToAntimony(sbml) except Exception as e: transtext = """*********************WARNING********************* Failed to translate the SBML model to Antimony string. Please check that the SBML file is valid. *********************WARNING*********************""" transtext = transtext + "\n\n" + str(e) sbmlstrlist.append(transtext) for j in range(len(sedmlloclist)): sedmlstr = pl.convertFile(os.path.join(zipextloc, sedmlloclist[j])) sedmlstr = sedmlstr.replace('"compartment"', '"compartment_"') sedmlstr = sedmlstr.replace("'compartment'", "'compartment_'") sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append( "AntimonyModel = '''\n" + sbmlstrlist[0] + "'''\n\nPhrasedMLstr = '''\n" + sedmlstrlist[k] + "'''\n\nimport tellurium as te\n\nexp = te.experiment([AntimonyModel], [PhrasedMLstr])\nexp.execute(PhrasedMLstr)\n\n" + outputstr) delseq(zipextloc) return outputstrlist
def getSBMLAsAntimony(self, sbmlfile): zf = ZipFile(self.combinePath, 'r') sbmlStr = zf.read(sbmlfile) zf.close() antStr = te.sbmlToAntimony(sbmlStr) return antStr
def translate(combine, filename): sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] outputstr = "# -*- coding: utf-8 -*-\n\n" + '"Generated by Import Combine with PhrasedML plugin ' + time.strftime( "%m/%d/%Y" ) + '"\n"Extracted from ' + filename + '"\n\n# Translated SBML\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(zipextloc + sbmlloclist[i]) sbmlstrlist.append(te.sbmlToAntimony(sbml)) for j in range(len(sedmlloclist)): sedmlstr = pl.convertFile(zipextloc + sedmlloclist[j]) sedmlstr = sedmlstr.replace('"compartment"', '"compartment_"') sedmlstr = sedmlstr.replace("'compartment'", "'compartment_'") sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append(outputstr + "AntimonyModel = '''\n" + sbmlstrlist[0] + "'''\n\nPhrasedMLstr = '''\n" + sedmlstrlist[k] + "'''") delseq(zipextloc) return outputstrlist
def selected_part(self): from tellurium.visualization import SBMLDiagram from tellurium.analysis import _annotations, make_submodel import tellurium as te self.set_visible(5) r = self.widgets['reactionResults'].value biomodel_id = _annotations.get_biomodel_id(r.model.getSBMLDocument()) self.sbml = self.matched_sbml_lookup[biomodel_id] self.submodel = make_submodel(r) antimony = te.sbmlToAntimony(self.submodel.toSBML()) self.widgets['selectedReaction'].children[1].value = antimony # Draw diagram diagram = SBMLDiagram(self.submodel, reactions={ 'shape': 'box' }) img = diagram.draw(layout='dot') self.widgets['selectedReaction'].children[0].value = img.data # Modular import code snippet self.widgets['selectedReaction'].children[2].value = '''!pip install git+https://github.com/biomodels/%s.git > /dev/null # Modular Import of Biomodel reaction import %s as m import tellurium as te from tellurium.analysis import make_submodel r = m.sbml.model.getReaction('%s') submodel = make_submodel(r) antimony = te.sbmlToAntimony(submodel.toSBML()) print antimony ''' % (biomodel_id, biomodel_id, r.getId())
def load_and_translate(self, sbmlfile, pythonfile, editor, set_current=True): """ Read filename as combine archive, unzip, translate, reconstitute in Python, and create an editor instance and return it *Warning* This is loading file, creating editor but not executing the source code analysis -- the analysis must be done by the editor plugin (in case multiple editorstack instances are handled) """ sbmlfile = str(sbmlfile) self.emit(SIGNAL('starting_long_process(QString)'), _("Loading %s...") % sbmlfile) text, enc = encoding.read(sbmlfile) sbmlstr = te.readFromFile(sbmlfile) text = "import tellurium as te\n\nr = te.loada('''\n" + str(te.sbmlToAntimony(sbmlstr)) + "''')" widgeteditor = editor.editorstacks[0] finfo = widgeteditor.create_new_editor(pythonfile, enc, text, set_current, new=True) index = widgeteditor.data.index(finfo) widgeteditor._refresh_outlineexplorer(index, update=True) self.emit(SIGNAL('ending_long_process(QString)'), "") if widgeteditor.isVisible() and widgeteditor.checkeolchars_enabled \ and sourcecode.has_mixed_eol_chars(text): name = os.path.basename(pythonfile) QMessageBox.warning(self, widgeteditor.title, _("<b>%s</b> contains mixed end-of-line " "characters.<br>Spyder will fix this " "automatically.") % name, QMessageBox.Ok) widgeteditor.set_os_eol_chars(index) widgeteditor.is_analysis_done = False finfo.editor.set_cursor_position('eof') finfo.editor.insert_text(os.linesep) return finfo, sbmlfile
def getComponentAntimony(self): ''' Returns list of antimony models generated from each model reaction ''' import tellurium as te sbmls = self.getComponentSBML() return [te.sbmlToAntimony(sbml) for sbml in sbmls]
def configpossiblechecker(sbmlstr): antimony_str = te.sbmlToAntimony(sbmlstr) is_match = bool(re.search('function', antimony_str)) if is_match == True: raise NotImplementedError( 'SBML string is too complex for module to convert') else: return
def sbmltoantimony(sbmlfile): """Get the sbml file and return the antimony string.""" antimony_str = te.sbmlToAntimony(sbmlfile) basename = os.path.basename(sbmlfile) sbmlfilename = basename.split(".")[0] antimony_str = antimony_str.replace("doc0", sbmlfilename) return antimony_str
def getSBMLAsAntimony(self, sbmlfile): """ returns SBML as antimony :param sbmlfile: filename of SBML file in COMBINE archive :return: antimony string :rtype: str """ zf = ZipFile(self.combinePath, 'r') sbmlStr = zf.read(sbmlfile) zf.close() antStr = te.sbmlToAntimony(sbmlStr) return antStr
def getSBMLAsAntimony(self, sbmlfile): """ returns SBML as antimony :param sbmlfile: filename of SBML file in COMBINE archive :return: antimony string :rtype: str """ warnings.warn('Use inline_omex instead.', DeprecationWarning) zf = ZipFile(self.combinePath, 'r') sbmlStr = zf.read(sbmlfile) zf.close() antStr = te.sbmlToAntimony(sbmlStr) return antStr
def translate(combine, filename): sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] rePath = r"loadSBMLModel\((.*)\)" reFig = r"savefig\((.*)\)" outputstr = '"End of code generated by Import Combine plugin ' + time.strftime( "%m/%d/%Y") + '"\n"Extracted from ' + filename + '"\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(os.path.join(zipextloc, sbmlloclist[i])) try: transtext = te.sbmlToAntimony(sbml) except Exception as e: transtext = """*********************WARNING********************* Failed to translate the SBML model to Antimony string. Please check that the SBML file is valid. *********************WARNING*********************""" transtext = transtext + "\n\n" + str(e) sbmlstrlist.append(transtext) for j in range(len(sedmlloclist)): sedmlstr = te.sedmlToPython( os.path.join(zipextloc, sedmlloclist[j])) lines = sedmlstr.splitlines() for i, s in enumerate(lines): reSearchPath = re.split(rePath, s) if len(reSearchPath) > 1: s = s.replace("loadSBMLModel", "loada") s = s.replace(reSearchPath[1], "AntimonyModel") lines[i] = s lines.insert( i - 1, "AntimonyModel = '''\n" + sbmlstrlist[0] + "'''\n") for i, s in enumerate(lines): reSearchFig = re.split(reFig, s) if len(reSearchFig) > 1: del lines[i] sedmlstr = '\n'.join(lines) sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append(sedmlstrlist[k] + '\n\n' + outputstr) delseq(zipextloc) return outputstrlist
def generateNetworkFromSBML(sbml): """ Generate network matrix from a given model :param sbml: sbml string or file path :rtype: array """ import roadrunner import tellurium as te try: ant_str = te.sbmlToAntimony(sbml) except: raise Exception("Cannot load SBML file/string. Check whether the \ filepath or SBML string is formatted correctly.") net_mat, ref_list = generateNetworkFromAntimony(ant_str) return net_mat, ref_list
def translate(combine, filename): sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] outputstr = "# -*- coding: utf-8 -*-\n\n" + '"Generated by Import Combine with PhrasedML plugin ' + time.strftime("%m/%d/%Y") + '"\n"Extracted from ' + filename + '"\n\n# Translated SBML\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(zipextloc + sbmlloclist[i]) sbmlstrlist.append(te.sbmlToAntimony(sbml)) for j in range(len(sedmlloclist)): sedmlstr = pl.convertFile(zipextloc + sedmlloclist[j]) sedmlstr = sedmlstr.replace('"compartment"', '"compartment_"') sedmlstr = sedmlstr.replace("'compartment'", "'compartment_'") sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append(outputstr + "AntimonyModel = '''\n" + sbmlstrlist[0] + "'''\n\nPhrasedMLstr = '''\n" + sedmlstrlist[k] + "'''") delseq(zipextloc) return outputstrlist
def gen_dictionary(data): ''' Passes XML data through beautifulsoup parser making data more easily readable :param data: SBML string in XML string format :returns: all required data in list format ''' antimony_str = te.sbmlToAntimony(data) Bs_data = BeautifulSoup(data, "xml") b_species = Bs_data.find_all('listOfSpecies') species_store = Convert(str(b_species)) b_parameters = Bs_data.find_all('listOfParameters') parameters_store = Convert(str(b_parameters)) b_reactions = Bs_data.find_all('listOfReactions') reactions_store = Convert(str(b_reactions)) b_rules = Bs_data.find_all('listOfRules') rules_store = Convert(str(b_rules)) #soup.find_all("a", class_="sister") #print(Bs_data.find_all('div', class_='dc:description')) if Bs_data.find_all(class_='dc:description') != []: b_description = Bs_data.find_all(class_='dc:description') description_store = Convert(str(b_description)) description_store = gen_description(description_store) else: description_store = '' if Bs_data.find_all(class_='dc:bibliographicCitation') != []: reference_store = gen_reference(Bs_data) else: reference_store = '' ''' print(species_store, '\n') print(parameters_store, '\n') print(reactions_store, '\n') print(rules_store, '\n') ''' #print(description_store) return species_store, parameters_store, reactions_store, rules_store, antimony_str, description_store, reference_store
def translate(combine, filename): sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] outputstr = '"End of code generated by Import Combine as PhrasedML plugin ' + time.strftime("%m/%d/%Y") + '"\n"Extracted from ' + filename + '"\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(zipextloc + sbmlloclist[i]) sbmlstrlist.append(te.sbmlToAntimony(sbml)) for j in range(len(sedmlloclist)): sedmlstr = pl.convertFile(zipextloc + sedmlloclist[j]) sedmlstr = sedmlstr.replace('"compartment"', '"compartment_"') sedmlstr = sedmlstr.replace("'compartment'", "'compartment_'") sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append("AntimonyModel = '''\n" + sbmlstrlist[0] + "'''\n\nPhrasedMLstr = '''\n" + sedmlstrlist[k] + "'''\n\nimport tellurium as te\n\nexp = te.experiment([AntimonyModel], [PhrasedMLstr])\nexp.execute(PhrasedMLstr)\n\n" + outputstr) delseq(zipextloc) return outputstrlist
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 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 translate(combine, filename): sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] rePath = r"loadSBMLModel\((.*)\)" reFig = r"savefig\((.*)\)" outputstr = '"End of code generated by Import Combine plugin ' + time.strftime("%m/%d/%Y") + '"\n"Extracted from ' + filename + '"\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(zipextloc + sbmlloclist[i]) sbmlstrlist.append(te.sbmlToAntimony(sbml)) for j in range(len(sedmlloclist)): sedmlstr = te.sedmlToPython(zipextloc + sedmlloclist[j]) lines = sedmlstr.splitlines() for i,s in enumerate(lines): reSearchPath = re.split(rePath, s) if len(reSearchPath) > 1: s = s.replace("loadSBMLModel", "loada") s = s.replace(reSearchPath[1],"AntimonyModel") lines[i] = s lines.insert(i - 1, "AntimonyModel = '''\n" + sbmlstrlist[0] + "'''\n") for i,s in enumerate(lines): reSearchFig = re.split(reFig, s) if len(reSearchFig) > 1: del lines[i] sedmlstr = '\n'.join(lines) sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append(sedmlstrlist[k] + '\n\n' + outputstr) delseq(zipextloc) return outputstrlist
# coding: utf-8 # Back to the main [Index](../index.ipynb) # ### Test models # 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 # To get the builtin models use listTestModels print(te.listTestModels()) # #### Load test model # In[2]: # To load one of the test models use loadTestModel: # r = te.loadTestModel('feedback.xml') # result = r.simulate (0, 10, 100) # r.plot (result) # If you need to obtain the SBML for the test model, use getTestModel sbml = te.getTestModel('feedback.xml') # To look at one of the test model in Antimony form: ant = te.sbmlToAntimony(te.getTestModel('feedback.xml')) print(ant)
def test_sbmlToAntimony_str(self): ant = te.sbmlToAntimony(self.sbml_str) self.assertIsNotNone(ant)
def test_sbmlToAntimony_file(self): ant = te.sbmlToAntimony(self.sbml_file) self.assertIsNotNone(ant)
import os, glob import tellurium as te from web_interface import SBML_FILE model_string = '' if model_string == '': with open(SBML_FILE, 'r') as f: sbml = f.read() model_string = te.sbmlToAntimony(sbml) if __name__ == '__main__': print(model_string)
def Combinecreator(core_model, settings, Plot_Variable, outputpath, KISAO_algorithm): ''' Generates and outputs COMBINE OMEX file. :param core_model: core model database of model :param settings: settings database of model :param Plot_Variable: Variables to be plotted in list format :param outputpath: filepath to output OMEX file in OS path format :param KISAO_algorithm: Kinetic Simulation Algorithm Ontology number in string format :return combine_filename : OMEX file name in string format :return total_scenarios : Total number of scenarios in string format ''' #--- Extract data from settings and clean up units --- number_init = len(settings['init']) number_parameters = len(settings['parameters']) addparam = settings['parameters'] unit_model = sbmlgen.unitlookup(settings) total_scenarios = number_init * number_parameters #print(total_scenarios) scenario_name = core_model["system_type"] scenario_name = scenario_name.replace(", ", "_") modelname_file = [] antimony_final = [] #--- Generates SBML string and adds to list #based on the number of combinations with init #and parameter amts --- for j in range(number_init): #Cycle through number of init for k in range(number_parameters): #Cycle through number of parameters sbmlstr = sbmlgen.SBMLcreation(core_model, settings, unit_model, addparam, j, k) antimony_final.append(te.sbmlToAntimony(sbmlstr)) #--- Generates the scenario name for each SBML string generated --- scenario_placeholder = [] for l in range(total_scenarios): for j in range(number_init): #Cycle through number of init for k in range(number_parameters): temp_scenario_name = '_' + str(j+1)+ '_' + str(k+1) scenario_placeholder.append(temp_scenario_name) #--- Names the models in antimony string according the scenario --- inline_omex = '\n' for l in range(total_scenarios): scenario_name = scenario_name + scenario_placeholder[l] modelname_file.append(scenario_name) antimony_final[l] = antimony_final[l].replace('*doc0', modelname_file[l]) scenario_name = scenario_name.replace(scenario_placeholder[l], "") inline_omex = inline_omex + str(antimony_final[l]) #print("This is antimony_final", scenario_number,": \n", antimony_final[l]) #--- Generates phrasedml file --- phrasedml_final = gen_phrasedml(settings, modelname_file, Plot_Variable, KISAO_algorithm) #--- Generates and outputs OMEX file--- inline_omex = inline_omex + phrasedml_final combine_filename = 'COMBINE_' + scenario_name + '.omex' archive = os.path.join(outputpath, combine_filename) print('COMBINE Archive output: ', archive) te.exportInlineOmex(inline_omex, archive) return combine_filename, total_scenarios
continue if case == '00999': continue if int(case) > int(1085): continue try: num_cases += 1 sbmlfname, sedmlfname = combine2python.manifestsearch(folder_path) # sbml = [file for file in sorted(ls) if 'sbml-l2v4.xml' in file][0] with open(path.join(folder_path, '.' + sbmlfname), 'rb') as f: sbml = f.read() rr = te.loada(te.sbmlToAntimony(sbml)) rr.simulate() combine2python.codestitch('test' + str(case) + '.py', folder_path, case) combine2python.codeanalysis('test' + str(case) + '.py', folder_path) pyscriptname = 'test' + str(case) test = __import__(pyscriptname) num_timepoints = len(test.allX_0) results_file = [file for file in ls if 'results.csv' in file][0] computed_result = np.hstack([test.allX_0[:,0].reshape(num_timepoints, 1), test.allY_0]) with open(os.path.join(folder_path, results_file), 'rb') as f: reader = csv.reader(f) rows = [] for i, row in enumerate(reader): if i == 0:
def translate(combine, filename): tempPath = [[]] sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] rePath = r"(\w*).load\('(.*)'\)" reLoad = r"(\w*) = roadrunner.RoadRunner\(\)" reSelections = r'(\w+)\.selections = \[(.*),?\]' outputstr = "# -*- coding: utf-8 -*-\n\n" + '"Generated by Import Combine plugin ' + time.strftime("%m/%d/%Y") + '"\n"Extracted from ' + filename + '"\n\n# Translated SBML\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(zipextloc + sbmlloclist[i]) sbmlstrlist.append(te.sbmlToAntimony(sbml)) for j in range(len(sedmlloclist)): sedmlstr = se.sedml_to_python(zipextloc + sedmlloclist[j]) lines = sedmlstr.splitlines() for i,s in enumerate(lines): reSearchPath = re.split(rePath, s) if len(reSearchPath) > 1: modpath = getbasename(reSearchPath[2])[:-4].replace('-','_') if modpath[0].isdigit() == True: modpath = 'Model_' + modpath tempPath.append([reSearchPath[1], modpath]) else: tempPath.append([reSearchPath[1], modpath]) #if '.xml' in s: del lines[i] for i,s in enumerate(lines): reSearchLoad = re.split(reLoad, s) if len(reSearchLoad) > 1: for k in range(len(tempPath) - 1): if reSearchLoad[1] == tempPath[k + 1][0]: s = s.replace("roadrunner.RoadRunner()", "te.loada(" + str(tempPath[k + 1][1])+ ")") lines[i] = s #if '"compartment"' or "'compartment'" in sedmlstr: # reSearchSelections = re.split(reSelections, s) # if len(reSearchSelections) > 1: # Vars = reSearchSelections[2].replace(' ','').split(',') # Vars = [s.replace('"','') for s in Vars] # for i in range(len(Vars)): # if Vars[i] == "compartment": # Vars[i] = "compartment_" if not "import tellurium" in sedmlstr: if "import roadrunner" in sedmlstr: for i,s in enumerate(lines): if "import roadrunner" in s: del lines[i] lines.insert(i, "import tellurium as te") else: pass else: outputstr = outputstr + "import tellurium as te\n\n" sedmlstr = '\n'.join(lines) # List of replacements sedmlstr = sedmlstr.replace('"compartment"', '"compartment_"') sedmlstr = sedmlstr.replace("'compartment'", "'compartment_'") sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append(outputstr + tempPath[1][1] + " = '''\n" + sbmlstrlist[0] + "'''\n\n" + sedmlstrlist[k]) delseq(zipextloc) return outputstrlist
import BMSS.simulation as sim if __name__ == '__main__': ''' Use following function to create SBML from BIOModel online database Outputs both the sbmlstring and the XML file ''' Biomodels_ID = 'BIOMD0000000012' #Input biomodels ID number SBMLfilename = 'Repressilator_TestModel_SBML.xml' #Name the XML file outputpath = str(Path.cwd()/SBMLfilename) onlinemodelstr = onlinegen.get_online_biomodel(Biomodels_ID, outputfile=outputpath) antimony_str = te.sbmlToAntimony(onlinemodelstr) ''' Use the following function to create SBML from local folder. XML file must be in same folder as this Tutorial ''' inputpath = str(Path.cwd()/'Repressilator_TestModel_SBML_1.xml') with open(inputpath, 'r', encoding='utf8', errors='ignore') as f: localmodelstr = f.read() ''' To create config ini file from SBML file in folder Reading the data inside the xml file to a variable
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))
def sbmlconv(zipextloc): #sbml conversion into antimony str sbmlloc, sedmlloc = manifestsearch(zipextloc) sbml = te.readFromFile(zipextloc + sbmlloc) sbmlantimony = te.sbmlToAntimony(sbml) return sbmlantimony
def sbmlconv(zipextloc): sbmlloc, sedmlloc = manifestsearch(zipextloc) sbml = te.readFromFile(zipextloc + sbmlloc) sbmlantimony = te.sbmlToAntimony(sbml) return sbmlantimony
# Back to the main [Index](../index.ipynb) # ### Test models # 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 # To get the builtin models use listTestModels print(te.listTestModels()) # #### Load test model # In[2]: # To load one of the test models use loadTestModel: # r = te.loadTestModel('feedback.xml') # result = r.simulate (0, 10, 100) # r.plot (result) # If you need to obtain the SBML for the test model, use getTestModel sbml = te.getTestModel('feedback.xml') # To look at one of the test model in Antimony form: ant = te.sbmlToAntimony(te.getTestModel('feedback.xml')) print(ant)
def translate(combine, filename): tempPath = [[]] sbmlstrlist = [] sedmlstrlist = [] outputstrlist = [] rePath = r"(\w*).load\('(.*)'\)" reLoad = r"(\w*) = roadrunner.RoadRunner\(\)" reSelections = r'(\w+)\.selections = \[(.*),?\]' outputstr = "# -*- coding: utf-8 -*-\n\n" + '"Generated by Import Combine plugin ' + time.strftime( "%m/%d/%Y" ) + '"\n"Extracted from ' + filename + '"\n\n# Translated SBML\n' zipextloc, sbmlloclist, sedmlloclist = manifestsearch(combine) for i in range(len(sbmlloclist)): sbml = te.readFromFile(zipextloc + sbmlloclist[i]) sbmlstrlist.append(te.sbmlToAntimony(sbml)) for j in range(len(sedmlloclist)): sedmlstr = se.sedml_to_python(zipextloc + sedmlloclist[j]) lines = sedmlstr.splitlines() for i, s in enumerate(lines): reSearchPath = re.split(rePath, s) if len(reSearchPath) > 1: modpath = getbasename(reSearchPath[2])[:-4].replace( '-', '_') if modpath[0].isdigit() == True: modpath = 'Model_' + modpath tempPath.append([reSearchPath[1], modpath]) else: tempPath.append([reSearchPath[1], modpath]) #if '.xml' in s: del lines[i] for i, s in enumerate(lines): reSearchLoad = re.split(reLoad, s) if len(reSearchLoad) > 1: for k in range(len(tempPath) - 1): if reSearchLoad[1] == tempPath[k + 1][0]: s = s.replace( "roadrunner.RoadRunner()", "te.loada(" + str(tempPath[k + 1][1]) + ")") lines[i] = s #if '"compartment"' or "'compartment'" in sedmlstr: # reSearchSelections = re.split(reSelections, s) # if len(reSearchSelections) > 1: # Vars = reSearchSelections[2].replace(' ','').split(',') # Vars = [s.replace('"','') for s in Vars] # for i in range(len(Vars)): # if Vars[i] == "compartment": # Vars[i] = "compartment_" if not "import tellurium" in sedmlstr: if "import roadrunner" in sedmlstr: for i, s in enumerate(lines): if "import roadrunner" in s: del lines[i] lines.insert(i, "import tellurium as te") else: pass else: outputstr = outputstr + "import tellurium as te\n\n" sedmlstr = '\n'.join(lines) # List of replacements sedmlstr = sedmlstr.replace('"compartment"', '"compartment_"') sedmlstr = sedmlstr.replace("'compartment'", "'compartment_'") sedmlstrlist.append(sedmlstr) for k in range(len(sedmlstrlist)): outputstrlist.append(outputstr + tempPath[1][1] + " = '''\n" + sbmlstrlist[0] + "'''\n\n" + sedmlstrlist[k]) delseq(zipextloc) return outputstrlist
def getAntimony(self): ''' Returns antimony representation of model ''' import tellurium as te return te.sbmlToAntimony(self.getSbml())