首页 > 解决方案 > 如何将 numpy.double、numpy.single 和 struct.Struct 类型的类属性转换为各自的 numba 类型?

问题描述

如何将 numpy.double、numpy.single 和 struct.Struct 类型的类属性转换为各自的 numba 类型,以便能够在 jitclass 中使用这些属性?

1)例如,类属性之一具有以下形式:

self.type = numpy.double

为了编译具有此类属性的 python 类,我必须将其映射到 numba 类型。我试过 numba.typeof(numpy.double) 但它会产生以下错误

In [1]: a=numpy.double
In [2]: numba.typeof(a)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-244-7ab9d6ba8d0a> in <module>
----> 1 numba.typeof(a)

C:\ProgramData\Anaconda3\lib\site-packages\numba\typing\typeof.py in typeof(val
 purpose)
     32         msg = _termcolor.errmsg(
     33             "cannot determine Numba type of %r") % (type(val),)
---> 34         raise ValueError(msg)
     35     return ty
     36

ValueError: cannot determine Numba type of <class 'type'>

2)在使用 struct.Struct 的情况下,我得到了类似的错误

In [1]: from struct import Struct
In [2]: a = Struct(">dd")
In [3]: numba.typeof(a)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-76-7ab9d6ba8d0a> in <module>
----> 1 numba.typeof(a)

C:\ProgramData\Anaconda3\lib\site-packages\numba\typing\typeof.py in typeof(val,
 purpose)
     32         msg = _termcolor.errmsg(
     33             "cannot determine Numba type of %r") % (type(val),)
---> 34         raise ValueError(msg)
     35     return ty
     36

ValueError: cannot determine Numba type of <class 'Struct'>

最小(工作)示例:

import numpy as np
import numba as nb
from struct import Struct

spec = [('type', nb.typeof(np.double)), ('h', nb.typeof(Struct(">f8")))]

@nb.jitclass(spec)
class TestClass:

    def __init__(self):
        self.type = np.double
        self.h = Struct(">f8")

当我尝试编译上述类时,出现以下错误:

C:>python classtest.py
Traceback (most recent call last):
  File "classtest.py", line 5, in <module>
    spec = [('type', nb.typeof(np.double)), ('h', nb.typeof(Struct(">f8")))]
  File "C:\ProgramData\Anaconda3\lib\site-packages\numba\typing\typeof.py", line
 34, in typeof
    raise ValueError(msg)
ValueError: ←[1mcannot determine Numba type of <class 'type'>←[0m

标签: pythonnumpynumba

解决方案


如何将 numpy.double、numpy.single 和 struct.Struct 类型的类属性转换为各自的 numba 类型,以便能够在 jitclass 中使用这些属性?

对于numpy.doublenumpy.single它很容易,numba.float64并且numba.float32是相应的 numba 类型。

在版本 0.43.1 中numba.typeof也适用于 NumPy 类型,但是该函数需要一个实例而不是类本身:

>>> import numpy as np
>>> import numba as nb
>>> nb.__version__
'0.43.1'
>>> nb.typeof(np.double(10))
float64

但是,目前(从 numba 的 0.43.1 版开始)不支持structin numba(请参阅numba 文档的“2.6。支持的 Python 功能”),因此您不能struct在 numba(包括jitclass)中使用 nopython 模式。

当然,您可以将 struct 解压缩到各个组件中,如果 numba 支持它们,请改用它们。例如,'dd'您可以numba.float64jitclass. 由于您一直在使用不同的结构,并且 numba 并非支持每种 Python 类型,您可能需要对此进行试验。


推荐阅读