Table of Contents

Class ChebyshevTT

Namespace
ChebyshevSharp
Assembly
ChebyshevSharp.dll

Chebyshev interpolation in Tensor Train (TT) format. Useful when the dense tensor grid is too large but the sampled tensor has low numerical TT rank. The default TT-Cross build path samples adaptively; TT-SVD and ALS are dense-grid alternatives for intentionally small grids.

public class ChebyshevTT
Inheritance
ChebyshevTT
Inherited Members

Constructors

ChebyshevTT(Func<double[], double>, int, double[][], int[], int, double, int, int, object?, int?, IProgress<int>?)

Create a new ChebyshevTT interpolant.

public ChebyshevTT(Func<double[], double> function, int numDimensions, double[][] domain, int[] nNodes, int maxRank = 10, double tolerance = 1E-06, int maxSweeps = 10, int maxDerivativeOrder = 2, object? additionalData = null, int? nWorkers = null, IProgress<int>? progress = null)

Parameters

function Func<double[], double>

Function to approximate. Signature: f(point) -> double.

numDimensions int

Number of input dimensions.

domain double[][]

Bounds [lo, hi] for each dimension.

nNodes int[]

Number of Chebyshev nodes per dimension.

maxRank int

Maximum positive TT rank. Default is 10.

tolerance double

Finite positive convergence tolerance for TT-Cross/ALS. Default is 1e-6.

maxSweeps int

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

maxDerivativeOrder int

Maximum derivative order to support. Default is 2.

additionalData object

Optional user data object stored for introspection via GetAdditionalData(). NOT threaded through build calls (TT function signature has no data arg).

nWorkers int?

Accepted for API symmetry with the other classes but ignored: TT-Cross is adaptive sampling, not pre-grid evaluation. Pass null.

progress IProgress<int>

Optional TT-Cross progress reporter; receives the cumulative sweep count after each completed sweep.

Remarks

Thread safety: TT-Cross is inherently sequential; nWorkers is accepted but has no effect.

Fields

DefaultRoundTolerance

Default tolerance for TT-SVD rounding after addition/subtraction.

public const double DefaultRoundTolerance = 1E-12

Field Value

double

Properties

BuildWarning

Warning emitted by Build() if maxRank was reached before tolerance was satisfied during ALS. Null otherwise.

public string? BuildWarning { get; }

Property Value

string

CompressionRatio

Ratio of full tensor elements to TT storage elements.

public double CompressionRatio { get; }

Property Value

double

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

DimOrder

Storage permutation: DimOrder[k] is the original-dimension index stored at TT position k. Identity by default; non-identity for TTs produced by Reorder(int[], int?, double?). Returns a defensive clone; mutating the returned array does not affect this TT.

public int[] DimOrder { get; }

Property Value

int[]

Domain

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

public double[][] Domain { get; }

Property Value

double[][]

LoadWarning

Warning message set when loading from a different library version.

public string? LoadWarning { get; }

Property Value

string

MaxRank

Maximum TT rank.

public int MaxRank { get; }

Property Value

int

Method

Build method that produced the current cores: "cross", "svd", or "als". null only before Build(bool, int?, string) is called or after Load(string) from a legacy JSON file that predates this property.

public string? Method { get; }

Property Value

string

NNodes

Number of Chebyshev nodes per dimension.

public int[] NNodes { get; }

Property Value

int[]

NumDimensions

Number of input dimensions.

public int NumDimensions { get; }

Property Value

int

TotalBuildEvals

Total number of function evaluations used during build.

public int TotalBuildEvals { get; }

Property Value

int

TtRanks

TT ranks [1, r_1, r_2, ..., r_{d-1}, 1]. Only available after Build(bool, int?, string).

public int[] TtRanks { get; }

Property Value

int[]

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

Methods

AddInPlace(ChebyshevTT)

In-place addition: this += other followed by TT-SVD rounding.

public void AddInPlace(ChebyshevTT other)

Parameters

other ChebyshevTT

Build(bool, int?, string)

Build TT approximation and convert to Chebyshev coefficient cores.

public void Build(bool verbose = true, int? seed = null, string method = "cross")

Parameters

verbose bool

If true, print build progress.

seed int?

Random seed for TT-Cross/ALS initialization. Ignored for method="svd".

method string

"cross" (default), "svd", or "als".

Exceptions

ArgumentException

If method is not "cross", "svd", or "als", or if the function returns NaN or Infinity at a sampled grid point.

InvalidOperationException

If this TT was loaded or created from values without the original function.

Clone()

Returns a deep copy of this tensor train. The source function callable is not duplicated; clones cannot be rebuilt without re-supplying the function. All TT cores and state are deep-copied.

public ChebyshevTT Clone()

Returns

ChebyshevTT

A fully independent ChebyshevTT.

ErrorEstimate()

Estimate interpolation error from Chebyshev coefficient cores. Sum of max|core[:, -1, :]| per dimension.

public double ErrorEstimate()

Returns

double

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

Eval(double[])

Evaluate at a single point via TT inner product with Chebyshev polynomial basis. Cost: O(d * n * r^2) per point.

public double Eval(double[] point)

Parameters

point double[]

Query point inside the declared domain, one coordinate per dimension.

Returns

double

Interpolated value.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

Eval(double[], int)

Evaluate at point using a previously-registered derivative id.

public double Eval(double[] point, int derivativeId)

Parameters

point double[]

Evaluation point.

derivativeId int

Id returned by GetDerivativeId(int[]).

Returns

double

Interpolated value at the given derivative order.

Exceptions

ArgumentOutOfRangeException

Thrown when derivativeId has not been registered.

EvalBatch(double[,])

Evaluate at multiple points simultaneously. Vectorized TT inner product that shares allocation and contraction work across query points.

public double[] EvalBatch(double[,] points)

Parameters

points double[,]

Query points inside the declared domain, shape (N, numDimensions).

Returns

double[]

Interpolated values, length N.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

EvalMulti(double[], int[][])

Evaluate with finite-difference derivatives at a single point.

public double[] EvalMulti(double[] point, int[][] derivativeOrders)

Parameters

point double[]

Evaluation point inside the declared domain.

derivativeOrders int[][]

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

Returns

double[]

One result per derivative order specification.

Remarks

TT derivatives are finite-difference derivatives of the TT interpolant, not spectral differentiation-matrix derivatives. Orders greater than 2 are not supported by this method.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentException

If point or a derivative-order row has the wrong length.

ArgumentOutOfRangeException

If a point coordinate is outside the declared domain or a derivative order exceeds the supported TT derivative order.

Extrude(int, (double Lo, double Hi), int)

Insert a new dimension at index dim where the function is constant. The extruded TT evaluates identically to the original over the existing dimensions, regardless of the new dimension's coordinate.

public ChebyshevTT Extrude(int dim, (double Lo, double Hi) newDomain, int newN)

Parameters

dim int

Insertion index, 0 <= dim <= NumDimensions.

newDomain (double lo, double hi)

Domain (lo, hi) for the new dimension.

newN int

Number of nodes for the new dimension.

Returns

ChebyshevTT

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentOutOfRangeException

If dim is outside [0, NumDimensions].

ArgumentException

If newDomain.Lo >= newDomain.Hi, or newN < 2.

FromValues(double[], int, double[][], int[], int, double)

Build a TT directly from a precomputed dense tensor (skips function evaluation). Uses TT-SVD for compression. The resulting TT cannot be rebuilt or completed because no callable source function is attached.

public static ChebyshevTT FromValues(double[] tensorValues, int numDimensions, double[][] domain, int[] nNodes, int maxRank = 10, double tolerance = 1E-06)

Parameters

tensorValues double[]

Flat row-major dense tensor of length Π nNodes.

numDimensions int

Number of dimensions.

domain double[][]

Bounds [lo, hi] per dimension.

nNodes int[]

Number of nodes per dimension.

maxRank int

Maximum positive TT rank (default 10).

tolerance double

Finite non-negative SVD truncation tolerance (default 1e-6).

Returns

ChebyshevTT

Exceptions

ArgumentException

If tensorValues length doesn't match Π nNodes, or contains NaN/Infinity.

GetAdditionalData()

Returns the user-supplied additionalData object passed to the constructor, or null if none was provided. Stored for introspection only — TT's function signature is Func<double[], double> (no data arg); wrap with a closure if you need data threading.

public object? GetAdditionalData()

Returns

object

GetConstructorType()

Returns one of: "clone" (if cloned), "cross"/"svd"/"als" (build method used), or "function" if not yet built.

public string GetConstructorType()

Returns

string

GetDerivativeId(int[])

Register or look up a derivative-orders tuple. Returns a stable session-local int id for the same orders. Used in conjunction with the Eval(point, derivativeId) overload.

public int GetDerivativeId(int[] orders)

Parameters

orders int[]

Derivative order per dimension.

Returns

int

A stable int id for this orders tuple (0-based, assigned in registration order).

GetDescriptor()

Get the descriptor previously set via SetDescriptor(string); null if unset.

public string? GetDescriptor()

Returns

string

GetEvaluationPoints()

Flat row-major array of the full Chebyshev grid coordinates. Generated on-demand using the domain and nNodes, independent of the sparse TT sampling. Length is GetNumEvaluationPoints() * NumDimensions. Result is lazily built and cached internally.

public double[] GetEvaluationPoints()

Returns

double[]

A snapshot of full-grid node coordinates, flattened in row-major order.

GetMaxDerivativeOrder()

Maximum derivative order this tensor train supports.

public int GetMaxDerivativeOrder()

Returns

int

GetNumEvaluationPoints()

Total number of evaluation points in the full Chebyshev grid (product of nNodes).

public int GetNumEvaluationPoints()

Returns

int

The total count of Chebyshev nodes across all dimensions.

GetUsedNs()

Per-dimension Chebyshev node counts actually used.

public int[] GetUsedNs()

Returns

int[]

InnerProduct(ChebyshevTT)

Frobenius inner product of the Chebyshev coefficient tensors of two TTs. Both TTs must share the same NumDimensions, Domain, and NNodes.

public double InnerProduct(ChebyshevTT other)

Parameters

other ChebyshevTT

The other TT.

Returns

double

Σ_{i_1,…,i_d} C_self[i] * C_other[i].

Exceptions

ArgumentNullException

If other is null.

InvalidOperationException

If either TT has not been built.

ArgumentException

If domain or nNodes do not match.

Integrate(int[]?, (double lo, double hi)[]?)

Integrate the TT-approximated function over selected dimensions. Per-dim Fejér-1 quadrature is applied to the value-space cores (Chebyshev coefficient cores are converted to value cores via ChebyshevSharp.Internal.TensorTrainKernel.CoeffCoreToValueCore(ChebyshevSharp.Internal.TensorTrainKernel.TtCore) before contraction).

public object Integrate(int[]? dims = null, (double lo, double hi)[]? bounds = null)

Parameters

dims int[]

Dimensions to integrate out. Null = all (full integration → scalar).

bounds (double lo, double hi)[]

Sub-interval bounds per dim (positional with sorted dims). Null = full domain.

Returns

object

A boxed double when every dim is integrated; otherwise a new ChebyshevTT over surviving dims.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentException

If dims contains out-of-range indices, or bounds are invalid. Duplicate dims entries are silently deduplicated (matches Integrate(int[]?, (double lo, double hi)[]?)).

IsConstructionFinished()

public bool IsConstructionFinished()

Returns

bool

Load(string)

Load a previously saved TT interpolant from a JSON file. The loaded object can evaluate immediately; no rebuild is needed.

public static ChebyshevTT Load(string path)

Parameters

path string

Path to the saved file.

Returns

ChebyshevTT

The restored TT interpolant.

Exceptions

InvalidOperationException

If the file cannot be deserialized as a ChebyshevTT state.

InvalidDataException

If the file contains a malformed ChebyshevTT state.

Maximize(int?, Dictionary<int, double>?)

Find the maximum value of the TT along a user-frame dimension.

public (double value, double location) Maximize(int? dim = null, Dictionary<int, double>? fixedDims = null)

Parameters

dim int?

User-frame dimension. For 1-D TTs, defaults to 0.

fixedDims Dictionary<int, double>

For multi-D, {dim_index: value} for all user-frame dims except dim. Validated against user-frame domain.

Returns

(double lo, double hi)

Tuple of (maximum value, location where maximum is achieved).

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentException

If validation fails.

Minimize(int?, Dictionary<int, double>?)

Find the minimum value of the TT along a user-frame dimension.

public (double value, double location) Minimize(int? dim = null, Dictionary<int, double>? fixedDims = null)

Parameters

dim int?

User-frame dimension. For 1-D TTs, defaults to 0.

fixedDims Dictionary<int, double>

For multi-D, {dim_index: value} for all user-frame dims except dim. Validated against user-frame domain.

Returns

(double lo, double hi)

Tuple of (minimum value, location where minimum is achieved).

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentException

If validation fails.

NegateInPlace()

Negate this TT in place.

public void NegateInPlace()

Nodes(int, double[][], int[])

Compute the Chebyshev Type I node positions per dimension scaled to the user's domain. Static factory matching Nodes(int, double[][], int[]).

public static (double[][] NodesPerDim, int[] Shape) Nodes(int numDimensions, double[][] domain, int[] nNodes)

Parameters

numDimensions int

Number of dimensions.

domain double[][]

Bounds [lo, hi] per dimension.

nNodes int[]

Number of nodes per dimension.

Returns

(double[][] NodesPerDim, int[] Shape)

(NodesPerDim[d][j], Shape[d]) — node arrays in ascending order.

OrthLeft(int)

Left-orthogonalize cores [0..position-1] in place by absorbing each core's R factor into the next core's left bond. The represented tensor is unchanged.

public void OrthLeft(int position)

Parameters

position int

Pivot index, must be in [1, NumDimensions - 1].

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentOutOfRangeException

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

OrthRight(int)

Right-orthogonalize cores [position+1..NumDimensions-1] in place by absorbing each core's L factor into the previous core's right bond. The represented tensor is unchanged.

public void OrthRight(int position)

Parameters

position int

Pivot index, must be in [0, NumDimensions - 2].

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentOutOfRangeException

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

Reorder(int[], int?, double?)

Realign storage to a target permutation via TT-swap (adjacent-axis SVDs in coefficient space). Functional API; returns a new TT. Inherits all build parameters (maxRank, tolerance, maxSweeps, descriptor, additionalData, maxDerivativeOrder, Method) from this TT.

public ChebyshevTT Reorder(int[] newOrder, int? maxRank = null, double? tolerance = null)

Parameters

newOrder int[]

Target permutation; must be a permutation of [0, NumDimensions-1].

maxRank int?

Optional override for swap-time SVD truncation. Default: this TT's maxRank.

tolerance double?

Optional relative-tolerance cutoff. Default: this TT's tolerance.

Returns

ChebyshevTT

A new TT with DimOrder == newOrder.

Exceptions

ArgumentException

If newOrder is not a valid permutation.

Roots(int?, Dictionary<int, double>?)

Find all real roots of the TT-approximated function along a specified dimension. Reduces to a 1-D problem by slicing all other dimensions to their fixed values, then delegates to Roots(int?, Dictionary<int, double>?).

public double[] Roots(int? dim = null, Dictionary<int, double>? fixedDims = null)

Parameters

dim int?

User-frame dimension. For 1-D TTs, defaults to 0.

fixedDims Dictionary<int, double>

For multi-D, {dim_index: value} for all user-frame dims except dim. Validated against user-frame domain.

Returns

double[]

Sorted real root locations in the physical domain. Empty if no roots.

Remarks

Under non-identity DimOrder, dim and fixedDims keys translate to storage frame transparently inside Slice(int, double) and ToDense().

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentException

If validation fails.

RoundInPlace(double)

Round TT to lower rank in place via TT-SVD recompression.

public void RoundInPlace(double tolerance)

Parameters

tolerance double

Finite non-negative relative singular-value cutoff. Zero keeps rank-only truncation.

Exceptions

ArgumentOutOfRangeException

If tolerance is negative, NaN, or infinite.

RunCompletion(double, int, bool)

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.

public void RunCompletion(double tolerance = 1E-08, int maxIter = 50, bool verbose = false)

Parameters

tolerance double

Stop when inner-sweep relative change falls below this.

maxIter int

Maximum number of outer ALS sweeps.

verbose bool

Print per-sweep residuals.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called or if Function is null (loaded TT).

ArgumentException

If the function returns NaN or Infinity at a sampled grid point.

Save(string)

Save the built TT interpolant to a JSON file. The original function is not saved — only numerical data needed for evaluation.

public void Save(string path)

Parameters

path string

Destination file path.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ScalarDivInPlace(double)

Divide this TT in place by scalar.

public void ScalarDivInPlace(double scalar)

Parameters

scalar double

Exceptions

DivideByZeroException

If scalar is zero.

ScalarMulInPlace(double)

Scale this TT in place by scalar.

public void ScalarMulInPlace(double scalar)

Parameters

scalar double

SetDescriptor(string)

Set a free-form descriptor string for this tensor train.

public void SetDescriptor(string descriptor)

Parameters

descriptor string

Slice(int, double)

Fix dimension dim at value, returning a TT over the remaining (NumDimensions - 1) dimensions.

public ChebyshevTT Slice(int dim, double value)

Parameters

dim int

Dimension to slice, 0 <= dim < NumDimensions.

value double

Value at which to fix the dimension; must lie within the domain.

Returns

ChebyshevTT

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

ArgumentOutOfRangeException

If dim is out of range or value is outside the domain.

InvalidOperationException

If NumDimensions == 1 (would produce 0D result).

SobolIndices()

Compute first-order + total-order variance-based sensitivity indices natively from the TT coefficient cores. The variance is with respect to the Chebyshev orthogonality weight on the normalized domain. O(d · n · r²) per dim, no dense materialization.

public SobolResult SobolIndices()

Returns

SobolResult

SobolResult with arrays keyed by user-frame dim indices and Chebyshev-weighted total Variance.

Remarks

Mathematically equivalent to SobolIndices() applied to the dense version of the same function, but skips the O(n^d) materialization. Under non-identity DimOrder, result keys are translated from storage frame to user frame internally.

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

SubInPlace(ChebyshevTT)

In-place subtraction: this -= other followed by TT-SVD rounding.

public void SubInPlace(ChebyshevTT other)

Parameters

other ChebyshevTT

ToDense()

Materialize the TT chain into a full row-major dense tensor. Length is Π NNodes; dense[flat] equals Eval(point_at_grid_idx) where flat is the row-major index into the grid shape. Use sparingly: storage is Π NNodes doubles.

public double[] ToDense()

Returns

double[]

Exceptions

InvalidOperationException

If Build(bool, int?, string) has not been called.

OverflowException

If the full tensor would be too large to materialize as a managed array.

ToString()

Returns a string that represents the current object.

public override string ToString()

Returns

string

A string that represents the current object.

WithAutoOrder(Func<double[], double>, int, double[][], int[], int, double, int, object?, int, string, int?, IProgress<int>?, bool)

Build a TT trying multiple dim orderings, returning the lowest-rank result. TT-Cross compression depends on dim order; different orderings yield different ranks for the same function.

public static ChebyshevTT WithAutoOrder(Func<double[], double> function, int numDimensions, double[][] domain, int[] numNodes, int maxRank = 10, double tolerance = 1E-06, int maxSweeps = 10, object? additionalData = null, int nTrials = 5, string method = "greedy_swap", int? seed = null, IProgress<int>? progress = null, bool verbose = false)

Parameters

function Func<double[], double>

f(point) → double in the original (user) dim order.

numDimensions int

Number of input dimensions.

domain double[][]

Bounds for each dimension in original order.

numNodes int[]

Node counts per dimension in original order.

maxRank int

Maximum positive TT rank passed to each trial. Default 10.

tolerance double

Finite positive convergence tolerance for each trial. Default 1e-6.

maxSweeps int

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

additionalData object

Stored on the result for introspection; not threaded into f.

nTrials int

Number of swap iterations / random samples. Default 5.

method string

"greedy_swap" (default, deterministic) or "random".

seed int?

Optional seed for "random". Ignored by "greedy_swap".

progress IProgress<int>

Optional per-sweep progress reporter (forwarded to each trial's Build).

verbose bool

If true, print per-trial diagnostics.

Returns

ChebyshevTT

The lowest-total-rank TT among the tried permutations, with DimOrder set.

Operators

operator +(ChebyshevTT, ChebyshevTT)

Binary addition: a + b. Result is rounded to the larger of the two TTs' maxRank.

public static ChebyshevTT operator +(ChebyshevTT a, ChebyshevTT b)

Parameters

a ChebyshevTT
b ChebyshevTT

Returns

ChebyshevTT

operator /(ChebyshevTT, double)

Scalar division: tt / scalar.

public static ChebyshevTT operator /(ChebyshevTT tt, double scalar)

Parameters

tt ChebyshevTT
scalar double

Returns

ChebyshevTT

Exceptions

DivideByZeroException

If scalar is zero.

operator *(ChebyshevTT, double)

Scalar multiplication: tt * scalar.

public static ChebyshevTT operator *(ChebyshevTT tt, double scalar)

Parameters

tt ChebyshevTT
scalar double

Returns

ChebyshevTT

operator *(double, ChebyshevTT)

Scalar multiplication: scalar * tt.

public static ChebyshevTT operator *(double scalar, ChebyshevTT tt)

Parameters

scalar double
tt ChebyshevTT

Returns

ChebyshevTT

operator -(ChebyshevTT, ChebyshevTT)

Binary subtraction: a - b.

public static ChebyshevTT operator -(ChebyshevTT a, ChebyshevTT b)

Parameters

a ChebyshevTT
b ChebyshevTT

Returns

ChebyshevTT

operator -(ChebyshevTT)

Unary negation: -tt.

public static ChebyshevTT operator -(ChebyshevTT tt)

Parameters

tt ChebyshevTT

Returns

ChebyshevTT