Oskar Paulsson
Oskar Paulsson

Reputation: 29

How do you use/view memoryview objects in Cython?

I've got a project where a handful of nested for-loops are slowing down the runtime of the code so I've started implementing some Cython typing and it sped up the runtime of the loops significantly but I've run into a new problem, the typing I'm using doesn't allow for any computations to be done one them. Here's a mock sketch of my code:

cdef double[:,:] my_matrix = np.zeros([width, height])

for i in range(0,width):
  for j in range(0,height):
    a = v1[i] - v2[j]
    my_matrix[i,j] = np.sqrt(a**2)

After that I want to compute the product of my_matrix using

product = constant1 * np.exp(-1j * constant2 * my_matrix) / my_matrix

By attempting this I get the error:

TypeError: unsupported operand type(s) for *: 'complex' and 'my_cython_function_cy._memoryviewslice'

I understand the implication of this error but I dont get how to use the contents of the memoryview-object as an array, I tried doing this;

    new_matrix = my_matrix

but that won't compile. I'm new to both C and Cython and the documentation isn't very helpful for these rookie-questions so I would be very grateful for any help here.

Upvotes: 0

Views: 342

Answers (1)

DavidW
DavidW

Reputation: 30936

The best thing to do is:

new_matrix = np.as_array(my_matrix)

That lets you access the full set of Numpy operations on the array. It should be a pretty lightweight transformation (they'll share the same underlying data).


You could also get the wrapped object with my_matrix.base (this would probably be the original Numpy array that you initialized it with). However, depending on what you've done with slicing this might not be quite the same as the memoryview, so be a bit wary of this approach.

Upvotes: 1

Related Questions