Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare 2D list in Cython

Tags:

python

cython

I'm trying to compile this kind of code:

def my_func(double c, int m):
    cdef double f[m][m]

    f = [[c for x in range(m)] for y in range(m)]
    ...

which raises:

Error compiling Cython file:
------------------------------------------------------------
def grow(double alpha, double beta, double gamma, int m, int s):
    cdef double f[m][m]
                     ^
------------------------------------------------------------
test.pyx:6:22: Not allowed in a constant expression

after which I assume I can't use variable at the pointed place and I try with numeric value:

def my_func(double c, int m):
    cdef double f[500][500]

    f = [[c for x in range(500)] for y in range(500)]
    ...

but then I get:

Error compiling Cython file:
------------------------------------------------------------
    f = [[beta for x in range(500)] for y in range(500)]
     ^
------------------------------------------------------------
test.pyx:13:6: Assignment to non-lvalue 'f'

So, I'm wondering how to declare and make 2D list in cython code. I couldn't find this kind of example in documentation of googling for "cython 2D list"

like image 364
theta Avatar asked Jan 02 '13 09:01

theta


1 Answers

Do not use list comprehension in Cython. There are not speedups as they create regular python list. Wiki says, that you should use dynamic allocation in Cython as follow:

from libc.stdlib cimport malloc, free

def my_func(double c, int m):
    cdef int x
    cdef int y
    cdef double *my_array = <double *>malloc(m * m * sizeof(double))

    try:

        for y in range(m):
            for x in range(m):
                #Row major array access
                my_array[ x + y * m ] = c

        #do some thing with my_array

    finally:
       free( my_array )

But if you need to have a python object of a 2D array, its recommended to use NumPy.

like image 84
Arpegius Avatar answered Oct 10 '22 14:10

Arpegius