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
functionFunc<double[], double>Function to approximate. Signature: f(point) -> double.
numDimensionsintNumber of input dimensions.
domaindouble[][]Bounds [lo, hi] for each dimension.
nNodesint[]Number of Chebyshev nodes per dimension.
maxRankintMaximum positive TT rank. Default is 10.
tolerancedoubleFinite positive convergence tolerance for TT-Cross/ALS. Default is 1e-6.
maxSweepsintMaximum positive number of TT-Cross sweeps. Default is 10.
maxDerivativeOrderintMaximum derivative order to support. Default is 2.
additionalDataobjectOptional user data object stored for introspection via GetAdditionalData(). NOT threaded through build calls (TT function signature has no data arg).
nWorkersint?Accepted for API symmetry with the other classes but ignored: TT-Cross is adaptive sampling, not pre-grid evaluation. Pass null.
progressIProgress<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
Properties
BuildWarning
Warning emitted by Build() if maxRank was reached before tolerance was satisfied during ALS. Null otherwise.
public string? BuildWarning { get; }
Property Value
CompressionRatio
Ratio of full tensor elements to TT storage elements.
public double CompressionRatio { get; }
Property Value
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
MaxRank
Maximum TT rank.
public int MaxRank { get; }
Property Value
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
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
TotalBuildEvals
Total number of function evaluations used during build.
public int TotalBuildEvals { get; }
Property Value
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
otherChebyshevTT
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
verboseboolIf true, print build progress.
seedint?Random seed for TT-Cross/ALS initialization. Ignored for method="svd".
methodstring"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
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
pointdouble[]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
pointdouble[]Evaluation point.
derivativeIdintId returned by GetDerivativeId(int[]).
Returns
- double
Interpolated value at the given derivative order.
Exceptions
- ArgumentOutOfRangeException
Thrown when
derivativeIdhas 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
pointsdouble[,]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
pointdouble[]Evaluation point inside the declared domain.
derivativeOrdersint[][]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
pointor 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
dimintInsertion index, 0 <= dim <= NumDimensions.
newDomain(double lo, double hi)Domain (lo, hi) for the new dimension.
newNintNumber of nodes for the new dimension.
Returns
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
tensorValuesdouble[]Flat row-major dense tensor of length Π nNodes.
numDimensionsintNumber of dimensions.
domaindouble[][]Bounds [lo, hi] per dimension.
nNodesint[]Number of nodes per dimension.
maxRankintMaximum positive TT rank (default 10).
tolerancedoubleFinite non-negative SVD truncation tolerance (default 1e-6).
Returns
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
GetConstructorType()
Returns one of: "clone" (if cloned), "cross"/"svd"/"als" (build method used), or "function" if not yet built.
public string GetConstructorType()
Returns
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
ordersint[]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
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
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
otherChebyshevTTThe other TT.
Returns
- double
Σ_{i_1,…,i_d} C_self[i] * C_other[i].
Exceptions
- ArgumentNullException
If
otheris 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
dimsint[]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
doublewhen every dim is integrated; otherwise a new ChebyshevTT over surviving dims.
Exceptions
- InvalidOperationException
If Build(bool, int?, string) has not been called.
- ArgumentException
If
dimscontains out-of-range indices, orboundsare invalid. Duplicatedimsentries are silently deduplicated (matches Integrate(int[]?, (double lo, double hi)[]?)).
IsConstructionFinished()
True if Build(bool, int?, string)/Load(string) completed.
public bool IsConstructionFinished()
Returns
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
pathstringPath 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
dimint?User-frame dimension. For 1-D TTs, defaults to 0.
fixedDimsDictionary<int, double>For multi-D,
{dim_index: value}for all user-frame dims exceptdim. Validated against user-frame domain.
Returns
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
dimint?User-frame dimension. For 1-D TTs, defaults to 0.
fixedDimsDictionary<int, double>For multi-D,
{dim_index: value}for all user-frame dims exceptdim. Validated against user-frame domain.
Returns
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
numDimensionsintNumber of dimensions.
domaindouble[][]Bounds [lo, hi] per dimension.
nNodesint[]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
positionintPivot 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
positionintPivot 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
newOrderint[]Target permutation; must be a permutation of [0, NumDimensions-1].
maxRankint?Optional override for swap-time SVD truncation. Default: this TT's maxRank.
tolerancedouble?Optional relative-tolerance cutoff. Default: this TT's tolerance.
Returns
- ChebyshevTT
A new TT with
DimOrder == newOrder.
Exceptions
- ArgumentException
If
newOrderis 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
dimint?User-frame dimension. For 1-D TTs, defaults to 0.
fixedDimsDictionary<int, double>For multi-D,
{dim_index: value}for all user-frame dims exceptdim. 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
tolerancedoubleFinite non-negative relative singular-value cutoff. Zero keeps rank-only truncation.
Exceptions
- ArgumentOutOfRangeException
If
toleranceis 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
tolerancedoubleStop when inner-sweep relative change falls below this.
maxIterintMaximum number of outer ALS sweeps.
verboseboolPrint per-sweep residuals.
Exceptions
- InvalidOperationException
If Build(bool, int?, string) has not been called or if
Functionis 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
pathstringDestination 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
scalardouble
Exceptions
- DivideByZeroException
If
scalaris zero.
ScalarMulInPlace(double)
Scale this TT in place by scalar.
public void ScalarMulInPlace(double scalar)
Parameters
scalardouble
SetDescriptor(string)
Set a free-form descriptor string for this tensor train.
public void SetDescriptor(string descriptor)
Parameters
descriptorstring
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
dimintDimension to slice, 0 <= dim < NumDimensions.
valuedoubleValue at which to fix the dimension; must lie within the domain.
Returns
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
otherChebyshevTT
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
functionFunc<double[], double>f(point) → double in the original (user) dim order.
numDimensionsintNumber of input dimensions.
domaindouble[][]Bounds for each dimension in original order.
numNodesint[]Node counts per dimension in original order.
maxRankintMaximum positive TT rank passed to each trial. Default 10.
tolerancedoubleFinite positive convergence tolerance for each trial. Default 1e-6.
maxSweepsintMaximum positive TT-Cross sweeps per trial. Default 10.
additionalDataobjectStored on the result for introspection; not threaded into f.
nTrialsintNumber of swap iterations / random samples. Default 5.
methodstring"greedy_swap" (default, deterministic) or "random".
seedint?Optional seed for "random". Ignored by "greedy_swap".
progressIProgress<int>Optional per-sweep progress reporter (forwarded to each trial's Build).
verboseboolIf true, print per-trial diagnostics.
Returns
- ChebyshevTT
The lowest-total-rank TT among the tried permutations, with
DimOrderset.
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
Returns
operator /(ChebyshevTT, double)
Scalar division: tt / scalar.
public static ChebyshevTT operator /(ChebyshevTT tt, double scalar)
Parameters
ttChebyshevTTscalardouble
Returns
Exceptions
- DivideByZeroException
If
scalaris zero.
operator *(ChebyshevTT, double)
Scalar multiplication: tt * scalar.
public static ChebyshevTT operator *(ChebyshevTT tt, double scalar)
Parameters
ttChebyshevTTscalardouble
Returns
operator *(double, ChebyshevTT)
Scalar multiplication: scalar * tt.
public static ChebyshevTT operator *(double scalar, ChebyshevTT tt)
Parameters
scalardoublettChebyshevTT
Returns
operator -(ChebyshevTT, ChebyshevTT)
Binary subtraction: a - b.
public static ChebyshevTT operator -(ChebyshevTT a, ChebyshevTT b)
Parameters
Returns
operator -(ChebyshevTT)
Unary negation: -tt.
public static ChebyshevTT operator -(ChebyshevTT tt)
Parameters
ttChebyshevTT