Example #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))
Example #2
0
def check(value, message):
    """
    Checks the libsbml return value and prints message if something happened.

    If 'value' is None, prints an error message constructed using
      'message' and then exits with status code 1. If 'value' is an integer,
      it assumes it is a libSBML return status code. If the code value is
      LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
      prints an error message constructed using 'message' along with text from
      libSBML explaining the meaning of the code, and exits with status code 1.

    """
    if value is None:
        logging.error('Error: LibSBML returned a null value trying to <' +
                      message + '>.')
    elif type(value) is int:
        if value == libsbml.LIBSBML_OPERATION_SUCCESS:
            return
        else:
            logging.error('Error encountered trying to <' + message + '>.')
            logging.error('LibSBML returned error code {}: {}'.format(
                str(value),
                libsbml.OperationReturnValue_toString(value).strip()))
    else:
        return
Example #3
0
    def _checklibSBML(self, value, message):
        """Private function that checks the libSBML calls.

        Check that the libSBML python calls do not return error INT and if so, display the error. Taken from: http://sbml.org/Software/libSBML/docs/python-api/create_simple_model_8py-example.html

        :param value: The libSBML command returned int
        :param message: The string that describes the call

        :type value: int
        :type message: str

        :raises AttributeError: If the libSBML command encounters an error or the input value is None

        :return: None
        :rtype: None
        """
        if value is None:
            self.logger.error('LibSBML returned a null value trying to ' +
                              message + '.')
            raise AttributeError
        elif type(value) is int:
            if value == libsbml.LIBSBML_OPERATION_SUCCESS:
                return
            else:
                err_msg = 'Error encountered trying to ' + message + '.' \
                        + 'LibSBML returned error code ' + str(value) + ': "' \
                        + libsbml.OperationReturnValue_toString(value).strip() + '"'
                self.logger.error(err_msg)
                raise AttributeError
        else:
            return None
Example #4
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}")
Example #5
0
def check(value, message):
    """
    If 'value' is None, logs an error message constructed using 'message'.
    If 'value' is an integer, it assumes it is a libSBML return status code.
    If the code value is LIBSBML_OPERATION_SUCCESS, returns without further action;
    if it is not, logs an error message constructed using 'message' along with text from
    libSBML explaining the meaning of the code.
    """
    if value is None:
        logging.error('LibSBML returned a null value trying to %s.' % message)
    elif type(value) is int and value != libsbml.LIBSBML_OPERATION_SUCCESS:
        logging.error('Error encountered trying to %s. LibSBML returned error code %s: "%s".'
                      % (message, value, libsbml.OperationReturnValue_toString(value).strip()))
Example #6
0
 def check(self, value, message):
     if value == None:
         raise SystemExit('LibSBML returned a null value trying to ' + \
                 message + '.')
     elif type(value) is int:
         if value == libsbml.LIBSBML_OPERATION_SUCCESS:
             return
         else:
             err_msg = 'Error trying to ' + message + '.' \
             + 'LibSBML returned error code ' + str(value) + ': "'\
             + libsbml.OperationReturnValue_toString(value).strip() + '"'
         raise SystemExit(err_msg)
     else:
         return
Example #7
0
def _check(value):
    """
    Validate a libsbml return value

    Raises ValueError if 'value' is a libsbml error code or None.
    """
    if type(value) is int and value != libsbml.LIBSBML_OPERATION_SUCCESS:
        raise ValueError(
            'Error encountered converting to SBML. '
            'LibSBML returned error code {}: "{}"'.format(
                value,
                libsbml.OperationReturnValue_toString(value).strip()))
    elif value is None:
        raise ValueError('LibSBML returned a null value')
Example #8
0
 def _checklibSBML(self, value, message):
     if value is None:
         self.logger.error('LibSBML returned a null value trying to ' + message + '.')
         raise SystemExit('LibSBML returned a null value trying to ' + message + '.')
     elif type(value) is int:
         if value==libsbml.LIBSBML_OPERATION_SUCCESS:
             return
         else:
             err_msg = 'Error encountered trying to ' + message + '.' \
                     + 'LibSBML returned error code ' + str(value) + ': "' \
                     + libsbml.OperationReturnValue_toString(value).strip() + '"'
             self.logger.error(err_msg)
             raise SystemExit(err_msg)
     else:
         #self.logger.info(message)
         return None
Example #9
0
def check(value, message):
    """If 'value' is None, prints an error message constructed using
    'message' and then exits with status code 1.  If 'value' is an integer,
    it assumes it is a libSBML return status code.  If the code value is
    LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
    prints an error message constructed using 'message' along with text from
    libSBML explaining the meaning of the code, and exits with status code 1.
    """
    if value == None:
        raise SystemExit('LibSBML returned a null value trying to ' + message + '.')
    elif type(value) is int:
        if value == libsbml.LIBSBML_OPERATION_SUCCESS:
            return
        else:
            err_msg = 'Error encountered trying to ' + message + '.' \
                 + 'LibSBML returned error code ' + str(value) + ': "' \
                 + libsbml.OperationReturnValue_toString(value).strip() + '"'
            raise TypeError(err_msg)
    else:
        return
def check(value, message):
    """If 'value' is None, prints an error message constructed using
    'message' and then exits with status code 1.  If 'value' is an integer,
    it assumes it is a libSBML return status code.  If the code value is
    LIBSBML_OPERATION_SUCCESS, returns without further action; if it is not,
    prints an error message constructed using 'message' along with text from
    libSBML explaining the meaning of the code, and exits with status code 1. """
    if value == None:
        err_msg = "Error processing libSBML returned a null value trying to {}".format(
            message)
        raise SystemExit(err_msg)
    elif type(value) is int:
        if value == libsbml.LIBSBML_OPERATION_SUCCESS:
            return
        else:
            err_msg = 'Error processing trying to {} libSBML returned error code {} : "{}"'.format(
                message, value,
                libsbml.OperationReturnValue_toString(value).strip())
            raise SystemExit(err_msg)
    else:
        return
Example #11
0
def Check(Value, Message):
    "Check Code"
    # If 'value' is None, prints an error message constructed using   
    # 'message' and then exits with status code 1.
    # If 'value' is an integer, it assumes it is a libSBML return status code.  
    # If the code value is LIBSBML_OPERATION_SUCCESS, 
    # returns without further action; if it is not,
    # prints an error message constructed using 'message' along with text from   
    #libSBML explaining the meaning of the code, and exits with status code 1.     
    if Value == None:
        raise SystemExit('LibSBML returned a null value trying to ' + Message + '.')   
    elif type(Value) is int:
        if Value == libsbml.LIBSBML_OPERATION_SUCCESS:
            return
        else:
            ErrorMessage = 'Error encountered trying to ' + Message + '.' + 'LibSBML returned error code ' + str(Value) + ': "' + libsbml.OperationReturnValue_toString(Value).strip() + '"'       
            raise SystemExit(ErrorMessage)
    else:
        return
Example #12
0
    def call_libsbml(cls, method, *args, returns_int=False, debug=False):
        """ Call a libSBML method and handle any errors.

        Unfortunately, libSBML methods that do not return data usually report errors via return codes,
        instead of exceptions, and the generic return codes contain virtually no information.
        This function wraps these methods and raises useful exceptions when errors occur.

        Set `returns_int` `True` to avoid raising false exceptions or warnings from methods that return
        integer values.

        Args:
            method (:obj:`type`, :obj:`types.FunctionType`, or :obj:`types.MethodType`): `libsbml` method to execute
            args (:obj:`list`): a `list` of arguments to the `libsbml` method
            returns_int (:obj:`bool`, optional): whether the method returns an integer; if `returns_int`
                is `True`, then an exception will not be raised if the method call returns an integer
            debug (:obj:`bool`, optional): whether to print debug output

        Returns:
            :obj:`obj` or `int`: if the call does not return an error, return the `libsbml`
                method's return value, either an object that has been created or retrieved, or an integer
                value, or the `libsbml` success return code, :obj:`libsbml.LIBSBML_OPERATION_SUCCESS`

        Raises:
            :obj:`LibSbmlError`: if the `libsbml` call raises an exception, or returns None, or
                returns a known integer error code != :obj:`libsbml.LIBSBML_OPERATION_SUCCESS`
        """
        new_args = []
        for arg in args:
            new_args.append(arg)
        if new_args:
            new_args_str = ', '.join([str(a) for a in new_args])
            call_str = "method: {}; args: {}".format(method, new_args_str)
        else:
            call_str = "method: {}".format(method)
        if debug:
            print('libSBML call:', call_str)
        try:
            rc = method(*tuple(new_args))
        except BaseException as error:
            raise LibSbmlError(
                "Error '{}' in libSBML method call '{}'.".format(
                    error, call_str))
        if rc == None:
            raise LibSbmlError(
                "libSBML returned None when executing '{}'.".format(call_str))
        elif type(rc) is int:
            # if `method` returns an int value, do not interpret rc as an error code
            if returns_int:
                if debug:
                    print('libSBML returns an int:', rc)
                return rc

            if rc == libsbml.LIBSBML_OPERATION_SUCCESS:
                if debug:
                    print('libSBML returns: LIBSBML_OPERATION_SUCCESS')
                return rc
            else:
                error_code = libsbml.OperationReturnValue_toString(rc)
                if error_code is None:
                    if debug:
                        print("libSBML returns:", rc)
                    warnings.warn(
                        "call_libsbml: unknown error code {} returned by '{}'."
                        "\nPerhaps an integer value is being returned; if so, to avoid this warning "
                        "pass 'returns_int=True' to call_libsbml().".format(
                            error_code, call_str), wc_lang.core.WcLangWarning)
                    return rc
                else:
                    raise LibSbmlError(
                        "LibSBML returned error code '{}' when executing '{}'."
                        "\nWARNING: if this libSBML call returns an int value, then this error may be "
                        "incorrect; to avoid this error pass 'returns_int=True' to call_libsbml()."
                        .format(error_code, call_str))
        else:
            # return data provided by libSBML method
            if debug:
                print('libSBML returns:', rc)
            return rc
Example #13
0
def convertSBML2EML(
        aSBMLString,
        anODEStepper="ODEStepper",
        aFixedODEStepper='FixedODE1Stepper',
        aDiscreteStepper='DiscreteTimeStepper'):  ## 'PassiveStepper'

    theDefaultStepperID = 'Default'
    theDefaultODEStepperID = 'ODE'
    theDefaultDiscreteStepperID = 'Discrete'

    Steppers = dict(ODE=anODEStepper,
                    FixedODE=aFixedODEStepper,
                    Discrete=aDiscreteStepper)

    StepperIDs = dict(default=theDefaultStepperID,
                      ODE=theDefaultODEStepperID,
                      Discrete=theDefaultDiscreteStepperID)

    aSBMLDocument = libsbml.readSBMLFromString(aSBMLString)

    # ------------------------------
    #  Function Definition Converter
    # ------------------------------

    theFunctionDefinitionConverter = libsbml.SBMLFunctionDefinitionConverter()
    theFunctionDefinitionConverter.setDocument(aSBMLDocument)
    print "    FunctionDefinitionConverter: %s" % \
        libsbml.OperationReturnValue_toString( theFunctionDefinitionConverter.convert() )

    # ------------------------------
    #  Initial Assignment Converter
    # ------------------------------

    theInitialAssignmentConverter = libsbml.SBMLInitialAssignmentConverter()
    theInitialAssignmentConverter.setDocument(aSBMLDocument)
    print "    InitialAssignmentConverter:  %s" % \
        libsbml.OperationReturnValue_toString( theInitialAssignmentConverter.convert() )

    ## FIXME: theInitialAssignmentConverter.convert() always returns None.

    aSBMLModel = aSBMLDocument.getModel()

    ##    theUndetermined =

    theModel = SBML_Model(aSBMLDocument, aSBMLModel)
    theCompartment = SBML_Compartment(theModel)
    theParameter = SBML_Parameter(theModel)
    theSpecies = SBML_Species(theModel)
    theRule = SBML_Rule(theModel)
    theReaction = SBML_Reaction(theModel)
    theEvent = SBML_Event(theModel)

    ##    # dump FunctionDefinition
    ##    print "\n"
    ##    for aFunctionDefinition in theModel.FunctionDefinitionList:
    ##        print "FunctionDefinition: %s\n" % str( aFunctionDefinition )

    anEml = Eml()

    set_Steppers(theModel, anEml, Steppers, StepperIDs)
    set_Compartments(theCompartment, anEml, StepperIDs)
    set_GlobalParameters(theParameter, anEml, StepperIDs)
    set_Species(theSpecies, anEml)
    set_Rules(theRule, anEml, StepperIDs)
    set_Reactions(theReaction, anEml, StepperIDs)
    set_Events(theEvent, anEml, StepperIDs)

    return anEml