Numba : Инициализируйте генератор членов класса, украшенного jitclass

#python #numpy #optimization #jit #numba

Вопрос:

При попытке инициализировать простой класс с помощью, как указано ниже, я столкнулся с двумя проблемами,

 # Python Version : 3.8.3
import numpy as np
# np.__version__ : 1.18.5
import numba as nb
# nb.__version__ : 0.50.1

mydict_like = nb.typed.Dict()
mydict_like['SomeKey'] = np.ones((100,6), dtype=np.float64)

myspecs = [('mydict', nb.typeof(mydict_like)),
#            ('tid_gen', #<----What Type??--->#)
          ]

@nb.experimental.jitclass(spec=myspecs)
class MyClass:
    def __init__(self):
        pass

    def _initialiser(self, new_dict):
        self.mydict = new_dict
        # This is where the initialisation of the generator is supposed to 
        # take place. Although i am unsure of what type would be of the 
        # the attribute `tid_gen` to be difined in `myspecs`.
        # self.tid_gen = self._unique_id_generator()

    @staticmethod
    def _unique_id_generator():
        """
        At every next() call this generator needs to yield the next number.
        For Ex:
        - next(self.tid_gen) => 0
        - next(self.tid_gen) => 1
        - next(self.tid_gen) => 2
        - next(self.tid_gen) => 3
        - [next(self.tid_gen) for _ in range(5)] => [4,5,6,7,8]
        """
        n=0 #First Id
        while True:
            yield n
            n =1

clsObj = MyClass()

# A new Dictionary
updated_dict = nb.typed.Dict()
updated_dict['RandomKey'] = np.ones((200,12), dtype=np.float64)

# clsObj._initialiser(new_dict=updated_dict) # TypeError: some keyword arguments unexpected :: Why??
clsObj._initialiser(updated_dict)
print(clsObj.mydict)
 
  • Первая проблема : Когда я попытался инициализировать объект класса clsObj как clsObj._initialiser(new_dict=updated_dict) , я получаю ошибку, как указано ниже:
       ---------------------------------------------------------------------------
      TypeError                                 Traceback (most recent call last)
      <ipython-input-542-4ab32d47645b> in <module>
           37 updated_dict['RandomKey'] = np.ones((200,12), dtype=np.float64)
           38 
      ---> 39 clsObj._initialiser(new_dict=updated_dict) # TypeError: some keyword arguments unexpected :: Why??
           40 #     clsObj._initialiser(updated_dict)
           41 print(clsObj.mydict)
    
      c:users130453anaconda3libsite-packagesnumbaexperimentaljitclassboxing.py in wrapper(*args, **kwargs)
           58     @wraps(func)
           59     def wrapper(*args, **kwargs):
      ---> 60         return method(*args, **kwargs)
           61 
           62     return wrapper
    
      TypeError: some keyword arguments unexpected
     

Хотя на данный момент это не такая острая проблема, я все же хотел бы знать, почему это произошло?

  • Вторая проблема : я пытаюсь инициализировать функцию генератора членов класса в _initialiser методе, и я знаю, что типы атрибутов каждого должны быть предварительно объявлены, чтобы numba мог выполнить jit-компиляцию. Но что бы это был за тип атрибута, который содержит функцию генератора? Если такой подход невозможен, приветствуется любой другой альтернативный подход. Просто имейте в виду, что
    • Всякий _initializer раз, когда вызывается функция, _unique_id_generator ее (или аналогичную функциональность) необходимо снова инициализировать.

Любая помощь будет оценена по достоинству 🙂 Спасибо.