blob: 8780d28ff54915bdaf24c417db1ab25ec59cfb29 [file] [log] [blame]
Wenzel Jakobd4258ba2015-07-26 16:33:49 +02001/*
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -04002 example/example-numpy-vectorize.cpp -- auto-vectorize functions over NumPy array
Wenzel Jakoba576e6a2015-07-29 17:51:54 +02003 arguments
Wenzel Jakobd4258ba2015-07-26 16:33:49 +02004
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakobd4258ba2015-07-26 16:33:49 +02006
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 "example.h"
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020012#include <pybind11/numpy.h>
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020013
14double my_func(int x, float y, double z) {
15 std::cout << "my_func(x:int=" << x << ", y:float=" << y << ", z:float=" << z << ")" << std::endl;
Boris Schäling20ee9352016-05-28 12:26:18 +020016 return (float) x*y*z;
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020017}
18
Wenzel Jakob43398a82015-07-28 16:12:20 +020019std::complex<double> my_func3(std::complex<double> c) {
20 return c * std::complex<double>(2.f);
21}
22
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -040023void init_ex_numpy_vectorize(py::module &m) {
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020024 // Vectorize all arguments of a function (though non-vector arguments are also allowed)
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020025 m.def("vectorized_func", py::vectorize(my_func));
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020026
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020027 // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
28 m.def("vectorized_func2",
Wenzel Jakobb50872a2015-10-13 17:38:22 +020029 [](py::array_t<int> x, py::array_t<float> y, float z) {
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020030 return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y);
31 }
32 );
Wenzel Jakoba576e6a2015-07-29 17:51:54 +020033
34 // Vectorize a complex-valued function
Wenzel Jakob43398a82015-07-28 16:12:20 +020035 m.def("vectorized_func3", py::vectorize(my_func3));
Wenzel Jakobb47a9de2016-05-19 16:02:09 +020036
37 /// Numpy function which only accepts specific data types
38 m.def("selective_func", [](py::array_t<int, py::array::c_style>) { std::cout << "Int branch taken. "<< std::endl; });
39 m.def("selective_func", [](py::array_t<float, py::array::c_style>) { std::cout << "Float branch taken. "<< std::endl; });
40 m.def("selective_func", [](py::array_t<std::complex<float>, py::array::c_style>) { std::cout << "Complex float branch taken. "<< std::endl; });
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020041}