Python

Install

Install the latest release from PyPI:

pip install treeweave

The wheel bundles the C ABI statically; the x86-64 wheel dispatches across the x86 SIMD ISAs at runtime. NumPy is the only dependency.

To test an unreleased change, every push to main publishes a staging wheel (X.Y.Z.devN) to TestPyPI; install it with TestPyPI as the primary index and real PyPI for the dependencies:

pip install --index-url https://test.pypi.org/simple/ \
            --extra-index-url https://pypi.org/simple/ treeweave

Minimal example

"""simple_1d.py: minimal 1D -> 1D fit and evaluation."""
import math
import numpy as np
import treeweave


def func(x):
    return math.exp(x[0])


# Fit exp(x) on [0, 1] syntax is fit(callback, lower_bound, upper_bound, tol).
approx = treeweave.fit(func, 0.0, 1.0, tol=1e-10)
print(approx)  # dtype, dim, out_dim, memory_usage

# The fit domain is [a, b); evaluating exactly at the upper corner b is allowed
# as a convenience and returns the boundary value (not NaN).
xs = np.linspace(0.0, 1.0, 11)  # includes the endpoint b = 1.0
# Evaluate approx on 11 points and print the maximum error.
ys = approx(xs)
exact = np.exp(xs)
max_err = float(np.max(np.abs(ys - exact)))
print(f"max |approx - exp| over 11 points: {max_err:.3e}")
assert max_err < 1e-8, f"too large: {max_err}"
print("OK")

fit infers the input and output dimensions by probing the callable, so the common case is fit(f, a, b, tol=...). Call the fitted object directly, with a single point or with a batch. A failing C++ fit raises a Python exception.

Decorator form

Omit the callable and fit returns a decorator, the functools.cache spelling. The decorated name becomes the fitted approximation:

"""decorator_1d.py: @fit(a, b, tol) replaces a function with its approximation."""

import math
import numpy as np
import treeweave


# Same options as fit(f, a, b, tol), with the callable omitted.
@treeweave.fit(0.0, 1.0, tol=1e-10)
def expensive(x):
    """A slow callable, evaluated once per fit sample instead of per call."""
    return math.exp(x[0])


print(expensive)  # dtype, dim, out_dim, memory_usage

xs = np.linspace(0.0, 1.0, 11)
max_err = float(np.max(np.abs(expensive(xs) - np.exp(xs))))
print(f"max |approx - exp| over 11 points: {max_err:.3e}")
assert max_err < 1e-8, f"too large: {max_err}"

# The undecorated function stays reachable, as with functools.cache.
assert expensive.__wrapped__(np.array([0.5])) == math.exp(0.5)
assert expensive.__name__ == "expensive"
print("OK")

fit(a, b, tol) and fit(a, b, tol=...) are both accepted, and every keyword option below applies unchanged:

@treeweave.fit([0.0, 0.0], [1.0, 1.0], tol=1e-6, dtype="f32")
def surface(x):
    return math.cos(x[0] - x[1])

The decorated object is an ordinary TreeweaveFunction, so sorted= / transposed= and the properties all work on it. __name__ and __doc__ come from the original function, which stays reachable as __wrapped__. Fitting happens at decoration time, so an import-time failure raises there.

Evaluation routes

Calling the fitted object dispatches on the shape of its argument, and two keyword flags select the fast paths:

approx(3.5)                       # single point  -> scalar (or (out_dim,))
approx(xs)                        # batch (N,)     -> (N,) / (N, out_dim)
approx(xs, sorted=True)           # promise xs is non-decreasing, xs[i] <= xs[i+1] (dim == 1)
approx(xs, transposed=True)       # batch -> (out_dim, N)  (requires out_dim > 1)

sorted=True skips treeweave’s internal counting-sort and is ~3-4x faster when the caller can promise xs is ascending, which covers linspace grids, quadrature nodes and time series. Nothing checks the promise, and unsorted input gives wrong values, so use the plain batch path when the order is unknown. transposed=True returns each output component in its own contiguous row.

Every path handles out-of-domain input the same way. A point exactly at b returns the boundary value. Points below a, points above b, and NaN or ±Inf inputs all return NaN.

Multi-dimensional fits

Pass sequence corners; the callback receives a length-dim row and returns a scalar or a length-out_dim sequence:

def bump(x):
    return math.exp(-100 * (x[0] - 0.5) ** 2 - (x[1] - 0.5) ** 2)

approx = treeweave.fit(bump, [0.0, 0.0], [1.0, 1.0], tol=1e-8)
y = approx(np.array([[0.4, 0.6]]))   # shape (N, dim) -> (N, out_dim)

Options

Pass keyword arguments to fit to override defaults:

Kwarg

Default

Meaning

tol_kind

'relative_max'

Tolerance interpretation. One of 'relative_max', 'absolute_max', 'relative_l2', 'absolute_l2', 'relative_tail', 'absolute_tail', 'relative_pointwise'.

max_depth

0 (auto)

Tree-depth ceiling. 0 = auto, 50; -1 = the root panel only. Raises RuntimeError with MaxDepthExceeded if hit.

max_memory_mib

0 (auto)

Memory budget in MiB. 0 = auto (4/32/256 MiB for dim 1/2/3); -1 = no cap.

allow_max_depth_leaves

False

Keep non-converged panels at max depth instead of raising.

min_uniform_depth

0

Force uniform refinement to this depth before adaptivity.

filename

None

Path (str or os.PathLike) of a plain-text fit file. A matching file loads without calling f. Else the fit runs and writes the file. A malformed file or an unwritable path raises RuntimeError. Pass out_dim too: without it, fit still probes f once.

dim

inferred

Input dimension; inferred from len(a) (scalar corners → 1).

out_dim

inferred

Output dimension; inferred by probing f at the box midpoint.

dtype

'f64'

Floating-point precision: 'f64' or 'f32'.

See Fit options for a full description of each option and the tolerance kinds.

Further

cmake --preset bindings-python
cmake --build build/bindings-python -j
ctest --test-dir build/bindings-python -R python_treeweave

Examples: bindings/python/examples/.