Numba совместимый эквивалент numpy.gradient - PullRequest
1 голос
/ 30 октября 2019

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

Сейчас я пытаюсь использовать предложенное там решение Numba для другой, аналогичной функции. В этом случае я создаю еще одно движущееся окно с вложенными циклами for, которое проходит по всем строкам и столбцам простой матрицы, содержащей данные высот. Конкретная функция, над которой я сейчас работаю, требует вызова numpy.gradient

[fx, fy] = np.gradient(DEM, cellsize, cellsize)

Однако, когда я пытаюсь реализовать свою функцию с помощью Numba, я сталкиваюсь с проблемойс gradient.

TypingError: Use of unsupported NumPy function 'numpy.gradient' or unsupported use of the function.

Я не смог найти подходящую замену для функции градиента через поиск в Интернете. Я думал, что это сообщество может помочь. Я очень ценю любые идеи и советы, которые вы можете предоставить.

Если вам требуется больше контекста или информации, я также могу предоставить это.

После комментария Max9111 я решил создать две разные функции, однуэто убрало градиент из функции Нумба. first fuction

def DCE_preprocess(DEM, cellsize, w):

    [nrows, ncols] = np.shape(DEM)

    #initiate an empty array same size as dem
    rms = DEM*np.nan
#    rms = np.float32(rms)

#    #compute the directional cosines
    [fx, fy] = np.gradient(DEM, cellsize, cellsize)


    grad = np.sqrt(fx**2 + fy**2)
    asp = np.arctan2(fy, fx)



    grad=np.pi/2-np.arctan(grad) #normal of steepest slope
    asp[asp<np.pi]=asp[asp<np.pi]+[np.pi/2]
    asp[asp<0]=asp[asp<0]+[2*np.pi]

    #spherical to cartesian conversion
    r = 1
    cy = r * np.cos(grad) * np.sin(asp)
    cx = r * np.cos(grad) * np.cos(asp)
    cz = r * np.sin(grad)

    return(cx,cy,cz)

возвращает ввод для second function

eps = np.finfo(float).eps
def DC_eig_par(DEM,w,cx,cy,cz,eps):
    [nrows, ncols] = np.shape(DEM)
#
#    #initiate an empty array same size as dem
    rms = DEM*np.nan

    #Compute RMS cycling through the DEM
    nw=(w*2)**2
    for i in nb.prange(w+1,nrows-w):


        for j in range(w+1,(ncols-w)):
            d1=np.int64(np.linspace(i-w,i+w,11))
            d2=np.int64(np.linspace(j-w,j+w,11))

            tempx = cx[d1[0]:d1[-1],d2[0]:d2[-1]]

            tx=np.reshape(tempx,-1)
            tempy = cy[d1[0]:d1[-1],d2[0]:d2[-1]]
            ty=np.reshape(tempy,-1)
            tempz = cz[d1[0]:d1[-1],d2[0]:d2[-1]]
            tz=np.reshape(tempz,-1)

            if np.isnan(np.concatenate((tx,ty,tz))) == 0:
                T=np.array([[np.sum(tx**2), np.sum(tx*ty), np.sum(tx*tz)],
                             [np.sum(ty*tx), np.sum(ty**2), np.sum(ty*tz)], 
                             [np.sum(tz*tx), np.sum(tz*ty), np.sum(tz**2)]])


                [Te,_] = np.linalg.eig(T) # this step is a bit different from the matlab version b/c np.eig outputs two values.
                l = (Te/nw)
                l[l<eps] = 0
                rms[i,j] = 1/np.log(l[0]/l[1])


            else:
                rms[i,j] = np.nan

    return(rms)

Теперь я получаю следующую ошибку:

TypingError: Invalid use of Function(<built-in function getitem>) with argument(s) of type(s): (int64, Literal[int](0))
 * parameterized
In definition 0:
    All templates rejected with literals.
In definition 1:
    All templates rejected without literals.
In definition 2:
    All templates rejected with literals.
In definition 3:
    All templates rejected without literals.
In definition 4:
    All templates rejected with literals.
In definition 5:
    All templates rejected without literals.
In definition 6:
    All templates rejected with literals.
In definition 7:
    All templates rejected without literals.
In definition 8:
    All templates rejected with literals.
In definition 9:
    All templates rejected without literals.
This error is usually caused by passing an argument of a type that is unsupported by the named function.
[1] During: typing of intrinsic-call at U:\GHP\Projects\NSF - Morris Landslides\Code\Developmemnt\Wavelets\DC_eig_par.py (58)
[2] During: typing of static-get-item at U:\GHP\Projects\NSF - Morris Landslides\Code\Developmemnt\Wavelets\DC_eig_par.py (58)

, которая появляется вбыть проблема с нарезкой я пытаюсь сделать, используя tempx / y / z

...