Commit 85a14938 authored by Klaus Reuter's avatar Klaus Reuter
Browse files

add minimal numpy example for illustration purposes

parent 1fcfcbd8
cmake_minimum_required(VERSION 3.18) cmake_minimum_required(VERSION 3.18)
project(pybind11-hello-world VERSION "1.0")
project(hello-world VERSION "1.0")
find_package(pybind11) find_package(pybind11)
pybind11_add_module(_hello MODULE src/hello/hello.cpp) pybind11_add_module(_cumsum MODULE src/cumsum/cumsum.cpp)
install(TARGETS _cumsum DESTINATION .)
install(TARGETS _hello DESTINATION .) \ No newline at end of file
import sys
from skbuild import setup from skbuild import setup
setup( setup(
name="hello-world", name="pybind11-numpy-like-cumsum-example",
version="1.0", version="1.0",
description="hello world example", description="pybind11-numpy example",
author='MPCDF', author='MPCDF',
license="MIT", license="MIT",
packages=['hello'], packages=['cumsum'],
package_dir={'': 'src'}, package_dir={'': 'src'},
cmake_install_dir='src/hello' cmake_install_dir='src/cumsum'
) )
from ._cumsum import cumsum
\ No newline at end of file
// pybind11 example module 'cumsum'
#include <numeric>
#include <functional>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
// numpy-like cumulative sum, taking a NumPy array as input and returning a NumPy array
py::array_t<double> cumsum(py::array_t<double> a)
{
// obtain information about the nd input array
auto shape = a.request().shape;
size_t count = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());
// create output NumPy array
py::array_t<double> b(count);
// obtain raw pointers
double * a_p = (double*) a.request().ptr;
double * b_p = (double*) b.request().ptr;
// compute cumulative sum into b
double cs = 0.0;
for (size_t i = 0; i<count; ++i) {
cs += a_p[i];
b_p[i] = cs;
}
return b;
}
// Python binary module _cumsum, expose cumsum C++ function as cumsum to Python
PYBIND11_MODULE(_cumsum, m) {
m.doc() = "pybind11 cumulative sum example"; // module docstring
m.def("cumsum", &cumsum, // third parameter is the function docstring
"return the cumulative sum of a double-precision numpy array");
}
#!/usr/bin/env python3
import numpy as np
import cumsum
a = np.random.rand(80)
ap = a.reshape(20,4)
b = cumsum.cumsum(ap)
c = np.cumsum(ap)
assert(np.allclose(b, c))
print("OK!")
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment