fused type for a numpy array?

1,202 views
Skip to first unread message

Warren Weckesser

unread,
Apr 24, 2012, 8:43:09 PM4/24/12
to cython...@googlegroups.com
I'm digging into the new fused types--thanks for adding this!

I would like to apply the idea to numpy arrays, but the following does not work ("no suitable method found" and "Invalid use of fused types, type cannot be specialized" at the lines 'func(a)' and 'func(b)'):


cimport cython
import numpy as np
cimport numpy as np


ctypedef fused np_numeric:
    np.int_t
    np.float_t

cdef void func(np.ndarray[np_numeric, ndim=1] a):
    print "a.dtype is", a.dtype

def test_array():
    a = np.array([1,2,3], dtype=np.int)
    b = np.array([4.0, 5.0], dtype=np.float)
    func(a)
    func(b)


Is something like this possible?


Warren

Warren Weckesser

unread,
Apr 24, 2012, 11:41:06 PM4/24/12
to cython...@googlegroups.com


Answering my own question:  it looks like it works if I use the full ndarray type specification in the fused type:



cimport cython
import numpy as np
cimport numpy as np


ctypedef fused numeric_array:
    np.ndarray[np.float64_t, ndim=1]
    np.ndarray[np.uint64_t, ndim=1]

cdef numeric_array func(numeric_array a):
    print "a.dtype =", a.dtype
    cdef numeric_array b = a[0:1] + a[1:2]
    return b

def check():
    cdef np.ndarray[np.uint64_t, ndim=1] x = np.array([2**60, 1], dtype=np.uint64)
    cdef np.ndarray[np.float64_t, ndim=1] y = np.array([2**60, 1], dtype=np.float64)

    z = func(x)
    print type(z), z.dtype
    print np.equal(z, x[0:1])

    print

    z = func(y)
    print type(z), z.dtype
    print np.equal(z, x[0:1])
 


Tips on better ways to use fused numpy arrays would be appreciated!


Warren

mark florisson

unread,
Apr 25, 2012, 7:28:37 AM4/25/12
to cython...@googlegroups.com

Yes, but you need to type both your 'a' and 'b' variables in order for
the compiler to understand which type you mean. Currently the compiler
doesn't type infer the variables (and it has no awareness of numpy),
so it doesn't know how to match "an arbitrary object" to "some typed
ndarray".

>
> Warren
>

Warren Weckesser

unread,
Apr 25, 2012, 7:58:53 AM4/25/12
to cython...@googlegroups.com


Thanks, Mark, that makes sense.  After declaring the variables appropriately, it works just fine.

Warren

Reply all
Reply to author
Forward
0 new messages