有没有办法让Numba不要尝试编译函数的特定行?

2024-05-16 03:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数正在调用Numba没有实现的函数,因此代码失败并返回以下错误:

Traceback (most recent call last):
  File "makearray.py", line 45, in <module>
    arrNp = loop(100*i)
  File "~/.local/lib/python3.8/site-packages/numba/core/dispatcher.py", line 414, in _compile_for_args
    error_rewrite(e, 'typing')
  File "~/.local/lib/python3.8/site-packages/numba/core/dispatcher.py", line 357, in error_rewrite
    raise e.with_traceback(None)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<built-in function setitem>) found for signature:
 
 >>> setitem(array(undefined, 1d, C), int64, array(int64, 1d, C))
 
There are 16 candidate implementations:
   - Of which 16 did not match due to:
   Overload of function 'setitem': File: <numerous>: Line N/A.
     With argument(s): '(array(undefined, 1d, C), int64, array(int64, 1d, C))':
    No match.

During: typing of setitem at makearray.py (39)

File "makearray.py", line 39:
def loop(zoom):
    <source elided>
            row.append(theM.real)
        arra.append(row)
        ^

代码在循环中调用loop,现在Numba不喜欢它。如果没有循环,onyl只调用一次loop,它就可以工作了。更改fastmath和其他Numba参数没有什么区别。那么,有没有一种方法可以告诉Numba让一行代码成为普通的Python代码,这样它在尝试寻找优化时就不会收到这个错误消息

供参考,代码如下:

from numba import njit
import numpy as np

nmax=50

@njit(fastmath=True)
def mandelbrot(c):
    z=0
    n=0
    while abs(z) <= 2 and n < nmax:
        z = z*z+c
        n+=1
    return n

@njit()
def loop(zoom):
    img = []
    for a in range(-1500,500+1,1):
        col = []
        for b in range(-1050,1050+1,1):
            c = complex(-np.e/7+a/(1000+zoom),b/(1000+zoom)-np.e/20)
            theM = mandelbrot(c)
            row.append(theM.real)
        img.append(row)
    imgNp = np.array(img)
    return imgNp


for i in range(50):
    imgNp = loop(100*i)
    np.save('mbsNp'+str(i).zfill(3),imgNp)

Tags: 代码inpyloopfornplinearray