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()
Beispiel #2
0
    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)
Beispiel #3
0
    def exportAsCombine(self, outputPath, execute=False):
        """ Creates COMBINE archive for given antimony and phrasedml files.

        If execute=True all phrasedml are executed and the results written

        :param exportPath: full path of the combine zip file to create
        :type exportPath: str
        """
        # Create empty archive
        m = tecombine.CombineArchive()

        # Add antimony models to archive
        for aStr in self.antimonyList:
            r = te.loada(aStr)
            name = r.getModel().getModelName()
            m.addAntimonyStr(aStr, "{}.xml".format(name))

        # Add phrasedml models to archive
        for k, phrasedmlStr in enumerate(self.phrasedmlList):
            phrasedml.clearReferencedSBML()
            self._setReferencedSBML(phrasedmlStr)
            m.addPhraSEDMLStr(phrasedmlStr, self._phrasedmlFileName(k), master=True)
        phrasedml.clearReferencedSBML()

        # Add README.md to archive
        readmeStr = self.createReadmeString(outputPath)
        m.addStr(readmeStr, location='README.md', filetype='md')

        # add output files to archive
        if execute:
            for phrasedmlStr in self.phrasedmlList:
                # execute in temporary directory
                workingDir = tempfile.mkdtemp(suffix="_sedml")
                execStr = self._toPython(phrasedmlStr, workingDir=workingDir)
                exec execStr

                # Add output files to archive
                files = [f for f in os.listdir(workingDir)]

                for f in files:
                    filepath = os.path.join(workingDir, f)
                    if f.endswith('.xml'):
                        # SBML or SEDML resulting from antimony/phrasedml (already in archive)
                        pass
                    elif f.endswith('.md'):
                        # README.md (already in archive)
                        pass
                    elif f.endswith('.png'):
                        # outputPlot2D | outputPlot3D
                        m.addFile(filepath, filetype="png")
                    elif f.endswith('.csv'):
                        # outputReport
                        m.addFile(filepath, filetype="csv")
                    else:
                        warnings.warn('Unsupported file type not written in COMBINE archive: {}'.format(filepath))
                # remove temporary workingDir
                shutil.rmtree(workingDir)

        # Write archive
        m.write(outputPath)
    def exportToCombine(self, outfile):
        '''Exports this Omex instance to a Combine archive.

        :param outfile: A path to the output file'''

        import phrasedml
        phrasedml.clearReferencedSBML()

        archive = CombineArchive()
        description = OmexDescription()
        description.setAbout(self.about)
        description.setDescription(self.description)
        description.setCreated(OmexDescription.getCurrentDateAndTime())

        # TODO: pass in creator
        if self.creator is not None:
            creator = VCard()
            creator.setFamilyName(self.creator['last_name'])
            creator.setGivenName(self.creator['first_name'])
            creator.setEmail(self.creator['email'])
            creator.setOrganization(self.creator['organization'])
            description.addCreator(creator)

        archive.addMetadata('.', description)

        # Write out to temporary files
        # TODO: can add content via strings now
        workingDir = tempfile.mkdtemp(suffix="_sedml")
        files = []  # Keep a list of files to remove

        for t in self.getSedmlAssets():
            fname = os.path.join(workingDir, os.path.normpath(t.getLocation()))
            dname = os.path.dirname(fname)
            if not os.path.exists(dname):
                os.makedirs(dname)
            with open(fname, 'w') as f:
                files.append(fname)
                f.write(t.getContent())
                archive.addFile(fname, t.getLocation(),
                                KnownFormats.lookupFormat("sedml"),
                                t.getMaster())

        for t in self.getSbmlAssets():
            fname = os.path.join(workingDir, os.path.normpath(t.getLocation()))
            dname = os.path.dirname(fname)
            if not os.path.exists(dname):
                os.makedirs(dname)
            with open(fname, 'w') as f:
                files.append(fname)
                f.write(t.getContent())
                archive.addFile(
                    fname, t.getLocation(), KnownFormats.lookupFormat("sbml"),
                    t.getMaster() if t.getMaster() is not None else False)

        archive.writeToFile(outfile)

        for f in files:
            os.remove(f)
Beispiel #5
0
    def exportToCombine(self, outfile):
        """ Export Omex instance as combine archive.

        :param outfile: A path to the output file"""
        import phrasedml
        phrasedml.clearReferencedSBML()

        archive = libcombine.CombineArchive()
        description = libcombine.OmexDescription()
        description.setAbout(self.about)
        description.setDescription(self.description)
        time_now = libcombine.OmexDescription.getCurrentDateAndTime()
        description.setCreated(time_now)

        # TODO: pass in creator
        if self.creator is not None:
            creator = libcombine.VCard()
            creator.setFamilyName(self.creator['last_name'])
            creator.setGivenName(self.creator['first_name'])
            creator.setEmail(self.creator['email'])
            creator.setOrganization(self.creator['organization'])
            description.addCreator(creator)

        archive.addMetadata('.', description)

        # Write out to temporary files
        # TODO: can add content via strings now
        workingDir = tempfile.mkdtemp(suffix="_sedml")
        files = []  # Keep a list of files to remove

        def addAssetToArchive(asset, format):
            """ Helper to add asset of given format. """
            fname = os.path.join(workingDir,
                                 os.path.normpath(asset.getLocation()))
            dname = os.path.dirname(fname)
            if not os.path.exists(dname):
                os.makedirs(dname)
            with open(fname, 'w') as f:
                files.append(fname)
                f.write(t.getContent())
                archive.addFile(fname, asset.getLocation(),
                                libcombine.KnownFormats.lookupFormat(format),
                                asset.getMaster())

        try:
            for t in self.getSedmlAssets():
                addAssetToArchive(t, 'sedml')

            for t in self.getSbmlAssets():
                addAssetToArchive(t, 'sbml')

            archive.writeToFile(outfile)
        finally:
            # put this in finally to make sure files are removed even under Exception
            for f in files:
                os.remove(f)
Beispiel #6
0
    def exportToCombine(self, outfile):
        """ Export Omex instance as combine archive.

        :param outfile: A path to the output file"""
        import phrasedml
        phrasedml.clearReferencedSBML()

        archive = libcombine.CombineArchive()
        description = libcombine.OmexDescription()
        description.setAbout(self.about)
        description.setDescription(self.description)
        time_now = libcombine.OmexDescription.getCurrentDateAndTime()
        description.setCreated(time_now)

        # TODO: pass in creator
        if self.creator is not None:
            creator = libcombine.VCard()
            creator.setFamilyName(self.creator['last_name'])
            creator.setGivenName(self.creator['first_name'])
            creator.setEmail(self.creator['email'])
            creator.setOrganization(self.creator['organization'])
            description.addCreator(creator)

        archive.addMetadata('.', description)

        # Write out to temporary files
        # TODO: can add content via strings now
        workingDir = tempfile.mkdtemp(suffix="_sedml")
        files = []  # Keep a list of files to remove

        def addAssetToArchive(asset, format):
            """ Helper to add asset of given format. """
            fname = os.path.join(workingDir, os.path.normpath(asset.getLocation()))
            dname = os.path.dirname(fname)
            if not os.path.exists(dname):
                os.makedirs(dname)
            with open(fname, 'w') as f:
                files.append(fname)
                f.write(t.getContent())
                archive.addFile(fname,
                                asset.getLocation(),
                                libcombine.KnownFormats.lookupFormat(format),
                                asset.getMaster())

        try:
            for t in self.getSedmlAssets():
                addAssetToArchive(t, 'sedml')

            for t in self.getSbmlAssets():
                addAssetToArchive(t, 'sbml')

            archive.writeToFile(outfile)
        finally:
            # put this in finally to make sure files are removed even under Exception
            for f in files:
                os.remove(f)
    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
Beispiel #8
0
    def executeOmex(self):
        '''Executes this Omex instance.'''

        import phrasedml
        phrasedml.clearReferencedSBML()

        workingDir = tempfile.mkdtemp(suffix="_sedml")
        self.writeFiles(workingDir)
        from tellurium import executeSEDML
        for sedml_asset in self.getSedmlAssets():
            if sedml_asset.getMaster():
                sedml_path = os.path.join(workingDir, sedml_asset.getLocation())
                executeSEDML(sedml_path,
                    workingDir=os.path.dirname(sedml_path))
Beispiel #9
0
    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))
Beispiel #10
0
    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))
Beispiel #11
0
    def executeOmex(self):
        """ Executes this Omex instance.

        :return:
        """
        import phrasedml
        phrasedml.clearReferencedSBML()

        workingDir = tempfile.mkdtemp(suffix="_sedml")
        self.writeFiles(workingDir)
        from tellurium import executeSEDML
        for sedml_asset in self.getSedmlAssets():
            if sedml_asset.getMaster():
                sedml_path = os.path.join(workingDir, sedml_asset.getLocation())
                executeSEDML(sedml_path,
                             workingDir=os.path.dirname(sedml_path))
Beispiel #12
0
    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
Beispiel #13
0
    def checkKisaoAlgorithmParameter(self, exp, kisao, name, value):
        """ Helper function for checking kisao parameter. """
        p = exp.phrasedmlList[0]

        # check that set AlgorithmParameter set correctly in SED-ML
        phrasedml.clearReferencedSBML()
        exp._setReferencedSBML(p)
        sedml = exp._phrasedmlToSEDML(p)
        doc = libsedml.readSedMLFromString(sedml)
        simulation = doc.getSimulation('sim0')
        algorithm = simulation.getAlgorithm()
        pdict = {
            p.getKisaoID(): p
            for p in algorithm.getListOfAlgorithmParameters()
        }

        self.assertTrue(kisao in pdict)
        pkey = SEDMLCodeFactory.algorithmParameterToParameterKey(pdict[kisao])

        if pkey.dtype == str:
            self.assertEqual(pkey.value, value)
        else:
            # numerical parameter
            self.assertAlmostEqual(float(pkey.value), value)

        # check that integrator is set in python code
        pystr = exp._toPython(p)

        print(simulation.getElementName())
        print(pystr)
        if simulation.getTypeCode() is libsedml.SEDML_SIMULATION_STEADYSTATE:
            if pkey.dtype == str:
                self.assertTrue(
                    ".steadyStateSolver.setValue('{}', '{}')".format(
                        name, value) in pystr)
            else:
                # numerical parameter
                self.assertTrue(".steadyStateSolver.setValue('{}', {})".format(
                    name, value) in pystr)
        else:
            if pkey.dtype == str:
                self.assertTrue(".integrator.setValue('{}', '{}')".format(
                    name, value) in pystr)
            else:
                # numerical parameter
                self.assertTrue(".integrator.setValue('{}', {})".format(
                    name, value) in pystr)
Beispiel #14
0
 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 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())
Beispiel #16
0
    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 checkKisaoIntegrator(self, exp, kisao, name):
        """ Helper function for checking kisao integrator. """
        p = exp.phrasedmlList[0]

        # is kisao correct in SedDocument
        phrasedml.clearReferencedSBML()
        exp._setReferencedSBML(p)
        sedml = exp._phrasedmlToSEDML(p)
        doc = libsedml.readSedMLFromString(sedml)
        simulation = doc.getSimulation('sim0')
        algorithm = simulation.getAlgorithm()
        self.assertEqual(algorithm.getKisaoID(), kisao)

        # is integrator/solver set in python code
        pystr = exp._toPython(p)
        if simulation.getTypeCode() is libsedml.SEDML_SIMULATION_STEADYSTATE:
            self.assertTrue(".setSteadyStateSolver('{}')".format(name) in pystr)
        else:
            self.assertTrue(".setIntegrator('{}')".format(name) in pystr)
Beispiel #18
0
    def _toPython(self, phrasedmlStr, workingDir=None):
        """ Create and return python script given phrasedml string.
        
        :param phrasedmlStr: Name of PhraSEDML string defined in the code
        :type phrasedmlStr: str

        :returns: python string to execute
        :rtype: str
        """
        warnings.warn('Use inline_omex instead.', DeprecationWarning)
        if phrasedmlStr is None:
            phrasedmlStr = self._getDefaultPhrasedml()

        # Models have to be resolved from phrasedml string and set as referenced
        phrasedml.clearReferencedSBML()
        self._setReferencedSBML(phrasedmlStr)

        # check if conversion is possible
        self._phrasedmlToSEDML(phrasedmlStr)

        # create temporary working directory
        import tempfile
        isTmpDir = False
        if workingDir is None:
            workingDir = tempfile.mkdtemp(suffix="_sedml")
            isTmpDir = True

        # Export archive
        expId = self.getId()
        expArchive = os.path.join(workingDir, "{}.omex".format(expId))
        self.exportAsCombine(expArchive)

        # Create python code from archive
        # This is the clean way to generate the code !
        pycode = tesedml.sedmlToPython(expArchive)

        # remove the temporary directory
        if isTmpDir:
            shutil.rmtree(workingDir)

        return pycode
Beispiel #19
0
    def checkKisaoAlgorithmParameter(self, exp, kisao, name, value):
        """ Helper function for checking kisao parameter. """
        p = exp.phrasedmlList[0]

        # check that set AlgorithmParameter set correctly in SED-ML
        phrasedml.clearReferencedSBML()
        exp._setReferencedSBML(p)
        sedml = exp._phrasedmlToSEDML(p)
        doc = libsedml.readSedMLFromString(sedml)
        simulation = doc.getSimulation('sim0')
        algorithm = simulation.getAlgorithm()
        pdict = {p.getKisaoID(): p for p in algorithm.getListOfAlgorithmParameters()}

        self.assertTrue(kisao in pdict)
        pkey = SEDMLCodeFactory.algorithmParameterToParameterKey(pdict[kisao])

        if pkey.dtype == str:
            self.assertEqual(pkey.value, value)
        else:
            # numerical parameter
            self.assertAlmostEqual(float(pkey.value), value)

        # check that integrator is set in python code
        pystr = exp._toPython(p)

        print(simulation.getElementName())
        print(pystr)
        if simulation.getTypeCode() is libsedml.SEDML_SIMULATION_STEADYSTATE:
            if pkey.dtype == str:
                self.assertTrue(".steadyStateSolver.setValue('{}', '{}')".format(name, value) in pystr)
            else:
                # numerical parameter
                self.assertTrue(".steadyStateSolver.setValue('{}', {})".format(name, value) in pystr)
        else:
            if pkey.dtype == str:
                self.assertTrue(".integrator.setValue('{}', '{}')".format(name, value) in pystr)
            else:
                # numerical parameter
                self.assertTrue(".integrator.setValue('{}', {})".format(name, value) in pystr)
Beispiel #20
0
    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 exportAsCombine(self, outputPath, execute=False):
        """ Creates COMBINE archive for given antimony and phrasedml files.

        If execute=True all phrasedml are executed and the results written

        :param exportPath: full path of the combine zip file to create
        :type exportPath: str
        """

        # Create empty archive
        m = tecombine.CombineArchive()

        # Add antimony models to archive
        for aStr in self.antimonyList:
            r = te.loada(aStr)
            name = r.getModel().getModelName()
            m.addAntimonyStr(aStr, "{}.xml".format(name))

        # Add phrasedml models to archive
        for k, phrasedmlStr in enumerate(self.phrasedmlList):
            phrasedml.clearReferencedSBML()
            self._setReferencedSBML(phrasedmlStr)
            m.addPhraSEDMLStr(phrasedmlStr,
                              self._phrasedmlFileName(k),
                              master=True)
        phrasedml.clearReferencedSBML()

        # Add README.md to archive
        readmeStr = self.createReadmeString(outputPath)
        m.addStr(readmeStr, location='README.md', filetype='md')

        # add output files to archive
        if execute:
            for phrasedmlStr in self.phrasedmlList:
                # execute in temporary directory
                workingDir = tempfile.mkdtemp(suffix="_sedml")
                execStr = self._toPython(phrasedmlStr, workingDir=workingDir)
                exec execStr

                # Add output files to archive
                files = [f for f in os.listdir(workingDir)]

                for f in files:
                    filepath = os.path.join(workingDir, f)
                    if f.endswith('.xml'):
                        # SBML or SEDML resulting from antimony/phrasedml (already in archive)
                        pass
                    elif f.endswith('.md'):
                        # README.md (already in archive)
                        pass
                    elif f.endswith('.png'):
                        # outputPlot2D | outputPlot3D
                        m.addFile(filepath, filetype="png")
                    elif f.endswith('.csv'):
                        # outputReport
                        m.addFile(filepath, filetype="csv")
                    else:
                        warnings.warn(
                            'Unsupported file type not written in COMBINE archive: {}'
                            .format(filepath))
                # remove temporary workingDir
                shutil.rmtree(workingDir)

        # Write archive
        m.write(outputPath)