Exemple #1
0
 def test_WriteL3SBML_Model_substanceUnits(self):
     expected = wrapSBML_L3v1("  <model substanceUnits=\"mole\"/>\n")
     m = self.D.createModel("")
     m.setSubstanceUnits("mole")
     self.S = libsbml.writeSBMLToString(self.D)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
def _parse_yaml_dict(yaml_dict) -> str:
    """
    Generates a string, containing the SBML from a yaml_dict.

    Arguments:
        yaml_dict: dictionary, containing to the yaml file with the ODEs
                   specification.

    Returns:
        sbml_string: a string containing the ODEs in SBML format.

    """

    try:
        document = sbml.SBMLDocument(3, 1)
    except ValueError:
        raise SystemExit('Could not create SBMLDocument object')

    model = document.createModel()
    model = _create_compartment(model)

    _convert_yaml_blocks_to_sbml(model, yaml_dict)

    # check consistency and give warnings for errors in SBML:
    if document.checkConsistency():

        for error_num in range(document.getErrorLog().getNumErrors()):
            if not document.getErrorLog().getError(error_num).isWarning():
                warnings.warn(
                    document.getErrorLog().getError(error_num).getMessage(),
                    RuntimeWarning)

    sbml_string = sbml.writeSBMLToString(document)

    return sbml_string
Exemple #3
0
def xpath_expressions_exist(doc, xpath_expressions):
    # type: (libsbml.SBMLDocument, List[str]) -> bool
    sbml = libsbml.writeSBMLToString(doc)
    tree = etree.fromstring(sbml.encode('utf-8'))
    result = True
    for xpath in xpath_expressions:
        if ':' not in xpath:
            logging.warning(
                f"no prefix used in xpath expression: {xpath} this likely cannot be resolved"
            )
        try:
            elements = tree.xpath(
                xpath, namespaces={'sbml': doc.getSBMLNamespaces().getURI()})
            num_elements = len(elements)
            if num_elements == 0:
                logging.error(f"no match for xpath expression: {xpath}")
                result = False
            if num_elements > 1:
                logging.warning(
                    f"more than one match for xpath expression, this is not supported by many tools: {xpath}"
                )
        except TypeError:
            logging.error(f"invalid xpath expression: {xpath}")
            result = False
    return result
Exemple #4
0
 def test_WriteL3SBML_Model_timeUnits(self):
     expected = wrapSBML_L3v1("  <model timeUnits=\"second\"/>\n")
     m = self.D.createModel("")
     m.setTimeUnits("second")
     self.S = libsbml.writeSBMLToString(self.D)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
 def test_WriteL3SBML_Model(self):
   expected = wrapSBML_L3v1("  <model/>\n"  
   )
   m = self.D.createModel("")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #6
0
def CreateExample3(Repetitions = 1):
    "Create SBML Array simulation example 3"
    PopulationSize = 100
    TimeLimit = 10
    (NameSpace,Document,Model,IndividualsUnit,SimulationSize,InstructionNumber,DefineDimension,Random,Time) = InitExample(PopulationSize*Repetitions)

    StateList = ['Healthy','Sick','Dead']
    DefineStates(Model, StateList, SimulationSize)  

    DefineParamArray(Model,'Male',SimulationSize)


    DefineInitialAssignment(Container = Model, Symbol = 'Healthy', Size = SimulationSize, MathExpression = 'selector(vector('+str([1]*PopulationSize*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Sick', Size = SimulationSize, MathExpression = 'selector(vector('+str([0]*PopulationSize*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Dead', Size = SimulationSize, MathExpression = 'selector(vector('+str([0]*PopulationSize*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Male', Size = SimulationSize, MathExpression = 'selector(vector('+str(([0]*(PopulationSize/2)+[1]*(PopulationSize/2))*Repetitions)[1:-1]+ '),d0)')



    # terminate event at start of loop
    DefineTerminalEvent (Model = Model, TerminalStates = ['Dead'], Size = SimulationSize, TimeLimit=TimeLimit)

    TransitionFormula(Model = Model, FromStates = [ 'Healthy' ], ToStates = [ 'Dead', 'Sick'] , Probabilities = [ [ '0.01' ,'0.1*(1+selector(Male,d0))'] ] , Size = SimulationSize, InstructionNumber = 1, NextLine = 0)
    TransitionFormula(Model = Model, FromStates = [ 'Sick' ], ToStates = [ 'Healthy','Dead'] , Probabilities = [ [ '0.1','0.3' ] ] , Size = SimulationSize, InstructionNumber = 1, NextLine = 0)

    return libsbml.writeSBMLToString(Document)
    def test_write_sbml_file(self):

        import libsbml
        from biocrnpyler import ChemicalReactionNetwork
        from biocrnpyler import Species
        from biocrnpyler import Reaction

        s1 = Species(name='test_species1')
        s2 = Species(name='test_species2')

        species_list = [s1, s2]

        rx1 = Reaction(inputs=[s1], outputs=[s2], k=0.1)
        rxn_list = [rx1]

        crn = ChemicalReactionNetwork(species=species_list, reactions=rxn_list)
        document, _ = crn.generate_sbml_model()
        sbml_string = libsbml.writeSBMLToString(document)

        file_name = 'test_sbml.xml'
        with patch("builtins.open", new=mock_open()) as _file:
            crn.write_sbml_file(file_name)

            _file.assert_called_once_with(file_name, 'w')
            _file().write.assert_called_once_with(sbml_string)
Exemple #8
0
 def test_WriteL3SBML_SBMLDocument_L3v1(self):
     expected = wrapXML(
         "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" " +
         "level=\"3\" version=\"1\"/>\n")
     self.S = libsbml.writeSBMLToString(self.D)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
Exemple #9
0
 def test_WriteL3SBML_elements(self):
     expected = wrapSBML_L3v1(
         "  <model>\n" + "    <listOfFunctionDefinitions>\n" +
         "      <functionDefinition/>\n" +
         "    </listOfFunctionDefinitions>\n" +
         "    <listOfUnitDefinitions>\n" + "      <unitDefinition/>\n" +
         "    </listOfUnitDefinitions>\n" + "    <listOfCompartments>\n" +
         "      <compartment/>\n" + "    </listOfCompartments>\n" +
         "    <listOfSpecies>\n" + "      <species/>\n" +
         "    </listOfSpecies>\n" + "    <listOfParameters>\n" +
         "      <parameter/>\n" + "    </listOfParameters>\n" +
         "    <listOfInitialAssignments>\n" +
         "      <initialAssignment/>\n" +
         "    </listOfInitialAssignments>\n" + "    <listOfRules>\n" +
         "      <algebraicRule/>\n" + "    </listOfRules>\n" +
         "    <listOfConstraints>\n" + "      <constraint/>\n" +
         "    </listOfConstraints>\n" + "    <listOfReactions>\n" +
         "      <reaction/>\n" + "    </listOfReactions>\n" +
         "    <listOfEvents>\n" + "      <event/>\n" +
         "    </listOfEvents>\n" + "  </model>\n")
     m = self.D.createModel()
     m.createUnitDefinition()
     m.createFunctionDefinition()
     m.createCompartment()
     m.createEvent()
     m.createParameter()
     m.createAlgebraicRule()
     m.createInitialAssignment()
     m.createConstraint()
     m.createReaction()
     m.createSpecies()
     self.S = libsbml.writeSBMLToString(self.D)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
Exemple #10
0
 def test_WriteL3SBML_Model_conversionFactor(self):
     expected = wrapSBML_L3v1("  <model conversionFactor=\"p\"/>\n")
     m = self.D.createModel("")
     m.setConversionFactor("p")
     self.S = libsbml.writeSBMLToString(self.D)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
Exemple #11
0
 def get_sbml(self) -> str:
     """Return SBML string of the model.
     :return: SBML string
     """
     if self.doc is None:
         self.create_sbml()
     return libsbml.writeSBMLToString(self.doc)
Exemple #12
0
 def toSBML(self):
     errors = self.document.checkConsistency();
     if (errors > 0):
         for i in range(errors):
             print self.document.getError(i).getSeverityAsString(), ": ", self.document.getError(i).getMessage();
           
     return libsbml.writeSBMLToString(self.document);
 def test_WriteL3SBML_Model(self):
   expected = wrapSBML_L3v1("  <model/>\n"  
   )
   m = self.D.createModel("")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #14
0
def petab_problem():
    # create test model
    document = libsbml.SBMLDocument(3, 1)
    model = document.createModel()
    model.setTimeUnits("second")
    model.setExtentUnits("mole")
    model.setSubstanceUnits('mole')

    p = model.createParameter()
    p.setId('fixedParameter1')
    p.setName('FixedParameter1')

    p = model.createParameter()
    p.setId('observable_1')
    p.setName('Observable 1')

    with tempfile.NamedTemporaryFile(mode='w', delete=False) as fh:
        sbml_file_name = fh.name
        fh.write(libsbml.writeSBMLToString(document))

    measurement_df = pd.DataFrame(
        data={
            'observableId': ['obs1', 'obs2'],
            'observableParameters': ['', 'p1;p2'],
            'noiseParameters': ['p3;p4', 'p5']
        })

    with tempfile.NamedTemporaryFile(mode='w', delete=False) as fh:
        measurement_file_name = fh.name
        measurement_df.to_csv(fh, sep='\t', index=False)

    condition_df = pd.DataFrame(
        data={
            'conditionId': ['condition1', 'condition2'],
            'conditionName': ['', 'Condition 2'],
            'fixedParameter1': [1.0, 2.0]
        })
    condition_df.set_index('conditionId', inplace=True)

    with tempfile.NamedTemporaryFile(mode='w', delete=False) as fh:
        condition_file_name = fh.name
        condition_df.to_csv(fh, sep='\t', index=True)

    parameter_df = pd.DataFrame(
        data={
            'parameterId': ['dynamicParameter1', 'dynamicParameter2'],
            'parameterName': ['', '...'],  # ...
        })

    with tempfile.NamedTemporaryFile(mode='w', delete=False) as fh:
        parameter_file_name = fh.name
        parameter_df.to_csv(fh, sep='\t', index=False)

    problem = petab.Problem.from_files(sbml_file=sbml_file_name,
                                       measurement_file=measurement_file_name,
                                       condition_file=condition_file_name,
                                       parameter_file=parameter_file_name)

    return problem
 def test_WriteL3SBML_Model_timeUnits(self):
   expected = wrapSBML_L3v1("  <model timeUnits=\"second\"/>\n"  
   )
   m = self.D.createModel("")
   m.setTimeUnits("second")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #16
0
def writerpSBMLtar(rpsbml_paths, outTar):
    with tarfile.open(outTar, 'w:xz') as tf:
        for rpsbml_name in rpsbml_paths:
            data = libsbml.writeSBMLToString(rpsbml_paths[rpsbml_name].document).encode('utf-8')
            fiOut = BytesIO(data)
            info = tarfile.TarInfo(rpsbml_name)
            info.size = len(data)
            tf.addfile(tarinfo=info, fileobj=fiOut)
Exemple #17
0
    def toSBML(self, disable_warnings=True):
        errors = self.document.checkConsistency()
        if (errors > 0) and not disable_warnings:
            for i in range(errors):
                print self.document.getError(i).getSeverityAsString(
                ), ": ", self.document.getError(i).getMessage()

        return libsbml.writeSBMLToString(self.document)
Exemple #18
0
    def toSBML(self):
        errors = self.document.checkConsistency()
        if (errors > 0):
            for i in range(errors):
                print self.document.getError(i).getSeverityAsString(
                ), ": ", self.document.getError(i).getMessage()

        return libsbml.writeSBMLToString(self.document)
 def test_WriteL3SBML_Model_conversionFactor(self):
   expected = wrapSBML_L3v1("  <model conversionFactor=\"p\"/>\n"  
   )
   m = self.D.createModel("")
   m.setConversionFactor("p")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
 def test_WriteL3SBML_Model_substanceUnits(self):
   expected = wrapSBML_L3v1("  <model substanceUnits=\"mole\"/>\n"  
   )
   m = self.D.createModel("")
   m.setSubstanceUnits("mole")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #21
0
def rp2Reader_mem(rpreader, rp2_pathways, rp2paths_pathways,
                  rp2paths_compounds, upper_flux_bound, lower_flux_bound,
                  maxRuleIds, pathway_id, compartment_id, species_group_id,
                  sink_species_group_id, pubchem_search, outputTar):
    """The main function to parse the files without writing to HDD

    :param rpreader: rpReader object
    :param rp2_pathways: The RetroPath2.0 results scope file
    :param rp2paths_pathways: The rp2paths result pathway (out_paths) file
    :param rp2paths_compounds: The rp2paths result compounds file
    :param upper_flux_bound: The default upper flux bound (Default: 999999)
    :param lower_flux_bound: The default lower flux bound (Default: 0)
    :param maxRuleIds: The maximal number of rules associated with each step (Default: 2)
    :param pathway_id: The Groups heterologous pathway id (Default: rp_pathway)
    :param compartment_id: The compartment SBML id (Default: MNXC3)
    :param species_group_id: The Groups id of the central species (Default: central_species)
    :param sink_species_group_id: The Groups id of the rp_sink_species (Default: rp_sink_species)
    :param pubchem_search: Use the pubchem database to search for missing cross reference (Default: False)
    :param outputTar: The output collection of rpSBML files

    :type rpreader: rpReader 
    :type rp2_pathways: str 
    :type rp2paths_pathways: str
    :type rp2paths_compounds: str
    :type upper_flux_bound: int
    :type lower_flux_bound: int
    :type maxRuleIds: int
    :type pathway_id: str
    :type compartment_id: str
    :type species_group_id: str
    :type sink_species_group_id: str
    :type pubchem_search: bool
    :type outputTar: str 

    :rtype: bool
    :return: Success or failure of the function
    """
    rpsbml_paths = rpreader.rp2ToSBML(rp2_pathways, rp2paths_pathways,
                                      rp2paths_compounds, None,
                                      upper_flux_bound, lower_flux_bound,
                                      maxRuleIds, pathway_id, compartment_id,
                                      species_group_id, sink_species_group_id,
                                      pubchem_search)
    #pass the SBML results to a tar
    if rpsbml_paths == {}:
        logging.error('rpReader did not generate any results')
        return False
    #outputTar = io.BytesIO()
    #with open(outputTar, 'w:xz') as tf:
    with tarfile.open(fileobj=outputTar, mode='w:gz') as tf:
        for rpsbml_name in rpsbml_paths:
            data = libsbml.writeSBMLToString(
                rpsbml_paths[rpsbml_name].document).encode('utf-8')
            fiOut = io.BytesIO(data)
            info = tarfile.TarInfo(name=rpsbml_name)
            info.size = len(data)
            tf.addfile(tarinfo=info, fileobj=fiOut)
    return True
 def test_WriteL3SBML_Model_otherUnits(self):
   expected = wrapSBML_L3v1("  <model volumeUnits=\"litre\" areaUnits=\"area\" lengthUnits=\"metre\"/>\n"  
   )
   m = self.D.createModel("")
   m.setVolumeUnits("litre")
   m.setAreaUnits("area")
   m.setLengthUnits("metre")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #23
0
def writerpSBMLzip(rpsbml_paths, outZip):
    zip_buffer = io.BytesIO()
    #with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
    with zipfile.ZipFile(zip_buffer, mode="a", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zip_file:
        for rpsbml_name in rpsbml_paths:
            data = libsbml.writeSBMLToString(rpsbml_paths[rpsbml_name].document).encode('utf-8')
            data = io.BytesIO(bytes(data))
            zip_file.writestr(rpsbml_name, data.getvalue())
    with open(outZip, 'wb') as f:
        f.write(zip_buffer.getvalue())
 def test_WriteL3SBML_Model_otherUnits(self):
   expected = wrapSBML_L3v1("  <model volumeUnits=\"litre\" areaUnits=\"area\" lengthUnits=\"metre\"/>\n"  
   )
   m = self.D.createModel("")
   m.setVolumeUnits("litre")
   m.setAreaUnits("area")
   m.setLengthUnits("metre")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #25
0
def runSingleSBML(rpcofactors, member_name, rpsbml_string, path_id,
                  compartment_id):
    #open one of the rp SBML files
    rpsbml = rpSBML.rpSBML(member_name,
                           libsbml.readSBMLFromString(rpsbml_string))
    #rpcofactors = rpRanker.rpCofactors()
    if rpcofactors.addCofactors(rpsbml, compartment_id, path_id):
        return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')
    else:
        return ''
Exemple #26
0
    def test_write_sbml_file(self):

        document, _ = self.crn.generate_sbml_model()
        sbml_string = libsbml.writeSBMLToString(document)

        file_name = 'test_sbml.xml'
        with patch("builtins.open", new=mock_open()) as _file:
            self.crn.write_sbml_file(file_name)

            _file.assert_called_once_with(file_name, 'w')
            _file().write.assert_called_once_with(sbml_string)
Exemple #27
0
def main():
    '''COMMENT'''
    terpenoid_pathway = 'ec00900'
    terpenoid_ec_numbers = ['2.3.1.9',
                            '2.3.3.10',
                            '1.1.1.34',
                            '2.7.1.36',
                            '2.7.4.2',
                            '4.1.1.33',
                            '5.3.3.2',
                            '2.5.1.1']

    monoterpenoid_pathway = 'ec00902'
    monoterpenoid_ec_numbers = ['4.2.3.16']

    pathway_ec_numbers = {terpenoid_pathway: terpenoid_ec_numbers,
                          monoterpenoid_pathway: monoterpenoid_ec_numbers}

    document = builder.build(pathway_ec_numbers)
    print libsbml.writeSBMLToString(document)
    def write_sbml_to_string(self):
        """ Write the SBML file.

        First create clean SBML file.

        :param sbml_out:
        :type sbml_out:
        :return:
        :rtype:
        """
        self._create_sbml()
        return libsbml.writeSBMLToString(self.doc)
Exemple #29
0
def create_model():
    document = libsbml.SBMLDocument(3, 1)
    model = document.createModel()
    model.setTimeUnits("second")
    model.setExtentUnits("mole")
    model.setSubstanceUnits('mole')

    create_unit_definitions(model)

    c1 = model.createCompartment()
    c1.setId('c1')
    c1.setConstant(True)
    c1.setSize(1)
    c1.setSpatialDimensions(3)
    c1.setUnits('litre')

    create_species(model, 'x1', 'c1', False, 0.1)
    create_species(model, 'x2', 'c1', False, 0.4)
    create_species(model, 'x3', 'c1', False, 0.7)

    #TODO: initial amounts should be parameters
    create_parameter(model, 'p1', True, 1.0, 'litre2_per_mole_per_second')
    create_parameter(model, 'p2', True, 0.5, 'litre2_per_mole_per_second')
    create_parameter(model, 'p3', True, 0.4, 'litre_per_second')
    create_parameter(model, 'p4', True, 2.0, 'litre_per_second')
    create_parameter(model, 'p5', True, 0.1, 'mole_per_second')
    create_parameter(model, 'k0', True, 1.0, 'litre_per_second')

    create_reaction(model, 'r1', [(2, 'x1')], [(1, 'x2')], 'p1 * x1^2')
    create_reaction(model, 'r2', [(1, 'x1'), (1, 'x2')], [(1, 'x3')],
                    'p2 * x1 * x2')
    create_reaction(model, 'r3', [(1, 'x2')], [(2, 'x1')], 'p3 * x2')
    create_reaction(model, 'r4', [(1, 'x3')], [(1, 'x1'), (1, 'x2')],
                    'p4 * x3')
    create_reaction(model, 'r5', [(1, 'x3')], [], 'k0 * x3')
    create_reaction(model, 'r6', [], [(1, 'x1')], 'p5')

    #    S -2 -1  2  1  0 1  v1: p1 x1^2
    #       1 -1 -1  1  0 0  v2: p2 x1 x2
    #       0  1  0 -1 -1 0  v3: p3 x2
    #                        v4: p4 x3
    #                        v5: k0 x3
    #                        v6: p5
    # R1: 2X1         ->       X2
    # R2:  X1 + X2    ->           X3
    # R3:       X2    -> 2X1
    # R4:          X3 ->  X1 + X2
    # R5:          X3 ->
    # R6:             ->  X1

    return libsbml.writeSBMLToString(document)
def runSingleSBML(member_name, rpsbml_string, inSBML, isMerge, path_id):
    #open one of the rp SBML files
    input_rpsbml = rpSBML.rpSBML('inputMergeModel',
                                 libsbml.readSBMLFromFile(inSBML))
    rpsbml = rpSBML.rpSBML(member_name,
                           libsbml.readSBMLFromString(rpsbml_string))
    #read the input GEM sbml model
    #input_rpsbml = rpSBML.rpSBML('inputMergeModel', libsbml.readSBMLFromString(inSBML_string))
    #print(input_rpsbml)
    #print(input_rpsbml.model)
    rpsbml.mergeModels(input_rpsbml.model)
    rpfba = rpFBA.rpFBA(input_rpsbml)
    rpfba.allObj(path_id)
    if isMerge:
        ##### pass FBA results to the original model ####
        groups = rpfba.rpsbml.model.getPlugin('groups')
        rp_pathway = groups.getGroup(path_id)
        for member in rp_pathway.getListOfMembers():
            reacFBA = rpfba.rpsbml.model.getReaction(member.getIdRef())
            reacIN = rpsbml.model.getReaction(member.getIdRef())
            reacIN.setAnnotation(reacFBA.getAnnotation())
        return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')
    else:
        return libsbml.writeSBMLToString(input_rpsbml.document).encode('utf-8')
 def test_WriteL3SBML_elements(self):
   expected = wrapSBML_L3v1("  <model>\n" + 
   "    <listOfFunctionDefinitions>\n" + 
   "      <functionDefinition/>\n" + 
   "    </listOfFunctionDefinitions>\n" + 
   "    <listOfUnitDefinitions>\n" + 
   "      <unitDefinition/>\n" + 
   "    </listOfUnitDefinitions>\n" + 
   "    <listOfCompartments>\n" + 
   "      <compartment constant=\"true\"/>\n" + 
   "    </listOfCompartments>\n" + 
   "    <listOfSpecies>\n" + 
   "      <species hasOnlySubstanceUnits=\"false\"" + 
   " boundaryCondition=\"false\" constant=\"false\"/>\n" + 
   "    </listOfSpecies>\n" + 
   "    <listOfParameters>\n" + 
   "      <parameter constant=\"true\"/>\n" + 
   "    </listOfParameters>\n" + 
   "    <listOfInitialAssignments>\n" + 
   "      <initialAssignment/>\n" + 
   "    </listOfInitialAssignments>\n" + 
   "    <listOfRules>\n" + 
   "      <algebraicRule/>\n" + 
   "    </listOfRules>\n" + 
   "    <listOfConstraints>\n" + 
   "      <constraint/>\n" + 
   "    </listOfConstraints>\n" + 
   "    <listOfReactions>\n" + 
   "      <reaction reversible=\"true\" fast=\"false\"/>\n" + 
   "    </listOfReactions>\n" + 
   "    <listOfEvents>\n" + 
   "      <event/>\n" + 
   "    </listOfEvents>\n" + 
   "  </model>\n")
   m = self.D.createModel()
   m.createUnitDefinition()
   m.createFunctionDefinition()
   m.createCompartment()
   m.createEvent()
   m.createParameter()
   m.createAlgebraicRule()
   m.createInitialAssignment()
   m.createConstraint()
   m.createReaction()
   m.createSpecies()
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Exemple #32
0
    def test_write_sbml_file(self):
        s1, s2 = Species("S1"), Species("S2")
        rx1 = Reaction.from_massaction(inputs=[s1],
                                       outputs=[s2],
                                       k_forward=0.1)
        crn = ChemicalReactionNetwork(species=[s1, s2], reactions=[rx1])

        model_id = 'test_model'
        document, _ = crn.generate_sbml_model(model_id=model_id)
        sbml_string = libsbml.writeSBMLToString(document)

        file_name = 'test_sbml.xml'
        with patch("builtins.open", new=mock_open()) as _file:
            crn.write_sbml_file(file_name, model_id=model_id)

            _file.assert_called_once_with(file_name, 'w')
            _file().write.assert_called_once_with(sbml_string)
Exemple #33
0
    def export(self, level=(3, 2)):
        """
        Export the SBML for the PySB model associated with the exporter

        Requires libsbml package.

        Parameters
        ----------
        level: (int, int)
            The SBML level and version to use. The default is SBML level 3, version 2. Conversion
            to other levels/versions may not be possible or may lose fidelity.

        Returns
        -------
        string
            String containing the SBML output.
        """
        return libsbml.writeSBMLToString(self.convert(level=level))
Exemple #34
0
    def export(self, level=(3, 2)):
        """
        Export the SBML for the PySB model associated with the exporter

        Requires libsbml package.

        Parameters
        ----------
        level: (int, int)
            The SBML level and version to use. The default is SBML level 3, version 2. Conversion
            to other levels/versions may not be possible or may lose fidelity.

        Returns
        -------
        string
            String containing the SBML output.
        """
        return libsbml.writeSBMLToString(self.convert(level=level))
Exemple #35
0
    def write_sbml_file(self,
                        file_name=None,
                        stochastic_model=False,
                        **keywords) -> bool:
        """"Writes CRN object to a SBML file

        :param file_name: name of the file where the SBML model gets written
        :param stochastic_model: export an SBML file which ready for stochastic simulations
        :param keywords: keywords that passed into generate_sbml_model()
        :return: bool, show whether the writing process was successful
        """

        document, _ = self.generate_sbml_model(
            stochastic_model=stochastic_model, **keywords)
        sbml_string = libsbml.writeSBMLToString(document)
        with open(file_name, 'w') as f:
            f.write(sbml_string)
        return True
    def simulate_with_roadrunner(self,
                                 timepoints: List[float],
                                 initial_condition_dict: Dict[str,
                                                              float] = None,
                                 return_roadrunner=False,
                                 check_validity=True):
        """To simulate using roadrunner.
        Arguments:
        timepoints: The array of time points to run the simulation for.
        initial_condition_dict:

        Returns the results array as returned by RoadRunner OR a Roadrunner model object.

        Refer to the libRoadRunner simulator library documentation 
        for details on simulation results: (http://libroadrunner.org/)[http://libroadrunner.org/]
        NOTE : Needs roadrunner package installed to simulate.
        """
        res_ar = None
        try:
            import roadrunner
            import io
            document, _ = self.generate_sbml_model(
                stochastic_model=False, check_validity=check_validity)
            sbml_string = libsbml.writeSBMLToString(document)
            # write the sbml_string into a temporary file in memory instead of a file
            string_out = io.StringIO()
            string_out.write(sbml_string)
            # use the temporary file in memory to load the model into libroadrunner
            rr = roadrunner.RoadRunner(string_out.getvalue())
            if initial_condition_dict:
                for species, value in initial_condition_dict.items():
                    rr.model[f"init([{species}])"] = value

            if return_roadrunner:
                return rr
            else:
                result = rr.simulate(timepoints[0], timepoints[-1],
                                     len(timepoints))
                res_ar = result
        except ModuleNotFoundError:
            warnings.warn(
                'libroadrunner was not found, please install libroadrunner')
        return res_ar
Exemple #37
0
def convertToSBMLModel( anEml, aBaseName, aLevel, aVersion ):
    '''
    this function is called from ecell3-eml2sbml
    '''

    global aSBMLLevel
    aSBMLLevel = aLevel

    aSBMLDocument = libsbml.SBMLDocument()
    aSBMLDocument.setLevelAndVersion( int( aLevel ), int( aVersion ) )
    aSBMLModel = aSBMLDocument.createModel()

    aSBMLModel.setId( aBaseName )

    createModel( anEml, aSBMLModel )

    # set abogadro number and EmptySet to SBML model
    setEssentialEntity( aSBMLModel )

    return libsbml.writeSBMLToString( aSBMLDocument )
Exemple #38
0
def convertToSBMLModel(anEml, aBaseName, aLevel, aVersion):
    '''
    this function is called from ecell3-eml2sbml
    '''

    global aSBMLLevel
    aSBMLLevel = aLevel

    aSBMLDocument = libsbml.SBMLDocument()
    aSBMLDocument.setLevelAndVersion(int(aLevel), int(aVersion))
    aSBMLModel = aSBMLDocument.createModel()

    aSBMLModel.setId(aBaseName)

    createModel(anEml, aSBMLModel)

    # set abogadro number and EmptySet to SBML model
    setEssentialEntity(aSBMLModel)

    return libsbml.writeSBMLToString(aSBMLDocument)
Exemple #39
0
def clamp_species(r: roadrunner.RoadRunner,
                  sids,
                  boundary_condition=True) -> roadrunner.RoadRunner:
    """ Clamp/Free specie(s) via setting boundaryCondition=True/False.

    This requires changing the SBML and ODE system.

    :param r: roadrunner.RoadRunner
    :param sids: sid or iterable of sids
    :param boundary_condition: boolean flag to clamp (True) or free (False) species
    :return: modified roadrunner.RoadRunner
    """
    # get model for current SBML state
    sbml_str = r.getCurrentSBML()
    doc = libsbml.readSBMLFromString(sbml_str)  # type: libsbml.SBMLDocument
    model = doc.getModel()  # type: libsbml.Model

    if isinstance(sids, str):
        sids = [sids]

    for sid in sids:
        # set boundary conditions
        sbase = model.getElementBySId(sid)  # type: libsbml.SBase
        if not sbase:
            logging.error("No element for SId in model: {}".format(sid))
            return None
        else:
            if sbase.getTypeCode() == libsbml.SBML_SPECIES:
                species = sbase  # type: libsbml.Species
                species.setBoundaryCondition(boundary_condition)
            else:
                logging.error(
                    "SId in clamp does not match species: {}".format(sbase))
                return None

    # create modified roadrunner instance
    sbmlmod_str = libsbml.writeSBMLToString(doc)
    rmod = load_model(sbmlmod_str)  # type: roadrunner.RoadRunner
    set_timecourse_selections(rmod, r.timeCourseSelections)

    return rmod
Exemple #40
0
def CreateExample4(Repetitions = 1):
    "Create SBML Array simulation example 4"
    PopulationSize = 100
    TimeLimit = 10
    (NameSpace,Document,Model,IndividualsUnit,SimulationSize,InstructionNumber,DefineDimension,Random,Time) = InitExample(PopulationSize*Repetitions)

    StateList = ['Healthy','Sick','Dead']
    DefineStates(Model, StateList, SimulationSize)  

    DefineParamArray(Model,'Male',SimulationSize)
    DefineParamArray(Model,'Age',SimulationSize)


    DefineInitialAssignment(Container = Model, Symbol = 'Healthy', Size = SimulationSize, MathExpression = 'selector(vector('+str([1]*PopulationSize*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Sick', Size = SimulationSize, MathExpression = 'selector(vector('+str([0]*PopulationSize*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Dead', Size = SimulationSize, MathExpression = 'selector(vector('+str([0]*PopulationSize*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Male', Size = SimulationSize, MathExpression = 'selector(vector('+str(([0]*(PopulationSize/2)+[1]*(PopulationSize/2))*Repetitions)[1:-1]+ '),d0)')
    DefineInitialAssignment(Container = Model, Symbol = 'Age', Size = SimulationSize, MathExpression = 'selector(vector('+str(list(range(1,(PopulationSize/2)+1))*2*Repetitions)[1:-1]+ '),d0)')

    # terminate event at start of loop
    DefineTerminalEvent (Model = Model, TerminalStates = ['Dead'], Size = SimulationSize, TimeLimit=TimeLimit)
    
    Assignments =   (
                        [ 
                            ('Age', 'selector(Age,d0)+1', (0,'variable','d0' ) ) ,
                        ]
                        ,
                       []
                    )                    

    DefineDualEventArrays(Container=Model, Size = SimulationSize, Name='Age Increase', InstructionNumber=1, TriggerFormulas = ('true','false'), LeadPriority = 0, DelayFormula='1', Assignments=Assignments)

    
    TransitionFormula(Model = Model, FromStates = [ 'Healthy' ], ToStates = [ 'Dead', 'Sick'] , Probabilities = [ [ 'selector(Age,d0)/1000' ,'min(0.8,0.1*(1+selector(Male,d0))+0.01*selector(Age,d0))'] ] , Size = SimulationSize, InstructionNumber = 2, NextLine = 0)
    TransitionFormula(Model = Model, FromStates = [ 'Sick' ], ToStates = [ 'Healthy','Dead'] , Probabilities = [ [ '0.1','min(0.9, 0.01*selector(Age,d0) + 0.2*selector(Male,d0))' ] ] , Size = SimulationSize, InstructionNumber = 2, NextLine = 0)


    return libsbml.writeSBMLToString(Document)
 def getComponentSBML(self):
     '''
     Returns list of SBML models generated from each model reaction
     '''
     import libsbml
     return [libsbml.writeSBMLToString(doc) for doc in self.submodels]
 def test_WriteL3SBML_SBMLDocument_L3v1(self):
   expected = wrapXML("<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" " + "level=\"3\" version=\"1\"/>\n")
   self.S = libsbml.writeSBMLToString(self.D)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
def flattenExternalModelDefinitions(doc):
    """ Converts all ExternalModelDefinitions to ModelDefinitions.

    I.e. the definition of models in external files are read
    and directly included in the top model. The resulting
    comp model consists than only of a single file.

    The model refs in the submodel do not change in the process,
    so no need to update the submodels.

    :param doc: SBMLDocument
    :return: SBMLDocument with ExternalModelDefinitions replaced
    """
    # FIXME: handle /multiple levels of hierarchies recursively (ExternalModelDefinitions of submodels)

    model = doc.getModel()
    if model is None:
        return doc

    comp_doc = doc.getPlugin("comp")
    emd_list = comp_doc.getListOfExternalModelDefinitions()

    # no ExternalModelDefinitions
    if (emd_list is None) or (len(emd_list) == 0):
        return doc

    # ExternalModelDefinitions set as ModelDefinitions
    emd_ids = []
    mds = []
    for emd in emd_list:
        emd_ids.append(emd.getId())

        # get the model definition from the model
        ref_model = emd.getReferencedModel()

        # store model definition
        md = libsbml.ModelDefinition(ref_model)
        mds.append(md)

    packages = []
    for emd in emd_list:
        # get the model definition from the model
        ref_model = emd.getReferencedModel()
        ref_doc = ref_model.getSBMLDocument()
        # print('\n', ref_model)
        for k in range(ref_doc.getNumPlugins()):

            plugin = ref_doc.getPlugin(k)
            uri = plugin.getURI()
            prefix = plugin.getPrefix()
            name = plugin.getPackageName()
            required = None
            if ref_doc.isSetPackageRequired(name):
                required = ref_doc.getPackageRequired(name)

            packages.append({
                'model': ref_model,
                'uri': uri,
                'prefix': prefix,
                'name': name,
                'required': required
            })

    # remove emds from model (do not remove while iterating over the list)
    for emd_id in emd_ids:
        comp_doc.removeExternalModelDefinition(emd_id)

    # activate all the packages
    from pprint import pprint
    pprint(packages)
    for pdict in packages:
        doc.enablePackage(pdict['uri'], pdict['prefix'], True)
        doc.setPackageRequired(pdict['name'], pdict['required'])

    # now add the model definitions
    for md in mds:
        comp_doc.addModelDefinition(md)

    sbml_str = libsbml.writeSBMLToString(doc)
    doc = libsbml.readSBMLFromString(sbml_str)

    # replacement finished, now go through all ModelDefinitions
    # and add things the packages require
    print("-"*80)
    for k in range(doc.getNumPlugins()):
        plugin = doc.getPlugin(k)
        name = plugin.getPackageName()
        print(name, '\n')
        md_list = comp_doc.getListOfModelDefinitions()
        for md_model in md_list:

            # if a package needs something on
            # a model we have to write it on all ModelDefinitions
            # this will break on a package per package basis ! We know about fbc it needs
            # a strict tag so writing this here
            if name == "fbc":
                # for some ModelDefinitions we don't get the fbc Plugin ???
                fbc_model = md_model.getPlugin(name)

                print('\tModel:', md_model)
                print('\tFBCModelPlugin:', fbc_model, type(fbc_model))

                # setting because it is required (if unlucky additional info required)
                # but we can't set it because we can't access the FBCModelPlugins of the ModelDefinitions
                if fbc_model is not None:
                    if not fbc_model.isSetStrict():
                        fbc_model.setStrict(False)
                else:
                    print("WARNING: This should never happen. All ModelDefinitions should have a FBCModelPlugin")

    doc.checkInternalConsistency()
    doc.printErrors()

    return doc
    # 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


if __name__ == "__main__":

    functions = [
        # distrib_normal,
        # distrib_all,
        uncertainty,
    ]
    for f_creator in functions:
        name = f_creator.__name__
        print(name)
        # distrib_example1()
        doc = f_creator()
        sbml = libsbml.writeSBMLToString(doc)
        print("-" * 80)
        print(sbml)
        print("-" * 80)
        sbml_path = "./{}.xml".format(name)

        libsbml.writeSBMLToFile(doc, sbml_path)
        validation.check_doc(doc)
Exemple #45
0
 def __repr__(self):
     return libsbml.writeSBMLToString(self.document)
Exemple #46
0
    def test_sbml(self):
        fwd = Direction.forward()
        rev = Direction.reversible()

        a = M("A_c")
        b = M("B_c")
        c = M("C_e")
        e = M("E_e", boundary=True)

        model = Model()
        model.reactions = [
            R("R1", 1*a, 3*b, direction=fwd, bounds=Bounds(-100, 100)),
            R("R2", 1*c, 3*b, direction=fwd, bounds=Bounds(-100, 100)),
            R("R3", 1*b + 1*c, 1*e, direction=rev, bounds=Bounds(-100, 100))]

        import libsbml
        import converter
        sbml = converter.Bioopt2SbmlConverter().convert(model)
        sbml_export = libsbml.writeSBMLToString(sbml)

        doc = libsbml.readSBMLFromString(sbml_export)
        self.assertEquals(0, doc.getNumErrors())

        exp_export = """<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version3" level="2" version="3">
  <model>
    <listOfUnitDefinitions>
      <unitDefinition id="mmol_per_gDW_per_hr">
        <listOfUnits>
          <unit kind="mole" scale="-3"/>
          <unit kind="second" exponent="-1" multiplier="0.00027778"/>
        </listOfUnits>
      </unitDefinition>
    </listOfUnitDefinitions>
    <listOfCompartments>
      <compartment id="C_0001" name="c"/>
      <compartment id="C_0002" name="e"/>
    </listOfCompartments>
    <listOfSpecies>
      <species id="M_0001_c" name="A_c" compartment="C_0001" initialAmount="0" boundaryCondition="false"/>
      <species id="M_0002_b" name="E_e" compartment="C_0002" initialAmount="0" boundaryCondition="true"/>
      <species id="M_0003_e" name="C_e" compartment="C_0002" initialAmount="0" boundaryCondition="false"/>
      <species id="M_0004_c" name="B_c" compartment="C_0001" initialAmount="0" boundaryCondition="false"/>
    </listOfSpecies>
    <listOfReactions>
      <reaction id="R_0001" name="R1" reversible="false">
        <listOfReactants>
          <speciesReference species="M_0001_c" stoichiometry="1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="M_0004_c" stoichiometry="3"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <ci> FLUX_VALUE </ci>
          </math>
          <listOfParameters>
            <parameter id="LOWER_BOUND" value="-100" units="mmol_per_gDW_per_hr"/>
            <parameter id="UPPER_BOUND" value="100" units="mmol_per_gDW_per_hr"/>
            <parameter id="OBJECTIVE_COEFFICIENT" value="0" units="dimensionless"/>
            <parameter id="FLUX_VALUE" value="0" units="mmol_per_gDW_per_hr"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
      <reaction id="R_0002" name="R2" reversible="false">
        <listOfReactants>
          <speciesReference species="M_0003_e" stoichiometry="1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="M_0004_c" stoichiometry="3"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <ci> FLUX_VALUE </ci>
          </math>
          <listOfParameters>
            <parameter id="LOWER_BOUND" value="-100" units="mmol_per_gDW_per_hr"/>
            <parameter id="UPPER_BOUND" value="100" units="mmol_per_gDW_per_hr"/>
            <parameter id="OBJECTIVE_COEFFICIENT" value="0" units="dimensionless"/>
            <parameter id="FLUX_VALUE" value="0" units="mmol_per_gDW_per_hr"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
      <reaction id="R_0003" name="R3" reversible="true">
        <listOfReactants>
          <speciesReference species="M_0004_c" stoichiometry="1"/>
          <speciesReference species="M_0003_e" stoichiometry="1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="M_0002_b" stoichiometry="1"/>
        </listOfProducts>
        <kineticLaw>
          <math xmlns="http://www.w3.org/1998/Math/MathML">
            <ci> FLUX_VALUE </ci>
          </math>
          <listOfParameters>
            <parameter id="LOWER_BOUND" value="-100" units="mmol_per_gDW_per_hr"/>
            <parameter id="UPPER_BOUND" value="100" units="mmol_per_gDW_per_hr"/>
            <parameter id="OBJECTIVE_COEFFICIENT" value="0" units="dimensionless"/>
            <parameter id="FLUX_VALUE" value="0" units="mmol_per_gDW_per_hr"/>
          </listOfParameters>
        </kineticLaw>
      </reaction>
    </listOfReactions>
  </model>
</sbml>
"""

        exp_export = sbml_export # TODO: we have a stochioustic processes in metabolite id generation so strings can't be used to assert
        self.assertEquals(exp_export, sbml_export)
def toSBMLString(net):
    try:
        m = libsbml.Model(net.id)
    except NotImplementedError:
        m = libsbml.Model(sbml_level, sbml_version)
        m.setId(net.id)
    m.setName(net.name)
    
    for id, fd in 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))
        m.addFunctionDefinition(sfd)
    
    for id, c in 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)
        m.addCompartment(sc)
    
    for id, s in 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)
        m.addSpecies(ss)
    
    for id, p in 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)
        m.addParameter(sp)

    for id, r in 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))
        m.addRule(sr)

    for id, r in 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))
        m.addRule(sr)

    for r, r in net.algebraicRules.items():
        try:
            sr = libsbml.AlgebraicRule()
        except NotImplementedError:
            sr = libsbml.AlgebraicRule(sbml_level, sbml_version)
        formula = r.replace('**', '^')
        sr.setMath(libsbml.parseFormula(formula))
        m.addRule(sr)
        
    for id, rxn in net.reactions.items():
        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 rxn.reactant_stoichiometry.items():
                for stoich in stoich_list:
                    rxn_add_stoich(srxn, rid, -stoich, is_product=False)
            for rid, stoich_list in 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 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)
        m.addReaction(srxn)
    
    for id, e in 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 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)
        m.addEvent(se)

    for id, con in 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)
        #try:
        scon.setMath(ast)
        #except TypeError:
        #    scon.setMath(libsbml.Trigger(ast))

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

    return sbmlStr
"""
Try to set SBOTerm on reaction.
"""
import libsbml

# using L3V2, so I don't need species on reaction
doc = libsbml.SBMLDocument(3, 1)
model = doc.createModel()
model.setId('test model')
r = model.createReaction()
r.setSBOTerm('SBO:0000631')

sbml_str = libsbml.writeSBMLToString(doc)
print(sbml_str)
 def getSbml(self):
     '''
     Returns SBML representation of model
     '''
     import libsbml
     return libsbml.writeSBMLToString(self.document)