Howto declare local variable ndarray[double, ndim=2] in @locals?

24 views
Skip to first unread message

Zaur Shibzukhov

unread,
May 24, 2013, 3:25:45 PM5/24/13
to cython...@googlegroups.com
Currently I can declare numpy 1d and 2d arrays both in args and local vars using syntax: ndarray[double, ndim=1] or ndarray[double, ndim=2].

When I write function in .py file and trying to use .pxd for type annotations I can declare 1d and 2d numpy arrays in args. For example:

cdef ndarray[double, ndim=1] func(ndarray[double, ndim=2] X, ndarray[double, ndim=1] y)

But I don't know howto define in function local var with a such 1d/2d numpy array using @locals decorator.

Is it doable?

Zaur Shibzukhov

unread,
May 28, 2013, 4:42:19 AM5/28/13
to cython...@googlegroups.com
To be clear. I uses pure .py files and .pxd files for typing. I looked up a way to declare numpy buffers as local variables into functions.
I found for myself solution based on typed memory views instead of numpy buffers.

(The issue was that @locals decorator in .pxd files has limitations that prevents declaration of typed memory views and numpy buffers because it uses pure python expression syntax)

Here is example to illustrate:

in test.pxd:

from cython cimport locals

ctypedef double[:] Vector
ctypedef double[:,:] Matrix

@locals(i=int, j=int, s=double, Y=Vector)
cdef Vector test(Matrix X)

in test.py:

import numpy as np

def test(a):
    Y = np.ndarray((a.shape[1],), dtype=np.double )
    for i in range(a.shape[0]):
        s = 0.0
        for j in range(a.shape[1]):
            s += a[i,j]
        Y[i] = s
    return Y

Is there a way to add support of typed memory views declaration in @locals decorator?

пятница, 24 мая 2013 г., 23:25:45 UTC+4 пользователь Zaur Shibzukhov написал:
Reply all
Reply to author
Forward
0 new messages