Table of Contents

Class ChebyshevApproximation

Namespace
ChebyshevSharp
Assembly
ChebyshevSharp.dll

Dense multi-dimensional Chebyshev interpolation on a full tensor-product grid. Provides barycentric evaluation and spectral differentiation on the represented polynomial interpolant.

public class ChebyshevApproximation
Inheritance
ChebyshevApproximation
Inherited Members

Constructors

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

Create a new ChebyshevApproximation.

public ChebyshevApproximation(Func<double[], object?, double> function, int numDimensions, double[][] domain, int[] nNodes, int maxDerivativeOrder = 2, object? additionalData = null, bool deferBuild = false, int? nWorkers = null, IProgress<int>? progress = null)

Parameters

function Func<double[], object, double>

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

numDimensions int

Number of input dimensions.

domain double[][]

Bounds for each dimension as double[ndim][2].

nNodes int[]

Number of Chebyshev nodes per dimension.

maxDerivativeOrder int

Maximum derivative order to support (default 2).

additionalData object

Optional user data object threaded through every f(point, data) call during Build.

deferBuild bool

If true, skip eager node materialization. Call SetOriginalFunctionValues(double[]) to finish construction.

nWorkers int?

Number of parallel workers for Build(): null (sequential), -1 (all cores), or positive int.

progress IProgress<int>

Optional progress reporter; receives cumulative evaluation count 1..N during Build().

Remarks

When nWorkers is non-null, function may be invoked concurrently from multiple threads via Parallel.For. Functions that capture mutable state must use locks or external synchronization, or pass nWorkers: null (the default).

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

Create a new ChebyshevApproximation with optional error-driven auto-N construction.

public ChebyshevApproximation(Func<double[], object?, double> function, int numDimensions, double[][] domain, int?[]? nNodes = null, double? errorThreshold = null, int maxN = 64, int maxDerivativeOrder = 2, object? additionalData = null, int? nWorkers = null, IProgress<int>? progress = null)

Parameters

function Func<double[], object, double>

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

numDimensions int

Number of input dimensions.

domain double[][]

Bounds for each dimension as double[ndim][2].

nNodes int?[]

Number of Chebyshev nodes per dimension; null entries signal auto-N for that dim. Pass null to make every dim auto-N (requires errorThreshold).

errorThreshold double?

Finite positive target supremum-norm error. Required if any nNodes entry is null.

maxN int

Cap on nodes per dimension during the doubling loop (default 64, must be at least 3).

maxDerivativeOrder int

Maximum derivative order to support (default 2).

additionalData object

Optional user data object threaded through every f(point, data) call during Build.

nWorkers int?

Number of parallel workers for Build(): null (sequential), -1 (all cores), or positive int.

progress IProgress<int>

Optional progress reporter; receives cumulative evaluation count 1..N during Build().

Remarks

When nWorkers is non-null, function may be invoked concurrently from multiple threads via Parallel.For. Functions that capture mutable state must use locks or external synchronization, or pass nWorkers: null (the default).

Properties

BuildTime

Time taken by Build() in seconds.

public double BuildTime { get; }

Property Value

double

BuildWarning

Warning emitted by Build() if maxN was reached before errorThreshold was satisfied. Null otherwise.

public string? BuildWarning { get; }

Property Value

string

DiffMatrices

Spectral differentiation matrices per dimension.

public double[][,]? DiffMatrices { get; }

Property Value

double[][,]

Domain

Domain bounds for each dimension, as [lo, hi] pairs.

public double[][] Domain { get; }

Property Value

double[][]

ErrorThreshold

Target supremum-norm error for auto-N construction. Null in fixed-N mode.

public double? ErrorThreshold { get; }

Property Value

double?

Function

Function used by Build(bool). Null for objects restored from saved numerical state or created by value-based/transformation APIs.

public Func<double[], object?, double>? Function { get; }

Property Value

Func<double[], object, double>

MaxDerivativeOrder

Maximum supported derivative order.

public int MaxDerivativeOrder { get; }

Property Value

int

MaxN

Maximum nodes per dimension for the auto-N doubling loop. Default 64.

public int MaxN { get; }

Property Value

int

NEvaluations

Number of function evaluations during Build().

public int NEvaluations { get; }

Property Value

int

NNodes

Number of Chebyshev nodes per dimension.

public int[] NNodes { get; }

Property Value

int[]

NodeArrays

Chebyshev nodes per dimension, each sorted ascending.

public double[][] NodeArrays { get; }

Property Value

double[][]

NumDimensions

Number of input dimensions.

public int NumDimensions { get; }

Property Value

int

TensorValues

Flat tensor of function values at all node combinations (C-order).

public double[]? TensorValues { get; }

Property Value

double[]

Weights

Barycentric weights per dimension.

public double[][]? Weights { get; }

Property Value

double[][]

Methods

Build(bool)

Build the Chebyshev approximation. Dispatches to the doubling loop if any dimension was constructed with a null entry in nNodes (auto-N), otherwise builds on the resolved fixed grid.

public void Build(bool verbose = true)

Parameters

verbose bool

If true, print build progress.

Exceptions

InvalidOperationException

If this object has no callable Function.

ArgumentException

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

ChebyshevCoefficients1D(double[])

Get Chebyshev coefficients for a 1D array of values at Type I nodes.

public static double[] ChebyshevCoefficients1D(double[] values)

Parameters

values double[]

Values sampled at one-dimensional Chebyshev Type-I nodes.

Returns

double[]

Chebyshev coefficients in increasing polynomial degree order.

Clone()

Returns a deep copy of this approximation. The source Function callable is not duplicated; clones cannot be rebuilt without re-supplying the function. All precomputed state, descriptor, derivative-id registry, and special points are deep-copied.

public ChebyshevApproximation Clone()

Returns

ChebyshevApproximation

A fully independent ChebyshevApproximation with Function set to null.

ErrorEstimate()

Estimate the supremum-norm interpolation error using Chebyshev coefficient decay. Sums per-dimension max last-coefficient magnitudes.

public double ErrorEstimate()

Returns

double

Estimated maximum interpolation error.

ErrorEstimatePerDim()

Compute per-dimension max last-coefficient magnitudes. Returns one entry per dimension; ErrorEstimate() returns the sum. Used by the auto-N doubling loop to pick the worst-contributing dim.

public double[] ErrorEstimatePerDim()

Returns

double[]

Per-dimension last-coefficient magnitudes, one entry per dim.

Eval(double[])

Evaluate the function value (no derivatives) at the given point. Convenience overload equivalent to Eval(point, new int[NumDimensions]).

public double Eval(double[] point)

Parameters

point double[]

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

Returns

double

Interpolated value at the query point.

Exceptions

InvalidOperationException

If the interpolant has not been built or populated from values.

ArgumentException

If point has the wrong length or contains a non-finite value.

ArgumentOutOfRangeException

If a point coordinate is outside the declared domain.

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.

Eval(double[], int[])

Evaluate using dimensional decomposition with barycentric interpolation.

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

Parameters

point double[]

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

derivativeOrder int[]

Derivative order per dimension.

Returns

double

Interpolated value or derivative at the query point.

Exceptions

InvalidOperationException

If the interpolant has not been built or populated from values.

ArgumentException

If point or derivativeOrder has the wrong length.

ArgumentOutOfRangeException

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

Extrude(params (int dimIndex, double[] bounds, int nNodes)[])

Add one or more dimensions where the represented interpolant is constant.

public ChebyshevApproximation Extrude(params (int dimIndex, double[] bounds, int nNodes)[] extrudeParams)

Parameters

extrudeParams (int dimIndex, double[] bounds, int nNodes)[]

Tuples of output dimension index, domain bounds, and node count for each inserted dimension.

Returns

ChebyshevApproximation

A built approximation with the inserted dimensions and no source function attached.

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

Create an interpolant from pre-computed function values.

public static ChebyshevApproximation FromValues(double[] tensorValues, int numDimensions, double[][] domain, int[] nNodes, int maxDerivativeOrder = 2)

Parameters

tensorValues double[]

Flat row-major tensor of values sampled on Nodes(int, double[][], int[]).

numDimensions int

Number of dimensions.

domain double[][]

Lower and upper bounds for each dimension.

nNodes int[]

Number of Chebyshev nodes per dimension.

maxDerivativeOrder int

Maximum derivative order to support.

Returns

ChebyshevApproximation

A built interpolant with Function set to null.

Exceptions

ArgumentException

If the tensor length does not match the grid shape or contains NaN/Infinity.

GetAdditionalData()

Returns the user-supplied additionalData object passed to the constructor, or null if none was provided. Same value is threaded through every f(point, data) call during Build(bool).

public object? GetAdditionalData()

Returns

object

GetConstructorType()

Returns one of: "function" (Build), "from_values" (FromValues factory), "load" (Load), "clone" (Clone).

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

GetErrorThreshold()

Return the error threshold passed to the constructor, or null in fixed-N mode.

public double? GetErrorThreshold()

Returns

double?

GetEvaluationPoints()

Flat row-major array of all Chebyshev node coordinates. Length is GetNumEvaluationPoints() * NumDimensions. Result is lazily built and cached internally.

public double[] GetEvaluationPoints()

Returns

double[]

A snapshot of shape [numPoints, ndim] flattened to 1D in row-major order.

GetMaxDerivativeOrder()

Maximum derivative order this approximation supports.

public int GetMaxDerivativeOrder()

Returns

int

GetNumEvaluationPoints()

Total number of evaluation points (product of nNodes across all dimensions).

public int GetNumEvaluationPoints()

Returns

int

The total count of Chebyshev nodes in the tensor grid.

GetOptimalN1(Func<double[], object?, double>, (double lo, double hi), double, int)

1-D capacity estimator: returns the first doubling-loop node count at which a 1-D Chebyshev build over domain hits errorThreshold, or maxN if the threshold is not met before the cap. Useful as a sizing pass before committing to a multi-dimensional build.

public static int GetOptimalN1(Func<double[], object?, double> function, (double lo, double hi) domain, double errorThreshold, int maxN = 64)

Parameters

function Func<double[], object, double>

Function to approximate; signature f(point[1], data) -> double.

domain (double lo, double hi)

(lo, hi) bounds for the single dimension.

errorThreshold double

Finite positive target supremum-norm error.

maxN int

Cap on the returned node count. Default 64. If the doubling loop cannot achieve errorThreshold within this cap, returns maxN.

Returns

int

Resolved node count on the single dimension.

GetSpecialPoints()

Get special points (e.g., knots or singularities) used in construction.

public double[][]? GetSpecialPoints()

Returns

double[][]

Special points per dimension, or null if not applicable.

GetUsedNs()

Per-dimension Chebyshev node counts actually used. After auto-N construction, these are the resolved values.

public int[] GetUsedNs()

Returns

int[]

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

Integrate the represented interpolant over one or more dimensions.

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

Parameters

dims int[]

Dimensions to integrate out. Null = all.

bounds (double lo, double hi)[]

Sub-interval bounds per dim. Null = full domain.

Returns

object

Scalar if all dims integrated, otherwise a lower-dimensional interpolant.

IsConstructionFinished()

public bool IsConstructionFinished()

Returns

bool

Load(string)

Load a previously saved dense interpolant. Auto-detects JSON vs binary .pcb by sniffing the first 4 bytes for the PCB\0 magic.

public static ChebyshevApproximation Load(string path)

Parameters

path string

Path to the saved file.

Returns

ChebyshevApproximation

The restored interpolant.

Exceptions

InvalidDataException

If a .pcb file has a non-approximation class tag or if the serialized state is malformed.

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

Find the maximum of the represented one-dimensional interpolant.

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

Parameters

dim int?

Dimension to optimize. Required for multi-dimensional approximations.

fixedDims Dictionary<int, double>

Values for every non-search dimension when the approximation is multi-dimensional.

Returns

(double lo, double hi)

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

Find the minimum of the represented one-dimensional interpolant.

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

Parameters

dim int?

Dimension to optimize. Required for multi-dimensional approximations.

fixedDims Dictionary<int, double>

Values for every non-search dimension when the approximation is multi-dimensional.

Returns

(double lo, double hi)

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

Generate Chebyshev nodes without evaluating any function.

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

Parameters

numDimensions int

Number of dimensions.

domain double[][]

Lower and upper bounds for each dimension.

nNodes int[]

Number of Chebyshev nodes per dimension.

Returns

NodeInfo

A NodeInfo containing per-dimension nodes, the full Cartesian grid, and the tensor shape.

Exceptions

ArgumentException

If dimensions, domains, or node counts are invalid, or if the full grid is too large to materialize.

PeekFormatVersion(string)

Read the major version byte of a .pcb binary file without deserializing the body. Useful for forward-compat tooling.

public static int PeekFormatVersion(string path)

Parameters

path string

Path to a .pcb file.

Returns

int

The major format version (currently 1).

Exceptions

FileNotFoundException

Thrown if the path does not exist.

InvalidDataException

Thrown if the file is not a .pcb file (no magic header) or is shorter than 12 bytes.

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

Find real roots of the represented one-dimensional interpolant.

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

Parameters

dim int?

Dimension to search. Required for multi-dimensional approximations.

fixedDims Dictionary<int, double>

Values for every non-search dimension when the approximation is multi-dimensional.

Returns

double[]

Save(string, string)

Save the built interpolant to a file.

public void Save(string path, string format = "json")

Parameters

path string

Destination file path.

format string

"json" (default) or "binary". Binary writes the documented .pcb primitive layout for dense approximations.

SetDescriptor(string)

Set a free-form descriptor string for this interpolant.

public void SetDescriptor(string descriptor)

Parameters

descriptor string

SetOriginalFunctionValues(double[])

Populate this interpolant's tensor values from a precomputed flat array. Used after constructing with deferBuild: true. Performs the same numerical pre-computation as the FromValues(double[], int, double[][], int[], int) factory.

public void SetOriginalFunctionValues(double[] values)

Parameters

values double[]

Flat C-order tensor of length nNodes[0]nNodes[1]...

Exceptions

ArgumentNullException

Thrown when values is null.

ArgumentException

Thrown when values length does not match the expected product of nNodes.

InvalidOperationException

Thrown when the interpolant is already constructed.

Slice(params (int dimIndex, double value)[])

Fix one or more dimensions at given values using barycentric interpolation.

public ChebyshevApproximation Slice(params (int dimIndex, double value)[] sliceParams)

Parameters

sliceParams (int dimIndex, double value)[]

Tuples of current dimension index and value to fix.

Returns

ChebyshevApproximation

A built lower-dimensional approximation with no source function attached.

SobolIndices()

Compute first- and total-order variance-based sensitivity indices directly from this approximation's spectral Chebyshev coefficients. The variance is with respect to the Chebyshev orthogonality weight on the normalized domain, not a Monte Carlo estimate under a uniform input distribution.

public SobolResult SobolIndices()

Returns

SobolResult

A SobolResult with per-dim FirstOrder, TotalOrder, and Chebyshev-weighted total Variance.

Exceptions

InvalidOperationException

If Build(bool) has not been called.

ToReprString()

Compact representation of the interpolant.

public string ToReprString()

Returns

string

ToString()

Returns a string that represents the current object.

public override string ToString()

Returns

string

A string that represents the current object.

VectorizedEval(double[], int[])

Fully vectorized evaluation using matrix operations. Uses BLAS-style matrix-vector products where possible.

public double VectorizedEval(double[] point, int[] derivativeOrder)

Parameters

point double[]

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

derivativeOrder int[]

Derivative order per dimension.

Returns

double

Interpolated value or derivative.

Exceptions

InvalidOperationException

If the interpolant has not been built or populated from values.

ArgumentException

If point or derivativeOrder has the wrong length.

ArgumentOutOfRangeException

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

VectorizedEvalBatch(double[][], int[])

Evaluate at multiple points. Hoists derivative-matrix matmuls outside the per-point loop (they are point-independent), then does only barycentric reductions per point.

public double[] VectorizedEvalBatch(double[][] points, int[] derivativeOrder)

Parameters

points double[][]

Points inside the declared domain as double[N][numDimensions].

derivativeOrder int[]

Derivative order per dimension.

Returns

double[]

Results array of length N.

Exceptions

InvalidOperationException

If the interpolant has not been built or populated from values.

ArgumentException

If a point row or derivativeOrder has the wrong length.

ArgumentOutOfRangeException

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

VectorizedEvalMulti(double[], int[][])

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

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

Parameters

point double[]

Query point inside the declared domain.

derivativeOrders int[][]

Each inner array specifies derivative order per dimension.

Returns

double[]

One result per derivative order.

Exceptions

InvalidOperationException

If the interpolant has not been built or populated from values.

ArgumentException

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

ArgumentOutOfRangeException

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

Operators

operator +(ChebyshevApproximation, ChebyshevApproximation)

Add two interpolants with the same grid.

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

Parameters

a ChebyshevApproximation
b ChebyshevApproximation

Returns

ChebyshevApproximation

operator /(ChebyshevApproximation, double)

Divide interpolant by a scalar.

public static ChebyshevApproximation operator /(ChebyshevApproximation a, double scalar)

Parameters

a ChebyshevApproximation
scalar double

Returns

ChebyshevApproximation

operator *(ChebyshevApproximation, double)

Multiply interpolant by a scalar.

public static ChebyshevApproximation operator *(ChebyshevApproximation a, double scalar)

Parameters

a ChebyshevApproximation
scalar double

Returns

ChebyshevApproximation

operator *(double, ChebyshevApproximation)

Multiply scalar by interpolant.

public static ChebyshevApproximation operator *(double scalar, ChebyshevApproximation a)

Parameters

scalar double
a ChebyshevApproximation

Returns

ChebyshevApproximation

operator -(ChebyshevApproximation, ChebyshevApproximation)

Subtract two interpolants with the same grid.

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

Parameters

a ChebyshevApproximation
b ChebyshevApproximation

Returns

ChebyshevApproximation

operator -(ChebyshevApproximation)

Negate interpolant.

public static ChebyshevApproximation operator -(ChebyshevApproximation a)

Parameters

a ChebyshevApproximation

Returns

ChebyshevApproximation