Created
May 11, 2017 15:29
-
-
Save kbarbary/4c367a05a151bd680e1cf94a97a32635 to your computer and use it in GitHub Desktop.
Example: Using cython, convert numpy.ndarray to C++ std::valarray and back (using copies)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""example of converting a numpy array to a C++ valarray and back in cython | |
using copies. | |
Compile with `python setup.py build_ext --inplace` | |
Example | |
------- | |
>>> import cpptest, numpy as np | |
>>> x = np.array([0., 1., 2.]) | |
>>> cpptest.multiply(x, 4.) | |
array([ 0., 4., 8.]) | |
""" | |
import numpy as np | |
cimport numpy as np | |
# See the Cython docs on declaring templated C++ classes: | |
# http://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#templates | |
# | |
# See also, the definition of valarray in C++ standard library: | |
# http://en.cppreference.com/w/cpp/numeric/valarray | |
# | |
# We only declare here the methods we actually use | |
cdef extern from "<valarray>" namespace "std": | |
cdef cppclass valarray[T]: | |
valarray() | |
valarray(int) # constructor: empty constructor | |
T& operator[](int) # get/set element | |
def multiply(double[:] x, double factor): | |
"""Multiply the array x by some factor using c++ for some reason""" | |
cdef valarray[double] v | |
cdef int i | |
cdef double[:] out_view # memory view of output array | |
# allocate C++ valarray | |
v = valarray[double](len(x)) | |
# copy values in input memory view to C++ valarray | |
for i in range(len(x)): | |
v[i] = x[i] | |
# multiply each element in the C++ valarray | |
for i in range(len(x)): | |
v[i] = v[i] * factor | |
# allocate output numpy array. | |
out = np.empty(len(x), dtype=np.double) | |
out_view = out | |
# copy C++ valarray to output numpy array | |
for i in range(len(x)): | |
out_view[i] = v[i] | |
return out |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from distutils.core import setup | |
from distutils.extension import Extension | |
from Cython.Distutils import build_ext | |
import numpy | |
setup( | |
cmdclass = {'build_ext': build_ext}, | |
ext_modules = [Extension("cpptest", | |
sources=["cpptest.pyx"], | |
language="c++", | |
include_dirs=[numpy.get_include()])], | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment