reshape numpy arrays in cython

624 views
Skip to first unread message

laurama

unread,
Jul 21, 2011, 6:43:46 PM7/21/11
to cython-users
Hi all,
I am fairly new in Python and brand new in Cython, so I apologize in
advance because this is probably a dumb question... I read the
tutorials about working with numpy arrays and cython and I remember
reading somewhere that once defined, a cython array cannot be modified
(ie cannot be reshaped) but I cannot find this anymore. Is this
correct?
In my functions need to interact with lists and numpy arrays a lot. I
defined the numpy arrays as cython arrays but I didn't redefine the
lists as anything. So for example simple_function1 receives a list and
returns an array (and I have functions that do the opposite). I have
some questions:

1. When I run the cython version of the function simple_function, I
have an error indicating me that I have the wrong dimensions:
"Buffer has wrong number of dimensions (expected 1, got 3)"
I understand this, I told cython the dim was 1 but at the end I want
to reshape the array to have 3 dimensions. Is it possible to do this?
If not, what is the best way to "cythonize" this function?

#chromosome is just a list of numbers
def simple_function(chromosome):
chromoArray = np.array((chromosome),dtype = DTYPE2)
chromoArray = chromoArray.reshape(len(anotherlist),m,2)
... more stuff

return chromoArray

my cython code looks like:
def simple_function(chromosome):
cdef np.ndarray[DTYPE2_t, ndim=1] chromoArray =
np.array((chromosome),dtype = DTYPE2)
chromoArray =
chromoArray.reshape(len(self.totalVaccineList),self.numberOfCities,2)
...more stuff


2. Is there a way to "cythonize" lists?

3. Inside a Python class, so something of the form:
class MyClass:
blabla

is it best to define cpdef functions? I read the documentation online
and tried to do this but got an error at compilation.

Any ideas would be highly highly appreciated!
thanks a lot!

Laura Matrajt

unread,
Jul 21, 2011, 6:45:51 PM7/21/11
to cython-users
oops, forgot to tell you that DTYPE2 = np.float!
thanks!
--
Laura


Robert Bradshaw

unread,
Jul 21, 2011, 6:48:12 PM7/21/11
to cython...@googlegroups.com
On Thu, Jul 21, 2011 at 3:43 PM, laurama <mat...@gmail.com> wrote:

Assign it to a new variable.

   cdef np.ndarray[DTYPE2_t, ndim=3] chromoArray2 =
chromoArray.reshape(len(self.totalVaccineList),self.numberOfCities,2)

> 2. Is there a way to "cythonize" lists?

cdef list foo

> 3. Inside a Python class, so something of the form:
> class MyClass:
>    blabla
>
> is it best to define cpdef functions? I read the documentation online
> and tried to do this but got an error at compilation.

cpdef methods only make sense for cpdef classes.

- Robert

Reply all
Reply to author
Forward
0 new messages