Skip to content

Commit

Permalink
Support constant expressions in EquationFactory.
Browse files Browse the repository at this point in the history
Avoid errors for expressions that evaluate to numbers instead
of BaseBuilder instances.
  • Loading branch information
pavoljuhas committed Dec 7, 2016
1 parent 9352698 commit 632b2b7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
10 changes: 8 additions & 2 deletions diffpy/srfit/equation/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
_builders = {}


import numbers
import numpy

import diffpy.srfit.equation.literals as literals
Expand Down Expand Up @@ -145,8 +146,13 @@ def makeEquation(self, eqstr, buildargs = True, argclass =
"""
self._prepareBuilders(eqstr, buildargs, argclass, argkw)
beq = eval(eqstr, {}, self.builders)
eq = beq.getEquation()
self.equations.add(eq)
# handle scalar numbers or numpy arrays
if isinstance(beq, (numbers.Number, numpy.ndarray)):
lit = literals.Argument(value=beq, const=True)
eq = Equation(name='', root=lit)
else:
eq = beq.getEquation()
self.equations.add(eq)
return eq

def registerConstant(self, name, value):
Expand Down
13 changes: 13 additions & 0 deletions diffpy/srfit/tests/testbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,19 @@ def testParseEquation(self):
self.assertTrue(noObserversInGlobalBuilders())
return


def test_parse_constant(self):
"""Verify parsing of constant numeric expressions.
"""
factory = builder.EquationFactory()
eq = factory.makeEquation('3.12 + 2')
self.assertTrue(isinstance(eq, builder.Equation))
self.assertEqual(set(), factory.equations)
self.assertEqual(5.12, eq())
self.assertRaises(ValueError, eq, 3)
return


def testBuildEquation(self):

from numpy import array_equal
Expand Down

0 comments on commit 632b2b7

Please sign in to comment.