Esempio n. 1
0
    def convert_SBML_Formula_to_ecell_Expression( self, formula, aModel, aLocalParameterList = [], aDenominator = 1.0 ):

        '''## =================================================
          formula: string or libsbml.ASTNode
        '''## =================================================

        if isinstance( formula, str ):
            if aDenominator != 1.0:
                formula = '( 1.0 / %s ) * ( %s )' % ( aDenominator, formula )

            preprocessedFormula = formula.replace( '<t>', self.Model.TimeSymbol )
            aASTRootNode = libsbml.parseFormula( preprocessedFormula )

        elif isinstance( formula, libsbml.ASTNode ):
           if aDenominator != 1.0:
                aASTRootNode = libsbml.parseFormula( '( 1.0 / %s ) * ( x )' % aDenominator )
                aASTRootNode.removeChild( 1 )
                aASTRootNode.addChild( formula.deepCopy() )
           else:
               aASTRootNode = formula

        else:
            raise Exception,"DEBUG : Formula must be str or libsbml.ASTNode instance."

##        dump_tree_construction_of_AST_node( aASTRootNode )

        aASTRootNode = preprocess_math_tree( aASTRootNode, aModel.TimeSymbol )

        convertedAST = self._convert_SBML_variable_to_ecell_Expression( aASTRootNode, aLocalParameterList )

        return postprocess_math_string( libsbml.formulaToString( convertedAST ), aModel.TimeSymbol )
Esempio n. 2
0
    def convert_SBML_Formula_to_ecell_Expression( self, formula, aModel, aLocalParameterList = [], aDenominator = 1.0 ):
        
        '''## =================================================
          formula: string or libsbml.ASTNode
        '''## =================================================
        
        if isinstance( formula, str ):
            if aDenominator != 1.0:
                formula = '( 1.0 / %s ) * ( %s )' % ( aDenominator, formula )
        
            preprocessedFormula = formula.replace( '<t>', self.Model.TimeSymbol )
            aASTRootNode = libsbml.parseFormula( preprocessedFormula )

        elif isinstance( formula, libsbml.ASTNode ):
           if aDenominator != 1.0:
                aASTRootNode = libsbml.parseFormula( '( 1.0 / %s ) * ( x )' % aDenominator )
                aASTRootNode.removeChild( 1 )
                aASTRootNode.addChild( formula.deepCopy() )
           else:
               aASTRootNode = formula

        else:
            raise Exception,"DEBUG : Formula must be str or libsbml.ASTNode instance."

##        dump_tree_construction_of_AST_node( aASTRootNode )

        aASTRootNode = preprocess_math_tree( aASTRootNode, aModel.TimeSymbol )

        convertedAST = self._convert_SBML_variable_to_ecell_Expression( aASTRootNode, aLocalParameterList )

        return postprocess_math_string( libsbml.formulaToString( convertedAST ), aModel.TimeSymbol )
 def test_WriteL3SBML_Event_full(self):
   expected = wrapString("<event useValuesFromTriggerTime=\"true\">\n" + 
   "  <trigger initialValue=\"true\" persistent=\"false\">\n" + 
   "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" + 
   "      <true/>\n" + 
   "    </math>\n" + 
   "  </trigger>\n" + 
   "  <priority>\n" + 
   "    <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" + 
   "      <cn type=\"integer\"> 2 </cn>\n" + 
   "    </math>\n" + 
   "  </priority>\n" + 
   "</event>")
   e = self.D.createModel().createEvent()
   e.setUseValuesFromTriggerTime(True)
   t = e.createTrigger()
   t.setInitialValue(True)
   t.setPersistent(False)
   math1 = libsbml.parseFormula("true")
   t.setMath(math1)
   p = e.createPriority()
   math2 = libsbml.parseFormula("2")
   p.setMath(math2)
   self.assertEqual( True, self.equals(expected,e.toSBML()) )
   pass  
 def test_ValidASTNode_Number(self):
   n = libsbml.parseFormula("1.2")
   self.assertEqual( True, n.isWellFormedASTNode() )
   d = libsbml.parseFormula("d")
   n.addChild(d)
   self.assertEqual( False, (n.isWellFormedASTNode()) )
   n = None
   pass  
 def test_ValidASTNode_binary(self):
   n = libsbml.ASTNode(libsbml.AST_DIVIDE)
   self.assertEqual( False, (n.isWellFormedASTNode()) )
   c = libsbml.parseFormula("c")
   n.addChild(c)
   self.assertEqual( False, (n.isWellFormedASTNode()) )
   d = libsbml.parseFormula("d")
   n.addChild(d)
   self.assertEqual( True, n.isWellFormedASTNode() )
   n = None
   pass  
Esempio n. 6
0
 def test_ValidASTNode_binary(self):
     n = libsbml.ASTNode(libsbml.AST_DIVIDE)
     self.assertEqual(False, (n.isWellFormedASTNode()))
     c = libsbml.parseFormula("c")
     n.addChild(c)
     self.assertEqual(False, (n.isWellFormedASTNode()))
     d = libsbml.parseFormula("d")
     n.addChild(d)
     self.assertEqual(True, n.isWellFormedASTNode())
     n = None
     pass
Esempio n. 7
0
 def handleEvents(self, line, name):
     # expect an event, or a new context
     if (line[0] == "@"):
         self.handleNewContext(line, name)
     else:
         bits = line.split(":")
         if (len(bits) != 2):
             sys.stderr.write('Error: expected exactly one ":" on ')
             sys.stderr.write('line ' + str(self.count) + '\n')
             raise ParseError
         (event, assignments) = bits
         bits = event.split(";")
         trigbits = bits[0].split("=")
         if (len(trigbits) < 2):
             sys.stderr.write('Error: expected a "=" before ":" on ')
             sys.stderr.write('line ' + str(self.count) + '\n')
             raise ParseError
         id = trigbits[0]
         trig = "=".join(trigbits[1:])
         e = self.m.createEvent()
         e.setId(id)
         e.setUseValuesFromTriggerTime(True)
         trig = self.trigMangle(trig)
         triggerMath = libsbml.parseFormula(trig)
         self.replaceTime(triggerMath)
         trigger = e.createTrigger()
         trigger.setPersistent(True)
         trigger.setInitialValue(False)
         trigger.setMath(triggerMath)
         if (len(bits) == 2):
             e.setUseValuesFromTriggerTime(False)
             delay = e.createDelay()
             delayMath = libsbml.parseFormula(bits[1])
             delay.setMath(delayMath)
         # SPLIT
         if (self.mangle >= 230):
             asslist = assignments.split(";")
         else:
             asslist = assignments.split(",")
         for ass in asslist:
             bits = ass.split("=")
             if (len(bits) != 2):
                 sys.stderr.write(
                     'Error: expected exactly one "=" in assignment on')
                 sys.stderr.write('line ' + str(self.count) + '\n')
                 raise ParseError
             (var, math) = bits
             ea = self.m.createEventAssignment()
             ea.setVariable(var)
             ea.setMath(libsbml.parseFormula(math))
         if (name != ""):
             e.setName(name)
Esempio n. 8
0
 def handleEvents(self,line,name):
     # expect an event, or a new context
     if (line[0]=="@"):
         self.handleNewContext(line,name)
     else:
         bits=line.split(":")
         if (len(bits)!=2):
             sys.stderr.write('Error: expected exactly one ":" on ')
             sys.stderr.write('line '+str(self.count)+'\n')
             raise ParseError
         (event,assignments)=bits
         bits=event.split(";")
         trigbits=bits[0].split("=")
         if (len(trigbits)<2):
             sys.stderr.write('Error: expected a "=" before ":" on ')
             sys.stderr.write('line '+str(self.count)+'\n')
             raise ParseError
         id=trigbits[0]
         trig="=".join(trigbits[1:])
         e=self.m.createEvent()
         e.setId(id)
         e.setUseValuesFromTriggerTime(True)
         trig=self.trigMangle(trig)
         triggerMath=libsbml.parseFormula(trig)
         self.replaceTime(triggerMath)
         trigger=e.createTrigger()
         trigger.setPersistent(True)
         trigger.setInitialValue(False)
         trigger.setMath(triggerMath)
         if (len(bits)==2):
             e.setUseValuesFromTriggerTime(False)
             delay=e.createDelay()
             delayMath=libsbml.parseFormula(bits[1])
             delay.setMath(delayMath)
         # SPLIT
         if (self.mangle>=230):
             asslist=assignments.split(";")
         else:
             asslist=assignments.split(",")
         for ass in asslist:
             bits=ass.split("=")
             if (len(bits)!=2):
                 sys.stderr.write('Error: expected exactly one "=" in assignment on')
                 sys.stderr.write('line '+str(self.count)+'\n')
                 raise ParseError
             (var,math)=bits
             ea=self.m.createEventAssignment()
             ea.setVariable(var)
             ea.setMath(libsbml.parseFormula(math))
         if (name!=""):
             e.setName(name)
Esempio n. 9
0
 def test_ValidASTNode_root(self):
     n = libsbml.ASTNode(libsbml.AST_FUNCTION_ROOT)
     self.assertEqual(False, (n.isWellFormedASTNode()))
     c = libsbml.parseFormula("c")
     n.addChild(c)
     self.assertEqual(True, n.isWellFormedASTNode())
     d = libsbml.parseFormula("3")
     n.addChild(d)
     self.assertEqual(True, n.isWellFormedASTNode())
     e = libsbml.parseFormula("3")
     n.addChild(e)
     self.assertEqual(False, (n.isWellFormedASTNode()))
     n = None
     pass
Esempio n. 10
0
 def test_ValidASTNode_lambda(self):
     n = libsbml.ASTNode(libsbml.AST_LAMBDA)
     self.assertEqual(False, (n.isWellFormedASTNode()))
     c = libsbml.parseFormula("c")
     n.addChild(c)
     self.assertEqual(True, n.isWellFormedASTNode())
     d = libsbml.parseFormula("d")
     n.addChild(d)
     self.assertEqual(True, n.isWellFormedASTNode())
     e = libsbml.parseFormula("e")
     n.addChild(e)
     self.assertEqual(True, n.isWellFormedASTNode())
     n = None
     pass
Esempio n. 11
0
 def test_Model_getFunctionDefinitionById(self):
     fd1 = libsbml.FunctionDefinition(2, 4)
     fd2 = libsbml.FunctionDefinition(2, 4)
     fd1.setId("sin")
     fd2.setId("cos")
     fd1.setMath(libsbml.parseFormula("2"))
     fd2.setMath(libsbml.parseFormula("2"))
     self.M.addFunctionDefinition(fd1)
     self.M.addFunctionDefinition(fd2)
     self.assert_(self.M.getNumFunctionDefinitions() == 2)
     self.assert_(self.M.getFunctionDefinition("sin") != fd1)
     self.assert_(self.M.getFunctionDefinition("cos") != fd2)
     self.assert_(self.M.getFunctionDefinition("tan") == None)
     pass
Esempio n. 12
0
 def test_Model_getFunctionDefinitionById(self):
   fd1 = libsbml.FunctionDefinition(2,4)
   fd2 = libsbml.FunctionDefinition(2,4)
   fd1.setId( "sin" )
   fd2.setId( "cos" )
   fd1.setMath(libsbml.parseFormula("2"))
   fd2.setMath(libsbml.parseFormula("2"))
   self.M.addFunctionDefinition(fd1)
   self.M.addFunctionDefinition(fd2)
   self.assert_( self.M.getNumFunctionDefinitions() == 2 )
   self.assert_( self.M.getFunctionDefinition( "sin" ) != fd1 )
   self.assert_( self.M.getFunctionDefinition( "cos" ) != fd2 )
   self.assert_( self.M.getFunctionDefinition( "tan" ) == None )
   pass  
Esempio n. 13
0
 def test_Model_addRules(self):
     r1 = libsbml.AlgebraicRule(2, 4)
     r2 = libsbml.AssignmentRule(2, 4)
     r3 = libsbml.RateRule(2, 4)
     r2.setVariable("r2")
     r3.setVariable("r3")
     r1.setMath(libsbml.parseFormula("2"))
     r2.setMath(libsbml.parseFormula("2"))
     r3.setMath(libsbml.parseFormula("2"))
     self.M.addRule(r1)
     self.M.addRule(r2)
     self.M.addRule(r3)
     self.assert_(self.M.getNumRules() == 3)
     pass
Esempio n. 14
0
 def test_Model_add_get_FunctionDefinitions(self):
     fd1 = libsbml.FunctionDefinition(2, 4)
     fd2 = libsbml.FunctionDefinition(2, 4)
     fd1.setId("fd1")
     fd2.setId("fd2")
     fd1.setMath(libsbml.parseFormula("2"))
     fd2.setMath(libsbml.parseFormula("2"))
     self.M.addFunctionDefinition(fd1)
     self.M.addFunctionDefinition(fd2)
     self.assert_(self.M.getNumFunctionDefinitions() == 2)
     self.assert_(self.M.getFunctionDefinition(0) != fd1)
     self.assert_(self.M.getFunctionDefinition(1) != fd2)
     self.assert_(self.M.getFunctionDefinition(2) == None)
     pass
Esempio n. 15
0
 def test_Model_addRules(self):
   r1 = libsbml.AlgebraicRule(2,4)
   r2 = libsbml.AssignmentRule(2,4)
   r3 = libsbml.RateRule(2,4)
   r2.setVariable( "r2")
   r3.setVariable( "r3")
   r1.setMath(libsbml.parseFormula("2"))
   r2.setMath(libsbml.parseFormula("2"))
   r3.setMath(libsbml.parseFormula("2"))
   self.M.addRule(r1)
   self.M.addRule(r2)
   self.M.addRule(r3)
   self.assert_( self.M.getNumRules() == 3 )
   pass  
Esempio n. 16
0
 def test_ValidASTNode_root(self):
   n = libsbml.ASTNode(libsbml.AST_FUNCTION_ROOT)
   self.assertEqual( False, (n.isWellFormedASTNode()) )
   c = libsbml.parseFormula("c")
   n.addChild(c)
   self.assertEqual( True, n.isWellFormedASTNode() )
   d = libsbml.parseFormula("3")
   n.addChild(d)
   self.assertEqual( True, n.isWellFormedASTNode() )
   e = libsbml.parseFormula("3")
   n.addChild(e)
   self.assertEqual( False, (n.isWellFormedASTNode()) )
   n = None
   pass  
Esempio n. 17
0
 def test_Model_add_get_FunctionDefinitions(self):
   fd1 = libsbml.FunctionDefinition(2,4)
   fd2 = libsbml.FunctionDefinition(2,4)
   fd1.setId( "fd1")
   fd2.setId( "fd2")
   fd1.setMath(libsbml.parseFormula("2"))
   fd2.setMath(libsbml.parseFormula("2"))
   self.M.addFunctionDefinition(fd1)
   self.M.addFunctionDefinition(fd2)
   self.assert_( self.M.getNumFunctionDefinitions() == 2 )
   self.assert_( self.M.getFunctionDefinition(0) != fd1 )
   self.assert_( self.M.getFunctionDefinition(1) != fd2 )
   self.assert_( self.M.getFunctionDefinition(2) == None )
   pass  
Esempio n. 18
0
 def test_ValidASTNode_lambda(self):
   n = libsbml.ASTNode(libsbml.AST_LAMBDA)
   self.assertEqual( False, (n.isWellFormedASTNode()) )
   c = libsbml.parseFormula("c")
   n.addChild(c)
   self.assertEqual( True, n.isWellFormedASTNode() )
   d = libsbml.parseFormula("d")
   n.addChild(d)
   self.assertEqual( True, n.isWellFormedASTNode() )
   e = libsbml.parseFormula("e")
   n.addChild(e)
   self.assertEqual( True, n.isWellFormedASTNode() )
   n = None
   pass  
 def test_Trigger(self):
   t = libsbml.Trigger(2,4)
   self.assertEqual( False, (t.hasRequiredElements()) )
   t.setMath(libsbml.parseFormula("ar"))
   self.assertEqual( True, t.hasRequiredElements() )
   t = None
   pass  
 def test_EventAssignment(self):
   ea = libsbml.EventAssignment(2,4)
   self.assertEqual( False, (ea.hasRequiredElements()) )
   ea.setMath(libsbml.parseFormula("fd"))
   self.assertEqual( True, ea.hasRequiredElements() )
   ea = None
   pass  
 def test_SBMLConvertStrict_convertNonStrictUnits(self):
     d = libsbml.SBMLDocument(2, 4)
     m = d.createModel()
     c = m.createCompartment()
     c.setId("c")
     c.setConstant(False)
     p = m.createParameter()
     p.setId("p")
     p.setUnits("mole")
     math = libsbml.parseFormula("p")
     ar = m.createAssignmentRule()
     ar.setVariable("c")
     ar.setMath(math)
     self.assert_(d.setLevelAndVersion(2, 1, True) == False)
     self.assert_(d.getLevel() == 2)
     self.assert_(d.getVersion() == 4)
     self.assert_(d.setLevelAndVersion(2, 2, True) == False)
     self.assert_(d.getLevel() == 2)
     self.assert_(d.getVersion() == 4)
     self.assert_(d.setLevelAndVersion(2, 3, True) == False)
     self.assert_(d.getLevel() == 2)
     self.assert_(d.getVersion() == 4)
     self.assert_(d.setLevelAndVersion(1, 2, True) == False)
     self.assert_(d.getLevel() == 2)
     self.assert_(d.getVersion() == 4)
     _dummyList = [d]
     _dummyList[:] = []
     del _dummyList
     pass
Esempio n. 22
0
def main(args):
    """Usage: evaluateCustomMath formula [model containing values]
    """
    if len(args) < 2:
        print("Usage: evaluateCustomMath formula [model containing values]")
        return 1

    formula = args[1]
    filename = None
    if (len(args) > 2):
        filename = args[2]

    math = libsbml.parseFormula(formula)
    if (math == None):
        print("Invalid formula, aborting.")
        return 1

    doc = None
    if filename != None:
        doc = libsbml.readSBML(filename)
        if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
            print(
                "The models contains errors, please correct them before continuing."
            )
            doc.printErrors()
            return 1
        # the following maps a list of ids to their corresponding model values
        # this makes it possible to evaluate expressions involving SIds.
        libsbml.SBMLTransforms.mapComponentValues(doc.getModel())
    else:
        # create dummy document
        doc = libsbml.SBMLDocument(3, 1)

    result = libsbml.SBMLTransforms.evaluateASTNode(math, doc.getModel())
    print("{0} = {1}".format(formula, result))
 def test_Constraint(self):
   c = libsbml.Constraint(2,4)
   self.assertEqual( False, (c.hasRequiredElements()) )
   c.setMath(libsbml.parseFormula("a+b"))
   self.assertEqual( True, c.hasRequiredElements() )
   c = None
   pass  
 def test_EventAssignment(self):
   ea = libsbml.EventAssignment(2,4)
   self.assertEqual( False, (ea.hasRequiredElements()) )
   ea.setMath(libsbml.parseFormula("fd"))
   self.assertEqual( True, ea.hasRequiredElements() )
   ea = None
   pass  
 def test_internal_consistency_check_21226(self):
   d = libsbml.SBMLDocument(3,1)
   m = d.createModel()
   r = m.createEvent()
   r.setUseValuesFromTriggerTime(True)
   ea = r.createEventAssignment()
   ea.setVariable("s")
   ast = libsbml.parseFormula("2*x")
   ea.setMath(ast)
   t = r.createTrigger()
   t.setMath(ast)
   d.getErrorLog().clearLog()
   errors = d.checkInternalConsistency()
   self.assert_( errors == 2 )
   self.assert_( d.getError(0).getErrorId() == 21226 )
   self.assert_( d.getError(1).getErrorId() == 21226 )
   t.setPersistent(True)
   d.getErrorLog().clearLog()
   errors = d.checkInternalConsistency()
   self.assert_( errors == 1 )
   self.assert_( d.getError(0).getErrorId() == 21226 )
   t.setInitialValue(False)
   d.getErrorLog().clearLog()
   errors = d.checkInternalConsistency()
   self.assert_( errors == 0 )
   d = None
   pass  
Esempio n. 26
0
 def test_InitialAssignment_setMath(self):
     math = libsbml.parseFormula("2 * k")
     self.IA.setMath(math)
     math1 = self.IA.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("2 * k" == formula))
     self.assert_(self.IA.getMath() != math)
     self.assertEqual(True, self.IA.isSetMath())
     self.IA.setMath(self.IA.getMath())
     math1 = self.IA.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("2 * k" == formula))
     self.assert_(self.IA.getMath() != math)
     self.IA.setMath(None)
     self.assertEqual(False, self.IA.isSetMath())
     if (self.IA.getMath() != None):
         pass
     _dummyList = [math]
     _dummyList[:] = []
     del _dummyList
     pass
Esempio n. 27
0
 def test_MathMLFormatter_cn_units(self):
   expected = wrapMathMLUnits("  <cn sbml:units=\"mole\"> 1.2 </cn>\n")
   self.N = libsbml.parseFormula("1.2")
   self.N.setUnits("mole")
   self.S = libsbml.writeMathMLToString(self.N)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Esempio n. 28
0
 def test_MathMLFormatter_lambda(self):
   expected = wrapMathML("  <lambda>\n" + 
   "    <bvar>\n" + 
   "      <ci> x </ci>\n" + 
   "    </bvar>\n" + 
   "    <bvar>\n" + 
   "      <ci> y </ci>\n" + 
   "    </bvar>\n" + 
   "    <apply>\n" + 
   "      <root/>\n" + 
   "      <degree>\n" + 
   "        <cn type=\"integer\"> 2 </cn>\n" + 
   "      </degree>\n" + 
   "      <apply>\n" + 
   "        <plus/>\n" + 
   "        <apply>\n" + 
   "          <power/>\n" + 
   "          <ci> x </ci>\n" + 
   "          <cn type=\"integer\"> 2 </cn>\n" + 
   "        </apply>\n" + 
   "        <apply>\n" + 
   "          <power/>\n" + 
   "          <ci> y </ci>\n" + 
   "          <cn type=\"integer\"> 2 </cn>\n" + 
   "        </apply>\n" + 
   "      </apply>\n" + 
   "    </apply>\n" + 
   "  </lambda>\n")
   self.N = libsbml.parseFormula("lambda(x, y, root(2, x^2 + y^2))")
   self.S = libsbml.writeMathMLToString(self.N)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Esempio n. 29
0
 def test_MathMLFormatter_cn_e_notation_7(self):
   expected = wrapMathML("  <cn type=\"e-notation\"> -1 <sep/> -6 </cn>\n"  
   )
   self.N = libsbml.parseFormula("-1e-6")
   self.S = libsbml.writeMathMLToString(self.N)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Esempio n. 30
0
 def test_MathMLFormatter_cn_e_notation_4(self):
   expected = wrapMathML("  <cn type=\"e-notation\"> 6.0221367 <sep/> 23 </cn>\n"  
   )
   self.N = libsbml.parseFormula("6.0221367e+23")
   self.S = libsbml.writeMathMLToString(self.N)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
 def test_SBMLConvertStrict_convertNonStrictUnits(self):
   d = libsbml.SBMLDocument(2,4)
   m = d.createModel()
   c = m.createCompartment()
   c.setId( "c")
   c.setConstant(False)
   p = m.createParameter()
   p.setId( "p")
   p.setUnits( "mole")
   math = libsbml.parseFormula("p")
   ar = m.createAssignmentRule()
   ar.setVariable( "c")
   ar.setMath(math)
   self.assert_( d.setLevelAndVersion(2,1,True) == False )
   self.assert_( d.getLevel() == 2 )
   self.assert_( d.getVersion() == 4 )
   self.assert_( d.setLevelAndVersion(2,2,True) == False )
   self.assert_( d.getLevel() == 2 )
   self.assert_( d.getVersion() == 4 )
   self.assert_( d.setLevelAndVersion(2,3,True) == False )
   self.assert_( d.getLevel() == 2 )
   self.assert_( d.getVersion() == 4 )
   self.assert_( d.setLevelAndVersion(1,2,True) == False )
   self.assert_( d.getLevel() == 2 )
   self.assert_( d.getVersion() == 4 )
   _dummyList = [ d ]; _dummyList[:] = []; del _dummyList
   pass  
 def test_AlgebraicRule(self):
   ar = libsbml.AlgebraicRule(2,4)
   self.assertEqual( False, (ar.hasRequiredElements()) )
   ar.setMath(libsbml.parseFormula("ar"))
   self.assertEqual( True, ar.hasRequiredElements() )
   ar = None
   pass  
def main (args):
    """Usage: evaluateCustomMath formula [model containing values]
    """
    if len(args) < 2:
      print("Usage: evaluateCustomMath formula [model containing values]")
      return 1;

    formula = args[1];
    filename = None
    if (len(args) > 2):
        filename = args[2]

    math = libsbml.parseFormula(formula);
    if (math == None):
      print("Invalid formula, aborting.");
      return 1;

    doc = None;
    if filename != None:
      doc = libsbml.readSBML(filename);
      if doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0:
        print("The models contains errors, please correct them before continuing.");
        doc.printErrors();
        return 1;
      # the following maps a list of ids to their corresponding model values
      # this makes it possible to evaluate expressions involving SIds. 
      libsbml.SBMLTransforms.mapComponentValues(doc.getModel());    
    else:
      # create dummy document
      doc = libsbml.SBMLDocument(3, 1);

    result = libsbml.SBMLTransforms.evaluateASTNode(math, doc.getModel());
    print("{0} = {1}".format(formula, result));
 def test_AssignmentRule(self):
   r = libsbml.AssignmentRule(2,4)
   self.assertEqual( False, (r.hasRequiredElements()) )
   r.setMath(libsbml.parseFormula("ar"))
   self.assertEqual( True, r.hasRequiredElements() )
   r = None
   pass  
Esempio n. 35
0
 def test_MathMLFormatter_cn_e_notation_7(self):
     expected = wrapMathML(
         "  <cn type=\"e-notation\"> -1 <sep/> -6 </cn>\n")
     self.N = libsbml.parseFormula("-1e-6")
     self.S = libsbml.writeMathMLToString(self.N)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
 def test_Delay(self):
   d = libsbml.Delay(2,4)
   self.assertEqual( False, (d.hasRequiredElements()) )
   d.setMath(libsbml.parseFormula("a+b"))
   self.assertEqual( True, d.hasRequiredElements() )
   d = None
   pass  
Esempio n. 37
0
 def test_MathMLFormatter_minus_unary_2(self):
     expected = wrapMathML("  <apply>\n" + "    <minus/>\n" +
                           "    <ci> a </ci>\n" + "  </apply>\n")
     self.N = libsbml.parseFormula("-a")
     self.S = libsbml.writeMathMLToString(self.N)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
 def test_Constraint(self):
   c = libsbml.Constraint(2,4)
   self.assertEqual( False, (c.hasRequiredElements()) )
   c.setMath(libsbml.parseFormula("a+b"))
   self.assertEqual( True, c.hasRequiredElements() )
   c = None
   pass  
 def test_AssignmentRule(self):
   r = libsbml.AssignmentRule(2,4)
   self.assertEqual( False, (r.hasRequiredElements()) )
   r.setMath(libsbml.parseFormula("ar"))
   self.assertEqual( True, r.hasRequiredElements() )
   r = None
   pass  
Esempio n. 40
0
    def initializeVariableReferenceList(self):

        self.theVariableReferenceList = []

        formulaString = self.theSBase.getFormula()

        anASTNode = libsbml.parseFormula(formulaString)
        self.__convertFormulaToExpression(anASTNode)

        self.theExpression = libsbml.formulaToString(anASTNode)

        # SBML_ASSIGNMENT_RULE or SBML_RATE_RULE
        ##         if self.theSBase.getType() == 1 \
        ##                or self.theSBase.getType() == 2:
        if type(self.theSBase) == libsbml.AssignmentRulePtr or type(self.theSBase) == libsbml.RateRulePtr:

            variable = self.theSBase.getVariable()
            (fullIDString, sbaseType) = self.rootobj.theSBMLIdManager.searchFullIDFromId(variable)

            if sbaseType == libsbml.SBML_SPECIES or sbaseType == libsbml.SBML_PARAMETER:
                pass

            elif sbaseType == libsbml.SBML_COMPARTMENT:
                fullID = ecell.ecssupport.createFullID(fullIDString)
                systemPath = ecell.ecssupport.createSystemPathFromFullID(fullID)
                fullIDString = "Variable:%s:SIZE" % (systemPath)

            else:
                raise SBMLConvertError, "SBase [%s] is not found" % (variable)

            self.__addVariableReference(fullIDString, 1)
 def test_Model_addEvent4(self):
     m = libsbml.Model(2, 2)
     e = libsbml.Event(2, 2)
     t = libsbml.Trigger(2, 2)
     t.setMath(libsbml.parseFormula("true"))
     e.setId("e")
     e.setTrigger(t)
     e.createEventAssignment()
     e1 = libsbml.Event(2, 2)
     e1.setId("e")
     e1.setTrigger(t)
     e1.createEventAssignment()
     i = m.addEvent(e)
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(m.getNumEvents() == 1)
     i = m.addEvent(e1)
     self.assert_(i == libsbml.LIBSBML_DUPLICATE_OBJECT_ID)
     self.assert_(m.getNumEvents() == 1)
     _dummyList = [e]
     _dummyList[:] = []
     del _dummyList
     _dummyList = [e1]
     _dummyList[:] = []
     del _dummyList
     _dummyList = [m]
     _dummyList[:] = []
     del _dummyList
     pass
Esempio n. 42
0
 def test_SBMLConvert_convertToL3_stoichiometryMath(self):
     d = libsbml.SBMLDocument(2, 1)
     m = d.createModel()
     c = m.createCompartment()
     c.setId("c")
     s = m.createSpecies()
     s.setId("s")
     s.setCompartment("c")
     r = m.createReaction()
     sr = r.createReactant()
     sr.setSpecies("s")
     sm = sr.createStoichiometryMath()
     ast = libsbml.parseFormula("c*2")
     sm.setMath(ast)
     self.assert_(m.getNumRules() == 0)
     self.assert_(sr.isSetId() == False)
     self.assert_(d.setLevelAndVersion(3, 1, False) == True)
     m = d.getModel()
     r = m.getReaction(0)
     sr = r.getReactant(0)
     self.assert_(m.getNumRules() == 1)
     self.assert_(sr.isSetId() == True)
     rule = m.getRule(0)
     self.assert_(sr.getId() == rule.getVariable())
     _dummyList = [d]
     _dummyList[:] = []
     del _dummyList
     pass
 def test_Delay(self):
   d = libsbml.Delay(2,4)
   self.assertEqual( False, (d.hasRequiredElements()) )
   d.setMath(libsbml.parseFormula("a+b"))
   self.assertEqual( True, d.hasRequiredElements() )
   d = None
   pass  
Esempio n. 44
0
def rxn_add_stoich(srxn, rid, stoich, is_product=True):
    try:
        stoich = float(stoich)
        if stoich < 0:
            sr = srxn.createReactant()
            sr.setStoichiometry(-stoich)
        elif stoich > 0:
            sr = srxn.createProduct()
            sr.setStoichiometry(stoich)
        elif stoich == 0:
            sr = srxn.createModifier()
        sr.setSpecies(rid)

    except ValueError:
        formula = stoich.replace('**', '^')
        math_ast = libsbml.parseFormula(formula)
        #try:
        #    smath = libsbml.StoichiometryMath(math_ast)
        #except:
        # normally this is in an except block but the try above doesn't throw erro
        # I am expecting in libSBML 4.0
        try:
            smath = libsbml.StoichiometryMath(math_ast)
        except NotImplementedError:
            smath = libsbml.StoichiometryMath(sbml_level, sbml_version)
            smath.setMath(math_ast)

        if is_product == True:
            sr = srxn.createProduct()
        else:
            sr = srxn.createReactant()

        sr.setSpecies(rid)
        sr.setStoichiometryMath(smath)
Esempio n. 45
0
def evaluableMathML(astnode, variables={}, array=False):
    """ Create evaluable python string.

    """
    # replace variables with provided values
    for key, value in variables.iteritems():
        astnode.replaceArgument(key, libsbml.parseFormula(str(value)))

    # get formula
    formula = libsbml.formulaToL3String(astnode)

    # <replacements>
    # FIXME: these are not exhaustive, but are improved with examples
    if array is False:
        # scalar
        formula = formula.replace("&&", 'and')
        formula = formula.replace("||", 'or')
    else:
        # np.array
        formula = formula.replace("max", 'np.max')
        formula = formula.replace("min", 'np.min')
        formula = formula.replace("sum", 'np.sum')
        formula = formula.replace("product", 'np.prod')

    return formula
 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  
 def test_StoichiometryMath(self):
   sm = libsbml.StoichiometryMath(2,4)
   self.assertEqual( False, (sm.hasRequiredElements()) )
   sm.setMath(libsbml.parseFormula("ar"))
   self.assertEqual( True, sm.hasRequiredElements() )
   sm = None
   pass  
Esempio n. 48
0
 def test_MathMLFormatter_minus_unary_1(self):
   expected = wrapMathML("  <cn type=\"integer\"> -2 </cn>\n"  
   )
   self.N = libsbml.parseFormula("-2")
   self.S = libsbml.writeMathMLToString(self.N)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
Esempio n. 49
0
 def handleFunctions(self, line, name):
     # expect either a function or a new section
     if (line[0] == "@"):
         self.handleNewContext(line, name)
     else:
         bits = line.split("=")
         if (len(bits) != 2):
             sys.stderr.write('Error: expected "=" on line ')
             sys.stderr.write(str(self.count) + '\n')
             raise ParseError
         (bit, body) = bits
         bits = bit.split("(")
         if (len(bits) != 2):
             sys.stderr.write('Error: expected "(" on function header ')
             sys.stderr.write(str(self.count) + '\n')
             raise ParseError
         (id, args) = bits
         if (args[-1] == ")"):
             args = args[:-1]
         else:
             sys.stderr.write('Error: expected ")" on function header ')
             sys.stderr.write(str(self.count) + '\n')
             raise ParseError
         if (len(args.strip()) > 0):
             lam = "lambda(" + args + ", " + body + " )"
         else:
             lam = "lambda( " + body + " )"
         value = libsbml.parseFormula(lam)
         # self.replaceTime(value)
         f = self.m.createFunctionDefinition()
         f.setId(id)
         f.setMath(value)
Esempio n. 50
0
 def test_SBMLConvert_convertToL3_stoichiometryMath(self):
   d = libsbml.SBMLDocument(2,1)
   m = d.createModel()
   c = m.createCompartment()
   c.setId( "c" )
   s = m.createSpecies()
   s.setId( "s")
   s.setCompartment( "c")
   r = m.createReaction()
   sr = r.createReactant()
   sr.setSpecies( "s")
   sm = sr.createStoichiometryMath()
   ast = libsbml.parseFormula("c*2")
   sm.setMath(ast)
   self.assert_( m.getNumRules() == 0 )
   self.assert_( sr.isSetId() == False )
   self.assert_( d.setLevelAndVersion(3,1,False) == True )
   m = d.getModel()
   r = m.getReaction(0)
   sr = r.getReactant(0)
   self.assert_( m.getNumRules() == 1 )
   self.assert_( sr.isSetId() == True )
   rule = m.getRule(0)
   self.assert_( sr.getId() == rule.getVariable() )
   _dummyList = [ d ]; _dummyList[:] = []; del _dummyList
   pass  
Esempio n. 51
0
 def test_MathMLFormatter_piecewise(self):
   expected = wrapMathML("  <piecewise>\n" + 
   "    <piece>\n" + 
   "      <apply>\n" + 
   "        <minus/>\n" + 
   "        <ci> x </ci>\n" + 
   "      </apply>\n" + 
   "      <apply>\n" + 
   "        <lt/>\n" + 
   "        <ci> x </ci>\n" + 
   "        <cn type=\"integer\"> 0 </cn>\n" + 
   "      </apply>\n" + 
   "    </piece>\n" + 
   "    <piece>\n" + 
   "      <cn type=\"integer\"> 0 </cn>\n" + 
   "      <apply>\n" + 
   "        <eq/>\n" + 
   "        <ci> x </ci>\n"  + 
   "        <cn type=\"integer\"> 0 </cn>\n" + 
   "      </apply>\n" + 
   "    </piece>\n" + 
   "    <piece>\n" + 
   "      <ci> x </ci>\n" + 
   "      <apply>\n" + 
   "        <gt/>\n" + 
   "        <ci> x </ci>\n"  + 
   "        <cn type=\"integer\"> 0 </cn>\n" + 
   "      </apply>\n" + 
   "    </piece>\n" + 
   "  </piecewise>\n")
   f =  "piecewise(-x, lt(x, 0), 0, eq(x, 0), x, gt(x, 0))";
   self.N = libsbml.parseFormula(f)
   self.S = libsbml.writeMathMLToString(self.N)
   self.assertEqual( True, self.equals(expected,self.S) )
   pass  
 def handleRules(self, line, name):
     # expect either a rule or a new section
     # changed by lukas: rules are AssignmentRule by default
     # "$assign:" and "$rate:" let choose between different kinds of rules
     # this requires the assigned species to have atrribute
     # constant set to "False"
     if (line[0] == "$" and (not re.match("$(?:rate|assign)\:", line))):
         self.handleNewContext(line, name)
     else:
         rule_type = 1  # standard set to assignment rule (1)
         if re.match("$rate\:", line):
             rule_type = 2  # set to rate rule
         elif re.match("$assign\:", line):
             rule_type = 1  # set to assignment rule
         line = re.sub("\$\w+\:", "",
                       line)  # replace rule declaration if there
         bits = line.split("=")
         if (len(bits) != 2):
             sys.stderr.write('Error: expected "=" on line ')
             sys.stderr.write(str(self.count) + '\n')
             raise ParseError
         (lhs, rhs) = bits
         value = libsbml.parseFormula(rhs)
         self.replaceTime(value)
         if rule_type == 1:
             rule = self.m.createAssignmentRule()
         elif rule_type == 2:
             rule = self.m.createRateRule()
         rule.setVariable(lhs)
         rule.setMath(value)
Esempio n. 53
0
 def test_FunctionDefinition_createWith(self):
     math = libsbml.parseFormula("lambda(x, x^3)")
     fd = libsbml.FunctionDefinition(2, 4)
     fd.setId("pow3")
     fd.setMath(math)
     self.assert_(fd.getTypeCode() == libsbml.SBML_FUNCTION_DEFINITION)
     self.assert_(fd.getMetaId() == "")
     self.assert_(fd.getNotes() == None)
     self.assert_(fd.getAnnotation() == None)
     self.assert_(fd.getName() == "")
     math1 = fd.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("lambda(x, x^3)" == formula))
     self.assert_(fd.getMath() != math)
     self.assertEqual(True, fd.isSetMath())
     self.assert_(("pow3" == fd.getId()))
     self.assertEqual(True, fd.isSetId())
     _dummyList = [math]
     _dummyList[:] = []
     del _dummyList
     _dummyList = [fd]
     _dummyList[:] = []
     del _dummyList
     pass
Esempio n. 54
0
 def test_MathMLFormatter_cn_e_notation_4(self):
     expected = wrapMathML(
         "  <cn type=\"e-notation\"> 6.0221367 <sep/> 23 </cn>\n")
     self.N = libsbml.parseFormula("6.0221367e+23")
     self.S = libsbml.writeMathMLToString(self.N)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
Esempio n. 55
0
 def test_KineticLaw_setMath(self):
     math = libsbml.parseFormula("k3 / k2")
     self.kl.setMath(math)
     math1 = self.kl.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("k3 / k2" == formula))
     self.assert_(self.kl.getMath() != math)
     self.assertEqual(True, self.kl.isSetMath())
     self.kl.setMath(self.kl.getMath())
     math1 = self.kl.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("k3 / k2" == formula))
     self.assert_(self.kl.getMath() != math)
     self.kl.setMath(None)
     self.assertEqual(False, self.kl.isSetMath())
     if (self.kl.getMath() != None):
         pass
     _dummyList = [math]
     _dummyList[:] = []
     del _dummyList
     pass
Esempio n. 56
0
 def test_MathMLFormatter_cn_units(self):
     expected = wrapMathMLUnits("  <cn sbml:units=\"mole\"> 1.2 </cn>\n")
     self.N = libsbml.parseFormula("1.2")
     self.N.setUnits("mole")
     self.S = libsbml.writeMathMLToString(self.N)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
 def test_FunctionDefinition(self):
   fd = libsbml.FunctionDefinition(2,4)
   self.assertEqual( False, (fd.hasRequiredElements()) )
   fd.setMath(libsbml.parseFormula("fd"))
   self.assertEqual( True, fd.hasRequiredElements() )
   fd = None
   pass  
Esempio n. 58
0
 def test_MathMLFormatter_sin(self):
     expected = wrapMathML("  <apply>\n" + "    <sin/>\n" +
                           "    <ci> x </ci>\n" + "  </apply>\n")
     self.N = libsbml.parseFormula("sin(x)")
     self.S = libsbml.writeMathMLToString(self.N)
     self.assertEqual(True, self.equals(expected, self.S))
     pass
 def test_InitialAssignment(self):
   ia = libsbml.InitialAssignment(2,4)
   self.assertEqual( False, (ia.hasRequiredElements()) )
   ia.setMath(libsbml.parseFormula("ia"))
   self.assertEqual( True, ia.hasRequiredElements() )
   ia = None
   pass