Exemplo n.º 1
0
def annotate_Karr():
    """
    Annotations of the original Karr SBML file and conversion to SBML L3V1.
    This takes the model and writes all the additional information to it.
    """
    validate_sbml(sbml_raw, ucheck=False)

    # read model
    doc = readSBML(sbml_raw)
    doc.setLevelAndVersion(2, 4, False, True)
    # write id and name
    m = doc.getModel()
    mid = 'Metabolism_annotated_{}'.format(VERSION)
    m.setId(mid)
    m.setName(mid)
    # annotate
    
    annotate_model_cv(m)
    annotate_model_sbo(m)
    set_model_history(m)

    # save
    writeSBMLToFile(doc, sbml_out)
    validate_sbml(sbml_out)
    
    # convert to 3.1
    convert = True
    if convert:
        props = ConversionProperties()
        props.addOption("convert cobra", True, "Convert Cobra model")
        check(doc.convert(props), 'Convert COBRA')
        writeSBMLToFile(doc, sbml_out_L3V1)
        validate_sbml(sbml_out_L3V1, ucheck=False)
Exemplo n.º 2
0
def flattenSBMLFile(sbml_path,
                    leave_ports=True,
                    output_path=None,
                    suffix='_flat'):
    """ Flatten given SBML file.

    :param sbml_path:
    :param leave_ports:
    :param output_path:
    :param suffix to add to model id
    :return:
    """
    # necessary to change the working directory to the sbml file directory
    # to resolve relative links to external model definitions.
    working_dir = os.getcwd()
    sbml_dir = os.path.dirname(sbml_path)
    os.chdir(sbml_dir)

    reader = libsbml.SBMLReader()
    check(reader, 'create an SBMLReader object.')
    doc = reader.readSBML(sbml_path)
    flat_doc = flattenSBMLDocument(doc,
                                   leave_ports=leave_ports,
                                   output_path=output_path,
                                   suffix=suffix)

    # change back the working dir
    os.chdir(working_dir)

    return flat_doc
Exemplo n.º 3
0
 def set_kinetic_law(model, reaction, formula):
     """ Sets the kinetic law in reaction based on given formula. """
     law = reaction.createKineticLaw()
     ast_node = libsbml.parseL3FormulaWithModel(formula, model)
     if ast_node is None:
         logging.error(libsbml.getLastParseL3Error())
     check(law.setMath(ast_node), 'set math in kinetic law')
     return law
Exemplo n.º 4
0
 def set_kinetic_law(model, reaction, formula):
     """ Sets the kinetic law in reaction based on given formula. """
     law = reaction.createKineticLaw()
     ast_node = libsbml.parseL3FormulaWithModel(formula, model)
     if ast_node is None:
         logging.error(libsbml.getLastParseL3Error())
     check(law.setMath(ast_node), 'set math in kinetic law')
     return law
Exemplo n.º 5
0
def set_notes(model, notes):
    """ Set notes information on model.

    :param model: Model
    :param notes: notes information (xml string)
    :return:
    """
    if not isinstance(notes, Notes):
        logging.error("Using notes strings is deprecated, use 'Notes' instead.")
        notes = Notes(notes)

    check(model.setNotes(notes.xml), message="Setting notes on model")
Exemplo n.º 6
0
def set_notes(model, notes):
    """ Set notes information on model.

    :param model: Model
    :param notes: notes information (xml string)
    :return:
    """
    if not isinstance(notes, Notes):
        logging.error("Using notes strings is deprecated, use 'Notes' instead.")
        notes = Notes(notes)

    check(model.setNotes(notes.xml), message="Setting notes on model")
Exemplo n.º 7
0
    def set_fields(self, obj: libsbml.Constraint, model: libsbml.Model):
        """ Set fields on given object.

        :param obj: constraint
        :param model: libsbml.Model instance
        :return:
        """
        super(Constraint, self).set_fields(obj)

        if self.math is not None:
            ast_math = libsbml.parseL3FormulaWithModel(self.math, model)
            obj.setMath(ast_math)
        if self.message is not None:
            check(obj.setMessage(self.message), message="Setting message on constraint: '{}'".format(self.message))
Exemplo n.º 8
0
    def set_fields(self, obj: libsbml.Constraint, model: libsbml.Model):
        """ Set fields on given object.

        :param obj: constraint
        :param model: libsbml.Model instance
        :return:
        """
        super(Constraint, self).set_fields(obj)

        if self.math is not None:
            ast_math = libsbml.parseL3FormulaWithModel(self.math, model)
            obj.setMath(ast_math)
        if self.message is not None:
            check(obj.setMessage(self.message), message="Setting message on constraint: '{}'".format(self.message))
Exemplo n.º 9
0
def set_model_history(model: libsbml.Model, creators) -> None:
    """Sets the model history from given creators.

    :param model: SBML model
    :param creators: list of creators
    :return None
    """
    if not model.isSetMetaId():
        model.setMetaId(create_metaid(sbase=model))

    if (creators is None) or (len(creators) == 0):
        # at least on
        return
    else:
        # create and set model history
        h = _create_history(creators)
        check(model.setModelHistory(h), "set model history")
Exemplo n.º 10
0
def set_model_history(model, creators):
    """ Sets the model history from given creators.

    :param model: SBML model
    :type model: libsbml.Model
    :param creators: list of creators
    :type creators:
    """
    if not model.isSetMetaId():
        model.setMetaId(create_metaid(sbase=model))

    if creators is None or len(creators) is 0:
        # at least on
        return
    else:
        # create and set model history
        h = _create_history(creators)
        check(model.setModelHistory(h), 'set model history')
Exemplo n.º 11
0
def set_model_history(model, creators):
    """ Sets the model history from given creators.

    :param model: SBML model
    :type model: libsbml.Model
    :param creators: list of creators
    :type creators:
    """
    if not model.isSetMetaId():
        model.setMetaId(create_metaid(sbase=model))

    if creators is None or len(creators) is 0:
        # at least on
        return
    else:
        # create and set model history
        h = _create_history(creators)
        check(model.setModelHistory(h), 'set model history')
Exemplo n.º 12
0
def set_cv_terms(model, cvterms_df):
    """ Set model cv terms from DataFrame. """
    from annotation import create_meta_id
    if not model.isSetMetaId():
        model.setMetaId(create_meta_id(model.getId()))

    # write all the annotations
    for index, row in cvterms_df.iterrows():
        qualifier = row.Qualifier
        qualifier_type = row.QualifierType
        resource = row.Resource

        cv = CVTerm()
        cv.setQualifierType(qualifier)
        if row.Qualifier == MODEL_QUALIFIER:
            cv.setModelQualifierType(qualifier_type)
        elif row.Qualifier == BIOLOGICAL_QUALIFIER:
            cv.setBiologicalQualifierType(qualifier_type)
        cv.addResource(resource)
        check(model.addCVTerm(cv), 'add cv term')
Exemplo n.º 13
0
def _create_history(creators):
    """ Creates the model history.

    Sets the create and modified date to the current time.
    Creators are a list or dictionary with values as
    """
    h = libsbml.ModelHistory()

    if isinstance(creators, dict):
        values = creators.values()
    else:
        values = creators

    # add all creators
    for creator in values:
        c = libsbml.ModelCreator()
        if creator.familyName:
            c.setFamilyName(creator.familyName)
        if creator.givenName:
            c.setGivenName(creator.givenName)
        if creator.email:
            c.setEmail(creator.email)
        if creator.organization:
            c.setOrganization(creator.organization)
        check(h.addCreator(c), 'add creator')

    # create time is now
    date = date_now()
    check(h.setCreatedDate(date), 'set creation date')
    check(h.setModifiedDate(date), 'set modified date')
    return h
Exemplo n.º 14
0
def _create_history(creators):
    """ Creates the model history.

    Sets the create and modified date to the current time.
    Creators are a list or dictionary with values as
    """
    h = libsbml.ModelHistory()

    if isinstance(creators, dict):
        values = creators.values()
    else:
        values = creators

    # add all creators
    for creator in values:
        c = libsbml.ModelCreator()
        if creator.familyName:
            c.setFamilyName(creator.familyName)
        if creator.givenName:
            c.setGivenName(creator.givenName)
        if creator.email:
            c.setEmail(creator.email)
        if creator.organization:
            c.setOrganization(creator.organization)
        check(h.addCreator(c), 'add creator')

    # create time is now
    date = date_now()
    check(h.setCreatedDate(date), 'set creation date')
    check(h.setModifiedDate(date), 'set modified date')
    return h
Exemplo n.º 15
0
def flattenSBMLFile(sbml_path, leave_ports=True, output_path=None, suffix='_flat'):
    """ Flatten given SBML file.

    :param sbml_path:
    :param leave_ports:
    :param output_path:
    :param suffix to add to model id
    :return:
    """
    # necessary to change the working directory to the sbml file directory
    # to resolve relative links to external model definitions.
    working_dir = os.getcwd()
    sbml_dir = os.path.dirname(sbml_path)
    os.chdir(sbml_dir)

    reader = libsbml.SBMLReader()
    check(reader, 'create an SBMLReader object.')
    doc = reader.readSBML(sbml_path)
    flat_doc = flattenSBMLDocument(doc, leave_ports=leave_ports, output_path=output_path, suffix=suffix)

    # change back the working dir
    os.chdir(working_dir)

    return flat_doc
Exemplo n.º 16
0
def annotate_objects(objects, o_df, o_cvdf, otype):
    # Metabolite annotation
    # no fancy things here: just take the ids of the species
    # and look up existing annotations. Than write the CV terms
    # from the defined list above.
    
    for s in objects:        
        sid = s.getId()
        
        if otype == 'SPECIES':
            cid = cid_from_sid(sid)
        elif otype == 'REACTION':
            cid = cid_from_rid(sid)
        print('***', sid, '->', cid, '***')
        
        # WTF - not working without meta id, but no proper warning
        # TODO: how to properly generate meta ids
        s.setMetaId(create_meta_id(sid))
        
        # get the annotation info & create all CV terms
        # check if in index
        if not cid in o_df.index:
            pass
            # print cid, 'not in annotation data'
        else:
            
            for cv_type in o_cvdf.ID:   
                cv_id = o_df.loc[cid, cv_type]

                # check the NaN in table
                if pd.isnull(cv_id):                    
                    # print cid, 'no id available'
                    continue
                
                # create cv term                                
                qt = int(o_cvdf.loc[cv_type, 'BQB'])
                bqt = int(o_cvdf.loc[cv_type, 'Qualifier'])
                uri = '{}{}'.format(o_cvdf.loc[cv_type, 'URI'], cv_id)
                print(qt, bqt, uri)
                
                cv = CVTerm()
                check(cv.setQualifierType(qt), 'setQualifier')
                check(cv.setBiologicalQualifierType(bqt), 'setQualifierType')
                check(cv.addResource(uri), 'setURI')
                check(s.addCVTerm(cv), 'addCVTerm')
Exemplo n.º 17
0
def _create_history(creators: Union[List[Any], Dict[Any, Any]],
                    set_timestamps: bool = False) -> libsbml.ModelHistory:
    """Create the model history.

    Sets the create and modified date to the current time.
    Creators are a list or dictionary with values as

    :param creators:
    :param set_timestamps:
    :return:
    """
    h = libsbml.ModelHistory()

    items: List[Any]
    if isinstance(creators, dict):
        items = list(creators.values())
    else:
        items = creators

    # add all creators
    for creator in items:
        c = libsbml.ModelCreator()
        if creator.familyName:
            c.setFamilyName(creator.familyName)
        if creator.givenName:
            c.setGivenName(creator.givenName)
        if creator.email:
            c.setEmail(creator.email)
        if creator.organization:
            c.setOrganization(creator.organization)
        check(h.addCreator(c), "add creator")

    # create time is now
    if set_timestamps:
        datetime = date_now()
    else:
        datetime = libsbml.Date("1900-01-01T00:00:00")
    check(h.setCreatedDate(datetime), "set creation date")
    check(h.setModifiedDate(datetime), "set modified date")

    return h
Exemplo n.º 18
0
def uncertainty() -> libsbml.SBMLDocument:
    """Create uncertainty with UncertParameter."""
    doc: libsbml.SBMLDocument = _distrib_doc()
    model: libsbml.Model = doc.createModel()

    # parameter
    p: libsbml.Parameter = _create_parameter("p1", model=model)
    p_distrib: libsbml.DistribSBasePlugin = p.getPlugin("distrib")

    # --------------------------------------------
    # Build generic uncertainty for parameter
    # --------------------------------------------
    # 5.0 (mean) +- 0.3 (std) [2.0 - 8.0]

    uncertainty: libsbml.Uncertainty = p_distrib.createUncertainty()
    uncertainty.setName("Basic example: 5.0 +- 0.3 [2.0 - 8.0]")
    unit = libsbml.UnitKind_toString(libsbml.UNIT_KIND_MOLE)
    up_mean: libsbml.UncertParameter = uncertainty.createUncertParameter()
    up_mean.setType(libsbml.DISTRIB_UNCERTTYPE_MEAN)
    up_mean.setValue(5.0)
    up_mean.setUnits(unit)

    up_sd: libsbml.UncertParameter = uncertainty.createUncertParameter()
    up_sd.setType(libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION)
    up_sd.setValue(0.3)
    up_sd.setUnits(unit)

    up_range = libsbml.UncertSpan()
    up_range.setType(libsbml.DISTRIB_UNCERTTYPE_RANGE)
    up_range.setValueLower(2.0)
    up_range.setValueUpper(8.0)
    up_range.setUnits(unit)
    check(uncertainty.addUncertParameter(up_range), "add the span")

    check(
        uncertainty.setAnnotation(
            """
    <body xmlns='http://www.w3.org/1999/xhtml'>
        <p>Experimental data from study</p>
    </body>
    """
        ),
        "set annotations",
    )

    # add an annotation with SBO terms
    uncertainty.setMetaId("meta_uncertainty1")
    cv1 = libsbml.CVTerm()
    cv1.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
    cv1.setBiologicalQualifierType(6)  # "BQB_IS_DESCRIBED_BY"
    cv1.addResource("https://identifiers.org/pubmed/123456")
    check(uncertainty.addCVTerm(cv1), "add cv term")

    cv2 = libsbml.CVTerm()
    cv2.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
    cv2.setBiologicalQualifierType(10)  # "BQB_HAS_PROPERTY"
    cv2.addResource("http://purl.obolibrary.org/obo/ECO_0006016")
    check(uncertainty.addCVTerm(cv2), "add cv term")

    # --------------------------------------------
    # Set of all UncertParameters
    # --------------------------------------------
    # create second uncertainty which contains all the individual uncertainties
    uncertainty = p_distrib.createUncertainty()
    uncertainty.setName("UncertParameter example")
    for k, parameter_type in enumerate(
        [
            libsbml.DISTRIB_UNCERTTYPE_COEFFIENTOFVARIATION,
            libsbml.DISTRIB_UNCERTTYPE_KURTOSIS,
            libsbml.DISTRIB_UNCERTTYPE_MEAN,
            libsbml.DISTRIB_UNCERTTYPE_MEDIAN,
            libsbml.DISTRIB_UNCERTTYPE_MODE,
            libsbml.DISTRIB_UNCERTTYPE_SAMPLESIZE,
            libsbml.DISTRIB_UNCERTTYPE_SKEWNESS,
            libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION,
            libsbml.DISTRIB_UNCERTTYPE_STANDARDERROR,
            libsbml.DISTRIB_UNCERTTYPE_VARIANCE,
        ]
    ):

        up: libsbml.UncertParameter = uncertainty.createUncertParameter()
        up.setType(parameter_type)
        up.setValue(k)
        up.setUnits(unit)

    # --------------------------------------------
    # Set of all UncertSpans
    # --------------------------------------------
    uncertainty = p_distrib.createUncertainty()
    uncertainty.setName("UncertSpan example")
    for k, parameter_type in enumerate(
        [
            libsbml.DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL,
            libsbml.DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL,
            libsbml.DISTRIB_UNCERTTYPE_INTERQUARTILERANGE,
            libsbml.DISTRIB_UNCERTTYPE_RANGE,
        ]
    ):

        up_range = libsbml.UncertSpan()
        up_range.setType(parameter_type)
        up_range.setValueLower(k - 1.0)
        up_range.setValueUpper(k + 1.0)
        up_range.setUnits(unit)
        check(uncertainty.addUncertParameter(up_range), "add the span")

    # --------------------------------------------
    # Use math for distribution definition
    # --------------------------------------------
    # 5.0 dimensionless * normal(1.0 mole, 3.0 mole)
    uncertainty = p_distrib.createUncertainty()
    uncertainty.setName("math example: 5.0 dimensionless * normal(1.0 mole, 3.0 mole)")
    up = uncertainty.createUncertParameter()
    up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION)
    up.setDefinitionURL("http://www.sbml.org/sbml/symbols/distrib/normal")
    ast = libsbml.parseL3FormulaWithModel(
        "5.0 dimensionless * normal(1.0 mole, 3.0 mole)", model
    )
    if not ast:
        raise ValueError
    up.setMath(ast)

    # --------------------------------------------
    # Use externalParameter
    # --------------------------------------------
    # https://sites.google.com/site/probonto/
    uncertainty = p_distrib.createUncertainty()
    uncertainty.setName("ExternalParameter example")
    up = uncertainty.createUncertParameter()
    up.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER)
    up.setName("skewness")
    up.setValue(0.25)
    up.setUnits(unit)
    up.setDefinitionURL("http://purl.obolibrary.org/obo/STATO_0000068")

    # --------------------------------------------
    # Use external distribution definition
    # --------------------------------------------
    uncertainty = p_distrib.createUncertainty()
    uncertainty.setName("External distribution example")
    up = uncertainty.createUncertParameter()
    up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION)
    up.setName("Geometric 1")
    up.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000782")
    up.setUnits(unit)

    # success probability of Geometric-1
    up_mean_geo1 = up.createUncertParameter()
    up_mean_geo1.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER)
    up_mean_geo1.setName("success probability of Geometric 1")
    up_mean_geo1.setValue(0.4)
    up_mean_geo1.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000789")

    return doc
Exemplo n.º 19
0
def uncertainty():
    """ Create uncertainty with UncertParameter.

    :return:
    """
    doc = _distrib_doc()
    model = doc.createModel()  # type: libsbml.Model

    # parameter
    p = _create_parameter("p1", model=model)  # type: libsbml.Parameter
    p_distrib = p.getPlugin("distrib")  # type: libsbml.DistribSBasePlugin

    # --------------------------------------------
    # Build generic uncertainty for parameter
    # --------------------------------------------
    # 5.0 (mean) +- 0.3 (std) [2.0 - 8.0]

    uncertainty = p_distrib.createUncertainty()  # type: libsbml.Uncertainty
    uncertainty.setName("Basic example: 5.0 +- 0.3 [2.0 - 8.0]")
    unit = libsbml.UnitKind_toString(libsbml.UNIT_KIND_MOLE)
    up_mean = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
    up_mean.setType(libsbml.DISTRIB_UNCERTTYPE_MEAN)
    up_mean.setValue(5.0)
    up_mean.setUnits(unit)

    up_sd = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
    up_sd.setType(libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION)
    up_sd.setValue(0.3)
    up_sd.setUnits(unit)

    # up_range = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
    up_range = libsbml.UncertSpan()
    up_range.setType(libsbml.DISTRIB_UNCERTTYPE_RANGE)
    up_range.setValueLower(2.0)
    up_range.setValueUpper(8.0)
    up_range.setUnits(unit)
    check(uncertainty.addUncertParameter(up_range), "add the span")

    check(uncertainty.setAnnotation("""
    <body xmlns='http://www.w3.org/1999/xhtml'>
        <p>Experimental data from study</p>
    </body>
    """), "set annotations")

    # add an annotation with SBO terms
    uncertainty.setMetaId("meta_uncertainty1")
    cv1 = libsbml.CVTerm()
    cv1.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
    cv1.setBiologicalQualifierType(6)  # "BQB_IS_DESCRIBED_BY"
    cv1.addResource("https://identifiers.org/pubmed/123456")
    check(uncertainty.addCVTerm(cv1), "add cv term")

    cv2 = libsbml.CVTerm()
    cv2.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
    cv2.setBiologicalQualifierType(10)  # "BQB_HAS_PROPERTY"
    cv2.addResource("http://purl.obolibrary.org/obo/ECO_0006016")
    check(uncertainty.addCVTerm(cv2), "add cv term")

    # --------------------------------------------
    # Set of all UncertParameters
    # --------------------------------------------
    # create second uncertainty which contains all the individual uncertainties
    uncertainty = p_distrib.createUncertainty()  # type: libsbml.Uncertainty
    uncertainty.setName("UncertParameter example")
    for k, parameter_type in enumerate([
            libsbml.DISTRIB_UNCERTTYPE_COEFFIENTOFVARIATION,
            libsbml.DISTRIB_UNCERTTYPE_KURTOSIS,
            libsbml.DISTRIB_UNCERTTYPE_MEAN,
            libsbml.DISTRIB_UNCERTTYPE_MEDIAN,
            libsbml.DISTRIB_UNCERTTYPE_MODE,
            libsbml.DISTRIB_UNCERTTYPE_SAMPLESIZE,
            libsbml.DISTRIB_UNCERTTYPE_SKEWNESS,
            libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION,
            libsbml.DISTRIB_UNCERTTYPE_STANDARDERROR,
            libsbml.DISTRIB_UNCERTTYPE_VARIANCE]):

        up = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
        up.setType(parameter_type)
        up.setValue(k)
        up.setUnits(unit)

    # --------------------------------------------
    # Set of all UncertSpans
    # --------------------------------------------
    uncertainty = p_distrib.createUncertainty()  # type: libsbml.Uncertainty
    uncertainty.setName("UncertSpan example")
    for k, parameter_type in enumerate([
            libsbml.DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL,
            libsbml.DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL,
            libsbml.DISTRIB_UNCERTTYPE_INTERQUARTILERANGE,
            libsbml.DISTRIB_UNCERTTYPE_RANGE]):

        up_range = libsbml.UncertSpan()
        up_range.setType(parameter_type)
        up_range.setValueLower(k-1.0)
        up_range.setValueUpper(k+1.0)
        up_range.setUnits(unit)
        check(uncertainty.addUncertParameter(up_range), "add the span")

    # --------------------------------------------
    # Use math for distribution definition
    # --------------------------------------------
    # 5.0 dimensionless * normal(1.0 mole, 3.0 mole)
    uncertainty = p_distrib.createUncertainty()  # type: libsbml.Uncertainty
    uncertainty.setName("math example: 5.0 dimensionless * normal(1.0 mole, 3.0 mole)")
    up = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
    up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION)
    up.setDefinitionURL("http://www.sbml.org/sbml/symbols/distrib/normal")
    ast = libsbml.parseL3FormulaWithModel("5.0 dimensionless * normal(1.0 mole, 3.0 mole)",
                                          model)
    if not ast:
        raise ValueError
    up.setMath(ast)

    # --------------------------------------------
    # Use externalParameter
    # --------------------------------------------
    # https://sites.google.com/site/probonto/
    uncertainty = p_distrib.createUncertainty()  # type: libsbml.Uncertainty
    uncertainty.setName("ExternalParameter example")
    up = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
    up.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER)
    up.setName("skewness")
    up.setValue(0.25)
    up.setUnits(unit)
    up.setDefinitionURL("http://purl.obolibrary.org/obo/STATO_0000068")

    # --------------------------------------------
    # Use external distribution definition
    # --------------------------------------------
    uncertainty = p_distrib.createUncertainty()  # type: libsbml.Uncertainty
    uncertainty.setName("External distribution example")
    up = uncertainty.createUncertParameter()  # type: libsbml.UncertParameter
    up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION)
    up.setName("Geometric 1")
    up.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000782")
    up.setUnits(unit)

    # success probability of Geometric-1
    up_mean_geo1 = up.createUncertParameter()  # type: libsbml.UncertParameter
    up_mean_geo1.setType(libsbml.DISTRIB_UNCERTTYPE_EXTERNALPARAMETER)
    up_mean_geo1.setName("success probability of Geometric 1")
    up_mean_geo1.setValue(0.4)
    up_mean_geo1.setDefinitionURL("http://www.probonto.org/ontology#PROB_k0000789")

    return doc
Exemplo n.º 20
0
    def create_sbml(self, sbase):
        """ Create libsbml Uncertainty.

        :param model:
        :return:
        """
        sbase_distrib = sbase.getPlugin(
            "distrib")  # type: libsbml.DistribSBasePlugin
        uncertainty = sbase_distrib.createUncertainty(
        )  # type: libsbml.Uncertainty

        for uncertParameter in self.uncertParameters:
            up = None
            if uncertParameter.type in [
                    libsbml.DISTRIB_UNCERTTYPE_INTERQUARTILERANGE,
                    libsbml.DISTRIB_UNCERTTYPE_CREDIBLEINTERVAL,
                    libsbml.DISTRIB_UNCERTTYPE_CONFIDENCEINTERVAL,
                    libsbml.DISTRIB_UNCERTTYPE_RANGE,
            ]:

                up = uncertainty.createUncertSpan()  # type: libsbml.UncertSpan
                up.setType(uncertParameter.type)
                if uncertParameter.valueLower is not None:
                    up.setValueLower(uncertParameter.valueLower)
                if uncertParameter.valueUpper is not None:
                    up.setValueUpper(uncertParameter.valueUpper)
                if uncertParameter.varLower is not None:
                    up.setVarLower(uncertParameter.varLower)
                if uncertParameter.varUpper is not None:
                    up.setValueLower(uncertParameter.varUpper)

            elif uncertParameter.type in [
                    libsbml.DISTRIB_UNCERTTYPE_COEFFIENTOFVARIATION,
                    libsbml.DISTRIB_UNCERTTYPE_KURTOSIS,
                    libsbml.DISTRIB_UNCERTTYPE_MEAN,
                    libsbml.DISTRIB_UNCERTTYPE_MEDIAN,
                    libsbml.DISTRIB_UNCERTTYPE_MODE,
                    libsbml.DISTRIB_UNCERTTYPE_SAMPLESIZE,
                    libsbml.DISTRIB_UNCERTTYPE_SKEWNESS,
                    libsbml.DISTRIB_UNCERTTYPE_STANDARDDEVIATION,
                    libsbml.DISTRIB_UNCERTTYPE_STANDARDERROR,
                    libsbml.DISTRIB_UNCERTTYPE_VARIANCE,
            ]:
                up = uncertainty.createUncertParameter(
                )  # type: libsbml.UncertParameter
                up.setType(uncertParameter.type)
                if uncertParameter.value is not None:
                    up.setValue(uncertParameter.value)
                if uncertParameter.var is not None:
                    up.setValue(uncertParameter.var)
            else:
                logging.error(
                    "Unsupported UncertParameter or UncertSpan type: %s",
                    uncertParameter.type)

            if up and uncertParameter.unit:
                up.setUnits(Unit.get_unit_string(uncertParameter.unit))

        # create a distribution uncertainty
        if self.formula:
            model = sbase.getModel()
            up = uncertainty.createUncertParameter(
            )  # type: libsbml.UncertParameter
            up.setType(libsbml.DISTRIB_UNCERTTYPE_DISTRIBUTION)
            for key in [
                    "normal", "uniform", "bernoulli", "binomial", "cauchy",
                    "chisquare", "exponential", "gamma", "laplace",
                    "lognormal", "poisson", "raleigh"
            ]:
                if key in self.formula:
                    up.setDefinitionURL(
                        "http://www.sbml.org/sbml/symbols/distrib/{}".format(
                            key))
                    ast = libsbml.parseL3FormulaWithModel(self.formula, model)
                    if ast is None:
                        logging.error(libsbml.getLastParseL3Error())
                    else:
                        check(up.setMath(ast), 'set math in distrib formula')

        return uncertainty
Exemplo n.º 21
0
def annotate_model_sbo(m):
    from public.models import Entry
    from public.models import Reaction as DBReaction
    from django.core.exceptions import ObjectDoesNotExist
    print('* Annotate SBO *')
    
    sbo_dict = {
            'Compartment': "SBO:0000290",     # physical compartment
            'Metabolite': 'SBO:0000247',      # simple chemical
            'Gene': 'SBO:0000243',            # gene
            'Protein': 'SBO:0000245',         # macromolecule
            'ProteinMonomer': 'SBO:0000245',  # macromolecule
            'ProteinComplex': 'SBO:0000297',  # protein complex
            'Stimulus': 'SBO:0000170',        # stimulation.
    
            'TransportReaction' : 'SBO:0000185',  # transport reaction (find via compartments)
            'Reaction': 'SBO:0000176',            # biochemical reaction
            
            'Modifier': 'SBO:0000019',  # modifier
            'Product': 'SBO:0000011',   # product
            'Reactant': 'SBO:0000010',  # reactant
    }
    
    # compartments
    for c in m.getListOfCompartments():
        sbo_id = sbo_dict['Compartment']
        check(c.setSBOTerm(sbo_id), 'Set SBO')
    
    # species
    for s in m.getListOfSpecies():
        # lookup the Entry in the database
        sid = s.getId()
        wid = cid_from_sid(sid)  # get wid from sid
        # print(sid, "->", wid)
        try:
            e = Entry.objects.get(wid=wid)
            m_type = e.model_type
            sbo_id = sbo_dict[m_type]
            check(s.setSBOTerm(sbo_id), 'Set SBO')
        except ObjectDoesNotExist:
            warnings.warn("Entry not existing in DB, no SBO: {} {}".format(sid, wid))

    # reactions
    for r in m.getListOfReactions():
        # lookup the Entry in the database
        sid = r.getId()
        wid = cid_from_rid(sid)  # get wid from sid
        try:
            e = Entry.objects.get(wid=wid)
            m_type = e.model_type
            if m_type == 'Reaction':
                # check if multiple compartments, than transporter
                reaction = DBReaction.objects.get(wid=wid)
                comps = set([c.compartment for c in reaction.stoichiometry.all()])
                if len(comps) > 1:
                    m_type = 'TransportReaction'
                    
            sbo_id = sbo_dict[m_type]
            check(r.setSBOTerm(sbo_id), 'Set SBO')
        except ObjectDoesNotExist:
            warnings.warn("Entry not existing in DB, no SBO: {} {}".format(sid, wid))
            
        # set the additional information for SpeciesReferences
        for reactant in r.getListOfReactants():
            check(reactant.setSBOTerm(sbo_dict['Reactant']), 'Set SBO')
        for product in r.getListOfProducts():
            check(product.setSBOTerm(sbo_dict['Product']), 'Set SBO')    
        for modifier in r.getListOfModifiers():
            check(modifier.setSBOTerm(sbo_dict['Modifier']), 'Set SBO')
Exemplo n.º 22
0
    def create_sbml(self, sbml_level=SBML_LEVEL, sbml_version=SBML_VERSION):
        """ Create the SBML model

        :return:
        :rtype:
        """
        from sbmlutils.validation import check

        logging.info('*'*40)
        logging.info(self.model_id)
        logging.info('*' * 40)

        # create core model
        sbmlns = libsbml.SBMLNamespaces(sbml_level, sbml_version)

        # add all the packages
        # FIXME: only add packages which are required for the model

        sbmlns.addPackageNamespace("fbc", 2)
        sbmlns.addPackageNamespace("comp", 1)
        # sbmlns.addPackageNamespace("distrib", 1)

        self.doc = libsbml.SBMLDocument(sbmlns)
        self.doc.setPackageRequired("comp", True)
        self.doc.setPackageRequired("fbc", False)
        # self.doc.setPackageRequired("distrib", True)

        self.model = self.doc.createModel()
        fbc_plugin = self.model.getPlugin("fbc")
        fbc_plugin.setStrict(False)

        # name & id
        check(self.model.setId(self.model_id), 'set id')
        check(self.model.setName(self.model_id), 'set name')
        # notes
        if hasattr(self, 'notes') and self.notes is not None:
            factory.set_notes(self.model, self.notes)
        # history
        if hasattr(self, 'creators'):
            history.set_model_history(self.model, self.creators)

        # model units
        if hasattr(self, 'model_units'):
            factory.set_model_units(self.model, self.model_units)

        # lists ofs
        for attr in [
            'externalModelDefinitions',
            'submodels',
            'units',
            'functions',
            'parameters',
            'compartments',
            'species',
            'assignments',
            'rules',
            'rate_rules',
            'reactions',
            'events',
            'constraints',
            'ports',
            'replacedElements',
            'deletions',
            'objectives',
            'layouts'
        ]:
            # create the respective objects
            if hasattr(self, attr):
                objects = getattr(self, attr)
                if objects:
                    factory.create_objects(self.model, obj_iter=objects, key=attr)
                else:
                    logging.warning("Not defined: <{}> ".format(attr))
Exemplo n.º 23
0
import libsbml
from sbmlutils.validation import check

doc = libsbml.SBMLDocument(3, 2)  # type: libsbml.SBMLDocument
model = doc.createModel()  # type: libsbml.Model
p = model.createParameter()  # type: libsbml.Parameter
p.setId("p")

check(p.setAnnotation("""
<body xmlns='http://www.w3.org/1999/xhtml'>
    <p>First annotation</p>
</body>
"""), "set annotations")

# add an annotation with SBO terms
p.setMetaId("meta_uncertainty1")
cv1 = libsbml.CVTerm()
cv1.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
cv1.setBiologicalQualifierType(6)  # "BQB_IS_DESCRIBED_BY"
cv1.addResource("https://identifiers.org/pubmed/123456")
check(p.addCVTerm(cv1), "add cv term")

sbml = libsbml.writeSBMLToString(doc)
print("-" * 80)
print(sbml)
print("-" * 80)

check(p.setAnnotation("""
<body xmlns='http://www.w3.org/1999/xhtml'>
    <p>New annotation.</p>
</body>
Exemplo n.º 24
0
    def create_sbml(self,
                    sbml_level: int = SBML_LEVEL,
                    sbml_version: int = SBML_VERSION) -> libsbml.SBMLDocument:
        """Create the SBML model.

        :return:
        :rtype:
        """

        logger.info(f"create_sbml: '{self.model_id}'")

        # create core model
        sbmlns = libsbml.SBMLNamespaces(sbml_level, sbml_version)

        # add all the packages
        # FIXME: only add packages which are required for the model
        supported_packages = {"fbc", "comp", "distrib"}
        sbmlns.addPackageNamespace("comp", 1)
        for package in self.packages:
            if package not in supported_packages:
                raise ValueError(
                    f"Supported packages are: '{supported_packages}', "
                    f"but package '{package}' found.")
            if package == "fbc":
                sbmlns.addPackageNamespace("fbc", 2)
            if package == "distrib":
                sbmlns.addPackageNamespace("distrib", 1)

        self.doc = libsbml.SBMLDocument(sbmlns)
        self.model = self.doc.createModel()
        self.doc.setPackageRequired("comp", True)
        if "fbc" in self.packages:
            self.doc.setPackageRequired("fbc", False)
            fbc_plugin = self.model.getPlugin("fbc")
            fbc_plugin.setStrict(False)
        if "distrib" in self.packages:
            self.doc.setPackageRequired("distrib", True)

        # name & id
        if self.model_id:
            check(self.model.setId(self.model_id), "set id")
            check(self.model.setName(self.model_id), "set name")
        else:
            logger.warning("Model id 'mid' should be set on model")
        # notes
        if hasattr(self, "notes") and self.notes is not None:
            factory.set_notes(self.model, self.notes)
        # history
        if hasattr(self, "creators"):
            history.set_model_history(self.model, self.creators)

        # model units
        if hasattr(self, "model_units"):
            factory.ModelUnits.set_model_units(
                self.model, self.model_units)  # type: ignore

        # lists ofs
        for attr in [
                "externalModelDefinitions",
                "submodels",
                "units",
                "functions",
                "parameters",
                "compartments",
                "species",
                "assignments",
                "rules",
                "rate_rules",
                "reactions",
                "events",
                "constraints",
                "ports",
                "replacedElements",
                "deletions",
                "objectives",
                "layouts",
        ]:
            # create the respective objects
            if hasattr(self, attr):
                objects = getattr(self, attr)
                if objects:
                    factory.create_objects(self.model,
                                           obj_iter=objects,
                                           key=attr)
                else:
                    logger.debug(f"Not defined: <{attr}>")

        return self.doc
Exemplo n.º 25
0
    def create_sbml(self, sbml_level=SBML_LEVEL, sbml_version=SBML_VERSION):
        """ Create the SBML model

        :return:
        :rtype:
        """
        from sbmlutils.validation import check

        logging.info('*' * 40)
        logging.info(self.model_id)
        logging.info('*' * 40)

        # create core model
        sbmlns = libsbml.SBMLNamespaces(sbml_level, sbml_version)

        # add all the packages
        # FIXME: only add packages which are required for the model

        sbmlns.addPackageNamespace("fbc", 2)
        sbmlns.addPackageNamespace("comp", 1)
        # sbmlns.addPackageNamespace("distrib", 1)

        self.doc = libsbml.SBMLDocument(sbmlns)
        self.doc.setPackageRequired("comp", True)
        self.doc.setPackageRequired("fbc", False)
        # self.doc.setPackageRequired("distrib", True)

        self.model = self.doc.createModel()
        fbc_plugin = self.model.getPlugin("fbc")
        fbc_plugin.setStrict(False)

        # name & id
        check(self.model.setId(self.model_id), 'set id')
        check(self.model.setName(self.model_id), 'set name')
        # notes
        if hasattr(self, 'notes') and self.notes is not None:
            factory.set_notes(self.model, self.notes)
        # history
        if hasattr(self, 'creators'):
            history.set_model_history(self.model, self.creators)

        # model units
        if hasattr(self, 'model_units'):
            factory.set_model_units(self.model, self.model_units)

        # lists ofs
        for attr in [
                'externalModelDefinitions', 'submodels', 'units', 'functions',
                'parameters', 'compartments', 'species', 'assignments',
                'rules', 'rate_rules', 'reactions', 'events', 'constraints',
                'ports', 'replacedElements', 'deletions', 'objectives',
                'layouts'
        ]:
            # create the respective objects
            if hasattr(self, attr):
                objects = getattr(self, attr)
                if objects:
                    factory.create_objects(self.model,
                                           obj_iter=objects,
                                           key=attr)
                else:
                    logging.info("Not defined: <{}> ".format(attr))
Exemplo n.º 26
0
import libsbml
from sbmlutils.validation import check

doc = libsbml.SBMLDocument(3, 2)  # type: libsbml.SBMLDocument
model = doc.createModel()  # type: libsbml.Model
p = model.createParameter()  # type: libsbml.Parameter
p.setId("p")

check(
    p.setAnnotation("""
<body xmlns='http://www.w3.org/1999/xhtml'>
    <p>First annotation</p>
</body>
"""), "set annotations")

# add an annotation with SBO terms
p.setMetaId("meta_uncertainty1")
cv1 = libsbml.CVTerm()
cv1.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER)
cv1.setBiologicalQualifierType(6)  # "BQB_IS_DESCRIBED_BY"
cv1.addResource("https://identifiers.org/pubmed/123456")
check(p.addCVTerm(cv1), "add cv term")

sbml = libsbml.writeSBMLToString(doc)
print("-" * 80)
print(sbml)
print("-" * 80)

check(
    p.setAnnotation("""
<body xmlns='http://www.w3.org/1999/xhtml'>