Skip to content
Advertisement

Translating python function with boolean indexing within loop to cython

Below I’ll write a function in pure python that I want to Cythonize.

JavaScript

Suppose that I know how to Cythonize the function do_stuff. The actual do_stuff function I’m interested in is more complicated than the one above but I thought I’d provide an example. The real do_stuff function computes determinants and takes inverses, in addition to matrix multiplication.

My main problem has to do with creating the M_i and C_i subvector and submatrix. I’m not sure I can do the same sort of boolean indexing in Cython. And if I can, I don’t know how. But I can get started with the bit of Cython I know.

JavaScript

Advertisement

Answer

You probably won’t gain too much speed here, since boolean indexing in Numpy is implemented in C anyway, so should be fairly fast. The main thing you’d avoid is creating some unnecessary intermediates (which involves a memory allocation so is potentially slow).

What you want to do is create temporary arrays for M_i and C_i that are the largest possible size (i.e. J or JxJ). As you iterate through isnan(M_I) you keep track of how many values you’ve actually stored. Then at the end you trim M_i and C_i to only the part that you’ve used:

Untested code:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement