示例#1
0
    def annotate_sbase(sbase: libsbml.SBase, annotation: Annotation):
        """ Annotate SBase based on given annotation data

        :param sbase: libsbml.SBase
        :param annotation: Annotation
        :return:
        """
        qualifier, resource = annotation.qualifier.value, annotation.resource
        cv = libsbml.CVTerm()  # type: libsbml.CVTerm

        # set correct type of qualifier
        if qualifier.startswith("BQB"):
            cv.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
            sbml_qualifier = ModelAnnotator.get_SBMLQualifier(qualifier)
            cv.setBiologicalQualifierType(sbml_qualifier)
        elif qualifier.startswith('BQM'):
            cv.setQualifierType(libsbml.MODEL_QUALIFIER)
            sbml_qualifier = ModelAnnotator.get_SBMLQualifier(qualifier)
            cv.setModelQualifierType(sbml_qualifier)
        else:
            LOGGER.error('Unsupported qualifier: {}'.format(qualifier))

        cv.addResource(resource)

        # meta id has to be set
        if not sbase.isSetMetaId():
            sbase.setMetaId(utils.create_metaid(sbase))

        success = sbase.addCVTerm(cv)

        if success != 0:
            LOGGER.error("RDF not written: ", success)
            LOGGER.error(libsbml.OperationReturnValue_toString(success))
            LOGGER.error("{}, {}, {}".format(object, qualifier, resource))
示例#2
0
def metaid_html(item: libsbml.SBase) -> str:
    """Create metaid data for the item.

    :param item: SBML object for which metaid data has to be generated
    :return: HTML code fragment enclosing metaid data for item
    """
    if item.isSetMetaId():
        return f"<code>{item.getMetaId()}</code>"
    return ""
示例#3
0
    def annotate_sbase(sbase: libsbml.SBase, annotation: Annotation) -> None:
        """Annotate SBase based on given annotation data.

        :param sbase: libsbml.SBase
        :param annotation: Annotation
        :return:
        """
        qualifier, resource = annotation.qualifier.value, annotation.resource
        cv: libsbml.CVTerm = libsbml.CVTerm()

        # set correct type of qualifier
        if isinstance(qualifier, str):
            if qualifier.startswith("BQB"):
                cv.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
                sbml_qualifier = ModelAnnotator.get_SBMLQualifier(qualifier)
                success = check(
                    cv.setBiologicalQualifierType(str(sbml_qualifier)),
                    f"Set biological qualifier: '{sbml_qualifier}'",
                )
                if success != 0:
                    logger.error(
                        f"Could not set biological qualifier: {qualifier}")
            elif qualifier.startswith("BQM"):
                cv.setQualifierType(libsbml.MODEL_QUALIFIER)
                sbml_qualifier = ModelAnnotator.get_SBMLQualifier(qualifier)
                success = check(
                    cv.setModelQualifierType(str(sbml_qualifier)),
                    f"Set model qualifier: '{sbml_qualifier}'",
                )
                if success != 0:
                    logger.error(f"Could not set model qualifier: {qualifier}")
            else:
                logger.error(f"Unsupported qualifier: '{qualifier}'")
        else:
            msg = (f"qualifier is not a string, but: '{qualifier}' of type "
                   f"'{type(qualifier)}'.")
            logger.error(msg)
            raise ValueError(msg)

        success = check(cv.addResource(resource),
                        f"Add resource: '{resource}'")
        if success != 0:
            logger.error(f"Could not add resource: {resource}")

        # meta id has to be set
        if not sbase.isSetMetaId():
            sbase.setMetaId(utils.create_metaid(sbase))

        success = sbase.addCVTerm(cv)

        if success != 0:
            logger.error(
                f"Annotation RDF for CVTerm could not be written: {cv}")
            logger.error(libsbml.OperationReturnValue_toString(success))
            logger.error(f"{sbase}, {qualifier}, {resource}")
示例#4
0
    def _get_pk(sbase: libsbml.SBase) -> str:
        """Calculate primary key."""

        if not hasattr(sbase, "pk"):
            pk: str = f"{SBMLDocumentInfo._sbml_type(sbase)}:"
            if sbase.isSetId():
                pk += sbase.getId()
            elif sbase.isSetMetaId():
                pk += sbase.getMetaId()
            else:
                xml = sbase.toSBML()
                pk += SBMLDocumentInfo._uuid(xml)
            sbase.pk = pk

        return pk
示例#5
0
    def sbase_dict(cls, sbase: libsbml.SBase) -> Dict[str, Any]:
        """Info dictionary for SBase.

        :param sbase: SBase instance for which info dictionary is to be created
        :return info dictionary for item
        """
        pk = cls._get_pk(sbase)
        d = {
            "pk": pk,
            "sbmlType": cls._sbml_type(sbase),
            "id": sbase.getId() if sbase.isSetId() else None,
            "metaId": sbase.getMetaId() if sbase.isSetMetaId() else None,
            "name": sbase.getName() if sbase.isSetName() else None,
            "sbo": sbase.getSBOTermID() if sbase.isSetSBOTerm() else None,
            "cvterms": cls.cvterms(sbase),
            "history": cls.model_history(sbase),
            "notes": sbase.getNotesString() if sbase.isSetNotes() else None,
        }

        # TODO: add the ports information

        if sbase.getTypeCode() in {libsbml.SBML_DOCUMENT, libsbml.SBML_MODEL}:
            d["xml"] = None
        else:
            d["xml"] = sbase.toSBML()

        # comp
        item_comp = sbase.getPlugin("comp")
        if item_comp and type(item_comp) == libsbml.CompSBasePlugin:
            # ReplacedBy
            if item_comp.isSetReplacedBy():
                replaced_by = item_comp.getReplacedBy()
                submodel_ref = replaced_by.getSubmodelRef()
                d["replacedBy"] = {
                    "submodelRef": submodel_ref,
                    "replacedBySbaseref": cls._sbaseref(replaced_by),
                }
            else:
                d["replacedBy"] = None

            # ListOfReplacedElements
            if item_comp.getNumReplacedElements() > 0:
                replaced_elements = []
                for rep_el in item_comp.getListOfReplacedElements():
                    submodel_ref = rep_el.getSubmodelRef()
                    replaced_elements.append({
                        "submodelRef":
                        submodel_ref,
                        "replacedElementSbaseref":
                        cls._sbaseref(rep_el),
                    })

                d["replacedElements"] = replaced_elements
            else:
                d["replacedElements"] = None

        # distrib
        sbml_distrib: libsbml.DistribSBasePlugin = sbase.getPlugin("distrib")
        if sbml_distrib and isinstance(sbml_distrib,
                                       libsbml.DistribSBasePlugin):
            d["uncertainties"] = []
            for uncertainty in sbml_distrib.getListOfUncertainties():
                u_dict = SBMLDocumentInfo.sbase_dict(uncertainty)

                u_dict["uncertaintyParameters"] = []
                upar: libsbml.UncertParameter
                for upar in uncertainty.getListOfUncertParameters():
                    param_dict = {
                        "var":
                        upar.getVar() if upar.isSetVar() else None,
                        "value":
                        upar.getValue() if upar.isSetValue() else None,
                        "units":
                        upar.getUnits() if upar.isSetUnits() else None,
                        "type":
                        upar.getTypeAsString() if upar.isSetType() else None,
                        "definitionURL":
                        upar.getDefinitionURL()
                        if upar.isSetDefinitionURL() else None,
                        "math":
                        astnode_to_latex(upar.getMath())
                        if upar.isSetMath() else None,
                    }

                    u_dict["uncertaintyParameters"].append(param_dict)

                d["uncertainties"].append(u_dict)

        return d