3

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.

Igor Markelov
  • 798
  • 2
  • 8
  • 16

2 Answers2

14

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.        ])
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
6

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.    ])
behzad.nouri
  • 74,723
  • 18
  • 126
  • 124