1

I am trying to optimize some object oriented numpy code using numexpr but I am not sure if it is possible to do so. I can't find anything in the documentation about it either way. I would like to get the following example to work:

import numpy as np
from numexpr import evaluate as neval

class nexp_eval_test:
    def __init__(self,size):
        self.a = np.random.randint(1,100,size)
        self.b = np.random.randint(1,100,size)
        self.c = np.random.randint(1,100,size)
        self.d = np.random.randint(1,100,size)
        self.e = np.random.randint(1,4,size)
        self.f = np.random.randint(1,100,size)

        self.out = np.zeros(self.a.shape)

    def calculate(self):
        self.out = self.a+self.b*(self.c+self.d)/self.f

    def calculate_ne(self):
        self.out = neval('self.a+self.b*(self.c+self.d)/self.f', local_dict=vars(self))

I have looked through some other answers about numexpr which suggested the local_dict argument as a way to pass the set of variables of an object to the numexpr evaluate function but it doesnt appear to work in this case. I get the following error:

AttributeError: 'VariableNode' object has no attribute 'a'

I assume I can get this to work if I pass everything to an external function but the overhead on passing everything back and forth seems like it would defeat the purpose of such an optimization in the first place. Is this possible?

algol
  • 399
  • 3
  • 15
  • 2
    You're using `local_dict` correctly, just remove `self`: `self.out = neval('a+b*(c+d)/f', local_dict=vars(self))` – user3483203 Jan 31 '20 at 21:50

0 Answers0