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
core-adapters

CI Docs

Third-party adapters for snicholls-core. Core is a header-only C++20 library that depends on the standard library alone, and stays that way; everything that joins it to a third-party library lives here, pinning core like every other member of the family.

What Target / package Depends on
nanobind helpers: the GIL, errors, NumPy arrays, bytes and text, std::optional / snicholls::result snicholls::core_nanobind (headers, <snicholls/core_adapters/nanobind/...>) core, nanobind v3.1.0
nlohmann/json hooks for core's utc, uuid, decimal, secret, and snicholls::json_error snicholls::core_json (headers, <snicholls/core_adapters/nlohmann/...>) core, nlohmann/json v3.12.0
Python bindings of core's game/ and stats/random Python package snicholls_core (abi3, CPython 3.12+) numpy

The Python package

import numpy as np
from snicholls_core import game, stats
glove = lambda s: float(min(bin(s & 3).count("1"), (s >> 2) & 1)) # a game: coalition bitmask -> value
table = game.tabulate(glove, 3) # v(S) for every coalition, once
game.shapley(table).values # [1/6, 1/6, 2/3], GIL released
game.owen(table, [[0, 1], [2]]).values # [0.25, 0.25, 0.5]
game.shapley_sampled(table, stats.Wyrand(7), permutations=2000) # same seed, same bits as C++
game.attribute_change(lambda x: x[0] * x[1] + 3 * x[2], np.array([1.0, 1, 0]), np.array([2.0, 3, 1]))

A game is either a table of v(S) - a float64 array of 2^n values (or 2^n x m for m metrics), indexed by the coalition's bits - or a Python callable v(s). Tables are the fast route: the arithmetic runs in C++ with the GIL released, and exact Shapley is practical up to about 20 players (2^20 values, passed once). A callable needs the GIL for every evaluation; the exact methods tabulate it first, Owen and the samplers call it as they go, and game.memoized(v) caches it in C++. game.set_game(f) adapts a game written for frozensets of players.

Exposed: shapley, banzhaf, harsanyi_dividends, shapley_from_dividends, banzhaf_from_dividends, owen, shapley_sampled (antithetic orders), shapley_sampled_lifts, memoized, attribute_change, interactions, the properties (is_monotone, is_superadditive, is_supermodular, is_submodular, is_additive, the find_* violations, in_core), the coalition helpers, and stats.Wyrand with random_u64, uniform_index, uniform_real, shuffle and permutation. Each docstring names its C++ counterpart; docs/python_api.md maps every name both ways. Errors share one hierarchy, snicholls_core.errors (CoreError, ResultError, TracedError, PreconditionError, a ValueError). Stubs (.pyi) generated by nanobind's stubgen ship in the wheel.

Install from a checkout (submodules included): pip install .

Interrogating it from a prompt

python -m snicholls_core opens a Python console with game, stats, errors and np loaded, and four helpers that read whatever the package binds (so anything bound later appears with no change to the console):

>>> inventory() # every class, function and exception, with the C++ each one calls
>>> describe("snicholls::game::owen") # signatures, documentation and C++ counterpart: by Python or C++ name
>>> a = game.shapley(np.array([0.0, 1, 2, 4]))
>>> fields(a) # {'baseline': 0.0, ..., 'total': 4.0, 'values': array([1.5, 2.5])}
>>> cpp("snicholls::stats::wyrand") # the Python names that call a C++ entity
>>> tour() # a short guided session

From the shell: python -m snicholls_core --list [MODULE], --describe NAME, --tour.

Consuming the C++ targets

add_subdirectory(third_party/core EXCLUDE_FROM_ALL) # your core pin: the top level's copy wins
snicholls_core_require(0.5.1)
add_subdirectory(third_party/core_adapters EXCLUDE_FROM_ALL) # snicholls::core_json, snicholls::core_nanobind,
# and nanobind_add_module() from the pinned nanobind
nanobind_add_module(my_module STABLE_ABI NB_STATIC NOMINSIZE src/my_module.cpp)
target_link_libraries(my_module PRIVATE snicholls::core_nanobind)
target_link_libraries(my_tool PRIVATE snicholls::core_json)
# last line of the top-level CMakeLists.txt:
snicholls_core_assert_single_version()

In each module: snicholls::python::register_exception_translators(); once in NB_MODULE, then release_gil(), without_gil(...), vector_in<T> / as_span / to_numpy, byte_view / text_view, and return core's results directly. The template for exposing a header-only function over NumPy arrays is demos/nanobind/ndarray_demo.cpp (region template). A module whose errors should be the shared Python classes lists snicholls_core as a Python dependency.

Options: CORE_ADAPTERS_WITH_NANOBIND (ON: find Python 3.12+ and nanobind), CORE_ADAPTERS_WITH_NLOHMANN (ON), CORE_ADAPTERS_BUILD_PYTHON / CORE_ADAPTERS_BUILD_TESTS (ON as the top-level project), CORE_ADAPTERS_BUILD_BENCHMARKS, CORE_ADAPTERS_BUILD_DOCS, CORE_ADAPTERS_WERROR, CORE_ADAPTERS_SANITIZE.

The gate

scripts/gate.sh is the repository's gate: non-interactive, offline, -j4, non-zero on any failure.

  1. a development venv (Python 3.12, numpy and pytest from the wheelhouse);
  2. Debug and Release, each configured into build-family/<config> with warnings as errors, built, and every CTest run (GoogleTest, the pytest suites against the build tree, demos, the static checks, the benchmark smoke run, and the Doxygen check in Release);
  3. pip install . into a clean venv and pytest against the installed package;
  4. the same abi3 wheel into a clean venv of every newer CPython found, and pytest there.

Python packages come from a local wheelhouse ($CORE_ADAPTERS_WHEELHOUSE, default ~/.cache/core-adapters/wheelhouse) filled once by scripts/fetch_wheels.sh - the only step that uses the network. Ubuntu: scripts/test_ubuntu.sh runs the gate in Docker (GCC, then Clang), in an image that carries its own wheelhouse.

Other commands: make test, make docs, make demos (scripts/run_demos.sh, or scripts/demos/<name>.sh for one), make benchmarks (rewrites BENCHMARKS.md; the tabular Shapley overhead is a fixed ~0.8 us per call).

Pins

Dependency Path Pinned to
snicholls-core third_party/core v0.9.0 (its GoogleTest v1.18.0 and Google Benchmark v1.9.5 serve the tests and benchmarks here)
nanobind third_party/nanobind v3.1.0
nlohmann/json third_party/nlohmann_json v3.12.0

Clone with git clone --recurse-submodules, or run git submodule update --init --recursive after cloning.