Exemplo n.º 1
0
 def test_ASTNode_replaceChild(self):
   node = libsbml.ASTNode()
   c1 = libsbml.ASTNode()
   c2 = libsbml.ASTNode()
   c3 = libsbml.ASTNode()
   newc = libsbml.ASTNode()
   i = 0
   node.setType(libsbml.AST_LOGICAL_AND)
   c1.setName( "a")
   c2.setName( "b")
   c3.setName( "c")
   node.addChild(c1)
   node.addChild(c2)
   node.addChild(c3)
   self.assert_( node.getNumChildren() == 3 )
   self.assert_((  "and(a, b, c)" == libsbml.formulaToString(node) ))
   newc.setName( "d")
   i = node.replaceChild(0,newc)
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assert_( node.getNumChildren() == 3 )
   self.assert_((  "and(d, b, c)" == libsbml.formulaToString(node) ))
   i = node.replaceChild(3,newc)
   self.assert_( i == libsbml.LIBSBML_INDEX_EXCEEDS_SIZE )
   self.assert_( node.getNumChildren() == 3 )
   self.assert_((  "and(d, b, c)" == libsbml.formulaToString(node) ))
   i = node.replaceChild(1,c1)
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assert_( node.getNumChildren() == 3 )
   self.assert_((  "and(d, a, c)" == libsbml.formulaToString(node) ))
   _dummyList = [ node ]; _dummyList[:] = []; del _dummyList
   pass  
Exemplo n.º 2
0
 def test_ASTNode_swapChildren(self):
   node = libsbml.ASTNode()
   c1 = libsbml.ASTNode()
   c2 = libsbml.ASTNode()
   node_1 = libsbml.ASTNode()
   c1_1 = libsbml.ASTNode()
   c2_1 = libsbml.ASTNode()
   i = 0
   node.setType(libsbml.AST_LOGICAL_AND)
   c1.setName( "a")
   c2.setName( "b")
   node.addChild(c1)
   node.addChild(c2)
   self.assert_( node.getNumChildren() == 2 )
   self.assert_((  "and(a, b)" == libsbml.formulaToString(node) ))
   node_1.setType(libsbml.AST_LOGICAL_AND)
   c1_1.setName( "d")
   c2_1.setName( "f")
   node_1.addChild(c1_1)
   node_1.addChild(c2_1)
   self.assert_( node_1.getNumChildren() == 2 )
   self.assert_((  "and(d, f)" == libsbml.formulaToString(node_1) ))
   i = node.swapChildren(node_1)
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assert_( node.getNumChildren() == 2 )
   self.assert_((  "and(d, f)" == libsbml.formulaToString(node) ))
   self.assert_( node_1.getNumChildren() == 2 )
   self.assert_((  "and(a, b)" == libsbml.formulaToString(node_1) ))
   _dummyList = [ node_1 ]; _dummyList[:] = []; del _dummyList
   _dummyList = [ node ]; _dummyList[:] = []; del _dummyList
   pass  
  def test_read_l2v4_new(self):
    reader = libsbml.SBMLReader()
    filename = "../../sbml/test/test-data/"
    filename += "l2v4-new.xml"
    d = reader.readSBML(filename)
    if (d == None):
      pass    
    self.assert_( d.getLevel() == 2 )
    self.assert_( d.getVersion() == 4 )
    m = d.getModel()
    self.assert_( m != None )
    self.assert_( m.getId() ==  "l2v4_all" )
    self.assert_( m.getNumCompartments() == 1 )
    c = m.getCompartment(0)
    self.assert_( c != None )
    self.assert_( c.getId() ==  "a" )
    self.assert_( c.getSize() == 1 )
    self.assertEqual( False, c.getConstant() )
    self.assert_( m.getNumEvents() == 1 )
    e = m.getEvent(0)
    self.assert_( e != None )
    self.assertEqual( True, e.getUseValuesFromTriggerTime() )
    self.assertEqual( True, e.isSetTrigger() )
    trigger = e.getTrigger()
    self.assert_( trigger != None )
    ast = trigger.getMath()
    self.assert_((  "lt(x, 3)" == libsbml.formulaToString(ast) ))
    self.assert_( e.getNumEventAssignments() == 1 )
    ea = e.getEventAssignment(0)
    self.assert_( ea != None )
    self.assert_( ea.getVariable() ==  "a" )
    ast = ea.getMath()
    self.assert_((  "x * p3" == libsbml.formulaToString(ast) ))
    d = None
Exemplo n.º 4
0
def stoichToString(species, stoich):
    if stoich is None:
        stoich = str(species.getStoichiometry())
    elif hasattr(stoich, 'getMath'): # libsbml > 3.0
        stoich = libsbml.formulaToString(stoich.getMath())
    else: # libsbml 2.3.4
        stoich = libsbml.formulaToString(stoich) 
    return stoich    
Exemplo n.º 5
0
 def __getRawAssignmentRules(self,arule):
     variable =   arule.getVariable()
     rate = libsbml.formulaToString(arule.getMath())
     
     #try to separate into positive and negative sections
     if arule.getMath().getCharacter() == '-' and arule.getMath().getNumChildren() > 1 and not arule.isAssignment():
         rateL = libsbml.formulaToString(arule.getMath().getLeftChild())
         if(arule.getMath().getRightChild().getCharacter()) == '*':
             if libsbml.formulaToString(arule.getMath().getRightChild().getLeftChild()) == variable:
                 rateR = libsbml.formulaToString(arule.getMath().getRightChild().getRightChild())
             elif libsbml.formulaToString(arule.getMath().getRightChild().getRightChild()) == variable:
                 rateR = libsbml.formulaToString(arule.getMath().getRightChild().getLeftChild())
             else:
                 rateR = 'if({0} >0,{1}/{0} ,0)'.format(variable,libsbml.formulaToString(arule.getMath().getRightChild()))
         else:
             rateR = 'if({0} >0,{1}/{0} ,0)'.format(variable,libsbml.formulaToString((arule.getMath().getRightChild())))
     else:
         rateL = libsbml.formulaToString(arule.getMath())
         rateR = '0'
     if not self.useID:
         rateL = self.convertToName(rateL)
         rateR = self.convertToName(rateR)
         variable = self.convertToName(variable).strip()
     #print arule.isAssignment(),arule.isRate()
     return variable,[rateL,rateR],arule.isAssignment(),arule.isRate()
Exemplo n.º 6
0
def create_value_dictionary(model):
    values = dict()
    
    # parse all the initial assignments
    for assignment in model.getListOfInitialAssignments():
        sid = assignment.getId()
        math = ' = {}'.format(libsbml.formulaToString(assignment.getMath()))
        values[sid] = math
    # rules
    for rule in model.getListOfRules():
        sid = rule.getVariable()
        math = ' = {}'.format(libsbml.formulaToString(rule.getMath()))
        values[sid] = math
    return values
 def test_read_MathML_1(self):
   reader = libsbml.SBMLReader()
   filename = "../../sbml/math/test/test-data/"
   filename += "mathML_1-invalid.xml"
   d = reader.readSBML(filename)
   if (d == None):
     pass    
   m = d.getModel()
   self.assert_( m != None )
   self.assert_( m.getNumFunctionDefinitions() == 2 )
   self.assert_( m.getNumInitialAssignments() == 1 )
   self.assert_( m.getNumRules() == 2 )
   self.assert_( m.getNumReactions() == 1 )
   fd = m.getFunctionDefinition(0)
   fd_math = fd.getMath()
   self.assert_( fd_math.getType() == libsbml.AST_LAMBDA )
   self.assert_( fd_math.getNumChildren() == 2 )
   self.assert_((  "lambda(x, )" == libsbml.formulaToString(fd_math) ))
   self.assert_( fd_math.getParentSBMLObject() == fd )
   child = fd_math.getRightChild()
   self.assert_( child.getType() == libsbml.AST_UNKNOWN )
   self.assert_( child.getNumChildren() == 0 )
   self.assert_((  "" == libsbml.formulaToString(child) ))
   fd = m.getFunctionDefinition(1)
   fd1_math = fd.getMath()
   self.assert_( fd1_math.getType() == libsbml.AST_LAMBDA )
   self.assert_( fd1_math.getNumChildren() == 2 )
   self.assert_((  "lambda(x, true)" == libsbml.formulaToString(fd1_math) ))
   self.assert_( fd1_math.getParentSBMLObject() == fd )
   child1 = fd1_math.getRightChild()
   self.assert_( child1.getType() == libsbml.AST_CONSTANT_TRUE )
   self.assert_( child1.getNumChildren() == 0 )
   self.assert_((  "true" == libsbml.formulaToString(child1) ))
   ia = m.getInitialAssignment(0)
   ia_math = ia.getMath()
   self.assert_( ia_math.getType() == libsbml.AST_UNKNOWN )
   self.assert_( ia_math.getNumChildren() == 0 )
   self.assert_((  "" == libsbml.formulaToString(ia_math) ))
   self.assert_( ia_math.getParentSBMLObject() == ia )
   r = m.getRule(0)
   r_math = r.getMath()
   self.assert_( r_math.getType() == libsbml.AST_CONSTANT_TRUE )
   self.assert_( r_math.getNumChildren() == 0 )
   self.assert_((  "true" == libsbml.formulaToString(r_math) ))
   self.assert_( r_math.getParentSBMLObject() == r )
   r = m.getRule(1)
   r1_math = r.getMath()
   self.assert_( r1_math.getType() == libsbml.AST_REAL )
   self.assert_( r1_math.getNumChildren() == 0 )
   self.assert_((  "INF" == libsbml.formulaToString(r1_math) ))
   self.assert_( r1_math.getParentSBMLObject() == r )
   kl = m.getReaction(0).getKineticLaw()
   kl_math = kl.getMath()
   self.assert_( kl_math.getType() == libsbml.AST_REAL )
   self.assert_( kl_math.getNumChildren() == 0 )
   self.assert_((  "4.5" == libsbml.formulaToString(kl_math) ))
   self.assert_( kl_math.getParentSBMLObject() == kl )
   d = None
   pass  
Exemplo n.º 8
0
 def getPrunnedTree(math,remainderPatterns):
     while math.getCharacter() == '*' and len(remainderPatterns) > 0:
         if libsbml.formulaToString(math.getLeftChild()) in remainderPatterns:
             remainderPatterns.remove(libsbml.formulaToString(math.getLeftChild()))
             math = math.getRightChild()
         elif libsbml.formulaToString(math.getRightChild()) in remainderPatterns:
             remainderPatterns.remove(libsbml.formulaToString(math.getRightChild()))
             math = math.getLeftChild()            
         else:
             if(math.getLeftChild().getCharacter()) == '*':
                 math.replaceChild(0,getPrunnedTree(math.getLeftChild(),remainderPatterns))
             if(math.getRightChild().getCharacter()) == '*':
                 math.replaceChild(math.getNumChildren() - 1,getPrunnedTree(math.getRightChild(),remainderPatterns))
             break
     return math
Exemplo n.º 9
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 )
Exemplo n.º 10
0
 def test_element_not(self):
   s = wrapMathML("<apply> <not/> <ci> TooShabby </ci> </apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "not(TooShabby)" == self.F ))
   pass  
Exemplo n.º 11
0
 def test_element_function_call_1(self):
   s = wrapMathML("<apply> <ci> foo </ci> <ci> x </ci> </apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "foo(x)" == self.F ))
   pass  
Exemplo n.º 12
0
 def removeFactorFromMath(self, math, reactants, products):
     ifStack = Counter()
     remainderPatterns = []
     highStoichoiMetryFactor = 1
     for x in reactants:
         highStoichoiMetryFactor  *= factorial(x[1])
         y = [i[1] for i in products if i[0] == x[0]]
         y = y[0] if len(y) > 0 else 0
         #TODO: check if this actually keeps the correct dynamics
         # this is basically there to address the case where theres more products
         #than reactants (synthesis)
         if x[1] > y:
             highStoichoiMetryFactor /= comb(int(x[1]), int(y), exact=True)
         for counter in range(0, int(x[1])):
             remainderPatterns.append(x[0])
     #for x in products:
     #    highStoichoiMetryFactor /= math.factorial(x[1])
     #remainderPatterns = [x[0] for x in reactants]
     math = self.getPrunnedTree(math,remainderPatterns)
     
     rateR = libsbml.formulaToString(math)
     for element in remainderPatterns:
         ifStack.update([element])
     for element in ifStack:
         if ifStack[element] > 1:
             rateR = 'if({0}>0,{1}/({0}^{2}),0)'.format(element,rateR,ifStack[element])
         else:
             rateR = 'if({0}>0,{1}/{0},0)'.format(element,rateR)
     if highStoichoiMetryFactor != 1:
         rateR = '{0}*{1}'.format(rateR, int(highStoichoiMetryFactor))
     return rateR,math.getNumChildren()
Exemplo n.º 13
0
 def test_element_root_2(self):
   s = wrapMathML("<apply> <root/> <ci> a </ci> </apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "sqrt(a)" == self.F ))
   pass  
Exemplo n.º 14
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)
Exemplo n.º 15
0
 def test_element_power(self):
   s = wrapMathML("<apply><power/> <ci>x</ci> <cn>3</cn> </apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "pow(x, 3)" == self.F ))
   pass  
Exemplo n.º 16
0
 def test_element_ceiling(self):
   s = wrapMathML("<apply><ceiling/><cn> 1.6 </cn></apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "ceil(1.6)" == self.F ))
   pass  
Exemplo n.º 17
0
 def test_element_factorial(self):
   s = wrapMathML("<apply><factorial/><cn> 5 </cn></apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "factorial(5)" == self.F ))
   pass  
Exemplo n.º 18
0
 def test_element_tanh(self):
   s = wrapMathML("<apply><tanh/><ci> x </ci></apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "tanh(x)" == self.F ))
   pass  
Exemplo n.º 19
0
 def test_element_floor(self):
   s = wrapMathML("<apply><floor/><cn> 1.2 </cn></apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "floor(1.2)" == self.F ))
   pass  
Exemplo n.º 20
0
 def removeFactorFromMath(self,math,reactants):
     '''
     walks through a series of * nodes and removes the remainder reactant factors
     '''
     def getPrunnedTree(math,remainderPatterns):
         while math.getCharacter() == '*' and len(remainderPatterns) > 0:
             if libsbml.formulaToString(math.getLeftChild()) in remainderPatterns:
                 remainderPatterns.remove(libsbml.formulaToString(math.getLeftChild()))
                 math = math.getRightChild()
             elif libsbml.formulaToString(math.getRightChild()) in remainderPatterns:
                 remainderPatterns.remove(libsbml.formulaToString(math.getRightChild()))
                 math = math.getLeftChild()            
             else:
                 if(math.getLeftChild().getCharacter()) == '*':
                     math.replaceChild(0,getPrunnedTree(math.getLeftChild(),remainderPatterns))
                 if(math.getRightChild().getCharacter()) == '*':
                     math.replaceChild(math.getNumChildren() - 1,getPrunnedTree(math.getRightChild(),remainderPatterns))
                 break
         return math
         
     
     remainderPatterns = [x[0] for x in reactants]
     math = getPrunnedTree(math,remainderPatterns)
     rateR = libsbml.formulaToString(math) 
     for element in remainderPatterns:
         rateR = 'if({0} >0,{1}/{0} ,0)'.format(element,rateR)
     return rateR
Exemplo n.º 21
0
 def function_definitions(self, evalfunc=None, kwargs={}):
     for func in self.model.function_definitions:
         args = [func.getArgument(i).getName() for i in range(func.getNumArguments())]
         formula = libsbml.formulaToString(func.getBody())
         if evalfunc is None:
             yield (func.id, (args, formula))
         else:
             yield (func.id, LambdaFunction(args, formula, evalfunc))
Exemplo n.º 22
0
 def test_element_operator_times(self):
   s = wrapMathML("<apply> <times/> <ci> x </ci> <ci> y </ci> <ci> z </ci> </apply>"  
   )
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "x * y * z" == self.F ))
   pass  
Exemplo n.º 23
0
 def test_element_leq(self):
   s = wrapMathML("<apply> <leq/> <cn>0</cn> <ci>x</ci> <cn>1</cn> </apply>"  
   )
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "leq(0, x, 1)" == self.F ))
   pass  
Exemplo n.º 24
0
 def test_element_neq(self):
   s = wrapMathML("<apply> <neq/> <notanumber/> <notanumber/> </apply>"  
   )
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "neq(NaN, NaN)" == self.F ))
   pass  
Exemplo n.º 25
0
    def convertRuleFormula( self, aFormula ):

        aASTRootNode = libsbml.parseFormula( aFormula )

        convertedAST = self.__convertVariableName( aASTRootNode )
        convertedFormula = libsbml.formulaToString( convertedAST )
        
        return convertedFormula
Exemplo n.º 26
0
 def getReactionMath(self, reaction):
     try:
         kineticLaw = reaction.getKineticLaw()
         mathNode = kineticLaw.getMath()
         mathString = libsbml.formulaToString(mathNode)
         return mathString
     except: # most often happens when creating a new reaction that does not have a kinetic law
         return
Exemplo n.º 27
0
 def test_element_operator_plus(self):
   s = wrapMathML("<apply> <plus/> <cn> 1 </cn> <cn> 2 </cn> <cn> 3 </cn> </apply>"  
   )
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "1 + 2 + 3" == self.F ))
   pass  
Exemplo n.º 28
0
 def test_element_xor(self):
   s = wrapMathML("<apply> <xor/> <ci>a</ci> <ci>b</ci> <ci>b</ci> <ci>a</ci> </apply>"  
   )
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "xor(a, b, b, a)" == self.F ))
   pass  
Exemplo n.º 29
0
 def test_element_root_1(self):
   s = wrapMathML("<apply> <root/> <degree> <cn type='integer'> 3 </cn> </degree>" + 
   "               <ci> a </ci>" + 
   "</apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "root(3, a)" == self.F ))
   pass  
Exemplo n.º 30
0
 def test_element_lt(self):
   s = wrapMathML("<apply> <lt/> <apply> <minus/> <infinity/> <infinity/> </apply>" + 
   "              <cn>1</cn>" + 
   "</apply>")
   self.N = libsbml.readMathMLFromString(s)
   self.assert_( self.N != None )
   self.F = libsbml.formulaToString(self.N)
   self.assert_((  "lt(INF - INF, 1)" == self.F ))
   pass  
Exemplo n.º 31
0
 def test_element_lambda(self):
     s = wrapMathML(
         "<lambda>" + "  <bvar> <ci>x</ci> </bvar>" + "  <apply> <sin/>" +
         "          <apply> <plus/> <ci>x</ci> <cn>1</cn> </apply>" +
         "  </apply>" + "</lambda>")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("lambda(x, sin(x + 1))" == self.F))
     pass
Exemplo n.º 32
0
 def test_element_piecewise_otherwise(self):
     s = wrapMathML("<piecewise>" + "  <piece>" + "    <cn>0</cn>" +
                    "    <apply> <lt/> <ci>x</ci> <cn>0</cn> </apply>" +
                    "  </piece>" + "  <otherwise>" + "    <ci>x</ci>" +
                    "  </otherwise>" + "</piecewise>")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("piecewise(0, lt(x, 0), x)" == self.F))
     pass
 def test_element_function_call_2(self):
     s = wrapMathML(
         "<apply> <plus/> <cn> 1 </cn>" +
         "                <apply> <ci> f </ci> <ci> x </ci> </apply>" +
         "</apply>")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("1 + f(x)" == self.F))
     pass
 def test_element_gt(self):
     s = wrapMathML(
         "<apply> <gt/> <infinity/>" +
         "              <apply> <minus/> <infinity/> <cn>1</cn> </apply>" +
         "</apply>")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("gt(INF, INF - 1)" == self.F))
     pass
Exemplo n.º 35
0
 def test_element_csymbol_delay_2(self):
     s = wrapMathML(
         "<apply>" +
         "  <csymbol encoding='text' definitionURL='http://www.sbml.org/sbml/"
         + "symbols/delay'> my_delay </csymbol>" + "  <ci> x </ci>" +
         "  <cn> 0.1 </cn>" + "</apply>\n")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("my_delay(x, 0.1)" == self.F))
     pass
Exemplo n.º 36
0
 def test_ValidASTNode_infix_nary_times0(self):
     n = libsbml.readMathMLFromString(
         "<math xmlns='http://www.w3.org/1998/Math/MathML'>" + "  <apply>" +
         "    <times/>" + "  </apply>" + "</math>")
     self.assert_(n != None)
     formula = libsbml.formulaToString(n)
     node = libsbml.parseFormula(formula)
     self.assert_(node != None)
     n = None
     node = None
     pass
Exemplo n.º 37
0
 def test_element_bug_math_xmlns(self):
     s = wrapXML(
         "<foo:math xmlns:foo='http://www.w3.org/1998/Math/MathML'>" +
         "  <foo:apply>" +
         "    <foo:plus/> <foo:cn>1</foo:cn> <foo:cn>2</foo:cn>" +
         "  </foo:apply>" + "</foo:math>")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("1 + 2" == self.F))
     pass
 def test_read_MathML_1(self):
     reader = libsbml.SBMLReader()
     filename = "../../sbml/math/test/test-data/"
     filename += "mathML_1-invalid.xml"
     d = reader.readSBML(filename)
     if (d == None):
         pass
     m = d.getModel()
     self.assert_(m != None)
     self.assert_(m.getNumFunctionDefinitions() == 2)
     self.assert_(m.getNumInitialAssignments() == 1)
     self.assert_(m.getNumRules() == 2)
     self.assert_(m.getNumReactions() == 1)
     fd = m.getFunctionDefinition(0)
     fd_math = fd.getMath()
     self.assert_(fd_math.getType() == libsbml.AST_LAMBDA)
     self.assert_(fd_math.getNumChildren() == 2)
     self.assert_(("lambda(x, )" == libsbml.formulaToString(fd_math)))
     self.assert_(fd_math.getParentSBMLObject() == fd)
     child = fd_math.getRightChild()
     self.assert_(child.getType() == libsbml.AST_UNKNOWN)
     self.assert_(child.getNumChildren() == 0)
     self.assert_(("" == libsbml.formulaToString(child)))
     fd = m.getFunctionDefinition(1)
     fd1_math = fd.getMath()
     self.assert_(fd1_math.getType() == libsbml.AST_LAMBDA)
     self.assert_(fd1_math.getNumChildren() == 2)
     self.assert_(("lambda(x, true)" == libsbml.formulaToString(fd1_math)))
     self.assert_(fd1_math.getParentSBMLObject() == fd)
     child1 = fd1_math.getRightChild()
     self.assert_(child1.getType() == libsbml.AST_CONSTANT_TRUE)
     self.assert_(child1.getNumChildren() == 0)
     self.assert_(("true" == libsbml.formulaToString(child1)))
     ia = m.getInitialAssignment(0)
     ia_math = ia.getMath()
     self.assert_(ia_math.getType() == libsbml.AST_UNKNOWN)
     self.assert_(ia_math.getNumChildren() == 0)
     self.assert_(("" == libsbml.formulaToString(ia_math)))
     self.assert_(ia_math.getParentSBMLObject() == ia)
     r = m.getRule(0)
     r_math = r.getMath()
     self.assert_(r_math.getType() == libsbml.AST_CONSTANT_TRUE)
     self.assert_(r_math.getNumChildren() == 0)
     self.assert_(("true" == libsbml.formulaToString(r_math)))
     self.assert_(r_math.getParentSBMLObject() == r)
     r = m.getRule(1)
     r1_math = r.getMath()
     self.assert_(r1_math.getType() == libsbml.AST_REAL)
     self.assert_(r1_math.getNumChildren() == 0)
     self.assert_(("INF" == libsbml.formulaToString(r1_math)))
     self.assert_(r1_math.getParentSBMLObject() == r)
     # kl = m.getReaction(0).getKineticLaw()
     # kl_math = kl.getMath()
     # self.assert_( kl_math == None )
     d = None
     pass
Exemplo n.º 39
0
 def function_definitions(self, evalfunc=None, kwargs=None):
     kwargs = kwargs or {}
     for func in self.model.function_definitions:
         args = [
             func.getArgument(i).getName()
             for i in range(func.getNumArguments())
         ]
         formula = libsbml.formulaToString(func.getBody())
         if evalfunc is None:
             yield (func.id, (args, formula))
         else:
             yield (func.id, LambdaFunction(args, formula, evalfunc))
Exemplo n.º 40
0
 def test_element_csymbol_delay_3(self):
     s = wrapMathML(
         "<apply>" + "  <power/>" + "  <apply>" +
         "    <csymbol encoding='text' definitionURL='http://www.sbml.org/sbml/"
         + "symbols/delay'> delay </csymbol>" + "    <ci> P </ci>" +
         "    <ci> delta_t </ci>" + "  </apply>\n" + "  <ci> q </ci>" +
         "</apply>\n")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(("pow(delay(P, delta_t), q)" == self.F))
     pass
Exemplo n.º 41
0
 def test_Delay_setMath(self):
     math = libsbml.parseFormula("lambda(x, x^3)")
     self.D.setMath(math)
     math1 = self.D.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("lambda(x, x^3)" == formula))
     self.assert_(self.D.getMath() != math)
     self.assertEqual(True, self.D.isSetMath())
     self.D.setMath(self.D.getMath())
     math1 = self.D.getMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1)
     self.assert_(formula != None)
     self.assert_(("lambda(x, x^3)" == formula))
     self.D.setMath(None)
     self.assertEqual(False, self.D.isSetMath())
     if (self.D.getMath() != None):
         pass
     pass
Exemplo n.º 42
0
    def initial_assignments(self, evalfunc=None, kwargs=None):
        evalfunc = evalfunc or None
        kwargs = kwargs.copy() if kwargs else {}

        for assignment in self.model.initial_assignments:
            formula = libsbml.formulaToString(assignment.math)
            if evalfunc is None:
                yield (assignment.id, formula)
            else:
                val = evalfunc(formula, kwargs)
                kwargs[assignment.id] = val
                yield (assignment.id, val)
Exemplo n.º 43
0
 def test_SpeciesReference_setStoichiometryMath(self):
     math = libsbml.parseFormula("k3 / k2")
     stoich = libsbml.StoichiometryMath(2, 4)
     stoich.setMath(math)
     self.SR.setStoichiometryMath(stoich)
     math1 = self.SR.getStoichiometryMath()
     self.assert_(math1 != None)
     formula = libsbml.formulaToString(math1.getMath())
     self.assert_(formula != None)
     self.assert_(("k3 / k2" == formula))
     self.assertEqual(True, self.SR.isSetStoichiometryMath())
     pass
Exemplo n.º 44
0
def __get_rules(sbml_model, gillespy_model, errors):
    for i in range(sbml_model.getNumRules()):
        rule = sbml_model.getRule(i)
        rule_name = rule.getId()
        rule_variable = rule.getVariable()
        rule_string = __get_math(rule.getMath())
        if rule_variable in gillespy_model.listOfParameters:
            # Treat Non-Constant Parameters as Species
            value = gillespy_model.listOfParameters[rule_variable].expression
            species = gillespy2.Species(name=rule_variable,
                                        initial_value=value,
                                        allow_negative_populations=True,
                                        mode='continuous')
            gillespy_model.delete_parameter(rule_variable)
            gillespy_model.add_species([species])

        t = []

        if rule.isAssignment():
            assign_value = eval(rule_string, {**eval_globals, **init_state})
            postponed_evals[rule_variable] = rule_string
            gillespy_rule = gillespy2.AssignmentRule(name=rule_name,
                                                     variable=rule_variable,
                                                     formula=rule_string)
            gillespy_model.add_assignment_rule(gillespy_rule)
            init_state[gillespy_rule.variable] = eval(gillespy_rule.formula, {
                **init_state,
                **eval_globals
            })

        if rule.isRate():
            gillespy_rule = gillespy2.RateRule(name=rule_name,
                                               variable=rule_variable,
                                               formula=rule_string)
            gillespy_model.add_rate_rule(gillespy_rule)

        if rule.isAlgebraic():
            t.append('algebraic')

            if len(t) > 0:
                t[0] = t[0].capitalize()

                msg = ", ".join(t)
                msg += " rule"
            else:
                msg = "Rule"

            errors.append([
                "{0} '{1}' found on line '{2}' with equation '{3}'. gillespy does not support SBML Algebraic Rules"
                .format(msg, rule.getId(), rule.getLine(),
                        libsbml.formulaToString(rule.getMath())), -5
            ])
Exemplo n.º 45
0
    def generate_functions(self, model):
        # global parameters
        for f in model.getListOfFunctionDefinitions():
            ast = f.getMath()
            idx = ast.getNumChildren() - 1
            ast_func = ast.getChild(idx)  # most right child is the function
            self.functions[f.getId()] = formulaToString(ast_func)
            arglist = []
            for i in range(ast.getNumChildren() - 1):
                child = ast.getChild(i)
                arglist.append(child.getName())

            self.funcargs[f.getId()] = arglist
Exemplo n.º 46
0
def parse_mathML_to_annonymous(mathML):

    mathML = ET.tostring(mathML).decode().replace('ns0:', '')
    ast = libsbml.readMathMLFromString(mathML)
    result = libsbml.formulaToString(ast)
    parsed_equation = lambda x: eval(result, {
        "x": x,
        "exp": math.exp,
        "lt": lt,
        "gt": gt
    })

    return parsed_equation, result
Exemplo n.º 47
0
 def test_EventAssignment_setMath(self):
   math = libsbml.parseFormula("2 * k")
   self.EA.setMath(math)
   math1 = self.EA.getMath()
   self.assert_( math1 != None )
   formula = libsbml.formulaToString(math1)
   self.assert_( formula != None )
   self.assert_((  "2 * k" == formula ))
   self.assert_( self.EA.getMath() != math )
   self.assertEqual( True, self.EA.isSetMath() )
   self.EA.setMath(self.EA.getMath())
   math1 = self.EA.getMath()
   self.assert_( math1 != None )
   formula = libsbml.formulaToString(math1)
   self.assert_( formula != None )
   self.assert_((  "2 * k" == formula ))
   self.assert_( self.EA.getMath() != math )
   self.EA.setMath(None)
   self.assertEqual( False, self.EA.isSetMath() )
   if (self.EA.getMath() != None):
     pass    
   _dummyList = [ math ]; _dummyList[:] = []; del _dummyList
   pass  
Exemplo n.º 48
0
    def generate_varspecs(self, model):
        # Generate Rate equation for all variable Species (ex. dx/dt = v1 - v2 + v3).
        for s in model.getListOfSpecies():
            #if s.isSetBoundaryCondition() or s.isSetConstant:
            #    continue
            root = None
            for r in model.getListOfReactions():
                if self.is_species_reactant_of(s, r):
                    root = self.add_ast_as_reactant(root, r)
                if self.is_species_product_of(s, r):
                    root = self.add_ast_as_product(root, r)

            if root is not None:
                self.varspecs[s.getId()] = formulaToString(root)
Exemplo n.º 49
0
 def test_element_piecewise(self):
     s = wrapMathML("<piecewise>" + "  <piece>" +
                    "    <apply> <minus/> <ci>x</ci> </apply>" +
                    "    <apply> <lt/> <ci>x</ci> <cn>0</cn> </apply>" +
                    "  </piece>" + "  <piece>" + "    <cn>0</cn>" +
                    "    <apply> <eq/> <ci>x</ci> <cn>0</cn> </apply>" +
                    "  </piece>" + "  <piece>" + "    <ci>x</ci>" +
                    "    <apply> <gt/> <ci>x</ci> <cn>0</cn> </apply>" +
                    "  </piece>" + "</piecewise>")
     self.N = libsbml.readMathMLFromString(s)
     self.assert_(self.N != None)
     self.F = libsbml.formulaToString(self.N)
     self.assert_(
         ("piecewise(-x, lt(x, 0), 0, eq(x, 0), x, gt(x, 0))" == self.F))
     pass
Exemplo n.º 50
0
 def test_AlgebraicRule_createWithFormula(self):
     ar = libsbml.AlgebraicRule(2, 4)
     ar.setFormula("1 + 1")
     self.assert_(ar.getTypeCode() == libsbml.SBML_ALGEBRAIC_RULE)
     self.assert_(ar.getMetaId() == "")
     math = ar.getMath()
     self.assert_(math != None)
     formula = libsbml.formulaToString(math)
     self.assert_(formula != None)
     self.assert_(("1 + 1" == formula))
     self.assert_((formula == ar.getFormula()))
     _dummyList = [ar]
     _dummyList[:] = []
     del _dummyList
     pass
Exemplo n.º 51
0
 def test_AssignmentRule_createWithFormula(self):
     ar = libsbml.AssignmentRule(2, 4)
     ar.setVariable("s")
     ar.setFormula("1 + 1")
     self.assert_(ar.getTypeCode() == libsbml.SBML_ASSIGNMENT_RULE)
     self.assert_(ar.getMetaId() == "")
     self.assert_(("s" == ar.getVariable()))
     math = ar.getMath()
     self.assert_(math != None)
     formula = libsbml.formulaToString(math)
     self.assert_(formula != None)
     self.assert_(("1 + 1" == formula))
     self.assert_((formula == ar.getFormula()))
     _dummyList = [ar]
     _dummyList[:] = []
     del _dummyList
     pass
 def test_KineticLaw_setMath1(self):
   math = libsbml.ASTNode(libsbml.AST_TIMES)
   a = libsbml.ASTNode()
   b = libsbml.ASTNode()
   a.setName( "a")
   b.setName( "b")
   math.addChild(a)
   math.addChild(b)
   i = self.kl.setMath(math)
   self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS )
   self.assertEqual( True, self.kl.isSetMath() )
   math1 = self.kl.getMath()
   self.assert_( math1 != None )
   formula = libsbml.formulaToString(math1)
   self.assert_( formula != None )
   self.assert_((  "a * b" == formula ))
   _dummyList = [ math ]; _dummyList[:] = []; del _dummyList
   pass  
Exemplo n.º 53
0
 def test_ASTNode_freeName(self):
     node = libsbml.ASTNode()
     i = 0
     i = node.setName("a")
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(("a" == libsbml.formulaToString(node)))
     self.assert_(("a" == node.getName()))
     i = node.freeName()
     self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS)
     self.assert_(node.getName() == None)
     i = node.freeName()
     self.assert_(i == libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE)
     self.assert_(node.getName() == None)
     node.setType(libsbml.AST_UNKNOWN)
     i = node.freeName()
     self.assert_(i == libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE)
     self.assert_(node.getName() == None)
     _dummyList = [node]
     _dummyList[:] = []
     del _dummyList
     pass
 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  
Exemplo n.º 55
0
def ParseFunction(functionIndex, function):

    newFunction = sbmltoodepy.dataclasses.FunctionData()
    #    outputFile.write("Function; " + str(functionIndex + 1) + "\n")

    if function.isSetName():
        newFunction.name = function.getName()
    else:
        newFunction.name = ''


#    outputFile.write(function.getId() + ";" + functionName + "\n")
    newFunction.Id = function.getId()
    newFunction.mathString = libsbml.formulaToL3String(function.getMath())
    numArguments = function.getNumArguments()
    funcStringIter = re.finditer(",", newFunction.mathString)
    newFunction.arguments = []
    for i in range(numArguments):
        match = next(funcStringIter)
        newFunction.arguments.append(
            libsbml.formulaToString(function.getArgument(i)))

    newFunction.mathString = newFunction.mathString[match.end() + 1:-1]

    #    functionMath = formulaToL3String(function.getMath())
    #    numArguments = function.getNumArguments()
    #    funcStringIter = re.finditer(",", functionMath)
    #    argumentString = ""
    #    for i in range(numArguments):
    #        match = next(funcStringIter)
    #        argumentString += formulaToString(function.getArgument(i))
    #        if i != numArguments-1:
    #            argumentString += ";"
    #    argumentString += "\n"
    #    functionMath = functionMath[match.end()+1:-1]
    #    outputFile.write(argumentString)
    #    outputFile.write(functionMath + "\n")

    return newFunction
Exemplo n.º 56
0
 def analyseModelStructure(self):
     Parser.analyseModelStructure(self)
     for i in range(0, len(self.listOfReactions)):
         for n in range(0, self.numLocalParameters[i]):
             self.parameterId.append(
                 self.listOfReactions[i].getKineticLaw().getParameter(
                     n).getId())
             if ((len(self.writer.parsedModel.parameterId) - self.comp) <
                     10):
                 self.writer.parsedModel.parameterId.append(
                     "parameter0" + repr(len(self.parameterId) - self.comp))
             else:
                 self.writer.parsedModel.parameterId.append(
                     "parameter" + repr(len(self.parameterId) - self.comp))
             name = self.listOfReactions[i].getKineticLaw().getParameter(
                 n).getId()
             new_name = 'parameter' + repr(
                 len(self.parameterId) - self.comp)
             node = self.sbmlModel.getReaction(i).getKineticLaw().getMath()
             new_node = self.rename(node, name, new_name)
             self.writer.parsedModel.kineticLaw[i] = formulaToString(
                 new_node)
Exemplo n.º 57
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 _get_sbml_ini_dict(sbml_model):
    return {
        ini.getId(): libsbml.formulaToString(ini.getMath())
        for ini in sbml_model.getListOfInitialAssignments()
    }
Exemplo n.º 59
0
 def __init__(self, rule: libsbml.AssignmentRule):
     super().__init__(rule)
     self.variable = rule.getVariable()  # target variable
     self.formula_string = libsbml.formulaToString(rule.math)
     self.formula = compile(self.formula_string, "<string>", "eval")
def _get_sbml_allrules_dict(sbml_model):
    return {
        rule.getId(): libsbml.formulaToString(rule.getMath())
        for rule in sbml_model.getListOfRules()
    }