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: |
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 |
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 |
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: |
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
|
|
Examples:
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 |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If this interpolant is already constructed ( |
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 |
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 |
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
|
None
|
derivative_id
|
int
|
Stable session-local id returned by :meth: |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Interpolated value or derivative at the query point. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
ValueError
|
If both or neither of |
KeyError
|
If |
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
|
None
|
derivative_id
|
int
|
Stable session-local id returned by :meth: |
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
|
None
|
derivative_id
|
int
|
Stable session-local id returned by :meth: |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Interpolated value or derivative. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
ValueError
|
If both or neither of |
KeyError
|
If |
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
|
None
|
derivative_id
|
int
|
Stable session-local id returned by :meth: |
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 |
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
int
|
Stable session-local id for this orders tuple. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
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 |
get_evaluation_points()
¶
Return the grid of points where f was (or will be) evaluated.
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape |
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'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the interpolant has not been built yet. |
ValueError
|
If |
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. |
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 |
required |
domain_1d
|
tuple or list
|
|
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 |
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
|
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If tensor_values shape does not match n_nodes, contains NaN or Inf, or if dimension parameters are inconsistent. |
Examples:
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevApproximation
|
A new, higher-dimensional interpolant (already built).
The result has |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the interpolant has not been built yet. |
TypeError
|
If |
ValueError
|
If |
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevApproximation
|
A new, lower-dimensional interpolant (already built).
The result has |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the interpolant has not been built yet. |
TypeError
|
If |
ValueError
|
If a slice value is outside the domain, if slicing all
dimensions, or if |
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
|
bounds
|
tuple, list of tuple/None, or None
|
Sub-interval bounds for integration. |
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 |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Sorted array of root locations in the physical domain. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
The minimum value and its coordinate in the target dimension. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
The maximum value and its coordinate in the target dimension. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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: |
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. |
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 |
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 |
None
|
derivative_id
|
int
|
Session-local integer returned by |
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 |
__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 |
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 |
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: |
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevSlider
|
A new, higher-dimensional slider (already built).
The result has |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the slider has not been built yet. |
TypeError
|
If |
ValueError
|
If |
slice(params)
¶
Fix one or more dimensions at given values, reducing dimensionality.
Two cases per sliced dimension:
- Multi-dim group: The slide's
ChebyshevApproximationis 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 exactnp.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 shiftdelta = s_val - pivot_valueis absorbed intopivot_valueand each remaining slide'stensor_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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevSlider
|
A new, lower-dimensional slider (already built).
The result has |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the slider has not been built yet. |
TypeError
|
If |
ValueError
|
If a slice value is outside the domain, if slicing all
dimensions, or if |
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
|
bounds
|
tuple, list of tuple/None, or None
|
Sub-interval bounds for integration. |
None
|
Returns:
| Type | Description |
|---|---|
float or ChebyshevSlider
|
Scalar if every dimension is integrated; otherwise a
lower-dimensional slider (already built, |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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, |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Sorted real root locations in the physical domain. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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, |
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
The minimum value and its coordinate in the target dimension. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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: |
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:
When any dim is nested, all dims must be (no mixing). Entries may
be |
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 |
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
|
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 |
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 |
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 |
None
|
derivative_id
|
int or None
|
Session-local identifier registered via :meth: |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Approximated function value or derivative. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
ValueError
|
If the point is at a knot and a non-zero derivative is requested. |
KeyError
|
If |
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 |
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 |
None
|
derivative_id
|
int or None
|
Session-local identifier registered via :meth: |
None
|
Returns:
| Type | Description |
|---|---|
ndarray of shape (N,)
|
Approximated values or derivatives at each point. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
KeyError
|
If |
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 |
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
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
__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 |
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 |
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'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the spline has not been built yet. |
ValueError
|
If |
NotImplementedError
|
If |
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. |
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
|
|
Examples:
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 ( |
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevSpline
|
A new, higher-dimensional spline (already built).
The result has |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the spline has not been built yet. |
TypeError
|
If |
ValueError
|
If |
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevSpline
|
A new, lower-dimensional spline (already built).
The result has |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the spline has not been built yet. |
TypeError
|
If |
ValueError
|
If a slice value is outside the domain, if slicing all
dimensions, or if |
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
|
bounds
|
tuple, list of tuple/None, or None
|
Sub-interval bounds for integration. |
None
|
Returns:
| Type | Description |
|---|---|
float or ChebyshevSpline
|
Scalar for full integration; lower-dimensional spline for partial integration. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Sorted array of root locations in the physical domain. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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: |
required |
num_dimensions
|
int
|
Number of input dimensions. |
required |
domain
|
list of [float, float]
|
Bounds |
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 |
5.0
|
n_nodes_per_piece
|
int
|
Chebyshev node count per piece per dimension (default 10). |
10
|
additional_data
|
object
|
Passed through to |
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: |
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: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
total_build_evals
property
¶
Total number of function evaluations used during build.
Returns:
| Type | Description |
|---|---|
int
|
Number of function evaluations. Only meaningful after
:meth: |
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:
- Generate Chebyshev grids. Compute Type I Chebyshev nodes in each dimension, scaled to the specified domain.
- 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).
- 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 |
True
|
seed
|
int or None
|
Random seed for initialization. Used by |
None
|
method
|
``'cross'``, ``'svd'``, or ``'als'``
|
Build algorithm. |
'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 |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the TT has not been built. |
ValueError
|
If |
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 |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the TT has not been built. |
ValueError
|
If |
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 |
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 |
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 |
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
|
bounds
|
list of (lo, hi), (lo, hi), or None
|
Per-dim integration bounds. Length must match |
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 |
ValueError
|
If |
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
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Sorted real root locations in the physical domain. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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
|
|
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
The minimum value and its location in the physical domain. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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
|
|
None
|
Returns:
| Type | Description |
|---|---|
(value, location) : (float, float)
|
The maximum value and its location in the physical domain. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevTT
|
TT over |
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 |
required |
Returns:
| Type | Description |
|---|---|
ChebyshevTT
|
TT over |
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 |
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\):
- Scale the query coordinate to \([-1, 1]\).
- Evaluate all Chebyshev polynomials \(T_0, \ldots, T_{n_k-1}\).
- 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 |
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 |
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 |
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 |
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
|
required |
max_rank
|
int
|
Cap for the rank introduced by each swap's SVD. Defaults to
|
None
|
tolerance
|
float
|
Relative singular-value cutoff for each swap's SVD. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
ChebyshevTT
|
New TT representing the same function with storage permuted to
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
__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 |
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 |
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
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
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
|
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 ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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'
|
Returns:
| Type | Description |
|---|---|
ChebyshevTT
|
Built TT with possibly-permuted dim order; the :attr: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
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 |
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: |
__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). |