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 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 getSEDMLAsPhrasedml(self, sedmlfile): zf = ZipFile(self.combinePath, 'r') sedmlStr = zf.read(sedmlfile) zf.close() phrasedmlStr = phrasedml.convertString(sedmlStr) return phrasedmlStr
def fromPhrasedML(cls, phrasedmlStr, location, master=None): sedmlStr = phrasedml.convertString(phrasedmlStr) # necessary to add xml extensions to antimony models phrasedml.addDotXMLToModelSources() sedmlStr = phrasedml.getLastSEDML() if sedmlStr is None: raise Exception(phrasedml.getLastError()) return cls.fromRaw(raw=sedmlStr, location=location, filetype='sed-ml', master=master)
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 toPhrasedml(self): 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 getSEDMLAsPhrasedml(self, sedmlfile): """ returns SEDML as phraSEDML :param sbmlfile: filename of SEDML file in COMBINE archive :return: phraSEDML string :rtype: str """ zf = ZipFile(self.combinePath, 'r') sedmlStr = zf.read(sedmlfile) zf.close() phrasedmlStr = phrasedml.convertString(sedmlStr) return phrasedmlStr
def get_sedml(self): """ Convert phrasedml into sedml. This method is concrete and prevents the need for the user to write their own sedml. Instead they provide theiry user input as phrasedml which this method automatically converts to sedml Returns: str SEDML string """ sedml_str = phrasedml.convertString(self.phrasedml()) if not sedml_str: raise ValueError(phrasedml.getLastError()) return sedml_str
def getSEDMLAsPhrasedml(self, sedmlfile): """ returns SEDML as phraSEDML :param sbmlfile: filename of SEDML file in COMBINE archive :return: phraSEDML string :rtype: str """ warnings.warn('Use inline_omex instead.', DeprecationWarning) zf = ZipFile(self.combinePath, 'r') sedmlStr = zf.read(sedmlfile) zf.close() phrasedmlStr = phrasedml.convertString(sedmlStr) return phrasedmlStr
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 _phrasedmlToSEDML(self, phrasedmlStr): """ Convert phrasedml string to SEDML. Necessary to set the reference models via phrasedml.setReferencedSBML first. :param phrasedmlStr: :type phrasedmlStr: :return: :rtype: """ sedmlstr = phrasedml.convertString(phrasedmlStr) if sedmlstr is None: raise Exception(phrasedml.getLastError()) return sedmlstr
def fromContent(cls, sedml_str): importer = phrasedmlImporter() importer.sedml_str = sedml_str # test for errors result = phrasedml.convertString(sedml_str) if result is None: # get errors from libsedml doc = SedReader().readSedMLFromString(sedml_str) if doc.getNumErrors(): max_len = 100 message = doc.getError(doc.getNumErrors() - 1).getMessage() message = message[:max_len] + '...' if len( message) > max_len else message raise RuntimeError('Errors reading SED-ML: {}'.format(message)) else: raise RuntimeError('Unable to read SED-ML.') return importer
def _phrasedmlToSEDML(self, phrasedmlStr): """ Convert phrasedml string to SEDML. Necessary to set the reference models via phrasedml.setReferencedSBML first. :param phrasedmlStr: :type phrasedmlStr: :return: :rtype: """ warnings.warn('Use inline_omex instead.', DeprecationWarning) sedmlstr = phrasedml.convertString(phrasedmlStr) if sedmlstr is None: raise Exception(phrasedml.getLastError()) return sedmlstr
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
def create_sedml(sedml_location, sbml_location, directory, dt, tend, species_ids, reaction_ids): """ Creates SED-ML file for the given simulation. :param sedml_location: :param sbml_location: :param directory: :param dt: :param tend: :return: """ phrasedml.setWorkingDirectory(directory) steps = int(1.0 * tend / dt) p = """ model1 = model "{}" sim1 = simulate uniform(0, {}, {}) sim1.algorithm = kisao.500 task1 = run sim1 on model1 plot "Figure 1: DFBA species vs. time" time vs {} plot "Figure 2: DFBA fluxes vs. time" time vs {} report "Report 1: DFBA species vs. time" time vs {} report "Report 2: DFBA fluxes vs. time" time vs {} """.format(sbml_location, tend, steps, species_ids, reaction_ids, species_ids, reaction_ids) return_code = phrasedml.convertString(p) if return_code is None: print(phrasedml.getLastError()) sedml = phrasedml.getLastSEDML() # print(sedml) sedml_file = os.path.join(directory, sedml_location) with open(sedml_file, "w") as f: f.write(sedml) print(sedml_file)
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) f_sedml = tempfile.NamedTemporaryFile(suffix=".sedml")
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)
import phrasedml as p with open("sedml_webtools_transcription.xml") as f: sedml = f.read() pml = p.convertString(sedml) with open("phrasedml_converted_transcription.phrasedml", "w") as f: f.write(pml)
task2 = run sim1 on model2 # A simple timecourse simulation plot "Figure 1.1 Timecourse of repressilator" task1.time vs task1.PX, task1.PZ, task1.PY # Applying preprocessing plot "Figure 1.2 Timecourse after pre-processing" task2.time vs task2.PX, task2.PZ, task2.PY # Applying postprocessing plot "Figure 1.3 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 SED-ML sedmlStr = phrasedml.convertString(phrasedmlStr) if sedmlStr == None: print(phrasedml.getLastError()) # Run the SED-ML file with results written in workingDir import tempfile import shutil workingDir = tempfile.mkdtemp(suffix="_sedml") te.executeSEDML(sedmlStr, workingDir=workingDir) shutil.rmtree(workingDir) # ### Execute Combine Archive # Executing the SED-ML from a combine archive. # In[2]:
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)
import phrasedml as p with open('sedml_webtools_gillespie_transcription.xml') as f: sedml = f.read() pml = p.convertString(sedml) with open('phrasedml_converted_gillespie_transcription.phrasedml', 'w') as f: f.write(pml)
def getSEDMLStr(self): sedmlstr = phrasedml.convertString(self.getRawStr()) if sedmlstr == None: raise Exception(phrasedml.getLastError()) return sedmlstr