Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython buffer declarations for object members

Tags:

I want to have a Cython "cdef" object with a NumPy member, and be able to use fast buffer access. Ideally, I would do something like:

import numpy as np cimport numpy as np  cdef class Model:   cdef np.ndarray[np.int_t, ndim=1] A    def sum(self):     cdef int i, s=0, N=len(self.A)     for 0 <= i < N:       s += self.A[i]     return s    def __init__(self):     self.A = np.arange(1000) 

Unfortunately, Cython can't compile this, with the error Buffer types only allowed as function local variables.

The workaround I'm using is to declare the buffer attributes on a new local variable, assigned to the object member:

cdef class Model:   cdef np.ndarray A    def sum(self):     cdef int i, s=0, N=len(self.A)     cdef np.ndarray[np.int_t, ndim=1] A = self.A     for 0 <= i < N:       s += A[i]     return s 

This becomes really annoying if you want to have multiple methods accessing the same data structures -- which seems like a pretty common use case, no?

Is there a better solution that doesn't require re-declaring the types inside every method?

like image 324
Brendan OConnor Avatar asked Jan 10 '12 18:01

Brendan OConnor


1 Answers

There is the option to work with memory slices or cython arrays http://docs.cython.org/src/userguide/memoryviews.html

import numpy as np cimport numpy as np    cdef class Model:      cdef int [:] A      def sum(self):          for 0 <= i < N:             s += self.A[i]         return s      def __init__(self):         self.A = np.arange(1000) 
like image 131
fco Avatar answered Oct 21 '22 13:10

fco