I have made a function for doing optimization in python (let's call it optimizer). It requires the function to be optimized (let's call it objective) as one of the function arguments. objective is a function that accepts a one-dimensional np.ndarray and return a float number (which is the same as double in C++?).
I have read this post, but I'm not sure if it is actually the same problem as mine and when I use ctypedef int (*f_type)(int, str), but I get the error Cannot convert 'f_type' to Python object during compilation. Does it only work for C functions? How do I type a python function?
Edit: How my code looks like:
cpdef optimizer(objective, int num_particle, int dim,
np.ndarray[double, ndim=1] lower_bound,
np.ndarray[double, ndim=1] upper_bound):
cdef double min_value
cdef np.ndarray[double, ndim=2] positions = np.empty((num_particle,dim), dtype=np.double)
cdef np.ndarray[double, ndim=1] fitness = np.empty(num_particle, dtype=np.double)
cdef int i, j
# do lots of stuff not shown here
# involve the following code:
for i in range(num_particle):
fitness[i] = objective(positions[i])
return min_value
I want to know if it is possible to type objective to make the code run faster.