I'm trying to Cythonize a simple function and I want to be able to compile it with the nogil statement. What I have (in a jupyter notebook) is:
%%cython -a
import numpy as np
cimport numpy as np
cimport cython
from libc.math cimport exp, pi
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
cdef double[:, ::1] _gauss(Py_ssize_t yw, Py_ssize_t xw, double y0, double x0, double sy, double sx):
"""Simple normalized 2D gaussian function for rendering"""
# for this model, x and y are seperable, so we can generate
# two gaussians and take the outer product
cdef double amp = 1 / (2 * pi * sy * sx)
cdef double[:, ::1] result = np.empty((yw, xw), dtype=np.float64)
cdef Py_ssize_t x, y
for y in range(yw):
for x in range(xw):
result[y, x] = exp(-((y - y0) / sy) ** 2 / 2 - ((x - x0) / sx) ** 2 / 2) * amp
return result
def gauss(yw, xw, y0, x0, sy, sx):
return _gauss(yw, xw, y0, x0, sy, sx)
Which compiles fine. If I change the first cdef line to read:
...
cdef double[:, ::1] _gauss(Py_ssize_t yw, Py_ssize_t xw, double y0, double x0, double sy, double sx) nogil:
...
Then the compilation fails because the first and third cdef lines interact with the python interpreter and I'm not sure why (especially for the first one).