Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython return tuple within cdef?

Tags:

cython

Hi I am trying to convert a python code into cython in order to speed up its calculation. I am trying to return multiple arrays within the cython code from a cdef to cpdef. Based on classical C, I could either use a pointer or a tuple. I decide to use tuple because the size varies. I know the following code doesn't work, any help? Thank you!

import numpy as np
cimport numpy as np

cdef tuple funA(double[:] X, double[:] Y): 
    cdef int nX, nY, i
    nX = len(X)
    nY = len(Y)

    for i in range(nX):
        X[i] = X[i]*X[i]

    for i in range(nY):
        Y[i] = Y[i]*Y[i]

    return X,Y

cpdef Run(double[:] X, double[:] Y)
    cdef Tuple1, Tuple2 = funA(X,Y)

    # Do some calculation with Tuple1 and Tuple2 
    # Example

    cdef int i, nTuple1, nTuple2

    nTuple1 = len(Tuple1)    
    for i in range(nTuple1):
        Tuple1[i] = Tuple1[i]**2

    nTuple2 = len(Tuple2)
    for i in range(nTuple2):
        Tuple2[i] = Tuple2[i]/2

    return Tuple1, Tuple2
like image 947
user4627923 Avatar asked Oct 29 '25 09:10

user4627923


1 Answers

You've got a few indentation errors and missing colons. But your real issue is:

cdef Tuple1, Tuple2 = funA(X,Y)

Remove the cdef and it's fine. It doesn't look like cdef and tuple unpacking quite mix, and since you're treating them as Python objects it should be OK.

However, note that you don't really need to return anything from funA since you modify X and Y them in place there.

like image 73
DavidW Avatar answered Oct 31 '25 13:10

DavidW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!