6

I am implementing the code in python which has the variables stored in numpy vectors. I need to perform simple operation: something like (vec1+vec2^2)/vec3. Each element of each vector is summed and multiplied. (analog of MATLAB elementwise .* operation).

The problem is in my code that I have dictionary which stores all vectors:

    var = {'a':np.array([1,2,2]),'b':np.array([2,1,3]),'c':np.array([3])}

The 3rd vector is just 1 number which means that I want to multiply this number by each element in other arrays like 3*[1,2,3]. And at the same time I have formula which is provided as a string:

    formula = '2*a*(b/c)**2'

I am replacing the formula using Regexp:

    formula_for_dict_variables = re.sub(r'([A-z][A-z0-9]*)', r'%(\1)s', formula)

which produces result:

    2*%(a)s*(%(b)s/%(c)s)**2

and substitute the dictionary variables:

    eval(formula%var)

In the case then I have just pure numbers (Not numpy arrays) everything is working, but when I place numpy.arrays in dict I receive an error.

  1. Could you give an example how can I solve this problem or maybe suggest some different approach. Given that vectors are stored in dictionary and formula is a string input.

  2. I also can store variables in any other container. The problem is that I don't know the name of variables and formula before the execution of code (they are provided by user).

  3. Also I think iteration through each element in vectors probably will be slow given the python for loops are slow.

0

2 Answers 2

16

Using numexpr, then you could do this:

In [143]: import numexpr as ne
In [146]: ne.evaluate('2*a*(b/c)**2', local_dict=var)
Out[146]: array([ 0.88888889,  0.44444444,  4.        ])
Sign up to request clarification or add additional context in comments.

3 Comments

I accepted your answer due to it is faster and it is great bundle. Thanks
Thanks @unutbu. What is the benefit of using ne.evaluate over eval(...)? (in the case there is no security problem, for example single user app, no connection to external input)
@unutbu, would you have an idea for stackoverflow.com/questions/78180518/… ?
9

Pass the dictionary to python eval function:

>>> var = {'a':np.array([1,2,2]),'b':np.array([2,1,3]),'c':np.array([3])}
>>> formula = '2*a*(b/c)**2'
>>> eval(formula, var)
array([ 0.8889,  0.4444,  4.    ])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.