Evaluator

Motivation

After being able to analyze an expression for its variables we now want to evaluate this expression. As described hedge comes along with the pymbolic python package which contains the mapper allowing to analyze an expression due to its variables. Another feature is the evaluator which can be found in pymbolic/pymbolic/mapper/evaluator.py. To run the evaluator you need to initiate the class by:

import pymbolic as p
from pymbolic.mapper.evaluator import EvaluationMapper
from pymbolic.mapper.evaluator import evaluate

Run an example with the parsed expression:

expr = p.parse("x**(2*z)+y/2+z")

You need to tell the evaluator what the variables stand for via a dictionary:

list = {'x': 2, 'y': 4, 'z': 5}

To evaluate the expression you need to call the evaluator:

value = evaluate(expr,list)

Exercise

(Before starting with the evaluator you should do the ../DependencyMapper exercise.)

The exercise will be to build a function providing an evaluation of the following expressions:

expr = p.parse("x+z+y")
expr = p.parse("x*y+z")
expr = p.parse("(3+x)*(3+y)")
expr = p.parse("3*x+z-y*3")
expr = p.parse("3*(x+z)**(2*r)+5-y")
expr = p.parse("3*x**2+5-y")
expr = p.parse("x**2+y/2+z")
expr = p.parse("x**(2*z)+y/2+z")

Use the following set values for the variables:

list = dict({'x': 2, 'y': 4, 'z': 5})

Guideline:

  1. Find out how to get the value related to the variable from the dictionary to your code and try to evaluate the first expression in a mini function only being able to evaluate this expression.
  2. How can you solve this problem without knowing that you have to evaluate a sum? Look back at the mapper and check whether you can use a visitor pattern method for this issues or the isinstance method which you already might have used for the mapper.

  3. Generalize the method implemented in a. and b. for all other expressions in the above given list.

  4. Implement a visitor pattern based evaluator and a separate evaluator only using the isinstance feature of python.

Hedge/Exercises/Evaluator (last edited 2013-01-16 23:15:50 by AndreasKloeckner)