예제 #1
0
 def test_KineticLaw_copyConstructor(self):
   o1 = libsbml.KineticLaw(2,4)
   p = libsbml.Parameter(2,4)
   p.setId("jake")
   o1.addParameter(p)
   p = None
   self.assert_( o1.getNumParameters() == 1 )
   self.assert_( o1.getParameter(0).getId() ==  "jake" )
   o2 = libsbml.KineticLaw(o1)
   self.assert_( o2.getNumParameters() == 1 )
   self.assert_( o2.getParameter(0).getId() ==  "jake" )
   self.assert_( o2.getParentSBMLObject() == o1.getParentSBMLObject() )
   o2 = None
   o1 = None
   pass  
예제 #2
0
 def test_L3_KineticLaw_addParameter1(self):
     kl = libsbml.KineticLaw(3, 1)
     p = libsbml.Parameter(3, 1)
     i = self.KL.addParameter(p)
     self.assert_(i == libsbml.LIBSBML_INVALID_OBJECT)
     p.setId("p")
     i = self.KL.addParameter(p)
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(self.KL.getNumParameters() == 1)
     self.assert_(self.KL.getNumLocalParameters() == 1)
     self.assert_(kl.getNumParameters() == 0)
     self.assert_(kl.getNumLocalParameters() == 0)
     i = kl.addParameter(p)
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(self.KL.getNumParameters() == 1)
     self.assert_(self.KL.getNumLocalParameters() == 1)
     self.assert_(kl.getNumParameters() == 1)
     self.assert_(kl.getNumLocalParameters() == 1)
     _dummyList = [p]
     _dummyList[:] = []
     del _dummyList
     _dummyList = [kl]
     _dummyList[:] = []
     del _dummyList
     pass
예제 #3
0
 def test_KineticLaw_getParameterById(self):
     k1 = libsbml.Parameter(2, 4)
     k2 = libsbml.Parameter(2, 4)
     k1.setId("k1")
     k2.setId("k2")
     k1.setValue(3.14)
     k2.setValue(2.72)
     self.M.addParameter(k1)
     self.M.addParameter(k2)
     r1 = libsbml.Reaction(2, 4)
     r1.setId("reaction_1")
     kl = libsbml.KineticLaw(2, 4)
     kl.setFormula("k1 * X0")
     k3 = libsbml.Parameter(2, 4)
     k4 = libsbml.Parameter(2, 4)
     k3.setId("k1")
     k4.setId("k2")
     k3.setValue(2.72)
     k4.setValue(3.14)
     kl.addParameter(k3)
     kl.addParameter(k4)
     r1.setKineticLaw(kl)
     self.M.addReaction(r1)
     kl1 = self.M.getReaction(0).getKineticLaw()
     self.assert_(kl1.getParameter("k1") != k3)
     self.assert_(kl1.getParameter("k1") != k1)
     self.assert_(kl1.getParameter("k2") != k4)
     self.assert_(kl1.getParameter("k3") == None)
     pass
 def test_KineticLaw_setTimeUnits4(self):
   kl1 = libsbml.KineticLaw(1,2)
   i = kl1.setTimeUnits("")
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assertEqual( False, kl1.isSetTimeUnits() )
   _dummyList = [ kl1 ]; _dummyList[:] = []; del _dummyList
   pass  
 def test_KineticLaw(self):
   kl = libsbml.KineticLaw(2,4)
   self.assertEqual( False, (kl.hasRequiredElements()) )
   kl.setMath(libsbml.parseFormula("kl"))
   self.assertEqual( True, kl.hasRequiredElements() )
   kl = None
   pass  
예제 #6
0
 def test_KineticLaw_L1(self):
     kl = libsbml.KineticLaw(1, 2)
     self.assertEqual(False, (kl.hasRequiredAttributes()))
     kl.setFormula("kl")
     self.assertEqual(True, kl.hasRequiredAttributes())
     kl = None
     pass
 def test_KineticLaw_createParameter(self):
   self.kl = libsbml.KineticLaw(2,2)
   p = self.kl.createParameter()
   self.assert_( self.kl.getNumParameters() == 1 )
   self.assert_( (p).getLevel() == 2 )
   self.assert_( (p).getVersion() == 2 )
   _dummyList = [ self.kl ]; _dummyList[:] = []; del _dummyList
   pass  
 def test_KineticLaw_addParameter4(self):
   self.kl = libsbml.KineticLaw(2,2)
   p = None
   i = self.kl.addParameter(p)
   self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED )
   self.assert_( self.kl.getNumParameters() == 0 )
   _dummyList = [ self.kl ]; _dummyList[:] = []; del _dummyList
   pass  
예제 #9
0
 def test_KineticLaw_parent_add(self):
     kl = libsbml.KineticLaw(2, 4)
     kl.setMath(libsbml.parseFormula("1"))
     r = libsbml.Reaction(2, 4)
     r.setKineticLaw(kl)
     self.assert_(r == r.getKineticLaw().getParentSBMLObject())
     r = None
     pass
 def test_KineticLaw_addParameter3(self):
   self.kl = libsbml.KineticLaw(2,2)
   p = libsbml.Parameter(1,2)
   p.setId( "p")
   i = self.kl.addParameter(p)
   self.assert_( i == libsbml.LIBSBML_LEVEL_MISMATCH )
   self.assert_( self.kl.getNumParameters() == 0 )
   _dummyList = [ p ]; _dummyList[:] = []; del _dummyList
   _dummyList = [ self.kl ]; _dummyList[:] = []; del _dummyList
   pass  
 def test_KineticLaw_setSubstanceUnits2(self):
   kl1 = libsbml.KineticLaw(1,2)
   i = kl1.setSubstanceUnits( "mole")
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assertEqual( True, kl1.isSetSubstanceUnits() )
   i = kl1.unsetSubstanceUnits()
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assertEqual( False, kl1.isSetSubstanceUnits() )
   _dummyList = [ kl1 ]; _dummyList[:] = []; del _dummyList
   pass  
 def test_Reaction_setKineticLaw2(self):
     kl = libsbml.KineticLaw(1, 1)
     kl.setMath(libsbml.parseFormula("1"))
     i = self.R.setKineticLaw(kl)
     self.assert_(i == libsbml.LIBSBML_VERSION_MISMATCH)
     self.assertEqual(False, self.R.isSetKineticLaw())
     _dummyList = [kl]
     _dummyList[:] = []
     del _dummyList
     pass
 def test_KineticLaw_setTimeUnits3(self):
   kl1 = libsbml.KineticLaw(1,2)
   i = kl1.setTimeUnits( "1second")
   self.assert_( i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE )
   self.assertEqual( False, kl1.isSetTimeUnits() )
   i = kl1.unsetTimeUnits()
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assertEqual( False, kl1.isSetTimeUnits() )
   _dummyList = [ kl1 ]; _dummyList[:] = []; del _dummyList
   pass  
 def test_Reaction_setKineticLaw3(self):
     kl = libsbml.KineticLaw(1, 2)
     kl.setMath(libsbml.parseFormula("1"))
     i = self.R.setKineticLaw(kl)
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assertEqual(True, self.R.isSetKineticLaw())
     _dummyList = [kl]
     _dummyList[:] = []
     del _dummyList
     pass
예제 #15
0
 def test_KineticLaw_Parameter_parent_create(self):
     kl = libsbml.KineticLaw(2, 4)
     p = kl.createParameter()
     self.assert_(kl.getNumParameters() == 1)
     lop = kl.getListOfParameters()
     self.assert_(kl == lop.getParentSBMLObject())
     self.assert_(lop == p.getParentSBMLObject())
     self.assert_(lop == kl.getParameter(0).getParentSBMLObject())
     kl = None
     pass
예제 #16
0
 def test_KineticLaw_ancestor_add(self):
   kl = libsbml.KineticLaw(2,4)
   kl.setMath(libsbml.parseFormula("1"))
   r = libsbml.Reaction(2,4)
   r.setKineticLaw(kl)
   obj = r.getKineticLaw()
   self.assert_( obj.getAncestorOfType(libsbml.SBML_REACTION) == r )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_MODEL) == None )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_DOCUMENT) == None )
   r = None
   pass  
 def test_KineticLaw_addParameter1(self):
   self.kl = libsbml.KineticLaw(2,2)
   p = libsbml.Parameter(2,2)
   i = self.kl.addParameter(p)
   self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT )
   p.setId( "p")
   i = self.kl.addParameter(p)
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assert_( self.kl.getNumParameters() == 1 )
   _dummyList = [ p ]; _dummyList[:] = []; del _dummyList
   _dummyList = [ self.kl ]; _dummyList[:] = []; del _dummyList
   pass  
예제 #18
0
 def test_KineticLaw_Parameter_parent_add(self):
     kl = libsbml.KineticLaw(2, 4)
     p = libsbml.Parameter(2, 4)
     p.setId("jake")
     kl.addParameter(p)
     p = None
     self.assert_(kl.getNumParameters() == 1)
     self.assert_(kl.getParameter(0).getId() == "jake")
     lop = kl.getListOfParameters()
     self.assert_(kl == lop.getParentSBMLObject())
     self.assert_(lop == kl.getParameter(0).getParentSBMLObject())
     kl = None
     pass
예제 #19
0
 def test_KineticLaw_Parameter_ancestor_add(self):
   kl = libsbml.KineticLaw(2,4)
   p = libsbml.Parameter(2,4)
   p.setId("jake")
   kl.addParameter(p)
   p = None
   lop = kl.getListOfParameters()
   obj = kl.getParameter(0)
   self.assert_( obj.getAncestorOfType(libsbml.SBML_KINETIC_LAW) == kl )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_LIST_OF) == lop )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_DOCUMENT) == None )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_COMPARTMENT) == None )
   kl = None
   pass  
 def test_KineticLaw_addParameter2(self):
     self.kl = libsbml.KineticLaw(2, 2)
     p = libsbml.Parameter(2, 1)
     p.setId("p")
     i = self.kl.addParameter(p)
     self.assert_(i == libsbml.LIBSBML_VERSION_MISMATCH)
     self.assert_(self.kl.getNumParameters() == 0)
     _dummyList = [p]
     _dummyList[:] = []
     del _dummyList
     _dummyList = [self.kl]
     _dummyList[:] = []
     del _dummyList
     pass
예제 #21
0
 def test_KineticLaw_Parameter_ancestor_create(self):
   kl = libsbml.KineticLaw(2,4)
   p = kl.createParameter()
   self.assert_( kl.getNumParameters() == 1 )
   lop = kl.getListOfParameters()
   self.assert_( p.getAncestorOfType(libsbml.SBML_KINETIC_LAW) == kl )
   self.assert_( p.getAncestorOfType(libsbml.SBML_LIST_OF) == lop )
   self.assert_( p.getAncestorOfType(libsbml.SBML_DOCUMENT) == None )
   self.assert_( p.getAncestorOfType(libsbml.SBML_COMPARTMENT) == None )
   obj = kl.getParameter(0)
   self.assert_( obj.getAncestorOfType(libsbml.SBML_KINETIC_LAW) == kl )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_LIST_OF) == lop )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_DOCUMENT) == None )
   self.assert_( obj.getAncestorOfType(libsbml.SBML_COMPARTMENT) == None )
   kl = None
   pass  
 def test_internal_consistency_check_99911_kl(self):
   d = libsbml.SBMLDocument(2,4)
   d.setLevelAndVersion(2,1,False)
   m = d.createModel()
   r = m.createReaction()
   r.setId("r")
   sr = r.createReactant()
   sr.setSpecies("s")
   kl = libsbml.KineticLaw(2,4)
   kl.setSBOTerm(2)
   p = kl.createParameter()
   p.setId("p")
   r.setKineticLaw(kl)
   errors = d.checkInternalConsistency()
   self.assert_( errors == 0 )
   d = None
   pass  
 def test_internal_consistency_check_99904_kl(self):
   d = libsbml.SBMLDocument(2,4)
   kl = libsbml.KineticLaw(2,4)
   m = d.createModel()
   d.setLevelAndVersion(1,2,False)
   c = m.createCompartment()
   c.setId("cc")
   r = m.createReaction()
   r.setId("r")
   sr = r.createReactant()
   sr.setSpecies("s")
   kl.setFormula("2")
   kl.setMetaId("mmm")
   r.setKineticLaw(kl)
   errors = d.checkInternalConsistency()
   self.assert_( errors == 0 )
   d = None
   pass  
예제 #24
0
 def test_KineticLaw_createWithNS(self):
     xmlns = libsbml.XMLNamespaces()
     xmlns.add("http://www.sbml.org", "testsbml")
     sbmlns = libsbml.SBMLNamespaces(2, 1)
     sbmlns.addNamespaces(xmlns)
     object = libsbml.KineticLaw(sbmlns)
     self.assert_(object.getTypeCode() == libsbml.SBML_KINETIC_LAW)
     self.assert_(object.getMetaId() == "")
     self.assert_(object.getNotes() == None)
     self.assert_(object.getAnnotation() == None)
     self.assert_(object.getLevel() == 2)
     self.assert_(object.getVersion() == 1)
     self.assert_(object.getNamespaces() != None)
     self.assert_(object.getNamespaces().getLength() == 2)
     _dummyList = [object]
     _dummyList[:] = []
     del _dummyList
     pass
예제 #25
0
 def test_Reaction_copyConstructor(self):
   o1 = libsbml.Reaction(2,4)
   o1.setId("c")
   self.assert_( o1.getId() ==  "c" )
   kl = libsbml.KineticLaw(2,4)
   kl.setMath(libsbml.parseFormula("1"))
   o1.setKineticLaw(kl)
   kl = None
   self.assert_( o1.isSetKineticLaw() == True )
   self.assert_( o1.getKineticLaw() != None )
   o2 = libsbml.Reaction(o1)
   self.assert_( o2.getId() ==  "c" )
   self.assert_( o2.isSetKineticLaw() == True )
   self.assert_( o2.getKineticLaw() != None )
   self.assert_( o2.getParentSBMLObject() == o1.getParentSBMLObject() )
   o2 = None
   o1 = None
   pass  
예제 #26
0
 def get_and_set(self, reaction_name, lista, category):
     # Prendo tutti i reagenti con i loro valori stechiometrici
     elements = []
     for element in lista:
         # Ottengo un oggetto SpeciesReference
         # Devo ottenere il valore stechiometrico
         stoichiometry_value = element.getStoichiometry()
         if stoichiometry_value == 1.0 and element.isSetStoichiometryMath():
             tmp_kinetic = libsbml.KineticLaw(2, 4)
             tmp_kinetic.setMath(element.getStoichiometryMath().getMath())
             stoichiometry_value = tmp_kinetic.getFormula()
         if category == "r":
             self.species_dict[element.getSpecies()].add_reaction_as_reactant(
                 reaction_name, stoichiometry_value
             )
         elif category == "p":
             self.species_dict[element.getSpecies()].add_reaction_as_product(
                 reaction_name, stoichiometry_value
             )
         elements.append(element.getSpecies())
     return elements
예제 #27
0
 def test_L3_KineticLaw_addParameter2(self):
     kl = libsbml.KineticLaw(3, 1)
     lp = libsbml.LocalParameter(3, 1)
     lp1 = libsbml.LocalParameter(3, 1)
     i = kl.addLocalParameter(lp)
     self.assert_(i == libsbml.LIBSBML_INVALID_OBJECT)
     lp.setId("p")
     lp1.setId("p1")
     i = kl.addLocalParameter(lp)
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(kl.getNumParameters() == 1)
     self.assert_(kl.getNumLocalParameters() == 1)
     i = kl.addParameter(lp1)
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(kl.getNumParameters() == 2)
     self.assert_(kl.getNumLocalParameters() == 2)
     _dummyList = [lp]
     _dummyList[:] = []
     del _dummyList
     _dummyList = [kl]
     _dummyList[:] = []
     del _dummyList
     pass
예제 #28
0
 def test_KineticLaw(self):
     kl = libsbml.KineticLaw(2, 4)
     self.assertEqual(True, kl.hasRequiredAttributes())
     kl = None
     pass
예제 #29
0
파일: sbml.py 프로젝트: wbryant/cobrapy
def get_libsbml_document(cobra_model,
                         sbml_level=2, sbml_version=1,
                         print_time=False,
                         use_fbc_package=True):
    """ Return a libsbml document object for writing to a file. This function
    is used by write_cobra_model_to_sbml_file(). """
    note_start_tag, note_end_tag = '<p>', '</p>'
    if sbml_level > 2 or (sbml_level == 2 and sbml_version == 4):
        note_start_tag, note_end_tag = '<html:p>', '</html:p>'

    sbml_doc = libsbml.SBMLDocument(sbml_level, sbml_version)
    sbml_model = sbml_doc.createModel(cobra_model.id.split('.')[0])
    # Note need to set units
    reaction_units = 'mmol_per_gDW_per_hr'
    model_units = sbml_model.createUnitDefinition()
    model_units.setId(reaction_units)
    sbml_unit = model_units.createUnit()
    sbml_unit.setKind(libsbml.UNIT_KIND_MOLE)
    sbml_unit.setScale(-3)
    sbml_unit = model_units.createUnit()
    sbml_unit.setKind(libsbml.UNIT_KIND_GRAM)
    sbml_unit.setExponent(-1)
    sbml_unit = model_units.createUnit()
    sbml_unit.setKind(libsbml.UNIT_KIND_SECOND)
    sbml_unit.setMultiplier(1.0 / 60 / 60)
    sbml_unit.setExponent(-1)

    # Add in the common compartment abbreviations.  If there are additional
    # compartments they also need to be added.
    if not cobra_model.compartments:
        cobra_model.compartments = {'c': 'cytosol',
                                    'p': 'periplasm',
                                    'e': 'extracellular'}
    for the_key in cobra_model.compartments.keys():
        sbml_comp = sbml_model.createCompartment()
        sbml_comp.setId(the_key)
        sbml_comp.setName(cobra_model.compartments[the_key])
        sbml_comp.setSize(1)  # Just to get rid of warnings

    if print_time:
        warn("print_time is deprecated", DeprecationWarning)
    # Use this dict to allow for fast look up of species id
    # for references created in the reaction section.
    metabolite_dict = {}

    for cobra_metabolite in cobra_model.metabolites:
        metabolite_dict[cobra_metabolite.id] = add_sbml_species(
            sbml_model, cobra_metabolite, note_start_tag=note_start_tag,
            note_end_tag=note_end_tag)

    for the_reaction in cobra_model.reactions:
        # This is probably the culprit.  Including cobra.Reaction
        # objects explicitly in cobra.Model will speed this up.
        sbml_reaction = sbml_model.createReaction()
        # Need to remove - for proper SBML.  Replace with __
        the_reaction_id = 'R_' + the_reaction.id.replace('-', '__')
        sbml_reaction.setId(the_reaction_id)
        # The reason we are not using the Reaction.reversibility property
        # is because the SBML definition of reversibility does not quite
        # match with the cobra definition. In cobra, reversibility implies
        # that both positive and negative flux values are feasible. However,
        # SBML requires negative-flux-only reactions to still be classified
        # as reversible. To quote from the SBML Level 3 Version 1 Spec:
        # > However, labeling a reaction as irreversible is interpreted as
        # > an assertion that the rate expression will not have negative
        # > values during a simulation.
        # (Page 60 lines 44-45)
        sbml_reaction.setReversible(the_reaction.lower_bound < 0)
        if the_reaction.name:
            sbml_reaction.setName(the_reaction.name)
        else:
            sbml_reaction.setName(the_reaction.id)
        # Add in the reactant/product references
        for the_metabolite, the_coefficient in \
                iteritems(the_reaction._metabolites):
            sbml_stoichiometry = the_coefficient
            metabolite_id = str(metabolite_dict[the_metabolite.id])
            # Each SpeciesReference must have a unique id
            if sbml_stoichiometry < 0:
                species_reference = sbml_reaction.createReactant()
            else:
                species_reference = sbml_reaction.createProduct()
            species_reference.setId(metabolite_id + '_' + the_reaction_id)
            species_reference.setSpecies(metabolite_id)
            species_reference.setStoichiometry(abs(sbml_stoichiometry))
        # Deal with the case where the reaction is a boundary reaction
        if len(the_reaction._metabolites) == 1:
            the_metabolite, the_coefficient = list(
                the_reaction._metabolites.items())[0]
            metabolite_id = add_sbml_species(sbml_model, the_metabolite,
                                             note_start_tag=note_start_tag,
                                             note_end_tag=note_end_tag,
                                             boundary_metabolite=True)
            sbml_stoichiometry = -the_coefficient
            # Each SpeciesReference must have a unique id
            if sbml_stoichiometry < 0:
                species_reference = sbml_reaction.createReactant()
            else:
                species_reference = sbml_reaction.createProduct()
            species_reference.setId(metabolite_id + '_' + the_reaction_id)
            species_reference.setSpecies(metabolite_id)
            species_reference.setStoichiometry(abs(sbml_stoichiometry))

        # Add in the kineticLaw
        sbml_law = libsbml.KineticLaw(sbml_level, sbml_version)
        if hasattr(sbml_law, 'setId'):
            sbml_law.setId('FLUX_VALUE')
        sbml_law.setFormula('FLUX_VALUE')
        reaction_parameter_dict = {
            'LOWER_BOUND': [the_reaction.lower_bound, reaction_units],
            'UPPER_BOUND': [the_reaction.upper_bound, reaction_units],
            'FLUX_VALUE': [0, reaction_units],
            'OBJECTIVE_COEFFICIENT': [the_reaction.objective_coefficient,
                                      'dimensionless']}
        for k, v in reaction_parameter_dict.items():
            sbml_parameter = libsbml.Parameter(sbml_level, sbml_version)
            sbml_parameter.setId(k)
            if hasattr(v, '__iter__'):
                sbml_parameter.setValue(v[0])
                sbml_parameter.setUnits(v[1])
            else:
                sbml_parameter.setValue(v)
            sbml_law.addParameter(sbml_parameter)
        sbml_reaction.setKineticLaw(sbml_law)

        # Checks if GPR and Subsystem annotations are present in the notes
        # section and if they are the same as those in the reaction's
        # gene_reaction_rule/ subsystem attribute. If they are not identical,
        # they are set to be identical
        note_dict = the_reaction.notes.copy()
        if the_reaction.gene_reaction_rule:
            note_dict['GENE_ASSOCIATION'] = [
                str(the_reaction.gene_reaction_rule)]
        if the_reaction.subsystem:
            note_dict['SUBSYSTEM'] = [str(the_reaction.subsystem)]

        # In a cobrapy model the notes section is stored as a dictionary. The
        # following section turns the key-value-pairs of the dictionary into a
        # string and replaces recurring symbols so that the string has the i
        # required syntax for an SBML doc.
        note_str = str(list(iteritems(note_dict)))
        note_start_tag, note_end_tag, note_delimiter = '<p>', '</p>', ':'
        note_str = note_str.replace('(\'', note_start_tag)
        note_str = note_str.replace('\']),', note_end_tag)
        note_str = note_str.replace('\',', note_delimiter)
        note_str = note_str.replace('\']', '')
        note_str = note_str.replace('[\'', '')
        note_str = note_str.replace(
            '[', '<html xmlns="http://www.w3.org/1999/xhtml">')
        note_str = note_str.replace(')]', note_end_tag + '</html>')
        sbml_reaction.setNotes(note_str)

    if use_fbc_package:
        try:
            from libsbml import ConversionProperties, LIBSBML_OPERATION_SUCCESS
            conversion_properties = ConversionProperties()
            conversion_properties.addOption(
                "convert cobra", True, "Convert Cobra model")
            result = sbml_doc.convert(conversion_properties)
            if result != LIBSBML_OPERATION_SUCCESS:
                raise Exception("Conversion of COBRA to SBML+fbc failed")
        except Exception as e:
            error_string = 'Error saving as SBML+fbc. %s'
            try:
                # Check whether the FbcExtension is there
                from libsbml import FbcExtension
                error_string = error_string % e
            except ImportError:
                error_string = error_string % "FbcExtension not available in "
                "libsbml. If use_fbc_package == True then libsbml must be "
                "compiled with the fbc extension."
                from libsbml import getLibSBMLDottedVersion
                _sbml_version = getLibSBMLDottedVersion()
                _major, _minor, _patch = map(int, _sbml_version.split('.'))
                if _major < 5 or (_major == 5 and _minor < 8):
                    error_string += "You've got libsbml %s installed. "
                    "You need 5.8.0 or later with the fbc package"

            raise Exception(error_string)
    return sbml_doc
예제 #30
0
def toSBMLString(net):
    metaId = 0
    try:
        m = libsbml.Model(net.id)
    except NotImplementedError:
        m = libsbml.Model(sbml_level, sbml_version)
        m.setId(net.id)
    m.setName(net.name)
    m.setMetaId('SloppyCell_{0:05d}'.format(metaId))
    metaId += 1

    for id, fd in list(net.functionDefinitions.items()):
        try:
            sfd = libsbml.FunctionDefinition(id)
        except:
            sfd = libsbml.FunctionDefinition(sbml_level, sbml_version)
            sfd.setId(id)
        sfd.setName(fd.name)
        formula = fd.math
        formula = formula.replace('**', '^')
        formula = 'lambda(%s, %s)' % (','.join(fd.variables), formula)
        sfd.setMath(libsbml.parseFormula(formula))
        sfd.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addFunctionDefinition(sfd)

    for id, c in list(net.compartments.items()):
        try:
            sc = libsbml.Compartment(id)
        except NotImplementedError:
            sc = libsbml.Compartment(sbml_level, sbml_version)
            sc.setId(id)
        sc.setName(c.name)
        sc.setConstant(c.is_constant)
        sc.setSize(c.initialValue)
        sc.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addCompartment(sc)

    for id, s in list(net.species.items()):
        try:
            ss = libsbml.Species(id)
        except NotImplementedError:
            ss = libsbml.Species(sbml_level, sbml_version)
            ss.setId(id)
        ss.setName(s.name)
        ss.setCompartment(s.compartment)
        if s.initialValue is not None and not isinstance(s.initialValue, str):
            ss.setInitialConcentration(s.initialValue)
        ss.setBoundaryCondition(s.is_boundary_condition)
        ss.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addSpecies(ss)

    for id, p in list(net.parameters.items()):
        try:
            sp = libsbml.Parameter(id)
        except NotImplementedError:
            sp = libsbml.Parameter(sbml_level, sbml_version)
            sp.setId(id)
        sp.setName(p.name)
        if p.initialValue is not None:
            sp.setValue(p.initialValue)
        sp.setConstant(p.is_constant)
        sp.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addParameter(sp)

    for id, r in list(net.rateRules.items()):
        try:
            sr = libsbml.RateRule()
        except NotImplementedError:
            sr = libsbml.RateRule(sbml_level, sbml_version)
        sr.setVariable(id)
        formula = r.replace('**', '^')
        sr.setMath(libsbml.parseFormula(formula))
        sr.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addRule(sr)

    for id, r in list(net.assignmentRules.items()):
        try:
            sr = libsbml.AssignmentRule()
        except NotImplementedError:
            sr = libsbml.AssignmentRule(sbml_level, sbml_version)
        sr.setVariable(id)
        formula = r.replace('**', '^')
        sr.setMath(libsbml.parseFormula(formula))
        sr.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addRule(sr)

    for r, r in list(net.algebraicRules.items()):
        try:
            sr = libsbml.AlgebraicRule()
        except NotImplementedError:
            sr = libsbml.AlgebraicRule(sbml_level, sbml_version)
        formula = r.replace('**', '^')
        sr.setMath(libsbml.parseFormula(formula))
        sr.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addRule(sr)

    for id, rxn in list(net.reactions.items()):
        # Need to identify modifiers in kinetic law and add them to
        # stoichiometry
        kl_vars = ExprManip.extract_vars(rxn.kineticLaw)
        species_in_kl = kl_vars.intersection(list(net.species.keys()))
        for s in species_in_kl:
            if s not in rxn.stoichiometry:
                rxn.stoichiometry[s] = 0

        try:
            srxn = libsbml.Reaction(id)
        except NotImplementedError:
            srxn = libsbml.Reaction(sbml_level, sbml_version)
            srxn.setId(id)
        srxn.setName(rxn.name)
        # Handle the case where the model was originally read in from an
        # SBML file, so that the reactants and products of the Reaction
        # object are explicitly set.
        if rxn.reactant_stoichiometry != None and \
            rxn.product_stoichiometry != None:
            for rid, stoich_list in list(rxn.reactant_stoichiometry.items()):
                for stoich in stoich_list:
                    rxn_add_stoich(srxn, rid, -float(stoich), is_product=False)
            for rid, stoich_list in list(rxn.product_stoichiometry.items()):
                for stoich in stoich_list:
                    rxn_add_stoich(srxn, rid, stoich, is_product=True)
        # Handle the case where the model was created using the SloppyCell
        # API, in which case reactants and products are inferred from their
        # stoichiometries
        else:
            for rid, stoich in list(rxn.stoichiometry.items()):
                rxn_add_stoich(srxn, rid, stoich)

        formula = rxn.kineticLaw.replace('**', '^')
        try:
            kl = libsbml.KineticLaw(formula)
        except NotImplementedError:
            kl = libsbml.KineticLaw(sbml_level, sbml_version)
            kl.setFormula(formula)
        srxn.setKineticLaw(kl)
        srxn.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addReaction(srxn)

    for id, e in list(net.events.items()):
        try:
            se = libsbml.Event(id)
        except NotImplementedError:
            se = libsbml.Event(sbml_level, sbml_version)
            se.setId(id)
        se.setName(e.name)
        formula = e.trigger.replace('**', '^')
        formula = formula.replace('and_func(', 'and(')
        formula = formula.replace('or_func(', 'or(')

        ast = libsbml.parseFormula(formula)
        if ast is None:
            raise ValueError('Problem parsing event trigger: %s. Problem may '
                             'be use of relational operators (< and >) rather '
                             'than libsbml-friendly functions lt and gt.' %
                             formula)
        try:
            se.setTrigger(ast)
        except TypeError:
            try:
                trigger = libsbml.Trigger(ast)
            except NotImplementedError:
                trigger = libsbml.Trigger(sbml_level, sbml_version)
                trigger.setMath(ast)
            se.setTrigger(trigger)
        formula = str(e.delay).replace('**', '^')
        try:
            se.setDelay(libsbml.parseFormula(formula))
        except TypeError:
            try:
                se.setDelay(libsbml.Delay(libsbml.parseFormula(formula)))
            except NotImplementedError:
                delay = libsbml.Delay(sbml_level, sbml_version)
                delay.setMath(libsbml.parseFormula(formula))
                se.setDelay(delay)
        for varId, formula in list(e.event_assignments.items()):
            try:
                sea = libsbml.EventAssignment()
            except NotImplementedError:
                sea = libsbml.EventAssignment(sbml_level, sbml_version)
            sea.setVariable(varId)
            formula = str(formula).replace('**', '^')
            formula = formula.replace('and_func(', 'and(')
            formula = formula.replace('or_func(', 'or(')
            ast = libsbml.parseFormula(formula)
            replaceTime(ast)
            sea.setMath(ast)
            se.addEventAssignment(sea)
        se.setMetaId('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1
        m.addEvent(se)

    for id, con in list(net.constraints.items()):
        try:
            scon = libsbml.Constraint()
        except NotImplementedError:
            scon = libsbml.Constraint(sbml_level, sbml_version)
        scon.setId(con.id)
        scon.setName(con.name)
        formula = con.trigger.replace('**', '^')
        ast = libsbml.parseFormula(formula)
        if ast is None:
            raise ValueError(
                'Problem parsing constraint math: %s. Problem may '
                'be use of relational operators (< and >) rather '
                'than libsbml-friendly functions lt and gt.' % formula)
        scon.setMath(ast)
        se.setcon('SloppyCell_{0:05d}'.format(metaId))
        metaId += 1

        m.addConstraint(scon)

    d = libsbml.SBMLDocument(sbml_level, sbml_version)
    d.setModel(m)
    sbmlStr = libsbml.writeSBMLToString(d)

    return sbmlStr