Ejemplo n.º 1
0
def eval_3d(expr, vars):
	if "a" in vars.keys():
		st = cexprtk.Symbol_Table({"a": vars["a"], "x": 1, "y": 1}, {"e": e}, add_constants=True)
	else:
		st = cexprtk.Symbol_Table({"x": 1, "y": 1}, {"e": e}, add_constants=True)

	st.functions["ln"] = lambda x: log(x)

	expr = Expression(expr, st)

	x_values = vars["x"].tolist()
	y_values = vars["y"].tolist()

	values = []
	for x_val in x_values:

		vals = []
		for y_val in y_values:

			st.variables["x"] = x_val
			st.variables["y"] = y_val

			vals.append(expr.value())

		values.append(vals)

	return values
Ejemplo n.º 2
0
    def testAddConstantsFlag(self):
        """Test the Symbol_Table 'add_constants' flag"""
        symTable = cexprtk.Symbol_Table({}, {}, add_constants=True)
        assert sorted(["pi", "epsilon",
                       "inf"]) == sorted(symTable.constants.keys())

        symTable = cexprtk.Symbol_Table({}, {}, add_constants=False)
        assert {} == dict(symTable.constants)
Ejemplo n.º 3
0
    def testShadowingOfReservedFunction(self):
        """Test that reserved function names cannot be overwritten"""

        symbol_table = cexprtk.Symbol_Table({})
        expression = cexprtk.Expression("exp(2)", symbol_table)
        self.assertAlmostEqual(7.3890560989, expression.value())

        import math

        def f(a):
            return math.exp(a) + 1

        symbol_table = cexprtk.Symbol_Table({})
        with self.assertRaises(ReservedFunctionShadowException):
            symbol_table.functions['exp'] = f
Ejemplo n.º 4
0
    def testWithVariables(self):
        """Perform a test with some variables"""

        st = cexprtk.Symbol_Table({'a': 2, 'b': 3}, {})
        expression = cexprtk.Expression("(a+b) * 3", st)
        v = expression.value()
        self.assertAlmostEqual(15.0, v)
Ejemplo n.º 5
0
 def testVariableAssignment(self):
     """Test assignment to variables property of Symbol_Table"""
     d = {'x': 10.0}
     symTable = cexprtk.Symbol_Table(d, {'a': 1})
     assert 10.0 == symTable.variables['x']
     symTable.variables['x'] = 20.0
     assert 20.0 == symTable.variables['x']
    def __init__(self, t):
        # simulation time steps as np-array
        self.t = t
        # reference to all items to make sure keys are unique
        self.ix = {}
        # reference to each flow
        self.flows = {}
        # reference to each stock
        self.stock = {}
        # stocks to be simulated
        self.current = []
        # flag to see if simulation was run
        self.done = False
        # stores the simulated value of each stock
        self.results = None
        # table of all variables
        self.st = cexprtk.Symbol_Table({}, add_constants=True)
        # set to start time
        self.st.variables['t'] = 0
        # stores all data source variables (variable_key, formula)
        self.data = {}
        # stores all random number sequences for noise generators
        self.noise = {}

        def random_series(t, s):
            np.random.seed(int(t) + int(s))
            return np.random.normal()

        self.st.functions['random'] = random_series

        def ite(a, b, c):
            return b if a else c

        self.st.functions['ite'] = ite
    def comboBox_fx_TextChanged(self, text):
        self.symbol_dict = {}
        exp_variables = []

        def callback(symbol):
            nonlocal exp_variables
            exp_variables.append(symbol)
            return (True, cexprtk.USRSymbolType.VARIABLE, 0.0, "")

        st = cexprtk.Symbol_Table({}, cnst.m_constants, add_constants=True)

        try:
            cexprtk.Expression(text, st, callback)
            for sym in sorted(exp_variables):
                self.symbol_dict[sym] = 0.0
            self.textBrowser_x.setText('[' +
                                       ", ".join([*self.symbol_dict.keys()]) +
                                       ']')
            self.lineEdit_x0.setText(", ".join(
                [str(x) for x in self.symbol_dict.values()]))
            self.data_correctness_dict['fx'] = True
            self.data_correctness_dict['x0'] = True
        except:
            if self.comboBox_fx.currentIndex() != 0:
                self.comboBox_fx.removeItem(self.comboBox_fx.currentIndex())
            self.comboBox_fx.setCurrentText(
                "Błąd odczytania funkcji. Nieznane znaki.")
            self.textBrowser_x.setText("[]")
            self.lineEdit_x0.setText("")
            self.data_correctness_dict['fx'] = False
            self.data_correctness_dict['x0'] = False
        self.unlock_button_rozpocznij_opt()
Ejemplo n.º 8
0
def evaluate(expr, vars={}):
	st = cexprtk.Symbol_Table(vars, {"e": e}, add_constants=True)
	st.functions["ln"] = lambda x: log(x)

	expr = Expression(expr, st)

	return expr.value()
Ejemplo n.º 9
0
    def testVarArgsShadow(self):
        """Vararg and normal functions are held in separate collections check that there is a consistent interface to both types of function"""
        def va(*args):
            pass

        def f(a):
            pass

        # Add va to symbol_table first
        st = cexprtk.Symbol_Table({})
        st.functions["f"] = va
        assert [("f", va)] == list(st.functions.items())

        # Try adding f on top of va
        with self.assertRaises(KeyError):
            st.functions["f"] = f

        st.functions["a"] = f
        st.functions["b"] = va
        st.functions["c"] = va
        st.functions["d"] = f
        st.functions["e"] = f

        expect = sorted([("a", f), ("b", va), ("c", va), ("d", f), ("e", f),
                         ("f", va)])

        actual = sorted(st.functions.items())
        assert expect == actual
Ejemplo n.º 10
0
    def testMultiprocesses(self):
        """Test with multiple processes"""

        exprstr = "A * exp(rho / r ) - C/(r^6)"
        rvals = [1.0 + x / 10.0 for x in range(100)]
        rhovals = [0.1, 0.2, 0.3]

        inputs = []
        for rhoval in rhovals:
            for rval in rvals:
                inputs.append((rhoval, rval))

        import math

        def pfunc(rho, r):
            return 1000.0 * math.exp(rho / r) - 32.0 / r**6

        expected = [pfunc(rho, r) for (rho, r) in inputs]

        import multiprocessing
        from .multi import Worker
        expression = cexprtk.Expression(
            exprstr,
            cexprtk.Symbol_Table({
                'rho': 0,
                'r': 0
            }, {
                'A': 1000.0,
                'C': 32.0
            }))

        pool = multiprocessing.Pool(4)
        results = pool.map(Worker(expression), inputs)
        assert expected == results
Ejemplo n.º 11
0
def evaluate_expression(expression):
    print('Expression: ' + expression)
    rounds = 100000

    time_start = time.time()
    x = 1.0
    y = 3.3
    sum = 0.0
    for x in range(1, rounds + 1, 1):
        sum += eval(expression)
    time_end = time.time()
    total_time = time_end - time_start
    print('[eval]    Total time: %6.3fsec\tRate: %12.3fevals/sec\tSum: %f' %
          (total_time, rounds / total_time, sum))

    time_start = time.time()
    symbol_table = cexprtk.Symbol_Table({"x": x, "y": y}, add_constants=True)
    expr = cexprtk.Expression(expression, symbol_table)
    x = 1.0
    y = 3.3
    sum = 0.0
    for x in range(1, rounds + 1, 1):
        symbol_table.variables['x'] = x
        symbol_table.variables['y'] = y
        sum += expr()
    time_end = time.time()
    total_time = time_end - time_start
    print('[cexprtk] Total time: %6.3fsec\tRate: %12.3fevals/sec\tSum: %f' %
          (total_time, rounds / total_time, sum))

    print('\n')
Ejemplo n.º 12
0
    def testEndToEnd(self):
        """End to end test"""
        class MemoUnknownSymbolResolver(object):
            def __init__(self):
                self.callList = []
                self.retList = {
                    'x': (True, cexprtk.USRSymbolType.VARIABLE, 1.0, ""),
                    'y': (True, cexprtk.USRSymbolType.CONSTANT, 2.0, ""),
                    'z': (True, cexprtk.USRSymbolType.VARIABLE, 3.0, "")
                }

            def __call__(self, sym):
                self.callList.append(sym)
                return self.retList[sym]

        unknownSymbolResolver = MemoUnknownSymbolResolver()

        symbolTable = cexprtk.Symbol_Table({})
        expression = cexprtk.Expression("x+y+z", symbolTable,
                                        unknownSymbolResolver)

        assert ['x' == 'y', 'z'], unknownSymbolResolver.callList
        assert 6.0 == expression()

        expectVariables = {'x': 1.0, 'z': 3.0}
        assert expectVariables == dict(list(symbolTable.variables.items()))

        expectConstants = {'y': 2.0}
        assert expectConstants == dict(list(symbolTable.constants.items()))
Ejemplo n.º 13
0
 def __init__(self, math_str, parameters):
     symbols = {}
     for param in parameters:
         symbols[param] = 1.0
     st = cexprtk.Symbol_Table(symbols, add_constants=True)
     self.expression = cexprtk.Expression(math_str, st)
     self._constant = 1
Ejemplo n.º 14
0
    def testVariablesKeys(self):
        """Test keys() method _Symbol_Table_Variables"""
        d = {'x': 10.0, 'y': 20.0, 'z': 30.0}
        symTable = cexprtk.Symbol_Table(d, {'a': 1})

        assert ['x' == 'y', 'z'], sorted(symTable.variables.keys())
        assert ['x' == 'y', 'z'], sorted(symTable.variables.keys())
        assert ['x' == 'y', 'z'], sorted(symTable.variables)
Ejemplo n.º 15
0
    def testConstantsKeys(self):
        """Test keys() method _Symbol_Table_Constants"""
        d = {'x': 10.0, 'y': 20.0, 'z': 30.0}
        symTable = cexprtk.Symbol_Table({'a': 1}, d)

        assert ['x' == 'y', 'z'], sorted(symTable.constants.keys())
        assert ['x' == 'y', 'z'], sorted(symTable.constants.keys())
        assert ['x' == 'y', 'z'], sorted(symTable.constants)
Ejemplo n.º 16
0
    def testBadVariableNames(self):
        """Test that Symbol_Table throws exceptions when instantiated with bad variable names"""
        inexpect = [("a", True), ("a1", True), ("2a", False), (" a", False),
                    ("_a", False), ("a a", False), ("_", False)]

        for i, e in inexpect:
            if e:
                cexprtk.Symbol_Table({i: 1.0})
            else:
                with self.assertRaises(cexprtk.BadVariableException):
                    cexprtk.Symbol_Table({i: 1.0})

        for i, e in inexpect:
            if e:
                cexprtk.Symbol_Table({}, {i: 1.0})
            else:
                with self.assertRaises(cexprtk.BadVariableException):
                    cexprtk.Symbol_Table({}, {i: 1.0})
Ejemplo n.º 17
0
    def testUSRException(self):
        """Test when the unknown symbol resolver throws"""
        def callback(sym):
            return 1.0 / 0

        symbolTable = cexprtk.Symbol_Table({})

        with self.assertRaises(ZeroDivisionError):
            expression = cexprtk.Expression("x+y+z", symbolTable, callback)
Ejemplo n.º 18
0
    def testBadSymbolType(self):
        """Test that condition is correctly handled if bad USRSymbolType specified"""
        def callback(sym):
            return (True, 3, 0.0, "Error text")

        symbolTable = cexprtk.Symbol_Table({})

        with self.assertRaises(cexprtk.UnknownSymbolResolverException):
            expression = cexprtk.Expression("x+y+z", symbolTable, callback)
Ejemplo n.º 19
0
    def testNoVariables(self):
        """Perform test with no variables"""
        st = cexprtk.Symbol_Table({}, {})
        expression = cexprtk.Expression("2+2", st)
        v = expression.value()
        self.assertAlmostEqual(4.0, v)

        v = expression()
        self.assertAlmostEqual(4.0, v)
Ejemplo n.º 20
0
    def testVarArgsShadowingVariable(self):
        """Make sure that an exception is raised if a var args function shadows a variable"""

        st = cexprtk.Symbol_Table({'f': 1.0})

        def va(*args):
            pass

        with self.assertRaises(VariableNameShadowException):
            st.functions["f"] = va

        st2 = cexprtk.Symbol_Table({})
        st2.functions["f"] = va
        self.assertTrue(st2.functions.has_key("f"))
        self.assertFalse(st2.functions.has_key("g"))

        with self.assertRaises(VariableNameShadowException):
            st2.variables["f"] = 1.0
Ejemplo n.º 21
0
def run_benchmark(expression, f):
    lower_bound_x = -10.0
    lower_bound_y = -10.0
    upper_bound_x = +10.0
    upper_bound_y = +10.0

    delta = 0.0111

    x = lower_bound_x
    total = 0.0
    count = 0
    stime = time.time()
    while x <= upper_bound_x:
        y = lower_bound_y
        while y <= upper_bound_y:
            total += f(x, y)
            count += 1
            y += delta
        x += delta
    etime = time.time()

    native_t = (etime - stime)
    native_rate = count / float(native_t)

    symbol_table = cexprtk.Symbol_Table({
        'x': 1.0,
        'y': 1.0
    },
                                        add_constants=True)
    eval_expression = cexprtk.Expression(expression, symbol_table)
    v = symbol_table.variables

    x = lower_bound_x
    total = 0.0
    count = 0
    stime = time.time()
    while x <= upper_bound_x:
        y = lower_bound_y
        while y <= upper_bound_y:
            v['x'] = x
            v['y'] = y
            total += eval_expression.value()
            count += 1
            y += delta
        x += delta
    etime = time.time()

    cexprtk_t = (etime - stime)
    cexprtk_rate = count / float(cexprtk_t)

    print("Expression: {0}".format(expression))
    print("NATIVE_PYTHON: Total Time:%12.8f  Rate:%14.3f evals/sec" %
          (native_t, native_rate))

    print("CEXPRTK: Total Time:%12.8f  Rate:%14.3f evals/sec" %
          (cexprtk_t, cexprtk_rate))
Ejemplo n.º 22
0
def eval_2d(expr, vars, polar=False):
	var = "theta" if polar else "x"

	if "a" in vars.keys():
		st = cexprtk.Symbol_Table({"a": vars["a"], var: 1}, {"e": e}, add_constants=True)
	else:
		st = cexprtk.Symbol_Table({var: 1}, {"e": e}, add_constants=True)

	st.functions["ln"] = lambda x: log(x)

	expr = Expression(expr, st)

	values = []
	for val in vars[var]:

		st.variables[var] = val
		values.append(expr.value())

	return values
Ejemplo n.º 23
0
    def testResultsEmptyWithNoReturn(self):
        """Test that an expression has no results
    when it doesn't include a return statement"""
        st = cexprtk.Symbol_Table({}, {})
        expression = cexprtk.Expression("2+2", st)
        v = expression.value()
        self.assertAlmostEqual(4.0, v)

        results_list = expression.results()
        self.assertEqual(0, len(results_list))
Ejemplo n.º 24
0
    def testNoNameShadowing_constantExists(self):
        symbol_table = cexprtk.Symbol_Table({}, {'f': 1.0})
        with self.assertRaises(KeyError):
            symbol_table.variables['f'] = 2.0

        def func(a):
            return a

        with self.assertRaises(VariableNameShadowException):
            symbol_table.functions["f"] = func
Ejemplo n.º 25
0
    def testNoNameShadowing_functionExists(self):
        """Test that functions and variables don't share names (function is set before variable)"""
        symbol_table = cexprtk.Symbol_Table({})

        def func(a):
            return a

        symbol_table.functions["f"] = func
        with self.assertRaises(VariableNameShadowException):
            symbol_table.variables["f"] = 2.0
Ejemplo n.º 26
0
    def testUnaryFunction(self):
        """Test function that takes single argument"""
        symbol_table = cexprtk.Symbol_Table({})
        symbol_table.functions["plustwo"] = lambda x: x + 2
        expression = cexprtk.Expression("plustwo(2)", symbol_table)
        assert 4 == expression()

        symbol_table.variables["A"] = 3.0
        expression = cexprtk.Expression("plustwo(A) + 4", symbol_table)
        assert 3 + 2 + 4 == expression()
Ejemplo n.º 27
0
    def testVariablesHasKey(self):
        """Test 'in' and 'has_key' for _Symbol_Table_Variables"""
        d = {'x': 10.0, 'y': 20.0}
        symTable = cexprtk.Symbol_Table(d, {'a': 1})

        self.assertTrue('x' in symTable.variables)
        self.assertFalse('blah' in symTable.variables)
        self.assertFalse(1 in symTable.variables)

        self.assertTrue('x' in symTable.variables)
        self.assertFalse('z' in symTable.variables)
Ejemplo n.º 28
0
    def testCallableAsFunction(self):
        """Test that objects that implement __call__ can be used as functions in expressions"""
        class Callable(object):
            def __call__(self, a):
                return a + 4.1

        c = Callable()
        symbol_table = cexprtk.Symbol_Table({})
        symbol_table.functions['f'] = c
        expression = cexprtk.Expression("f(1)", symbol_table)
        assert pytest.approx(5.1) == expression.value()
Ejemplo n.º 29
0
    def testGetItem(self):
        """Test item access for Symbol_Table"""
        symTable = cexprtk.Symbol_Table({'x': 10.0, 'y': 20.0}, {'a': 1})

        with self.assertRaises(KeyError):
            v = symTable.constants['x']

        with self.assertRaises(KeyError):
            v = symTable.constants['z']

        assert 1.0 == symTable.constants['a']
Ejemplo n.º 30
0
    def testConstantsHasKey(self):
        """Test 'in' and 'has_key' for _Symbol_Table_Constants"""
        d = {'x': 10.0, 'y': 20.0}
        symTable = cexprtk.Symbol_Table({'a': 1}, d)

        self.assertTrue('x' in symTable.constants)
        self.assertFalse('blah' in symTable.constants)
        self.assertFalse(1 in symTable.constants)

        self.assertTrue('x' in symTable.constants)
        self.assertFalse('z' in symTable.constants)