test_numpy_vectorize.cpp revision 11986
1/* 2 tests/test_numpy_vectorize.cpp -- auto-vectorize functions over NumPy array 3 arguments 4 5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 6 7 All rights reserved. Use of this source code is governed by a 8 BSD-style license that can be found in the LICENSE file. 9*/ 10 11#include "pybind11_tests.h" 12#include <pybind11/numpy.h> 13 14double my_func(int x, float y, double z) { 15 py::print("my_func(x:int={}, y:float={:.0f}, z:float={:.0f})"_s.format(x, y, z)); 16 return (float) x*y*z; 17} 18 19std::complex<double> my_func3(std::complex<double> c) { 20 return c * std::complex<double>(2.f); 21} 22 23test_initializer numpy_vectorize([](py::module &m) { 24 // Vectorize all arguments of a function (though non-vector arguments are also allowed) 25 m.def("vectorized_func", py::vectorize(my_func)); 26 27 // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization) 28 m.def("vectorized_func2", 29 [](py::array_t<int> x, py::array_t<float> y, float z) { 30 return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y); 31 } 32 ); 33 34 // Vectorize a complex-valued function 35 m.def("vectorized_func3", py::vectorize(my_func3)); 36 37 /// Numpy function which only accepts specific data types 38 m.def("selective_func", [](py::array_t<int, py::array::c_style>) { return "Int branch taken."; }); 39 m.def("selective_func", [](py::array_t<float, py::array::c_style>) { return "Float branch taken."; }); 40 m.def("selective_func", [](py::array_t<std::complex<float>, py::array::c_style>) { return "Complex float branch taken."; }); 41}); 42