Example #1
0
    def guessXML(self, xml_content):

        root = etree.fromstring(xml_content)
        tag = root.tag.split("}")[1]

        if isinstance(xml_content, bytes):
            xml_content = str("%s" % xml_content.decode('ascii', 'ignore'))

        if tag == "sbml":
            sbmlReader = SBMLReader()
            if sbmlReader is not None:
                sbmlDoc = sbmlReader.readSBMLFromString(xml_content)
                return self.SBML + ".level-%d.version-%d" % (
                    sbmlDoc.getLevel(), sbmlDoc.getVersion())
            else:
                return self.SBML

        elif tag == "sedML":
            sedmlDoc = readSedMLFromString(xml_content)
            return self.SEDML + ".level-%d.version-%d" % (
                sedmlDoc.getLevel(), sedmlDoc.getVersion())

        elif tag == "numl":
            numlDoc = readNUMLFromString(xml_content)
            return self.NUML + ".level-%d.version-%d" % (numlDoc.getLevel(),
                                                         numlDoc.getVersion())

        elif tag == "omexManifest":
            return self.MANIFEST

        else:
            return self.XML
Example #2
0
def tags_info(archive_path):
    """ Reads the tags info from a given archive.

    :param archive_path:
    :return:
    """
    tags_info = []

    # add the file formats from omex
    omex = libcombine.CombineArchive()
    if omex.initializeFromArchive(archive_path) is None:
        print("Invalid Combine Archive: {}", archive_path)
        return None

    sedml_entries = []
    sbml_entries = []
    for i in range(omex.getNumEntries()):
        entry = omex.getEntry(i)
        format = entry.getFormat()
        location = entry.getLocation()
        format_id = base_format(format)

        if format_id in ['sbml', 'cellml', 'sed-ml', 'sedml', 'sbgn', 'sbol']:
            tags_info.append({
                'type': 'format',
                'name': format_id,
            })
        if format_id == 'sbml':
            sbml_entries.append(entry)
        if format_id in ['sedml', 'sed-ml']:
            sedml_entries.append(entry)

    # add the SBML contents
    # add the SED-ML contents
    for entry in sedml_entries:
        content = omex.extractEntryToString(entry.getLocation())
        doc = libsedml.readSedMLFromString(
            content)  # type: libsedml.SedDocument
        print(doc)

        for model in doc.getListOfModels():
            language = model.getLanguage()
            if language:
                name = language.split(':')[-1]
                tags_info.append({
                    'type': 'sedml',
                    'name': 'model:{}'.format(name)
                })

        if len(doc.getListOfDataDescriptions()) > 0:
            tags_info.append({'type': 'sedml', 'name': 'DataDescription'})

    omex.cleanUp()
    return tags_info
Example #3
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)
    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)
Example #5
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)
Example #6
0
    def listDetailedContents(self):
        """ List contents of the archive from the manifest.xml

        :return: contentList of dictionaries with keys: filename, type
        :rtype: [{}]
        """
        contents = []
        man = self.readManifest()
        xml = et.ElementTree(et.fromstring(man))
        root = xml.getroot()
        for child in root:
            # get content for xml element
            content = None
            attribute = child.attrib
            formtype = attribute.get('format')
            loc = attribute.get('location')
            # sbml
            if formtype == "http://identifiers.org/combine.specifications/sbml":
                if loc.startswith('http') or loc.startswith('www'):
                    content = {'filename': loc, 'type': 'sbml'}
                else:
                    content = {'filename': os.path.basename(loc), 'type': 'sbml'}
            # sedml
            elif formtype == "http://identifiers.org/combine.specifications/sed-ml":
                zf = ZipFile(self.combinePath, 'r')
                try:
                    sedmlRaw = zf.read(loc)
                except KeyError as e:
                    try:
                        sedmlRaw = zf.read(os.path.basename(loc))
                    except KeyError as e:
                        raise e
                sedmlDoc = libsedml.readSedMLFromString(sedmlRaw)
                tempSedmlSource = []
                for model in sedmlDoc.getListOfModels():
                    if os.path.splitext(os.path.basename(model.getSource()))[1] == '':
                        pass
                    else:
                        tempSedmlSource.append(os.path.basename(model.getSource()))
                content = {'filename': os.path.basename(loc), 
                           'type': 'sedml', 
                           'modelsource': tempSedmlSource}
                zf.close()
            # manifest
            elif formtype == "http://identifiers.org/combine.specifications/omex-manifest":
                content = {'filename': os.path.basename(loc), 'type': 'manifest'}
            # other formats
            elif formtype == "image/png":
                content = {'filename': os.path.basename(loc), 'type': 'png'}
            elif formtype == "image/jpg" or formtype == "image/jpeg":
                content = {'filename': os.path.basename(loc), 'type': 'jpg'}
            elif formtype == "application/pdf":
                content = {'filename': os.path.basename(loc), 'type': 'pdf'}
            elif formtype == "plain/text":
                content = {'filename': os.path.basename(loc), 'type': 'txt'}
            elif formtype == "plain/csv":
                content = {'filename': os.path.basename(loc), 'type': 'csv'}
            elif formtype == "plain/dat":
                content = {'filename': os.path.basename(loc), 'type': 'dat'}
            contents.append(content)
            
        return contents
Example #7
0
    def listDetailedContents(self):
        """ List contents of the archive from the manifest.xml

        :return: contentList of dictionaries with keys: filename, type
        :rtype: [{}]
        """
        contents = []
        man = self.readManifest()
        xml = et.ElementTree(et.fromstring(man))
        root = xml.getroot()
        for child in root:
            # get content for xml element
            content = None
            attribute = child.attrib
            formtype = attribute.get('format')
            loc = attribute.get('location')
            # sbml
            if formtype == "http://identifiers.org/combine.specifications/sbml":
                if loc.startswith('http') or loc.startswith('www'):
                    content = {'filename': loc, 'type': 'sbml'}
                else:
                    content = {
                        'filename': os.path.basename(loc),
                        'type': 'sbml'
                    }
            # sedml
            elif formtype == "http://identifiers.org/combine.specifications/sed-ml":
                zf = ZipFile(self.combinePath, 'r')
                try:
                    sedmlRaw = zf.read(loc)
                except KeyError as e:
                    try:
                        sedmlRaw = zf.read(os.path.basename(loc))
                    except KeyError as e:
                        raise e
                sedmlDoc = libsedml.readSedMLFromString(sedmlRaw)
                tempSedmlSource = []
                for model in sedmlDoc.getListOfModels():
                    if os.path.splitext(os.path.basename(
                            model.getSource()))[1] == '':
                        pass
                    else:
                        tempSedmlSource.append(
                            os.path.basename(model.getSource()))
                content = {
                    'filename': os.path.basename(loc),
                    'type': 'sedml',
                    'modelsource': tempSedmlSource
                }
                zf.close()
            # manifest
            elif formtype == "http://identifiers.org/combine.specifications/omex-manifest":
                content = {
                    'filename': os.path.basename(loc),
                    'type': 'manifest'
                }
            # other formats
            elif formtype == "image/png":
                content = {'filename': os.path.basename(loc), 'type': 'png'}
            elif formtype == "image/jpg" or formtype == "image/jpeg":
                content = {'filename': os.path.basename(loc), 'type': 'jpg'}
            elif formtype == "application/pdf":
                content = {'filename': os.path.basename(loc), 'type': 'pdf'}
            elif formtype == "plain/text":
                content = {'filename': os.path.basename(loc), 'type': 'txt'}
            elif formtype == "plain/csv":
                content = {'filename': os.path.basename(loc), 'type': 'csv'}
            elif formtype == "plain/dat":
                content = {'filename': os.path.basename(loc), 'type': 'dat'}
            if content != None:
                contents.append(content)

        return contents