Skip to content

API Reference

ChebyshevApproximation

Multi-dimensional Chebyshev approximation using barycentric interpolation.

Pre-computes barycentric weights for all dimensions at build time, enabling uniform O(N) evaluation complexity for every dimension. Supports analytical derivatives via spectral differentiation matrices.

Parameters:

Name Type Description Default
function callable

Function to approximate. Signature: f(point, data) -> float where point is a list of floats and data is arbitrary additional data (can be None).

required
num_dimensions int

Number of input dimensions.

required
domain list of (float, float)

Bounds [(lo, hi), ...] for each dimension.

required
n_nodes list of (int or None)

Number of Chebyshev nodes per dimension. Entries may be None when error_threshold is set, signalling auto-N mode for that dimension. If omitted entirely, error_threshold must be provided. Default is None.

None
max_derivative_order int

Maximum derivative order to support. Default is 2.

2
error_threshold float

When set, enables error-driven auto-N construction: any dimension with an unresolved (None) entry in n_nodes is refined via the build-time doubling loop until the sup-norm error estimate falls below this threshold (or max_n is reached). Default is None.

None
max_n int

Upper cap on per-dimension node count when the doubling loop refines auto dims. Default is 64.

64
special_points list of list of float

Per-dimension kinks or discontinuities. When any dimension has at least one point, construction transparently returns a :class:ChebyshevSpline via __new__ dispatch (precedent: :class:pathlib.Path). Each inner list must be strictly inside its domain interval, sorted, and free of duplicates. When set, n_nodes must be nested as List[List[int | None]] with len(n_nodes[d]) == len(special_points[d]) + 1. Default is None.

None

Examples:

>>> import math
>>> def f(x, _):
...     return math.sin(x[0]) + math.sin(x[1])
>>> cheb = ChebyshevApproximation(f, 2, [[-1, 1], [-1, 1]], [11, 11])
>>> cheb.build()
>>> cheb.vectorized_eval([0.5, 0.3], [0, 0])
0.7764...
Notes

When special_points is provided with any kink, the return value is a :class:ChebyshevSpline instance — not a :class:ChebyshevApproximation. Use type(obj) or isinstance(obj, ChebyshevSpline) to distinguish if needed. All downstream features (eval, integrate, algebra, extrude/slice, save/load) work identically on either type.

__new__(function=None, num_dimensions=None, domain=None, n_nodes=None, max_derivative_order=2, error_threshold=None, max_n=64, special_points=None, additional_data=None, *, defer_build=False, n_workers=None)

Dispatch to ChebyshevSpline when special_points declares any kink.

Python skips __init__ on this class when __new__ returns an instance that is not an instance of cls (or subclass). ChebyshevSpline is not a subclass of ChebyshevApproximation, so the spline's own __init__ (already run inside the return expression below) is not overwritten.

All parameters default to None so pickle/copy protocols can call __new__(cls) without positional arguments; real construction still goes through __init__.

nodes(num_dimensions, domain, n_nodes) staticmethod

Generate Chebyshev nodes without evaluating any function.

Use this to obtain the grid points, evaluate your function externally (e.g. on an HPC cluster), then pass the results to :meth:from_values.

Parameters:

Name Type Description Default
num_dimensions int

Number of dimensions.

required
domain list of (float, float)

Lower and upper bounds for each dimension.

required
n_nodes list of int

Number of Chebyshev nodes per dimension.

required

Returns:

Type Description
dict

'nodes_per_dim' : list of 1-D arrays — Chebyshev nodes for each dimension, sorted ascending.

'full_grid' : 2-D array, shape (prod(n_nodes), num_dimensions) — Cartesian product of all nodes. Row order matches np.ndindex(*n_nodes) (C-order), so values.reshape(info['shape']) produces the correct tensor.

'shape' : tuple of int — expected shape of the tensor (== tuple(n_nodes)).

Examples:

>>> info = ChebyshevApproximation.nodes(1, [[-1, 1]], [5])
>>> info['shape']
(5,)
>>> info['full_grid'].shape
(5, 1)

set_original_function_values(values)

In-place mutator: populate this interpolant's tensor with explicit function values. After this call the interpolant is fully evaluable.

Pairs with defer_build=True ctor: construct an empty grid-metadata object, then fill its tensor here — an in-place alternative to the :meth:from_values classmethod factory.

Parameters:

Name Type Description Default
values array_like

Tensor of shape tuple(self.n_nodes) containing the function values at the points returned by :meth:get_evaluation_points, laid out in C-order (matching :meth:nodes output).

required

Raises:

Type Description
RuntimeError

If this interpolant is already constructed (build() was called, or this method was already called).

ValueError

On shape mismatch or if values contains NaN or Inf.

build(verbose=True)

Build the Chebyshev approximation by evaluating the function on the grid.

If error_threshold was provided to __init__, runs the doubling loop until the target precision is reached (or max_n is hit on all auto dims). Otherwise builds on the fixed grid specified by n_nodes.

Parameters:

Name Type Description Default
verbose bool or int

If True or 1, print build progress. If 2, also show a tqdm progress bar (requires pychebyshev[viz]). Default is True.

True
Notes

In auto-N mode (error_threshold set), n_evaluations and build_time are accumulated across doubling iterations and reflect the total work performed, not just the final iteration. In fixed-N mode they reflect a single build.

Dispatch keys off the user's original n_nodes (preserved as _original_n_nodes), so a second build() after mutating error_threshold correctly re-runs the doubling loop instead of silently bypassing it.

Raises:

Type Description
RuntimeError

If function is None (e.g., object was produced via from_values(), load(), algebra, slice, or extrude — use those factories directly).

eval(point, derivative_order=None, *, derivative_id=None)

Evaluate using dimensional decomposition with barycentric interpolation.

Parameters:

Name Type Description Default
point list of float

Query point, one coordinate per dimension.

required
derivative_order list of int

Derivative order per dimension (0 = function value, 1 = first derivative, 2 = second derivative). Provide exactly one of derivative_order or derivative_id.

None
derivative_id int

Stable session-local id returned by :meth:get_derivative_id. Provide exactly one of derivative_order or derivative_id.

None

Returns:

Type Description
float

Interpolated value or derivative at the query point.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If both or neither of derivative_order / derivative_id are provided.

KeyError

If derivative_id is unknown (not yet registered).

fast_eval(point, derivative_order=None, *, derivative_id=None)

Fast evaluation using pre-allocated cache (skips validation).

.. deprecated:: 0.3.0 Use :meth:vectorized_eval instead, which is ~150x faster via BLAS GEMV and requires no optional dependencies.

Parameters:

Name Type Description Default
point list of float

Query point.

required
derivative_order list of int

Derivative order per dimension. Provide exactly one of derivative_order or derivative_id.

None
derivative_id int

Stable session-local id returned by :meth:get_derivative_id. Provide exactly one of derivative_order or derivative_id.

None

Returns:

Type Description
float

Interpolated value or derivative.

vectorized_eval(point, derivative_order=None, *, derivative_id=None)

Fully vectorized evaluation using NumPy matrix operations.

Replaces the Python loop with BLAS matrix-vector products. For 5-D with 11 nodes: 5 BLAS calls instead of 16,105 Python iterations.

Parameters:

Name Type Description Default
point list of float

Query point, one coordinate per dimension.

required
derivative_order list of int

Derivative order per dimension. Provide exactly one of derivative_order or derivative_id.

None
derivative_id int

Stable session-local id returned by :meth:get_derivative_id. Provide exactly one of derivative_order or derivative_id.

None

Returns:

Type Description
float

Interpolated value or derivative.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If both or neither of derivative_order / derivative_id are provided.

KeyError

If derivative_id is unknown (not yet registered).

vectorized_eval_batch(points, derivative_order=None, *, derivative_id=None)

Evaluate at multiple points.

Parameters:

Name Type Description Default
points ndarray

Points of shape (N, num_dimensions).

required
derivative_order list of int

Derivative order per dimension. Provide exactly one of derivative_order or derivative_id.

None
derivative_id int

Stable session-local id returned by :meth:get_derivative_id. Provide exactly one of derivative_order or derivative_id.

None

Returns:

Type Description
ndarray

Results of shape (N,).

vectorized_eval_multi(point, derivative_orders)

Evaluate multiple derivative orders at the same point, sharing weights.

Pre-computes normalized barycentric weights once per dimension and reuses them across all derivative orders. Computing price + 5 Greeks costs ~0.29 ms instead of 6 x 0.065 ms = 0.39 ms.

.. note:: derivative_id is not supported here because this method takes a list of orders. For derivative_id-based access, look up orders via self._derivative_id_to_orders[id].

Parameters:

Name Type Description Default
point list of float

Query point.

required
derivative_orders list of list of int

Each inner list specifies derivative order per dimension.

required

Returns:

Type Description
list of float

One result per derivative order.

Raises:

Type Description
RuntimeError

If build() has not been called.

is_construction_finished()

Return True iff this interpolant is built and usable.

get_constructor_type()

Return the class name (matches MoCaX getConstructorType convention).

get_used_ns()

Return the resolved per-dim node count after build (or as constructed).

set_descriptor(descriptor)

Set a free-form text label on this interpolant.

Parameters:

Name Type Description Default
descriptor str

Label to attach to this interpolant.

required

Raises:

Type Description
TypeError

If descriptor is not a string.

get_descriptor()

Return the descriptor label (default "").

get_max_derivative_order()

Return the maximum derivative order this interpolant was constructed with. Derivative orders up to and including this value are queryable via eval(point, derivative_order=...).

is_dimensionality_allowed(num_dimensions) staticmethod

Return whether this interpolant class supports the given number of dimensions. Returns True for any num_dimensions >= 1. Provided as a hook for future per-class capability caps.

get_special_points()

Return the special points (kinks/knots) declared at construction.

Returns None if no special_points was passed. If special_points declared any non-empty list, __new__ dispatched to :class:ChebyshevSpline; this getter on a :class:ChebyshevApproximation therefore returns either None or a list-of-empty-lists.

get_derivative_id(derivative_order)

Register a derivative-orders tuple and return a stable session-local int.

Calling with the same derivative_order returns the same int. IDs are sequential, starting at 0, and are persisted across pickle save/load but reset on binary .pcb save/load.

Parameters:

Name Type Description Default
derivative_order list of int

Per-dim derivative orders. Must have length num_dimensions.

required

Returns:

Type Description
int

Stable session-local id for this orders tuple.

Raises:

Type Description
ValueError

If derivative_order has the wrong length, or any entry is negative, or any entry exceeds max_derivative_order.

error_estimate()

Estimate the supremum-norm interpolation error.

Computes Chebyshev expansion coefficients via DCT-II for each 1-D slice of the tensor, and returns the sum of per-dimension maximum last-coefficient magnitudes:

.. math::

\hat{E} = \sum_{d=1}^{D}
    \max_{\text{slices along } d} |c_{n_d - 1}|

This follows the ex ante error estimation from Ruiz & Zeron (2021), Section 3.4, adapted for Type I Chebyshev nodes.

Returns:

Type Description
float

Estimated maximum interpolation error (sup-norm).

Raises:

Type Description
RuntimeError

If build() has not been called.

sobol_indices()

Compute first-order and total-order Sobol sensitivity indices.

Uses the Chebyshev spectral expansion of the interpolant to compute variance-based sensitivity indices analytically (no Monte Carlo).

Returns:

Type Description
dict

{"first_order": {dim: index}, "total_order": {dim: index}, "variance": float}

Raises:

Type Description
RuntimeError

If build() has not been called.

get_error_threshold()

Return the error_threshold passed to __init__, or None if unset.

This is the target precision specified at construction time, not the achieved error after build. For the post-build achieved error estimate, use :meth:error_estimate.

Returns:

Type Description
float or None

The error_threshold kwarg from construction, or None if the object was built with an explicit fixed grid.

get_num_evaluation_points()

Return the number of points where f was (or will be) evaluated.

For a fixed-grid construction this is prod(n_nodes).

Returns:

Type Description
int

Total number of grid points at which f is evaluated.

get_evaluation_points()

Return the grid of points where f was (or will be) evaluated.

Returns:

Type Description
ndarray

Shape (N, num_dimensions) where N = prod(n_nodes). Points are listed in C-order: dim-0 outermost, dim-(d-1) innermost.

clone()

Return an independent deep copy of this interpolant.

All mutable state (tensors, descriptor, additional_data, derivative-id registry) is duplicated. Mutating the clone does not affect the original.

Note

Like :meth:save / :meth:load, the source function callable is not duplicated -- the clone has function = None. All evaluation, algebra, serialization, and v0.16 surface methods continue to work; only :meth:build (which requires a function) does not.

Returns:

Type Description
ChebyshevApproximation

A new instance with deep-copied state.

plot_convergence(target_error=None, max_n=64, ax=None)

Plot convergence: builds at increasing N, plots error decay.

Requires the optional pychebyshev[viz] dependency group.

Parameters:

Name Type Description Default
target_error float | None

If provided, draws a horizontal dashed line at this level.

None
max_n int

Largest N to try in the doubling sweep.

64
ax Axes | None

Pre-existing axes to plot into. Creates a new figure if None.

None

Returns:

Type Description
Axes

plot_1d(ax=None, n_points=200, fixed=None)

Plot the 1-D slice of this interpolant.

Requires the optional pychebyshev[viz] dependency group.

Parameters:

Name Type Description Default
ax Axes | None

Pre-existing axes (creates a new figure if None).

None
n_points int

Number of sample points along the free dim.

200
fixed dict[int, float] | None

Map of dim → value to constrain other dims, leaving exactly one free.

None

Returns:

Type Description
Axes

plot_2d_surface(ax=None, n_points=50, fixed=None)

Plot a 3-D surface for the 2-D slice. Requires matplotlib.

plot_2d_contour(ax=None, n_points=50, n_levels=20, fixed=None)

Plot a filled-contour 2-D slice. Requires matplotlib.

__getstate__()

Return picklable state, excluding the original function and eval cache.

__setstate__(state)

Restore state and reconstruct the eval cache.

save(path, format='pickle')

Save the built interpolant to a file.

The original function is not saved — only the numerical data needed for evaluation. The saved file can be loaded with :meth:load without access to the original function.

Parameters:

Name Type Description Default
path str or path - like

Destination file path.

required
format ('pickle', 'binary')

'pickle' (default) writes the standard Python pickle stream — bit-identical to previous versions. 'binary' writes the portable .pcb format documented at docs/user-guide/binary-format.md, which can be read by consumers in C, Rust, Julia, and other languages.

'pickle'

Raises:

Type Description
RuntimeError

If the interpolant has not been built yet.

ValueError

If format is not 'pickle' or 'binary'.

Notes

Pickle stays the default and is unchanged. Binary support was added in v0.14 and is opt-in.

load(path) classmethod

Load a previously-saved interpolant from a file.

The file format is auto-detected by inspecting the first 4 bytes: files beginning with the magic b"PCB\x00" are read as the portable v0.14 binary format; everything else is read as a Python pickle stream.

Parameters:

Name Type Description Default
path str or path - like

Source file path.

required

Returns:

Type Description
ChebyshevApproximation

The loaded interpolant. function is always None — re-bind it manually if you need to call build() again.

Notes

Pickle deserialization runs arbitrary code from the file. Only load files you trust. The binary format is safe to load from untrusted sources but does not preserve the function object.

peek_format_version(filename) staticmethod

Read a .pcb file's header and return its major format version integer. Does not deserialize the body.

See docs/user-guide/binary-format.md for the format spec.

Parameters:

Name Type Description Default
filename str

Path to a .pcb file.

required

Returns:

Type Description
int

The major format version (currently 1).

Raises:

Type Description
ValueError

If the file's first 4 bytes do not match the .pcb magic, or if the file is shorter than the 12-byte header.

FileNotFoundError

If the file does not exist.

IOError

If the file cannot be opened.

get_optimal_n1(function, domain_1d, error_threshold, max_n=64) classmethod

Smallest N such that a 1-D Chebyshev build hits error_threshold.

Useful as a capacity estimate before committing to a full multi-dimensional build. Internally runs the same doubling loop as __init__(error_threshold=...) on a 1-D interpolant.

Parameters:

Name Type Description Default
function callable

Signature f(point, data) -> float where point is a list of length 1.

required
domain_1d tuple or list

(lo, hi) bounds.

required
error_threshold float

Target supremum-norm error.

required
max_n int

Cap on the returned N. Default is 64. If the doubling loop cannot achieve error_threshold within this cap, a RuntimeWarning is emitted and max_n is returned.

64

Returns:

Type Description
int

Resolved N on dimension 0.

from_values(tensor_values, num_dimensions, domain, n_nodes, max_derivative_order=2) classmethod

Create an interpolant from pre-computed function values.

The resulting object is fully functional: evaluation, derivatives, integration, rootfinding, algebra, extrusion/slicing, and serialization all work exactly as if build() had been called.

Parameters:

Name Type Description Default
tensor_values ndarray

Function values on the Chebyshev grid. Shape must equal tuple(n_nodes). Entry tensor_values[i0, i1, ...] corresponds to the function evaluated at (nodes[0][i0], nodes[1][i1], ...), where nodes are the arrays returned by :meth:nodes.

required
num_dimensions int

Number of dimensions.

required
domain list of (float, float)

Lower and upper bounds for each dimension.

required
n_nodes list of int

Number of Chebyshev nodes per dimension.

required
max_derivative_order int

Maximum derivative order (default 2).

2

Returns:

Type Description
ChebyshevApproximation

A fully built interpolant with function=None.

Raises:

Type Description
ValueError

If tensor_values shape does not match n_nodes, contains NaN or Inf, or if dimension parameters are inconsistent.

Examples:

>>> import math
>>> info = ChebyshevApproximation.nodes(1, [[0, 3.15]], [20])
>>> vals = np.sin(info['full_grid'][:, 0]).reshape(info['shape'])
>>> cheb = ChebyshevApproximation.from_values(vals, 1, [[0, 3.15]], [20])
>>> abs(cheb.vectorized_eval([1.0], [0]) - math.sin(1.0)) < 1e-10
True

extrude(params)

Add new dimensions where the function is constant.

The extruded interpolant evaluates identically to the original regardless of the new coordinate(s), because Chebyshev basis functions form a partition of unity: the barycentric weights sum to 1, so replicating tensor values along a new axis produces the same result for any coordinate in the new domain.

Parameters:

Name Type Description Default
params tuple or list of tuples

Single (dim_index, (lo, hi), n_nodes) or a list of such tuples. dim_index is the position in the output space (0-indexed). n_nodes must be >= 2 and lo < hi.

required

Returns:

Type Description
ChebyshevApproximation

A new, higher-dimensional interpolant (already built). The result has function=None and build_time=0.0.

Raises:

Type Description
RuntimeError

If the interpolant has not been built yet.

TypeError

If dim_index is not an integer.

ValueError

If dim_index is out of range, duplicated, lo >= hi, or n_nodes < 2.

slice(params)

Fix one or more dimensions at given values, reducing dimensionality.

Contracts the tensor along each sliced dimension using the barycentric interpolation formula: for each sliced axis the normalized weight vector w_i / (x - x_i) / sum(w_j / (x - x_j)) is contracted with the tensor via np.tensordot. When the slice value coincides with a Chebyshev node (within 1e-14), the contraction reduces to an exact np.take (fast path).

Parameters:

Name Type Description Default
params tuple or list of tuples

Single (dim_index, value) or a list of such tuples. value must lie within the domain for that dimension.

required

Returns:

Type Description
ChebyshevApproximation

A new, lower-dimensional interpolant (already built). The result has function=None and build_time=0.0.

Raises:

Type Description
RuntimeError

If the interpolant has not been built yet.

TypeError

If dim_index is not an integer.

ValueError

If a slice value is outside the domain, if slicing all dimensions, or if dim_index is out of range or duplicated.

integrate(dims=None, bounds=None)

Integrate the interpolant over one or more dimensions.

Uses Fejér-1 quadrature weights (Waldvogel 2006) at Chebyshev Type I nodes, computed in O(n log n) via DCT-III. For multi-D tensors, each dimension is contracted via np.tensordot.

Parameters:

Name Type Description Default
dims int, list of int, or None

Dimensions to integrate out. If None, integrates over all dimensions and returns a scalar.

None
bounds tuple, list of tuple/None, or None

Sub-interval bounds for integration. None (default) integrates over the full domain of each dimension. A single tuple (lo, hi) applies to a single dims entry. A list of tuples/None provides per-dimension bounds with positional correspondence to dims.

None

Returns:

Type Description
float or ChebyshevApproximation

If all dimensions are integrated, returns the scalar integral. Otherwise returns a lower-dimensional interpolant.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If any dimension index is out of range or duplicated, or if bounds are outside the domain.

References

Waldvogel (2006), "Fast Construction of the Fejér and Clenshaw–Curtis Quadrature Rules", BIT Numer. Math. 46(2):195–202.

roots(dim=None, fixed=None)

Find all roots of the interpolant along a specified dimension.

Uses the colleague matrix eigenvalue method (Good 1961) via numpy.polynomial.chebyshev.chebroots. For multi-D interpolants, all dimensions except the target must be fixed at specific values (the interpolant is sliced to 1-D first).

Parameters:

Name Type Description Default
dim int or None

Dimension along which to find roots. For 1-D interpolants, defaults to 0.

None
fixed dict or None

For multi-D interpolants, a dict {dim_index: value} for all dimensions except dim.

None

Returns:

Type Description
ndarray

Sorted array of root locations in the physical domain.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails or values are out of domain.

References

Good (1961), "The colleague matrix", Quarterly J. Math. 12(1):61–68. Trefethen (2013), "Approximation Theory and Approximation Practice", SIAM, Chapter 18.

minimize(dim=None, fixed=None)

Find the minimum value of the interpolant along a dimension.

Computes derivative roots to locate critical points, then evaluates the interpolant at all critical points and domain endpoints.

Parameters:

Name Type Description Default
dim int or None

Dimension along which to minimize. Defaults to 0 for 1-D.

None
fixed dict or None

For multi-D, dict {dim_index: value} for all other dims.

None

Returns:

Type Description
(value, location) : (float, float)

The minimum value and its coordinate in the target dimension.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails.

References

Trefethen (2013), "Approximation Theory and Approximation Practice", SIAM, Chapter 18.

maximize(dim=None, fixed=None)

Find the maximum value of the interpolant along a dimension.

Computes derivative roots to locate critical points, then evaluates the interpolant at all critical points and domain endpoints.

Parameters:

Name Type Description Default
dim int or None

Dimension along which to maximize. Defaults to 0 for 1-D.

None
fixed dict or None

For multi-D, dict {dim_index: value} for all other dims.

None

Returns:

Type Description
(value, location) : (float, float)

The maximum value and its coordinate in the target dimension.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails.

References

Trefethen (2013), "Approximation Theory and Approximation Practice", SIAM, Chapter 18.

ChebyshevSlider

Chebyshev Sliding approximation for high-dimensional functions.

Decomposes f(x_1, ..., x_n) into a sum of low-dimensional Chebyshev interpolants (slides) around a pivot point z:

f(x) ≈ f(z) + Σ_i [s_i(x_group_i) - f(z)]

where each slide s_i is a ChebyshevApproximation built on a subset of dimensions with the remaining dimensions fixed at z.

This trades accuracy for dramatically reduced build cost: instead of evaluating f at n_1 × n_2 × ... × n_d grid points (exponential), the slider evaluates at n_1 × n_2 + n_3 × n_4 + ... (sum of products within each group).

Parameters:

Name Type Description Default
function callable

Function to approximate. Signature: f(point, data) -> float where point is a list of floats and data is arbitrary additional data (can be None).

required
num_dimensions int

Total number of input dimensions.

required
domain list of (float, float)

Bounds [lo, hi] for each dimension.

required
n_nodes list of int

Number of Chebyshev nodes per dimension.

required
partition list of list of int

Grouping of dimension indices into slides. Each dimension must appear in exactly one group. E.g. [[0,1,2], [3,4]] creates a 3D slide for dims 0,1,2 and a 2D slide for dims 3,4.

required
pivot_point list of float

Reference point z around which slides are built.

required
max_derivative_order int

Maximum derivative order to pre-compute (default 2).

2

Examples:

>>> import math
>>> def f(x, _):
...     return math.sin(x[0]) + math.sin(x[1]) + math.sin(x[2])
>>> slider = ChebyshevSlider(
...     f, 3, [[-1,1], [-1,1], [-1,1]], [11,11,11],
...     partition=[[0], [1], [2]],
...     pivot_point=[0.0, 0.0, 0.0],
... )
>>> slider.build(verbose=False)
>>> round(slider.eval([0.5, 0.3, 0.1], [0,0,0]), 4)
0.8764

total_build_evals property

Total number of function evaluations used during build.

build(verbose=True)

Build all slides by evaluating the function at slide-specific grids.

For each slide, dimensions outside the slide group are fixed at their pivot values.

Parameters:

Name Type Description Default
verbose bool or int

If True or 1, print build progress. If 2, also show a tqdm progress bar (requires pychebyshev[viz]). Default is True.

True

get_derivative_id(derivative_order)

Register a derivative-orders tuple and return a stable session-local int.

eval(point, derivative_order=None, *, derivative_id=None)

Evaluate the slider approximation at a point.

Uses Equation 7.5 from Ruiz & Zeron (2021): f(x) ≈ f(z) + Σ_i [s_i(x_i) - f(z)]

For derivatives, only the slide containing that dimension contributes.

Parameters:

Name Type Description Default
point list of float

Evaluation point in the full n-dimensional space.

required
derivative_order list of int

Derivative order for each dimension (0 = function value). Mutually exclusive with derivative_id.

None
derivative_id int

Session-local integer returned by get_derivative_id(). Mutually exclusive with derivative_order.

None

Returns:

Type Description
float

Approximated function value or derivative.

eval_multi(point, derivative_orders)

Evaluate slider at multiple derivative orders for the same point.

Parameters:

Name Type Description Default
point list of float

Evaluation point in the full n-dimensional space.

required
derivative_orders list of list of int

Each inner list specifies derivative order per dimension.

required

Returns:

Type Description
list of float

Results for each derivative order.

error_estimate()

Estimate the sliding approximation error.

Returns the sum of per-slide Chebyshev error estimates. Each slide's error is estimated independently using the Chebyshev coefficient method from Ruiz & Zeron (2021), Section 3.4.

Note: This captures per-slide interpolation error only. Cross-group interaction error (inherent to the sliding decomposition) is not included.

Returns:

Type Description
float

Estimated interpolation error (per-slide sum).

Raises:

Type Description
RuntimeError

If build() has not been called.

__getstate__()

Return picklable state, excluding the original function.

__setstate__(state)

Restore state from a pickled dict.

is_construction_finished()

Return True iff this slider is built and usable.

get_constructor_type()

Return the class name.

get_used_ns()

Return the per-dim node count list.

set_descriptor(descriptor)

Set a free-form text label on this slider.

Parameters:

Name Type Description Default
descriptor str

Label to attach to this slider.

required

Raises:

Type Description
TypeError

If descriptor is not a string.

get_descriptor()

Return the descriptor label (default "").

get_max_derivative_order()

Return the maximum derivative order this interpolant was constructed with. Derivative orders up to and including this value are queryable via eval(point, derivative_order=...).

get_num_evaluation_points()

Return the number of points in the evaluation grid (slides only).

The pivot point's f-evaluation during build is not counted — the pivot is a build-time singleton, not a grid point. Equals sum(prod(n_nodes[d] for d in group) for group in partition).

Returns:

Type Description
int

Total number of slide grid points (excluding the pivot evaluation).

get_evaluation_points()

Return the slide evaluation grid lifted into d-D coordinate space.

Each slide's local grid is returned with off-group dims set to the pivot value. The pivot row itself is not included (the pivot is a build-time singleton, not a grid point). Returns shape (get_num_evaluation_points(), num_dimensions).

Returns:

Type Description
ndarray

Shape (N, num_dimensions) where N equals :meth:get_num_evaluation_points.

clone()

Return an independent deep copy of this interpolant.

All mutable state (slides, descriptor, additional_data) is duplicated. Mutating the clone does not affect the original.

Note

Like :meth:save / :meth:load, the source function callable is not duplicated -- the clone has function = None. All evaluation, algebra, serialization, and v0.16 surface methods continue to work; only :meth:build (which requires a function) does not.

Returns:

Type Description
ChebyshevSlider

A new instance with deep-copied state.

is_dimensionality_allowed(num_dimensions) staticmethod

Return whether this interpolant class supports the given number of dimensions. Returns True for any num_dimensions >= 1. Provided as a hook for future per-class capability caps.

save(path)

Save the built slider to a file.

The original function is not saved — only the numerical data needed for evaluation. The saved file can be loaded with :meth:load without access to the original function.

Parameters:

Name Type Description Default
path str or path - like

Destination file path.

required

Raises:

Type Description
RuntimeError

If the slider has not been built yet.

load(path) classmethod

Load a previously saved slider from a file.

The loaded object can evaluate immediately; no rebuild is needed. The function attribute will be None. Assign a new function before calling build() again if a rebuild is desired.

Parameters:

Name Type Description Default
path str or path - like

Path to the saved file.

required

Returns:

Type Description
ChebyshevSlider

The restored slider.

Warns:

Type Description
UserWarning

If the file was saved with a different PyChebyshev version.

.. warning::

This method uses :mod:pickle internally. Pickle can execute arbitrary code during deserialization. Only load files you trust.

extrude(params)

Add new dimensions where the function is constant.

Each new dimension becomes its own single-dim slide group with tensor_values = np.full(n, pivot_value), so that s_new(x) - pivot_value = 0 for all x (no contribution to the sliding sum). This is the partition-of-unity property: the barycentric weights sum to 1, so a constant tensor produces the same value for any coordinate.

Existing slide groups have their dimension indices remapped to account for the inserted dimensions.

Parameters:

Name Type Description Default
params tuple or list of tuples

Single (dim_index, (lo, hi), n_nodes) or a list of such tuples. dim_index is the position in the output space (0-indexed). n_nodes must be >= 2 and lo < hi.

required

Returns:

Type Description
ChebyshevSlider

A new, higher-dimensional slider (already built). The result has function=None.

Raises:

Type Description
RuntimeError

If the slider has not been built yet.

TypeError

If dim_index is not an integer.

ValueError

If dim_index is out of range, duplicated, lo >= hi, or n_nodes < 2.

slice(params)

Fix one or more dimensions at given values, reducing dimensionality.

Two cases per sliced dimension:

  • Multi-dim group: The slide's ChebyshevApproximation is sliced at the local dimension index via barycentric contraction. When the slice value coincides with a Chebyshev node (within 1e-14), the contraction reduces to an exact np.take (fast path). The dimension is removed from the group.
  • Single-dim group: The slide is evaluated at the value, giving a constant s_val. The shift delta = s_val - pivot_value is absorbed into pivot_value and each remaining slide's tensor_values, and the group is removed entirely.

Remaining dimension indices in all groups are remapped downward to stay contiguous.

Parameters:

Name Type Description Default
params tuple or list of tuples

Single (dim_index, value) or a list of such tuples. value must lie within the domain for that dimension.

required

Returns:

Type Description
ChebyshevSlider

A new, lower-dimensional slider (already built). The result has function=None.

Raises:

Type Description
RuntimeError

If the slider has not been built yet.

TypeError

If dim_index is not an integer.

ValueError

If a slice value is outside the domain, if slicing all dimensions, or if dim_index is out of range or duplicated.

integrate(dims=None, bounds=None)

Integrate the slider approximation over one or more dimensions.

Uses the closed-form decomposition of the sliding sum f(x) ≈ pv + Σ_i [s_i(x_{G_i}) - pv]. Each slide's integral is computed via :meth:ChebyshevApproximation.integrate.

Full integration (dims=None) collapses every dimension and returns a scalar. Partial integration returns a new :class:ChebyshevSlider over the surviving dimensions, with an adjusted pivot value that absorbs the contributions of every slide whose group is fully integrated.

Parameters:

Name Type Description Default
dims int, list of int, or None

Dimensions to integrate out. None integrates every dimension and returns a scalar.

None
bounds tuple, list of tuple/None, or None

Sub-interval bounds for integration. None (default) integrates over the full domain of each integrated dimension. A list of tuples/None provides per-dim bounds with positional correspondence to dims (after sorting).

None

Returns:

Type Description
float or ChebyshevSlider

Scalar if every dimension is integrated; otherwise a lower-dimensional slider (already built, function=None).

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If any dimension index is out of range/duplicated, or if bounds are outside the domain.

roots(dim=None, fixed=None)

Find all roots of the slider along a specified dimension.

Reduces to a 1-D problem by slicing all other dimensions to their fixed values, then delegates to ChebyshevApproximation.roots() (which uses the colleague matrix eigenvalue method, Good 1961).

Parameters:

Name Type Description Default
dim int or None

Dimension along which to find roots. For 1-D sliders, defaults to 0.

None
fixed dict or None

For multi-D sliders, {dim_index: value} for all dimensions except dim.

None

Returns:

Type Description
ndarray

Sorted real root locations in the physical domain.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails or values are out of domain.

References

Good (1961), "The colleague matrix", Quarterly J. Math. 12(1):61–68. Trefethen (2013), "Approximation Theory and Approximation Practice", SIAM, Chapter 18.

minimize(dim=None, fixed=None)

Find the minimum value of the slider along a dimension.

Computes derivative roots to locate critical points, then evaluates at all critical points and domain endpoints. For multi-D sliders, all dimensions except the target must be fixed.

Parameters:

Name Type Description Default
dim int or None

Dimension along which to minimize. Defaults to 0 for 1-D.

None
fixed dict or None

For multi-D, {dim_index: value} for all other dims.

None

Returns:

Type Description
(value, location) : (float, float)

The minimum value and its coordinate in the target dimension.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails.

maximize(dim=None, fixed=None)

Find the maximum value of the slider along a dimension.

See minimize() for parameter details. Returns (max_value, max_location) instead.

plot_1d(ax=None, n_points=200, fixed=None)

Plot the 1-D slice of this interpolant.

Requires the optional pychebyshev[viz] dependency group.

Parameters:

Name Type Description Default
ax Axes | None

Pre-existing axes (creates a new figure if None).

None
n_points int

Number of sample points along the free dim.

200
fixed dict[int, float] | None

Map of dim → value to constrain other dims, leaving exactly one free.

None

Returns:

Type Description
Axes

plot_2d_surface(ax=None, n_points=50, fixed=None)

Plot a 3-D surface for the 2-D slice. Requires matplotlib.

plot_2d_contour(ax=None, n_points=50, n_levels=20, fixed=None)

Plot a filled-contour 2-D slice. Requires matplotlib.

ChebyshevSpline

Piecewise Chebyshev interpolation with user-specified knots.

Partitions the domain into sub-intervals at interior knots and builds an independent :class:ChebyshevApproximation on each piece. Query points are routed to the appropriate piece for evaluation.

This is the correct approach when the target function has known singularities (kinks, discontinuities) at specific locations: place knots at those locations so that each piece is smooth, restoring spectral convergence.

Parameters:

Name Type Description Default
function callable

Function to approximate. Signature: f(point, data) -> float where point is a list of floats and data is arbitrary additional data (can be None).

required
num_dimensions int

Number of input dimensions.

required
domain list of (float, float)

Bounds [lo, hi] for each dimension.

required
n_nodes list

Number of Chebyshev nodes per dimension. Accepts two shapes:

  • Flat form List[int | None] — one N per dim, applied to every piece. Example: [11, 13] on a 2D spline uses 11 nodes per piece along dim 0 and 13 per piece along dim 1.
  • Nested form (v0.12+) List[List[int | None]] — per-piece Ns along each dim. Inner length must equal len(knots[d]) + 1. Example on a 2D spline with knots=[[0.0], []]: [[11, 13], [15]] gives piece-0-along-dim-0 eleven nodes, piece-1-along-dim-0 thirteen nodes, and the single dim-1 piece fifteen nodes.

When any dim is nested, all dims must be (no mixing). Entries may be None when error_threshold is set, signalling auto-N mode for that (dim, piece). If n_nodes is omitted entirely, error_threshold must be provided. Default is None.

None
knots list of list of float

Interior knots for each dimension. Each sub-list must be sorted and every knot must lie strictly inside the corresponding domain interval. Use an empty list [] for dimensions with no knots. If omitted or None, defaults to [[] for _ in range(num_dimensions)] (single piece per dim, no knots). Useful in combination with error_threshold for a flat spline with auto-N.

None
max_derivative_order int

Maximum derivative order to pre-compute (default 2).

2
error_threshold float

When set, enables error-driven auto-N construction on every piece: each piece is built with this threshold, so pieces near kinks may refine to higher N than smooth pieces. Default is None.

None
max_n int

Upper cap on per-dimension node count passed through to each piece's doubling loop. Default is 64.

64

Examples:

>>> import math
>>> def f(x, _):
...     return abs(x[0])
>>> sp = ChebyshevSpline(f, 1, [[-1, 1]], [15], [[0.0]])
>>> sp.build(verbose=False)
>>> round(sp.eval([0.5], [0]), 10)
0.5
>>> round(sp.eval([-0.3], [0]), 10)
0.3

num_pieces property

Total number of pieces (Cartesian product of per-dimension intervals).

total_build_evals property

Total number of function evaluations across all pieces.

After build() the total is computed by summing each piece's own n_evaluations counter, which handles auto-N mode where different pieces may end up at different grid sizes. For an unbuilt spline we predict from n_nodes when possible (both flat and nested forms); auto-N pieces with None entries return 0 because the total cannot be known up-front.

build_time property

Wall-clock time (seconds) for the most recent build() call.

set_original_function_values(per_piece_values)

Populate each piece's tensor in place.

Pairs with defer_build=True ctor: once you have per-piece function values (e.g., computed externally), call this to complete construction. After this call the spline is fully evaluable.

Parameters:

Name Type Description Default
per_piece_values list of array_like

One array per piece in C-order (matching the _pieces list). Each array must have the correct shape for its piece.

required

Raises:

Type Description
RuntimeError

If any piece is already constructed, or if the spline is in an invalid state.

ValueError

On length mismatch or per-piece shape mismatch.

build(verbose=True)

Build all pieces by evaluating the function on each sub-domain.

Each piece is an independent :class:ChebyshevApproximation built on the Cartesian product of per-dimension sub-intervals.

Parameters:

Name Type Description Default
verbose bool or int

If True or 1, print build progress. If 2, also show a tqdm progress bar (requires pychebyshev[viz]). Default is True.

True

get_derivative_id(derivative_order)

Register a derivative-orders tuple and return a stable session-local int.

Calling with the same derivative_order returns the same int. IDs are sequential, starting at 0, and are persisted across pickle save/load but reset on binary .pcb save/load.

Parameters:

Name Type Description Default
derivative_order list of int

Derivative order per dimension.

required

Returns:

Type Description
int

Stable session-local identifier for this derivative order.

eval(point, derivative_order=None, *, derivative_id=None)

Evaluate the spline approximation at a point.

Routes the query to the piece whose sub-domain contains point and delegates to its :meth:~ChebyshevApproximation.vectorized_eval.

Parameters:

Name Type Description Default
point list of float

Evaluation point in the full domain.

required
derivative_order list of int or None

Derivative order for each dimension (0 = function value). Provide either this or derivative_id, not both.

None
derivative_id int or None

Session-local identifier registered via :meth:get_derivative_id. Provide either this or derivative_order, not both.

None

Returns:

Type Description
float

Approximated function value or derivative.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If the point is at a knot and a non-zero derivative is requested.

KeyError

If derivative_id is not registered.

eval_multi(point, derivative_orders)

Evaluate multiple derivative orders at one point, sharing weights.

Routes to a single piece and delegates to its :meth:~ChebyshevApproximation.vectorized_eval_multi so that barycentric weight computation is shared across all requested derivative orders.

Parameters:

Name Type Description Default
point list of float

Evaluation point in the full domain.

required
derivative_orders list of list of int

Each inner list specifies derivative order per dimension.

required

Returns:

Type Description
list of float

One result per derivative order.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If the point is at a knot and a non-zero derivative is requested.

eval_batch(points, derivative_order=None, *, derivative_id=None)

Evaluate at multiple points, grouping by piece for efficiency.

Vectorises the piece-routing step using np.searchsorted and evaluates each piece's batch via :meth:~ChebyshevApproximation.vectorized_eval_batch.

Parameters:

Name Type Description Default
points ndarray of shape (N, num_dimensions)

Evaluation points.

required
derivative_order list of int or None

Derivative order for each dimension. Provide either this or derivative_id, not both.

None
derivative_id int or None

Session-local identifier registered via :meth:get_derivative_id. Provide either this or derivative_order, not both.

None

Returns:

Type Description
ndarray of shape (N,)

Approximated values or derivatives at each point.

Raises:

Type Description
RuntimeError

If build() has not been called.

KeyError

If derivative_id is not registered.

error_estimate()

Estimate the supremum-norm interpolation error.

Returns the maximum error estimate across all pieces. Since pieces cover disjoint sub-domains, the interpolation error at any point is bounded by the error of the piece containing that point. The worst-case error is therefore the maximum over all pieces (not the sum, unlike :class:ChebyshevSlider where all slides contribute to every point).

Returns:

Type Description
float

Estimated maximum interpolation error (sup-norm).

Raises:

Type Description
RuntimeError

If build() has not been called.

sobol_indices()

Compute Sobol indices aggregated across spline pieces.

Indices are computed per-piece (under the Chebyshev measure ω(x) = 1/sqrt(1-x²) on [-1, 1] mapped to each piece's local domain), then aggregated by piece volume × piece variance.

Note

Per-piece weighting uses uniform domain volume × Chebyshev-weighted variance — a hybrid measure. For a single-piece (no-knot) spline, this reduces to the Approximation case.

Returns:

Type Description
dict

{"first_order": {dim: index}, "total_order": {dim: index}, "variance": float}

Raises:

Type Description
RuntimeError

If build() has not been called.

__getstate__()

Return picklable state, excluding the original function.

__setstate__(state)

Restore state from a pickled dict.

is_construction_finished()

Return True iff this spline is built and usable.

get_constructor_type()

Return the class name.

get_used_ns()

Return per-dim n_nodes preserving nested vs flat shape.

set_descriptor(descriptor)

Set a free-form text label on this spline.

Parameters:

Name Type Description Default
descriptor str

Label to attach to this spline.

required

Raises:

Type Description
TypeError

If descriptor is not a string.

get_descriptor()

Return the descriptor label (default "").

get_max_derivative_order()

Return the maximum derivative order this interpolant was constructed with. Derivative orders up to and including this value are queryable via eval(point, derivative_order=...).

is_dimensionality_allowed(num_dimensions) staticmethod

Return whether this interpolant class supports the given number of dimensions. Returns True for any num_dimensions >= 1. Provided as a hook for future per-class capability caps.

get_error_threshold()

Return the error threshold this interpolant was constructed with, or None if no threshold was specified (fixed-N construction).

get_num_evaluation_points()

Return the number of points in the evaluation grid, summed across pieces.

Equals sum(prod(piece.n_nodes)). Under auto-N construction this differs from :attr:total_build_evals, which counts cumulative function-evaluation work across the doubling iterations rather than the final grid size.

Returns:

Type Description
int

Total number of grid points across all pieces.

get_evaluation_points()

Return the concatenated grid of evaluation points across all pieces.

Pieces are visited in C-order. Within each piece, points are listed in C-order as for :meth:ChebyshevApproximation.get_evaluation_points.

Returns:

Type Description
ndarray

Shape (N, num_dimensions) where N equals :meth:get_num_evaluation_points.

clone()

Return an independent deep copy of this interpolant.

All mutable state (piece tensors, descriptor, additional_data, derivative-id registry) is duplicated. Mutating the clone does not affect the original.

Note

Like :meth:save / :meth:load, the source function callable is not duplicated -- the clone has function = None. All evaluation, algebra, serialization, and v0.16 surface methods continue to work; only :meth:build (which requires a function) does not.

Returns:

Type Description
ChebyshevSpline

A new instance with deep-copied state.

get_special_points()

Return the per-dimension knot/kink locations this spline was built around.

Returns the knots parameter that was passed to the constructor, as a list of per-dimension knot lists.

save(path, format='pickle')

Save the built spline to a file.

Parameters:

Name Type Description Default
path str or path - like

Destination file path.

required
format ('pickle', 'binary')

'pickle' (default) writes the standard pickle stream. 'binary' writes the portable .pcb format. The binary format requires flat (shared-across-pieces) n_nodes; nested-n_nodes splines must use pickle.

'pickle'

Raises:

Type Description
RuntimeError

If the spline has not been built yet.

ValueError

If format is not 'pickle' or 'binary'.

NotImplementedError

If format='binary' is requested for a nested-n_nodes spline.

load(path) classmethod

Load a previously-saved spline.

File format is auto-detected via magic bytes (b"PCB\x00" → binary; otherwise pickle).

Parameters:

Name Type Description Default
path str or path - like

Source file path.

required

Returns:

Type Description
ChebyshevSpline

The loaded spline. function is always None.

Notes

Pickle deserialization runs arbitrary code from the file. Only load files you trust. The binary format is safe to load from untrusted sources but does not preserve the function object.

nodes(num_dimensions, domain, n_nodes, knots) staticmethod

Generate Chebyshev nodes for every piece without evaluating any function.

Use this to obtain the per-piece grid points, evaluate your function externally, then pass the results to :meth:from_values.

Parameters:

Name Type Description Default
num_dimensions int

Number of dimensions.

required
domain list of (float, float)

Lower and upper bounds for each dimension.

required
n_nodes list of int

Number of Chebyshev nodes per dimension per piece.

required
knots list of list of float

Knot positions for each dimension (may be empty).

required

Returns:

Type Description
dict

'pieces' : list of dicts, one per piece in C-order (np.ndindex(*piece_shape)). Each dict contains:

  • 'piece_index' : tuple — multi-index of this piece
  • 'sub_domain' : list of (float, float) — bounds for this piece
  • 'nodes_per_dim' : list of 1-D arrays
  • 'full_grid' : 2-D array, shape (prod(n_nodes), num_dimensions)
  • 'shape' : tuple of int

'num_pieces' : int — total number of pieces.

'piece_shape' : tuple of int — per-dimension piece counts.

Examples:

>>> info = ChebyshevSpline.nodes(1, [[-1, 1]], [10], [[0.0]])
>>> info['num_pieces']
2
>>> info['pieces'][0]['sub_domain']
[(-1, 0.0)]

from_values(piece_values, num_dimensions, domain, n_nodes, knots, max_derivative_order=2) classmethod

Create a spline from pre-computed function values on each piece.

The resulting object is fully functional: evaluation, derivatives, integration, rootfinding, algebra, extrusion/slicing, and serialization all work exactly as if build() had been called.

Parameters:

Name Type Description Default
piece_values list of numpy.ndarray

Function values for each piece. Length must equal the total number of pieces (prod of per-dimension piece counts). Order follows np.ndindex(*piece_shape) (C-order), matching the 'pieces' list returned by :meth:nodes. Each array must have shape tuple(n_nodes).

required
num_dimensions int

Number of dimensions.

required
domain list of (float, float)

Lower and upper bounds for each dimension.

required
n_nodes list of int

Number of Chebyshev nodes per dimension per piece.

required
knots list of list of float

Knot positions for each dimension (may be empty).

required
max_derivative_order int

Maximum derivative order (default 2).

2

Returns:

Type Description
ChebyshevSpline

A fully built spline with function=None.

Raises:

Type Description
ValueError

If the number of pieces does not match, or any piece has the wrong shape or contains NaN/Inf.

extrude(params)

Add new dimensions where the function is constant.

Each piece is extruded independently via :meth:ChebyshevApproximation.extrude. The extruded spline evaluates identically to the original regardless of the new coordinate(s), because Chebyshev basis functions form a partition of unity. The new dimension gets knots=[] and a single interval (lo, hi).

Parameters:

Name Type Description Default
params tuple or list of tuples

Single (dim_index, (lo, hi), n_nodes) or a list of such tuples. dim_index is the position in the output space (0-indexed). n_nodes must be >= 2 and lo < hi.

required

Returns:

Type Description
ChebyshevSpline

A new, higher-dimensional spline (already built). The result has function=None and build_time=0.0.

Raises:

Type Description
RuntimeError

If the spline has not been built yet.

TypeError

If dim_index is not an integer.

ValueError

If dim_index is out of range, duplicated, lo >= hi, or n_nodes < 2.

slice(params)

Fix one or more dimensions at given values, reducing dimensionality.

For each sliced dimension, only the pieces whose interval contains the slice value survive. Each surviving piece is then sliced via :meth:ChebyshevApproximation.slice, which contracts the tensor along that axis using the barycentric interpolation formula. When the slice value coincides with a Chebyshev node (within 1e-14), the contraction reduces to an exact np.take (fast path).

Parameters:

Name Type Description Default
params tuple or list of tuples

Single (dim_index, value) or a list of such tuples. value must lie within the domain for that dimension.

required

Returns:

Type Description
ChebyshevSpline

A new, lower-dimensional spline (already built). The result has function=None and build_time=0.0.

Raises:

Type Description
RuntimeError

If the spline has not been built yet.

TypeError

If dim_index is not an integer.

ValueError

If a slice value is outside the domain, if slicing all dimensions, or if dim_index is out of range or duplicated.

integrate(dims=None, bounds=None)

Integrate the spline over one or more dimensions.

For full integration, sums the integrals of each piece (pieces cover disjoint sub-domains). For partial integration, pieces along the integrated dimension are summed and the result is a lower-dimensional spline.

Parameters:

Name Type Description Default
dims int, list of int, or None

Dimensions to integrate out. If None, integrates over all dimensions and returns a scalar.

None
bounds tuple, list of tuple/None, or None

Sub-interval bounds for integration. None (default) integrates over the full domain of each dimension. A single tuple (lo, hi) applies to a single dims entry. A list of tuples/None provides per-dimension bounds with positional correspondence to dims.

None

Returns:

Type Description
float or ChebyshevSpline

Scalar for full integration; lower-dimensional spline for partial integration.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If any dimension index is out of range or duplicated, or if bounds are outside the domain.

roots(dim=None, fixed=None)

Find all roots of the spline along a specified dimension.

Slices the spline to 1-D, then finds roots in each piece and merges the results.

Parameters:

Name Type Description Default
dim int or None

Dimension along which to find roots.

None
fixed dict or None

For multi-D, dict {dim_index: value} for all other dims.

None

Returns:

Type Description
ndarray

Sorted array of root locations in the physical domain.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails.

minimize(dim=None, fixed=None)

Find the minimum value of the spline along a dimension.

Parameters:

Name Type Description Default
dim int or None

Dimension along which to minimize.

None
fixed dict or None

For multi-D, dict {dim_index: value} for all other dims.

None

Returns:

Type Description
(value, location) : (float, float)

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails.

maximize(dim=None, fixed=None)

Find the maximum value of the spline along a dimension.

Parameters:

Name Type Description Default
dim int or None

Dimension along which to maximize.

None
fixed dict or None

For multi-D, dict {dim_index: value} for all other dims.

None

Returns:

Type Description
(value, location) : (float, float)

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dim / fixed validation fails.

plot_1d(ax=None, n_points=200, fixed=None)

Plot the 1-D slice of this interpolant.

Requires the optional pychebyshev[viz] dependency group.

Parameters:

Name Type Description Default
ax Axes | None

Pre-existing axes (creates a new figure if None).

None
n_points int

Number of sample points along the free dim.

200
fixed dict[int, float] | None

Map of dim → value to constrain other dims, leaving exactly one free.

None

Returns:

Type Description
Axes

plot_2d_surface(ax=None, n_points=50, fixed=None)

Plot a 3-D surface for the 2-D slice. Requires matplotlib.

plot_2d_contour(ax=None, n_points=50, n_levels=20, fixed=None)

Plot a filled-contour 2-D slice. Requires matplotlib.

auto_knots(function, num_dimensions, domain, *, max_knots_per_dim=5, n_scan_points=200, threshold_factor=5.0, n_nodes_per_piece=10, additional_data=None) classmethod

Build a ChebyshevSpline with knots auto-placed at function kinks.

Algorithm: for each dimension, scan function on n_scan_points evenly-spaced points (all other dims fixed at their midpoints), compute |d²f| (second differences of the sampled values), cluster spikes above threshold_factor × mean(|d²f|), keep the top spike per cluster, cap at max_knots_per_dim.

mean is used instead of median so that sparse-signal inputs (piecewise-linear functions where almost all second differences are exactly zero) still yield a positive threshold.

Parameters:

Name Type Description Default
function callable

Function signature: f(point, additional_data) → float.

required
num_dimensions int

Number of input dimensions.

required
domain list of [float, float]

Bounds [lo, hi] for each dimension.

required
max_knots_per_dim int

Maximum number of knots placed in any single dimension (default 5).

5
n_scan_points int

Number of evenly-spaced scan points per dimension (default 200).

200
threshold_factor float

Spike threshold as a multiple of the mean |d²f|. Increase this to suppress knot placement for smooth functions (default 5.0).

5.0
n_nodes_per_piece int

Chebyshev node count per piece per dimension (default 10).

10
additional_data object

Passed through to function unchanged.

None

Returns:

Type Description
ChebyshevSpline

A built spline with auto-detected knots.

ChebyshevTT

Chebyshev interpolation in Tensor Train format.

For functions of 5+ dimensions where full tensor interpolation is infeasible. Uses TT-Cross to build from O(d * n * r^2) function evaluations instead of O(n^d), then evaluates via TT inner product.

Parameters:

Name Type Description Default
function callable

Function to approximate. Signature: f(point, data) -> float where point is a list of floats and data is arbitrary additional data (can be None).

required
num_dimensions int

Number of input dimensions.

required
domain list of (float, float)

Bounds [(lo, hi), ...] for each dimension.

required
n_nodes list of int

Number of Chebyshev nodes per dimension.

required
max_rank int

Maximum TT rank. Higher = more accurate, more expensive. Default is 10.

10
tolerance float

Convergence tolerance for TT-Cross. Default is 1e-6.

1e-06
max_sweeps int

Maximum number of TT-Cross sweeps. Default is 10.

10

Examples:

>>> import math
>>> def f(x, _):
...     return math.sin(x[0]) + math.sin(x[1]) + math.sin(x[2])
>>> tt = ChebyshevTT(f, 3, [[-1, 1], [-1, 1], [-1, 1]], [11, 11, 11])
>>> tt.build(verbose=False)
>>> tt.eval([0.5, 0.3, 0.1])
0.8764...

tt_ranks property

TT ranks [1, r_1, r_2, ..., r_{d-1}, 1].

Returns:

Type Description
list of int

The TT rank vector. Only available after :meth:build.

Raises:

Type Description
RuntimeError

If build() has not been called.

compression_ratio property

Ratio of full tensor elements to TT storage elements.

Returns:

Type Description
float

Compression ratio (> 1 means TT is more compact).

Raises:

Type Description
RuntimeError

If build() has not been called.

total_build_evals property

Total number of function evaluations used during build.

Returns:

Type Description
int

Number of function evaluations. Only meaningful after :meth:build.

dim_order property

Permutation of original dimension indices applied at construction.

dim_order[k] is the original dimension index stored at TT position k. For a default (non-permuted) TT this is [0, 1, ..., d-1]. For a TT built by :meth:with_auto_order it reflects the chosen ordering. :meth:eval uses this to transparently remap user-supplied coordinates into the internal storage order.

Returns:

Type Description
list of int

A copy of the internal permutation vector.

build(verbose=True, seed=None, method='cross')

Build TT approximation and convert to Chebyshev coefficient cores.

The build process has three stages:

  1. Generate Chebyshev grids. Compute Type I Chebyshev nodes in each dimension, scaled to the specified domain.
  2. Build value cores. Either TT-Cross (evaluating at \(O(d \cdot n \cdot r^2)\) strategically selected points), TT-SVD (evaluating the full \(O(n^d)\) tensor, then decomposing via sequential SVD), or TT-ALS (rank-adaptive alternating least squares against the full Chebyshev-grid tensor).
  3. Convert to coefficient cores. Apply DCT-II along the node axis of each core to convert from function values at Chebyshev nodes to Chebyshev expansion coefficients. This enables evaluation at arbitrary (non-grid) points via the Chebyshev polynomial inner product.

Parameters:

Name Type Description Default
verbose bool or int

If True or 1, print build progress. If 2, also show a tqdm progress bar on the sweep loop (requires pychebyshev[viz]). Default is True.

True
seed int or None

Random seed for initialization. Used by method='cross' to seed TT-Cross initialization and by method='als' to deterministically seed the initial cores. Ignored when method='svd'.

None
method ``'cross'``, ``'svd'``, or ``'als'``

Build algorithm. 'cross' (default) uses TT-Cross to evaluate the function at \(O(d \cdot n \cdot r^2)\) strategically selected points. 'svd' builds the full tensor and decomposes via truncated SVD -- only feasible for moderate dimensions (\(d \leq 6\)) but useful for validation. 'als' runs rank-adaptive alternating least squares: it starts at rank 1 and grows the TT rank by \(+1\) per outer iteration until the grid residual falls below tolerance or the rank reaches max_rank. The residual is the relative Frobenius norm \(\|T_{\text{als}} - T_{\text{grid}}\|_F / \|T_{\text{grid}}\|_F\) measured over the Chebyshev grid. Like 'svd', ALS materializes a target tensor of \(\prod_k n_k\) floats, so it is feasible for typical grids; users with very large grids should prefer 'cross'.

'cross'

orth_left(position)

Left-orthogonalize cores [0..position-1] in place.

After the call, each core C_k for k < position, reshaped as an (r_k * n_k, r_{k+1}) matrix, satisfies C^T C = I. The R factors are absorbed rightward into core[position]; the represented tensor is unchanged.

Parameters:

Name Type Description Default
position int

Pivot core index, must be in range(1, num_dimensions).

required

Raises:

Type Description
RuntimeError

If the TT has not been built.

ValueError

If position is outside [1, num_dimensions - 1].

orth_right(position)

Right-orthogonalize cores [position+1..d-1] in place.

Mirror of :meth:orth_left. Each core C_k for k > position, reshaped as an (r_k, n_k * r_{k+1}) matrix, satisfies C C^T = I. L factors are absorbed leftward; the tensor is unchanged.

Parameters:

Name Type Description Default
position int

Pivot core index, must be in range(0, num_dimensions - 1).

required

Raises:

Type Description
RuntimeError

If the TT has not been built.

ValueError

If position is outside [0, num_dimensions - 2].

run_completion(tolerance=1e-08, max_iter=50, verbose=False)

Refine the TT at its current rank via ALS sweeps.

Works on any built TT (from cross, svd, or als). Rank does not grow; only per-core coefficients are refined.

Requires self.function to be callable -- completion re-samples the grid to build the LS right-hand side. TTs loaded from pickle typically retain the function unless it was pickled without a closure; see Notes.

Parameters:

Name Type Description Default
tolerance float

Stop when inner-sweep relative change falls below this value.

1e-08
max_iter int

Maximum number of outer sweeps.

50
verbose bool

Print per-sweep residuals.

False

Raises:

Type Description
RuntimeError

If the TT has not been built, or if self.function is None.

Notes

Completion evaluates self.function on the full tensor-product grid (prod(n_nodes) points), which may dwarf the cost of a prior method='cross' build. The eval cache is rebuilt fresh, not reused from the original build.

inner_product(other)

Frobenius inner product of the Chebyshev coefficient tensors of two TTs.

Because _coeff_cores stores Chebyshev expansion coefficients (DCT-II applied during build()), contracting the cores core-by-core yields \(\sum_{i_1,\ldots,i_d} C_{\text{self}}[i_1,\ldots,i_d] \, C_{\text{other}}[i_1,\ldots,i_d]\), where \(C\) denotes the full coefficient tensor. The core-by-core contraction costs \(O(d \cdot n \cdot r_s^2 \cdot r_o^2)\) operations and \(O(r_s \cdot r_o)\) extra memory, where \(r_s, r_o\) are the TT ranks of self and other.

Parameters:

Name Type Description Default
other ChebyshevTT

Must have the same domain and the same n_nodes as self.

required

Returns:

Type Description
float

Frobenius inner product of the two Chebyshev coefficient tensors, \(\sum_{i_1,\ldots,i_d} C_{\text{self}}[i] \, C_{\text{other}}[i]\).

Raises:

Type Description
RuntimeError

If either TT is not built.

ValueError

If other is not a ChebyshevTT, or has a different domain or n_nodes.

integrate(dims=None, bounds=None)

Integrate the TT-approximated function over selected dimensions.

Parameters:

Name Type Description Default
dims list of int, int, or None

Dimensions to integrate over. None (default) integrates over all dimensions (full integration → scalar).

None
bounds list of (lo, hi), (lo, hi), or None

Per-dim integration bounds. Length must match dims. None means each dim's full domain. Individual None entries also mean full domain for that dim.

None

Returns:

Type Description
float

Scalar result when all dimensions are integrated.

ChebyshevTT

TT over surviving dimensions when only some dims are integrated.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If dims contains out-of-range indices, or bounds are invalid (outside domain, lo > hi, or length mismatch).

roots(dim=None, fixed=None)

Find all roots of the TT-approximated function along dim.

Reduces to a 1-D problem by slicing all other dimensions to their fixed values, then delegates to ChebyshevApproximation.roots(). The user-frame dim/fixed keys translate to storage frame transparently inside self.slice() and self.to_dense() per v0.20.1 frame discipline.

Parameters:

Name Type Description Default
dim int or None

User-frame dimension index. Defaults to 0 for 1-D.

None
fixed dict or None

{dim_index: value} for all dimensions except dim. User-frame indices.

None

Returns:

Type Description
ndarray

Sorted real root locations in the physical domain.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If validation fails or values are out of domain.

minimize(dim=None, fixed=None)

Find the minimum value of the TT along a dimension.

Reduces to a 1-D problem by slicing all other dimensions to their fixed values, then delegates to ChebyshevApproximation.minimize(). See roots() for parameter details.

Parameters:

Name Type Description Default
dim int or None

User-frame dimension index. Defaults to 0 for 1-D.

None
fixed dict or None

{dim_index: value} for all dimensions except dim. User-frame indices.

None

Returns:

Type Description
(value, location) : (float, float)

The minimum value and its location in the physical domain.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If validation fails or values are out of domain.

maximize(dim=None, fixed=None)

Find the maximum value of the TT along a dimension.

Reduces to a 1-D problem by slicing all other dimensions to their fixed values, then delegates to ChebyshevApproximation.maximize(). See minimize() for parameter details.

Parameters:

Name Type Description Default
dim int or None

User-frame dimension index. Defaults to 0 for 1-D.

None
fixed dict or None

{dim_index: value} for all dimensions except dim. User-frame indices.

None

Returns:

Type Description
(value, location) : (float, float)

The maximum value and its location in the physical domain.

Raises:

Type Description
RuntimeError

If build() has not been called.

ValueError

If validation fails or values are out of domain.

to_dense()

Materialize the TT chain into a full N-D tensor of values.

Returns:

Type Description
ndarray

Shape tuple(n_nodes). dense[i_0, i_1, ..., i_{d-1}] equals self.eval([nodes_0[i_0], ..., nodes_{d-1}[i_{d-1}]]) to machine precision.

Notes

Use sparingly: storage is prod(n_nodes) floats. Useful for inspection, conversion, or piping through :meth:ChebyshevApproximation.from_values to convert TT → barycentric. For TTs built with a non-identity _dim_order (e.g. via :meth:with_auto_order), the returned tensor is transposed into original-dim axis order so dense[i_0, ..., i_{d-1}] always indexes axes by user-frame dim numbering.

extrude(params)

Add one or more dimensions where the function is constant.

Inserts a rank-preserving TT core encoding the constant function 1 at the specified position(s). The extruded TT evaluates identically to the original over the existing dimensions, regardless of the new dimension's coordinate.

Parameters:

Name Type Description Default
params tuple | list[tuple]

Either a single tuple (dim_idx, (lo, hi), n_nodes_new) or a list of such tuples. dim_idx is the insertion index (0-based) in the result's dimensions.

required

Returns:

Type Description
ChebyshevTT

TT over (num_dimensions + len(params)) dims; the function is constant (equal to the original) over each newly added dim.

Notes

The new core has shape (r_at, n_new, r_at) where r_at is the rank at the insertion boundary. Only the c_0 coefficient slot is nonzero (set to 1.0), encoding the constant function 1 in DCT-II Chebyshev coefficient space.

slice(params)

Fix one or more dimensions at given values, returning a lower-dim TT.

Contracts each targeted TT core at the given value via barycentric interpolation (converting from coefficient space to value space first), then absorbs the resulting matrix into a neighboring core.

Parameters:

Name Type Description Default
params tuple | list[tuple]

Either a single tuple (dim_idx, value) or a list of such tuples. value must lie within the domain for that dimension.

required

Returns:

Type Description
ChebyshevTT

TT over (num_dimensions - len(params)) dims.

Raises:

Type Description
RuntimeError

If the interpolant has not been built yet.

ValueError

If a slice value is outside the domain, if slicing all dimensions, or if dim_index is out of range or duplicated.

eval(point)

Evaluate at a single point via TT inner product.

Computes the Chebyshev interpolant value at an arbitrary point by contracting the pre-computed coefficient cores with Chebyshev polynomial values. For each dimension \(k\):

  1. Scale the query coordinate to \([-1, 1]\).
  2. Evaluate all Chebyshev polynomials \(T_0, \ldots, T_{n_k-1}\).
  3. Contract with the coefficient core: \(v = \sum_j q_j \cdot \text{core}[:, j, :]\)

The chain of contractions reduces to a scalar. Cost: \(O(d \cdot n \cdot r^2)\) per point.

Parameters:

Name Type Description Default
point list of float

Query point, one coordinate per dimension.

required

Returns:

Type Description
float

Interpolated value at the query point.

Raises:

Type Description
RuntimeError

If build() has not been called.

eval_batch(points)

Evaluate at multiple points simultaneously.

Vectorizes the TT inner product over all N points using np.einsum for batched matrix contractions. For each dimension, all N polynomial vectors are contracted with the coefficient core in a single einsum call, then all N chain multiplications proceed in parallel. Typical speedup is 15--20x over calling :meth:eval in a loop.

Parameters:

Name Type Description Default
points ndarray of shape (N, num_dimensions)

Query points.

required

Returns:

Type Description
ndarray of shape (N,)

Interpolated values at each query point.

Raises:

Type Description
RuntimeError

If build() has not been called.

eval_multi(point, derivative_orders)

Evaluate with finite-difference derivatives at a single point.

Uses central finite differences. The first entry in derivative_orders is typically [0, 0, ..., 0] for the function value; subsequent entries specify derivative orders per dimension.

Parameters:

Name Type Description Default
point list of float

Evaluation point in the full n-dimensional space.

required
derivative_orders list of list of int

Each inner list specifies derivative order per dimension. Supports 0 (value), 1 (first derivative), and 2 (second derivative).

required

Returns:

Type Description
list of float

One result per derivative order specification.

Raises:

Type Description
RuntimeError

If build() has not been called.

error_estimate()

Estimate interpolation error from Chebyshev coefficient cores.

For each dimension d, takes the maximum magnitude of the last Chebyshev coefficient across all "rows" and "columns" of the core (i.e., max over left-rank and right-rank indices of |core[:, -1, :]|). Returns the sum across dimensions.

This is an approximate analog of the ex ante error estimation from Ruiz & Zeron (2021), Section 3.4, adapted for TT format.

Returns:

Type Description
float

Estimated interpolation error.

Raises:

Type Description
RuntimeError

If build() has not been called.

reorder(new_order, *, max_rank=None, tolerance=None)

Return a new TT whose storage permutation matches new_order.

Implements the realignment via TT-swap (adjacent-axis SVDs in coefficient space). The swap sequence is determined by bubble-sorting the current self._dim_order into new_order; each swap costs an SVD over the merged 2-core block.

Parameters:

Name Type Description Default
new_order sequence of int

Target permutation. Must be a permutation of range(self.num_dimensions). The result has dim_order == list(new_order).

required
max_rank int

Cap for the rank introduced by each swap's SVD. Defaults to self.max_rank.

None
tolerance float

Relative singular-value cutoff for each swap's SVD. Defaults to self.tolerance.

None

Returns:

Type Description
ChebyshevTT

New TT representing the same function with storage permuted to new_order. self is not mutated.

Raises:

Type Description
ValueError

If new_order is not a permutation of range(self.num_dimensions).

__getstate__()

Return picklable state, excluding the original function.

__setstate__(state)

Restore state from a pickled dict.

is_construction_finished()

Return True iff this TT interpolant is built and usable.

get_constructor_type()

Return the class name.

get_used_ns()

Return the per-dim node count list.

set_descriptor(descriptor)

Set a free-form text label on this TT interpolant.

Parameters:

Name Type Description Default
descriptor str

Label to attach to this TT interpolant.

required

Raises:

Type Description
TypeError

If descriptor is not a string.

get_descriptor()

Return the descriptor label (default "").

get_max_derivative_order()

Return the maximum derivative order this interpolant was constructed with. Derivative orders up to and including this value are queryable via eval_multi(point, derivative_orders=...).

get_num_evaluation_points()

Return the number of points in the underlying Cartesian evaluation grid (prod(n_nodes)).

Note: TT-Cross actually queries a sparse subset of size O(d·n·r²); this method returns the full Cartesian grid size to match :meth:get_evaluation_points and MoCaX semantics. The actual TT-Cross f-evaluation count is exposed separately as self.total_build_evals.

Returns:

Type Description
int

Size of the full Cartesian Chebyshev grid.

get_evaluation_points()

Return the full Cartesian grid of node positions across all dimensions. Note: TT-Cross only queries a sparse subset; this method returns the underlying full grid the cross algorithm samples from (matching :meth:get_num_evaluation_points).

Returns:

Type Description
ndarray

Shape (N, num_dimensions) where N = prod(n_nodes). Columns are in user-frame order: column d corresponds to user-frame dim d regardless of internal _dim_order.

clone()

Return an independent deep copy of this interpolant.

All mutable state (TT cores, descriptor, additional_data) is duplicated. Mutating the clone does not affect the original.

Note

Like :meth:save / :meth:load, the source function callable is not duplicated -- the clone has function = None. All evaluation, algebra, serialization, and v0.16 surface methods continue to work; only :meth:build (which requires a function) does not.

Returns:

Type Description
ChebyshevTT

A new instance with deep-copied state.

sobol_indices()

Compute first-order + total-order Sobol sensitivity indices.

Returns:

Type Description
dict

{"first_order": {dim: index}, "total_order": {dim: index}, "variance": float} -- keyed by user-frame dim indices.

Raises:

Type Description
RuntimeError

If build() has not been called.

Notes

Computed natively by contracting through the TT coefficient cores; no dense materialization. Cost O(d * n * r^2) per dim. Mathematically equivalent to ChebyshevApproximation.sobol_indices() on the dense version of the same function.

Under non-identity _dim_order (after with_auto_order / reorder), result keys are user-frame dim indices.

from_values(tensor_values, num_dimensions, domain, n_nodes, max_rank=None, tolerance=1e-06, max_derivative_order=2, additional_data=None, descriptor='') classmethod

Build a TT interpolant directly from a precomputed dense tensor.

Skips TT-Cross — runs TT-SVD compression on the supplied dense tensor of function values at the Chebyshev grid.

Parameters:

Name Type Description Default
tensor_values array - like

Shape tuple(n_nodes). Values at the Chebyshev grid returned by :meth:nodes.

required
num_dimensions int
required
domain list[tuple[float, float]] | Domain
required
n_nodes list[int] | Ns
required
max_rank int or None

Maximum TT rank. None defaults to max(n_nodes).

None
tolerance float

TT-SVD singular-value truncation tolerance.

1e-06
max_derivative_order int
2
additional_data object or None
None
descriptor str
''

Returns:

Type Description
ChebyshevTT

Function-less interpolant (function=None). Equivalent to a :meth:build (method='svd') round-trip up to TT-SVD precision.

Raises:

Type Description
ValueError

If tensor_values has the wrong shape or contains non-finite values.

with_auto_order(function, num_dimensions, domain, n_nodes, *, max_rank=10, tolerance=1e-06, max_sweeps=10, additional_data=None, n_trials=5, method='greedy_swap') classmethod

Build a TT, trying multiple dim orderings, returning the lowest-rank result.

TT-Cross compression depends on the order in which dimensions are processed. Different orderings yield different TT ranks for the same function. This classmethod tries several permutations via the chosen method and returns the TT whose total rank (sum of all bond dimensions) is smallest.

The returned TT has its :attr:dim_order set to the chosen permutation. :meth:eval and :meth:eval_batch transparently remap user-supplied coordinates so the caller never needs to permute by hand.

Parameters:

Name Type Description Default
function callable

Function f(point, data) -> float in the original dimension order (i.e., point[0] is the first user dimension, etc.).

required
num_dimensions int

Number of input dimensions.

required
domain list of (float, float)

Bounds for each dimension in the original order.

required
n_nodes list of int

Node counts per dimension in the original order.

required
max_rank int

Maximum TT rank passed to each trial build. Default is 10.

10
tolerance float

Convergence tolerance passed to each trial build. Default is 1e-6.

1e-06
max_sweeps int

Maximum TT-Cross sweeps per trial. Default is 10.

10
additional_data object

Passed through to function as its second argument.

None
n_trials int

Number of swap iterations / random permutations to attempt. Default is 5.

5
method ``"greedy_swap"`` or ``"random"``

Ordering strategy.

"greedy_swap" (default) starts from the canonical order and greedily performs adjacent transpositions that reduce total rank, repeating up to n_trials outer iterations.

"random" samples n_trials random permutations in addition to the canonical order and picks the best.

'greedy_swap'

Returns:

Type Description
ChebyshevTT

Built TT with possibly-permuted dim order; the :attr:dim_order property records the chosen permutation.

Raises:

Type Description
ValueError

If method is not one of the supported values.

Notes

Each trial is a full TT-Cross build. With greedy_swap and n_trials=5 on a 5-D function, up to ~13 builds may be performed. For expensive functions use a small n_trials or method='random' with a small n_trials.

Factory-derived objects (slice, extrude, algebra results) have an identity dim_order regardless of the source TT's order, because dimension indices shift when dims are added/removed.

nodes(num_dimensions, domain, n_nodes) staticmethod

Return the Chebyshev grid for the given configuration without evaluating any function.

Parameters:

Name Type Description Default
num_dimensions int
required
domain list[tuple[float, float]] | Domain
required
n_nodes list[int] | Ns
required

Returns:

Type Description
dict

{"nodes_per_dim": [np.ndarray of shape (n_d,) for each dim d]}. Identical layout to :meth:ChebyshevApproximation.nodes.

is_dimensionality_allowed(num_dimensions) staticmethod

Return whether this interpolant class supports the given number of dimensions. Returns True for any num_dimensions >= 1. Provided as a hook for future per-class capability caps.

save(path)

Save the built TT interpolant to a file.

The original function is not saved -- only the numerical data needed for evaluation. The saved file can be loaded with :meth:load without access to the original function.

Parameters:

Name Type Description Default
path str or path - like

Destination file path.

required

Raises:

Type Description
RuntimeError

If build() has not been called.

load(path) classmethod

Load a previously saved TT interpolant from a file.

The loaded object can evaluate immediately; no rebuild is needed. The function attribute will be None. Assign a new function before calling build() again if a rebuild is desired.

Parameters:

Name Type Description Default
path str or path - like

Path to the saved file.

required

Returns:

Type Description
ChebyshevTT

The restored TT interpolant.

Warns:

Type Description
UserWarning

If the file was saved with a different PyChebyshev version.

.. warning::

This method uses :mod:pickle internally. Pickle can execute arbitrary code during deserialization. Only load files you trust.

__add__(other)

Sum two TTs via block-diagonal core stacking + TT-SVD rounding.

Block-diagonal stacking gives an exact TT representation of the sum, but with combined ranks r_a + r_b. The result is then rounded to max(self.max_rank, other.max_rank) via TT-SVD recompression using self.tolerance as the relative singular-value cutoff.

__neg__()

Return the negation of this TT (scale one core by -1).

__sub__(other)

Difference of two TTs: self + (-other).

__mul__(scalar)

Scale this TT by a scalar (leftmost core is multiplied).

__rmul__(scalar)

Support scalar * tt (commutative scalar multiplication).

__truediv__(scalar)

Divide this TT by a scalar: equivalent to self * (1/scalar).

__iadd__(other)

In-place addition: tt += other (returns new object).

__isub__(other)

In-place subtraction: tt -= other (returns new object).

__imul__(scalar)

In-place scalar multiplication: tt *= scalar (returns new object).

__itruediv__(scalar)

In-place scalar division: tt /= scalar (returns new object).

plot_1d(ax=None, n_points=200, fixed=None)

Plot the 1-D slice of this interpolant.

Requires the optional pychebyshev[viz] dependency group.

Parameters:

Name Type Description Default
ax Axes | None

Pre-existing axes (creates a new figure if None).

None
n_points int

Number of sample points along the free dim.

200
fixed dict[int, float] | None

Map of dim → value to constrain other dims, leaving exactly one free.

None

Returns:

Type Description
Axes

plot_2d_surface(ax=None, n_points=50, fixed=None)

Plot a 3-D surface for the 2-D slice. Requires matplotlib.

plot_2d_contour(ax=None, n_points=50, n_levels=20, fixed=None)

Plot a filled-contour 2-D slice. Requires matplotlib.

Module Functions

Compute barycentric weights for given nodes.

Parameters:

Name Type Description Default
nodes ndarray

Interpolation nodes of shape (n,).

required

Returns:

Type Description
ndarray

Barycentric weights w_i = 1 / prod_{j!=i} (x_i - x_j).

Compute spectral differentiation matrix for barycentric interpolation.

Based on Berrut & Trefethen (2004), Section 9.3.

Parameters:

Name Type Description Default
nodes ndarray

Interpolation nodes of shape (n,).

required
weights ndarray

Barycentric weights of shape (n,).

required

Returns:

Type Description
ndarray

Differentiation matrix D of shape (n, n) such that D @ f gives derivative values at nodes.

Evaluate barycentric interpolation at a single point.

Parameters:

Name Type Description Default
x float

Evaluation point.

required
nodes ndarray

Interpolation nodes.

required
values ndarray

Function values at nodes.

required
weights ndarray

Barycentric weights.

required
skip_check bool

If True, skip node coincidence check (faster but may divide by zero).

False

Returns:

Type Description
float

Interpolated value p(x).