def exportAsCombine(self, outputpath): # parameter outputpath must be a full path of a zip file you wish to create # Temporary failsafe - Should be revised once libphrasedml adopts returning of model name reModel = r"""(\w*) = model ('|")(.*)('|")""" # rePlot = r"""plot ('|")(.*)('|") (.*)""" lines = self.phrasedmlStr.splitlines() for i, s in enumerate(lines): reSearchModel = re.split(reModel, s) # reSearchPlot = re.split(rePlot, s) if len(reSearchModel) > 1: modelsource = str(reSearchModel[3]) modelname = os.path.basename(modelsource) if ".xml" or ".sbml" not in modelsource: modelname = modelname + ".xml" s = s.replace(modelsource, modelname) lines[i] = s # if len(reSearchPlot) > 1: # plottitle = str(reSearchPlot[2]) revphrasedml = "\n".join(lines) phrasedml.setReferencedSBML(modelname, te.antimonyTosbml(self.antimonyStr)) combine.export(outputpath, self.antimonyStr, modelname, revphrasedml) phrasedml.clearReferencedSBML()
def addPhrasedml(self, phrasedmlStr, antimonyStr, arcname=None): """ Adds SEDML file as phraSEDML string into COMBINE archive. :param phrasedmlStr: phraSEDML string :param antimonyStr: antimony string to be referenced :param arcname: (optional) desired name of SEDML file """ warnings.warn('Use inline_omex instead.', DeprecationWarning) # FIXME: This does not work for multiple referenced models !. reModel = r"""(\w*) = model ('|")(.*)('|")""" phrasedmllines = phrasedmlStr.splitlines() for k, line in enumerate(phrasedmllines): reSearchModel = re.split(reModel, line) if len(reSearchModel) > 1: modelsource = str(reSearchModel[3]) modelname = os.path.basename(modelsource) modelname = str(modelname).replace(".xml", '') phrasedml.setReferencedSBML(modelsource, te.antimonyToSBML(antimonyStr)) sedmlstr = phrasedml.convertString(phrasedmlStr) if sedmlstr is None: raise Exception(phrasedml.getLastError()) phrasedml.clearReferencedSBML() self.addSEDML(sedmlstr, arcname)
def createpython(self): # Create and return Python script given antimony and phrasedml strings rePath = r"(\w*).load\('(.*)'\)" reLoad = r"(\w*) = roadrunner.RoadRunner\(\)" reModel = r"""(\w*) = model ('|")(.*)('|")""" phrasedmllines = self.phrasedmlStr.splitlines() for i, s in enumerate(phrasedmllines): reSearchModel = re.split(reModel, s) if len(reSearchModel) > 1: modelsource = str(reSearchModel[3]) modelname = os.path.basename(modelsource) modelname = str(modelname).replace(".xml", "") phrasedml.setReferencedSBML(modelsource, te.antimonyTosbml(self.antimonyStr)) sedmlstr = phrasedml.convertString(self.phrasedmlStr) if sedmlstr == None: raise Exception(phrasedml.getLastError()) phrasedml.clearReferencedSBML() fd1, sedmlfilepath = tempfile.mkstemp() os.write(fd1, sedmlstr) pysedml = te.SedmlToRr.sedml_to_python(sedmlfilepath) if self.modelispath == False: lines = pysedml.splitlines() for i, s in enumerate(lines): reSearchPath = re.split(rePath, s) if len(reSearchPath) > 1: del lines[i] for i, s in enumerate(lines): reSearchLoad = re.split(reLoad, s) if len(reSearchLoad) > 1: s = s.replace("roadrunner.RoadRunner()", "te.loada(" + str(modelname) + ")") lines[i] = s if not "import tellurium" in pysedml: if "import roadrunner" in pysedml: for i, s in enumerate(lines): if "import roadrunner" in s: del lines[i] lines.insert(i, "import tellurium as te") else: pass pysedml = "\n".join(lines) # List of replacements pysedml = pysedml.replace('"compartment"', '"compartment_"') pysedml = pysedml.replace("'compartment'", "'compartment_'") outputstr = str(modelname) + " = '''" + self.antimonyStr + "'''\n\n" + pysedml os.close(fd1) os.remove(sedmlfilepath) return outputstr
def __init__(self, sources): """ Converts a dictionary of PhraSEDML files and list of Antimony files into sedml/sbml. :param sources: Sources returned from partitionInlineOMEXString """ from .convert_omex import Omex, SbmlAsset, SedmlAsset, readCreator from .convert_antimony import antimonyConverter phrasedml.clearReferencedSBML() from .. import DumpJSONInfo self.omex = Omex(description=DumpJSONInfo(), creator=readCreator()) # Convert antimony to sbml for t, loc, master in ((x['source'], x['location'] if 'location' in x else None, x['master'] if 'master' in x else None) for x in sources if x['type'] == 'antimony'): modulename, sbmlstr = antimonyConverter().antimonyToSBML(t) outpath = loc if loc is not None else modulename + '.xml' self.omex.addSbmlAsset(SbmlAsset(outpath, sbmlstr, master=master)) # Convert phrasedml to sedml for t, loc, master in ((x['source'], x['location'] if 'location' in x else None, x['master'] if 'master' in x else None) for x in sources if x['type'] == 'phrasedml'): for sbml_asset in self.omex.getSbmlAssets(): if sbml_asset.location: if loc: path = os.path.relpath(sbml_asset.location, os.path.dirname(loc)) else: path = sbml_asset.location else: path = sbml_asset.getModuleName() # make windows paths like unix paths if os.path.sep == '\\': path = path.replace(os.path.sep, '/') phrasedml.setReferencedSBML(path, sbml_asset.getContent()) phrasedml.convertString(t) phrasedml.addDotXMLToModelSources(False) sedml = phrasedml.getLastSEDML() if sedml is None: raise RuntimeError( 'Unable to convert PhraSEDML to SED-ML: {}'.format( phrasedml.getLastError())) outpath = loc if loc is not None else 'main.xml' self.omex.addSedmlAsset(SedmlAsset(outpath, sedml, master=master))
def __init__(self, sources): """ Converts a dictionary of PhraSEDML files and list of Antimony files into sedml/sbml. :param sources: Sources returned from partitionInlineOMEXString """ from .convert_omex import Omex, SbmlAsset, SedmlAsset, readCreator from .convert_antimony import antimonyConverter phrasedml.clearReferencedSBML() from .. import DumpJSONInfo self.omex = Omex( description=DumpJSONInfo(), creator=readCreator() ) # Convert antimony to sbml for t, loc, master in ( (x['source'], x['location'] if 'location' in x else None, x['master'] if 'master' in x else None) for x in sources if x['type'] == 'antimony'): modulename, sbmlstr = antimonyConverter().antimonyToSBML(t) outpath = loc if loc is not None else modulename + '.xml' self.omex.addSbmlAsset(SbmlAsset(outpath, sbmlstr, master=master)) # Convert phrasedml to sedml for t, loc, master in ( (x['source'], x['location'] if 'location' in x else None, x['master'] if 'master' in x else None) for x in sources if x['type'] == 'phrasedml'): for sbml_asset in self.omex.getSbmlAssets(): if sbml_asset.location: if loc: path = os.path.relpath(sbml_asset.location, os.path.dirname(loc)) else: path = sbml_asset.location else: path = sbml_asset.getModuleName() # make windows paths like unix paths if os.path.sep == '\\': path = path.replace(os.path.sep, '/') phrasedml.setReferencedSBML(path, sbml_asset.getContent()) phrasedml.convertString(t) phrasedml.addDotXMLToModelSources(False) sedml = phrasedml.getLastSEDML() if sedml is None: raise RuntimeError('Unable to convert PhraSEDML to SED-ML: {}'.format(phrasedml.getLastError())) outpath = loc if loc is not None else 'main.xml' self.omex.addSedmlAsset(SedmlAsset(outpath, sedml, master=master))
def getSedmlString(self): reModel = r"""(\w*) = model ('|")(.*)('|")""" phrasedmllines = self.phrasedmlStr.splitlines() for i, s in enumerate(phrasedmllines): reSearchModel = re.split(reModel, s) if len(reSearchModel) > 1: modelsource = str(reSearchModel[3]) phrasedml.setReferencedSBML(modelsource, te.antimonyToSbml(self.antimonyStr)) sedmlstr = phrasedml.convertString(self.phrasedmlStr) if sedmlstr == None: raise Exception(phrasedml.getLastError()) phrasedml.clearReferencedSBML() return sedmlstr
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 toPhrasedml(self): # assign sbml resources # print('toPhrasedml sbml resources:') phrasedml.clearReferencedSBML() for sbml_resource in self.sbml_map: # print(' {} -> {}'.format(sbml_resource, self.sbml_map[sbml_resource][:30])) phrasedml.setReferencedSBML(sbml_resource, self.sbml_map[sbml_resource]) # convert to phrasedml if self.sedml_str: result = phrasedml.convertString(self.sedml_str) if result is None: raise RuntimeError(phrasedml.getLastError()) return self.fixModelRefs(phrasedml.getLastPhraSEDML()) elif self.sedml_path: result = phrasedml.convertFile(self.sedml_str) if result is None: raise RuntimeError(phrasedml.getLastError()) return self.fixModelRefs(phrasedml.getLastPhraSEDML())
def addPhrasedml(self, phrasedmlStr, antimonyStr, arcname=None): """ Adds phrasedml via conversion to SEDML. """ # FIXME: This does not work for multiple referenced models !. reModel = r"""(\w*) = model ('|")(.*)('|")""" phrasedmllines = phrasedmlStr.splitlines() for k, line in enumerate(phrasedmllines): reSearchModel = re.split(reModel, line) if len(reSearchModel) > 1: modelsource = str(reSearchModel[3]) modelname = os.path.basename(modelsource) modelname = str(modelname).replace(".xml", '') phrasedml.setReferencedSBML(modelsource, te.antimonyToSBML(antimonyStr)) sedmlstr = phrasedml.convertString(phrasedmlStr) if sedmlstr is None: raise Exception(phrasedml.getLastError()) phrasedml.clearReferencedSBML() self.addSEDML(sedmlstr, arcname)
def phrasedmltosedml(self, phrasedml_str, sbml_file, **kwargs): """Generate SEDML file from phrasedml. Example of phrasedml_str: phrasedml_str = ''' model1 = model "{}" ... ... ''' :param phrasedml_str: text-based way to represent SEDML :type phrasedml_str: str :param sbml_file: the SBML xml file/path to the file :type sbml_file: str :return: the sedml string :rtype: str """ try: with open(sbml_file, "r+") as f: sbml_str = f.read() except IOError: print("Error in opening sbml file") phrasedml_str = phrasedml_str.format(sbml_file) phrasedml.setReferencedSBML(sbml_file, sbml_str) sedml_str = phrasedml.convertString(phrasedml_str) if sedml_str is None: raise RuntimeError(phrasedml.getLastError()) sedml_file = os.path.join(self.workingdir0, "sedml.xml") for key, value in kwargs.items(): if "outputfile" in key: sedml_file = value with open(sedml_file, "wb") as f: f.write(sedml_str.encode("utf-8")) return sedml_str
S1 -> S2; k1*S1 S1 = 10; S2 = 0 k1 = 1 end ''' phrasedml_str = ''' model1 = model "myModel" sim1 = simulate uniform(0, 5, 100) task1 = run sim1 on model1 plot "Figure 1" time vs S1, S2 ''' # create the sedml xml string from the phrasedml sbml_str = te.antimonyToSBML(antimony_str) phrasedml.setReferencedSBML("myModel", sbml_str) sedml_str = phrasedml.convertString(phrasedml_str) if sedml_str == None: print(phrasedml.getLastPhrasedError()) print(sedml_str) # In[2]: # Create the temporary files and execute the code import tempfile f_sbml = tempfile.NamedTemporaryFile(prefix="myModel", suffix=".xml") f_sbml.write(sbml_str) f_sbml.flush() print(f_sbml.name)
# ### SED-ML L1V2 specification example # Repressilator example which demonstrates the use of phrasedml with URN examples. # # The examples are the reference examples from the SED-ML specification document available from http://sed-ml.sourceforge.net/documents/sed-ml-L1V2.pdf (Introduction Section). # 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 phrasedml # Get SBML from URN and set for phrasedml urn = "urn:miriam:biomodels.db:BIOMD0000000012" sbmlStr = te.temiriam.getSBMLFromBiomodelsURN(urn=urn) phrasedml.setReferencedSBML(urn, sbmlStr) # <SBML species> # PX - LacI protein # PY - TetR protein # PZ - cI protein # X - LacI mRNA # Y - TetR mRNA # Z - cI mRNA # <SBML parameters> # ps_a - tps_active: Transcrition from free promotor in transcripts per second and promotor # ps_0 - tps_repr: Transcrition from fully repressed promotor in transcripts per second and promotor phrasedmlStr = """ model1 = model "{}"
def test_repressilator(self): # Get SBML from URN and set for phrasedml urn = "urn:miriam:biomodels.db:BIOMD0000000012" sbml_str = temiriam.getSBMLFromBiomodelsURN(urn=urn) return_code = phrasedml.setReferencedSBML(urn, sbml_str) assert return_code # valid SBML # <SBML species> # PX - LacI protein # PY - TetR protein # PZ - cI protein # X - LacI mRNA # Y - TetR mRNA # Z - cI mRNA # <SBML parameters> # ps_a - tps_active: Transcription from free promotor in transcripts per second and promotor # ps_0 - tps_repr: Transcription from fully repressed promotor in transcripts per second and promotor phrasedml_str = """ model1 = model "{}" model2 = model model1 with ps_0=1.3E-5, ps_a=0.013 sim1 = simulate uniform(0, 1000, 1000) task1 = run sim1 on model1 task2 = run sim1 on model2 # A simple timecourse simulation plot "Timecourse of repressilator" task1.time vs task1.PX, task1.PZ, task1.PY # Applying preprocessing plot "Timecourse after pre-processing" task2.time vs task2.PX, task2.PZ, task2.PY # Applying postprocessing plot "Timecourse after post-processing" task1.PX/max(task1.PX) vs task1.PZ/max(task1.PZ), \ task1.PY/max(task1.PY) vs task1.PX/max(task1.PX), \ task1.PZ/max(task1.PZ) vs task1.PY/max(task1.PY) """.format(urn) # convert to sedml print(phrasedml_str) sedml_str = phrasedml.convertString(phrasedml_str) if sedml_str is None: print(phrasedml.getLastError()) raise IOError("sedml could not be generated") # run SEDML directly try: tmp_dir = tempfile.mkdtemp() executeSEDML(sedml_str, workingDir=tmp_dir) finally: shutil.rmtree(tmp_dir) # create combine archive and execute try: tmp_dir = tempfile.mkdtemp() sedml_location = "repressilator_sedml.xml" sedml_path = os.path.join(tmp_dir, sedml_location) omex_path = os.path.join(tmp_dir, "repressilator.omex") with open(sedml_path, "w") as f: f.write(sedml_str) entries = [ omex.Entry(location=sedml_location, formatKey="sedml", master=True) ] omex.combineArchiveFromEntries(omexPath=omex_path, entries=entries, workingDir=tmp_dir) executeCombineArchive(omex_path, workingDir=tmp_dir) finally: shutil.rmtree(tmp_dir)
model1 = model "test1" model2 = model "test2" model3 = model model1 with S1=S2+20 sim1 = simulate uniform(0, 6, 100) task1 = run sim1 on model1 task2 = run sim1 on model2 plot "Timecourse test1" task1.time vs task1.S1, task1.S2 plot "Timecourse test2" task2.time vs task2.X1, task2.X2 """ # phrasedml.setReferencedSBML("test1") exp = te.experiment(phrasedmlList=[phrasedmlStr], antimonyList=[antTest1Str]) print(exp) # set first model phrasedml.setReferencedSBML("test1", te.antimonyToSBML(antTest1Str)) phrasedml.setReferencedSBML("test2", te.antimonyToSBML(antTest2Str)) sedmlstr = phrasedml.convertString(phrasedmlStr) if sedmlstr is None: raise Exception(phrasedml.getLastError()) print(sedmlstr) # In[3]: # In[3]:
""" from __future__ import absolute_import, print_function import os import tempfile import shutil from tellurium import temiriam from tellurium.sedml.tesedml import executeCombineArchive, executeSEDML from tellurium.utils import omex import phrasedml # Get SBML from URN and set for phrasedml urn = "urn:miriam:biomodels.db:BIOMD0000000012" sbml_str = temiriam.getSBMLFromBiomodelsURN(urn=urn) return_code = phrasedml.setReferencedSBML(urn, sbml_str) print('valid SBML', return_code) # <SBML species> # PX - LacI protein # PY - TetR protein # PZ - cI protein # X - LacI mRNA # Y - TetR mRNA # Z - cI mRNA # <SBML parameters> # ps_a - tps_active: Transcription from free promotor in transcripts per second and promotor # ps_0 - tps_repr: Transcription from fully repressed promotor in transcripts per second and promotor phrasedml_str = """
import phrasedml, os with open('./model/BIOMD0000000144.xml') as f: sbml_str = f.read() with open('./experiment/Calzone2007-simulation-figure-1B.xml') as f: sedml_in = f.read() phrasedml.setReferencedSBML('../model/BIOMD0000000144.xml', sbml_str) phrasedml.convertString(sedml_in) phrased_str = phrasedml.getLastPhraSEDML() phrasedml.convertString(phrased_str) phrasedml.addDotXMLToModelSources() sedml_out = phrasedml.getLastSEDML() if not os.path.exists('phrased'): os.makedirs('phrased') with open('./phrased/Calzone2007-simulation-figure-1B.xml', 'w') as f: f.write(sedml_out)