Note that there are some explanatory texts on larger screens.

plurals
  1. POArray of pointers from C++ to NumPy through Cython
    text
    copied!<p>I have a library in c++ and I'm trying to wrap it for python using Cython. One function returns an array of 3D vectors (float (*x)[3]) and I want to access that data from python. I was able to do so by doing something like</p> <pre><code>res = [ (self.thisptr.x[j][0],self.thisptr.x[j][1],self.thisptr.x[j][2]) for j in xrange(self.natoms) ] </code></pre> <p>but I would like to access this as a numpy array, so I tried numpy.array on that and it was much slower. I also tried</p> <pre><code> cdef np.ndarray res = np.zeros([self.thisptr.natoms,3], dtype=np.float) cdef int i for i in range(self.natoms): res[i][0] = self.thisptr.x[i][0] res[i][1] = self.thisptr.x[i][1] res[i][2] = self.thisptr.x[i][2] </code></pre> <p>But is about three times slower than the list version. </p> <p>Any suggestions on how to convert the list of vectors to an numpy array faster?</p> <p>The complete code is </p> <pre><code>cimport cython import numpy as np cimport numpy as np ctypedef np.float_t ftype_t cdef extern from "ccxtc.h" namespace "ccxtc": cdef cppclass xtc: xtc(char []) except + int next() int natoms float (*x)[3] float time cdef class pyxtc: cdef xtc *thisptr def __cinit__(self, char fname[]): self.thisptr = new xtc(fname) def __dealloc__(self): del self.thisptr property natoms: def __get__(self): return self.thisptr.natoms property x: def __get__(self): cdef np.ndarray res = np.zeros([self.thisptr.natoms,3], dtype=np.float) cdef int i for i in range(self.natoms): res[i][0] = self.thisptr.x[i][0] res[i][1] = self.thisptr.x[i][1] res[i][2] = self.thisptr.x[i][2] return res #return [ (self.thisptr.x[j][0],self.thisptr.x[j][1],self.thisptr.x[j][2]) for j in xrange(self.natoms)] @cython.boundscheck(False) def next(self): return self.thisptr.next() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload