Skip to content

vectorizing a method that operates on an array #1294

Open
@nschloe

Description

@nschloe

I have a pybind11ified function that operates on a vector of dimension 1,

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

void distill(py::array_t<double, py::array::c_style | py::array::forcecast> p) {
  auto r = p.mutable_unchecked<1>();
  for (ssize_t i = 1; i < r.shape(0); i++) {
    r(i) = 3.14 * (r(i) + r(i-1));  // whatever
  }
}

PYBIND11_MODULE(_accupy, m) {
  m.def("distill", &distill);
}

I would now like to change the function to have it operate on the first dimension of numpy arrays of arbitrary dimensionality. The first thing that comes to mind is adding an inner loop

for (ssize_t j = 0; j < r.shape(1); j++) {
}

to the above and wrapping the method in Python code à la

def distill(p):
    q = p.reshape(p.shape[0], numpy.prod(p.shape[1:]))
    out = _mymod.distill(q)
    return out.reshape(p.shape)

This however wouldn't work with arrays of one dimension anymore. Also, instead of for (ssize_t j = 0; j < r.shape(1); j++) {} it's probably better to use BLAS's multiply-add functions there; a rabbit hole I'd rather not descend into.

Is there a canonical way for vectorizing pybind11 methods that operate on an array?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions