core-adapters 0.1.3
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
ndarray.hpp File Reference

NumPy arrays in and out of a header-only C++ function, with the GIL released: the names and the template. More...

#include <nanobind/nanobind.h>
#include <nanobind/ndarray.h>
#include <cstddef>
#include <memory>
#include <span>
#include <stdexcept>
#include <utility>
#include <vector>

Go to the source code of this file.

Typedefs

template<class T >
using snicholls::python::vector_in = ::nanobind::ndarray< const T, ::nanobind::ndim< 1 >, ::nanobind::c_contig, ::nanobind::device::cpu >
 A read-only, C-contiguous, one-dimensional CPU array of T, as a function argument.
 
template<class T >
using snicholls::python::matrix_in = ::nanobind::ndarray< const T, ::nanobind::ndim< 2 >, ::nanobind::c_contig, ::nanobind::device::cpu >
 A read-only, C-contiguous (row-major), two-dimensional CPU array of T, as a function argument.
 
template<class T >
using snicholls::python::vector_inout = ::nanobind::ndarray< T, ::nanobind::ndim< 1 >, ::nanobind::c_contig, ::nanobind::device::cpu >
 A writable, C-contiguous, one-dimensional CPU array of T, for functions that work in place.
 
template<class T >
using snicholls::python::numpy_vector = ::nanobind::ndarray<::nanobind::numpy, T, ::nanobind::ndim< 1 > >
 A one-dimensional NumPy array of T, as a result.
 
template<class T >
using snicholls::python::numpy_matrix = ::nanobind::ndarray<::nanobind::numpy, T, ::nanobind::ndim< 2 >, ::nanobind::c_contig >
 A two-dimensional, row-major NumPy array of T, as a result.
 

Functions

template<class... Args>
auto snicholls::python::as_span (const ::nanobind::ndarray< Args... > &a) noexcept
 A span over a C-contiguous array's elements, all dimensions flattened in row-major order.
 
template<class T >
numpy_matrix< T > snicholls::python::to_numpy (std::vector< T > &&values, std::size_t rows, std::size_t columns)
 A NumPy array of shape (rows, columns) owning values' buffer, without copying it.
 
template<class T >
numpy_vector< T > snicholls::python::to_numpy (std::vector< T > &&values)
 A one-dimensional NumPy array owning values' buffer, without copying it.
 

Detailed Description

NumPy arrays in and out of a header-only C++ function, with the GIL released: the names and the template.

Overview
Core's numerics take std::span of plain data and return plain data, so binding one is always the same four steps. This header names the pieces, and the demo holds the template that maintainers copy:
  1. In: vector_in<T> / matrix_in<T> - a read-only, C-contiguous, CPU nanobind::ndarray. NumPy arrays, and anything else exporting DLPack or the buffer protocol, convert; a non-contiguous array or one of another dtype is copied by nanobind first (pass .noconvert() on the argument to refuse instead).
  2. View: as_span(a) - a std::span over the array's memory, no copy.
  3. Compute: without_gil(...) (gil.hpp) around the core call; check preconditions with require(...) (errors.hpp) before, because Python passes anything.
  4. Out: to_numpy(std::move(vector)) (or with rows and columns) - the vector's buffer handed to a NumPy array, no copy, freed when the array is.
m.def(
"harsanyi_dividends",
[](snicholls::python::vector_in<double> table) { // 1. in: read-only, contiguous, CPU
snicholls::python::require(std::has_single_bit(table.size()), // check what core only asserts
"harsanyi_dividends: the table has 2^n values");
const std::span<const double> in = snicholls::python::as_span(table); // 2. view: no copy
std::vector<double> out = snicholls::python::without_gil([&] { // 3. compute: GIL released,
std::vector<double> d(in.begin(), in.end()); // plain data only
snicholls::game::to_dividends(std::span<double>(d));
return d;
});
return snicholls::python::to_numpy(std::move(out)); // 4. out: the vector's buffer
},
"table"_a,
"The Harsanyi dividends of a table of v(S). C++: snicholls::game::to_dividends.");
::nanobind::ndarray< const T, ::nanobind::ndim< 1 >, ::nanobind::c_contig, ::nanobind::device::cpu > vector_in
A read-only, C-contiguous, one-dimensional CPU array of T, as a function argument.
Definition ndarray.hpp:80
auto as_span(const ::nanobind::ndarray< Args... > &a) noexcept
A span over a C-contiguous array's elements, all dimensions flattened in row-major order.
Definition ndarray.hpp:108
numpy_matrix< T > to_numpy(std::vector< T > &&values, std::size_t rows, std::size_t columns)
A NumPy array of shape (rows, columns) owning values' buffer, without copying it.
Definition ndarray.hpp:138
decltype(auto) without_gil(F &&f)
Runs f() with the GIL released and returns its result.
Definition gil.hpp:102
void require(bool condition, const char *message)
Throws precondition_error(message) unless condition holds.
Definition errors.hpp:236
Relationships
Guarantees and contracts
  • as_span is O(1), noexcept, and valid while the ndarray argument lives (the whole call).
  • to_numpy is O(1) after one allocation for the owner; the NumPy array owns the data from then on.
  • Reading an input array with the GIL released is safe as long as no other Python thread writes to it at the same time - the same rule as NumPy's own released-GIL operations.
Errors
A wrong dtype, rank or device fails overload resolution: TypeError naming the expected signature. to_numpy throws std::bad_alloc (MemoryError), and std::length_error (ValueError) when rows times columns is not the vector's size.
Performance
The fixed cost of a call - argument conversion, the GIL round trip, building the result array - is measured in BENCHMARKS.md (tabular Shapley, Python against C++).
Tests and demos
  • Tests: tests/nanobind/ndarray_test.cpp (the test module), tests/nanobind/ndarray_test.py.
  • Demo: demos/nanobind/ndarray_demo.cpp, demos/nanobind/ndarray_demo.py; scripts/demos/ndarray_demo.sh.
Dependencies
CMake target snicholls::core_nanobind; <nanobind/ndarray.h>. NumPy is needed at run time only by functions that return NumPy arrays.
Known issues and gotchas
  • Never return a view of an input array as a new array without passing the input as its owner: the input may be freed first.
  • A uint64 coalition table or index array must be asked for as such; NumPy's default integer is int64.
Status
Experimental, pre-1.0.

Definition in file ndarray.hpp.