Cython + numpy ndim variable?

I need to initialize variable form arrays (dim,) + (nbins,)*dimwhere dim is usually small, but nbins can be large, so the array has ndims = dim + 1. For example, if dim = 1I need an array of form (1, nbins), if dim = 2form (2, nbins, nbins), etc.

Is it possible to introduce numpy arrays accordingly? I tried something like

 ctypedef uint32_t  uint_t
 ctypedef float     real_t
 ...
     cdef:
         uint_t dim = input_data.shape[1]
         np.ndarray[real_t, ndim=dim+1] my_array = np.zeros((dim,)\
     + (nbins,)*dim, dtype = np.float32)

Yes, I had a hunch that this would not work, but I still had to try;)

Is it possible to do something like this, or do I need to use pointers / memory allocation, etc.? Or do I need (gulp!) To just use a one-dimensional array and just change it at the end ??

+4
source share
1

(gulp!) ?

, . Cython , . malloc, .

cdef:
    np.npy_intp size = dim * n_bins ** dim
    np.ndarray[float, ndim=1, mode='c'] arr = np.zeros(size, dtype=np.float32)

    # do work, using "manual" index calculations

    return arr.reshape(dim, (n_bins,) * dim)

( : np.npy_intp, uint32_t.)

+2

All Articles