You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.6 KiB

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