sgpykit.src
Functions
|
Return entries from the Gauss-Kronrod level table. |
Compute the coefficients of the combination technique expression of a sparse grid. |
|
|
Compare the points of two sparse grids. |
|
Convert a tensor grid interpolant to a modal expansion in orthogonal polynomials. |
Compute the combination technique contributions of a multi-index. |
|
|
Check if the given tolerance is sufficient to detect identical points. |
|
Find specific rows of a matrix that is sorted lexicographically. |
|
Find specific rows of a matrix that is sorted lexicographically up to TOL. |
Generate a pattern matrix for the Cartesian product of sequences. |
|
|
Identify points to compute, recycle, and discard between two sparse grids. |
|
Sort the rows of a matrix in lexicographic order with a tolerance. |
|
Plot the status of a two-dimensional adaptive sparse grid. |
|
Generate a tensor grid and compute the corresponding weights. |
- sgpykit.src.GK_lev_table(row_idx, col_idx)[source]
Return entries from the Gauss-Kronrod level table.
This function returns the (row, col) submatrix of the pre-defined Gauss-Kronrod level table. The table maps between Gauss-Kronrod level indices, the number of knots, and the corresponding quadrature order.
- Parameters:
- row_idxint or array_like
Row index or indices of the table.
- col_idxint or array_like
Column index or indices of the table.
- Returns:
- Andarray
The submatrix of the Gauss-Kronrod level table at the specified row and column indices.
Notes
In the tabulated GK knots, many levels have the same knots (with weights identical up to 10th-11th digit). For each group of levels with the same number of knots, one representative is selected, and a map is defined as follows:
MAP= i: l: nb_knots: order: 0 0 0 0 1 1 1 1 2 3 3 3 3 8 9 15 4 15 19 29 5 25 35 51
- sgpykit.src.combination_technique(I)[source]
Compute the coefficients of the combination technique expression of a sparse grid.
The combination technique computes the coefficients for expressing a sparse grid as a linear combination of tensor grids. This function takes a multi-index set I (each row representing a multi-index associated with a Delta operator in the sparse grid construction) and computes the corresponding combination technique coefficients.
- Parameters:
- Indarray
0-based multi-index set matrix (one row per index), must be admissible and lexicographically sorted. These properties are not checked by the function.
- Returns:
- coeffndarray
Vector containing the combination technique coefficients.
Notes
The input matrix I must be admissible and lexicographically sorted. The function does not verify these properties, so incorrect input may lead to unexpected results.
- sgpykit.src.compare_sparse_grids(S, Sr, S_old, Sr_old, tol=1e-14)[source]
Compare the points of two sparse grids.
This function compares the points in S and S_old, and determines those in common, and those belonging exclusively to each of the two. Points are considered equal if coordinate-wise they are closer than TOL. SR is the reduced version of S and SR_OLD is the reduced version of S_OLD.
- Parameters:
- Sarray_like
Sparse grid structure.
- Srarray_like
Reduced version of S.
- S_oldarray_like
Old sparse grid structure.
- Sr_oldarray_like
Reduced version of S_old.
- tolfloat, optional
Tolerance for point comparison (default is 1e-14).
- Returns:
- pts_in_S_onlyndarray
Column indices of points in SR.KNOTS that are not in the intersection of S and S_OLD.
- pts_in_both_grids_Sndarray
Column indices of points in SR.KNOTS that are also in SR_OLD.KNOTS.
- pts_in_both_grids_S_oldndarray
Column indices of points in SR_OLD.KNOTS that are also in SR.KNOTS.
- pts_in_S_old_onlyndarray
Column indices of points in SR_OLD.KNOTS that are in SR_OLD but not in SR.
Notes
The same results would happen if SR_OLD.KNOTS are perturbed by numerical noise below tol: SR_OLD.KNOTS =[a+n f b h;
x s y-n r];
COMPARE_GRIDS is very efficient because it works with comparing integer indices coming from the multiindices in S.IDX and S_OLD.IDX as much as possible. See also LOOKUP_MERGE_AND_DIFF for the same kind of analysis based however on comparing the actual coordinates of the points.
Examples
Suppose SR.KNOTS = [a b c d e;
x y z w t]
- SR_OLD.KNOTS =[a f b h;
x s y r];
Then: pts_in_S_only = [3 4 5]; pts_in_both_grids_S = [1 2]; pts_in_both_grids_S_old = [1 3]; pts_in_S_old_only = [2 4];
- sgpykit.src.compute_modal_tensor(S, S_values, domain, flags)[source]
Convert a tensor grid interpolant to a modal expansion in orthogonal polynomials.
This function takes a tensor grid and its associated point evaluations, and converts the resulting Lagrange multivariate interpolant to a sum of orthogonal polynomials. The type of polynomials used can be specified via the flags parameter.
- Parameters:
- Sstruct
A struct containing the tensor grid information, including knots and size.
- S_valuesndarray
The values of the interpolant at the tensor grid points.
- domainndarray or list of ndarrays
The domain of the sparse grid. The format depends on the polynomial family: - For Legendre, Chebyshev: 2xN matrix [a1, a2, …; b1, b2, …] - For Hermite: 2xN matrix [mu1, mu2, …; sigma1, sigma2, …] - For Laguerre: 1xN matrix [lambda1, lambda2, …] - For generalized Laguerre: 2xN matrix [alpha1, alpha2, …; beta1, beta2, …] - For Jacobi: 4xN matrix [alpha1, alpha2, …; beta1, beta2, …; a1, a2, …; b1, b2, …] - For mixed families: a cell array where each cell contains the domain for the corresponding polynomial.
- flagsstr or list of str
The type of orthogonal polynomials to use. Can be a single string or a list of strings for mixed families. Supported values are: - ‘legendre’ - ‘chebyshev’ - ‘hermite’ - ‘laguerre’ - ‘generalized laguerre’ - ‘jacobi’
- Returns:
- Ustruct
A struct with the following fields: - size: the number of polynomials in the expansion. - multi_indices: the multi-indices corresponding to each polynomial. - modal_coeffs: the coefficients of the modal expansion.
- Raises:
- ValueError
If one or more strings in flags are unrecognized, or if the input argument domain is not a cell array when flags is a cell array.
- sgpykit.src.delta_to_combitec(ii)[source]
Compute the combination technique contributions of a multi-index.
DELTA_TO_COMBITEC computes the combination technique contributions of a multi-index I = delta_to_combitec(ii) takes as input a multi-index (row-vector) ii that describes a delta operator in the sparse grids construction and returns the set I of the corresponding quadrature/interpolation operators (lexicosorted). It does not return instead the coefficient of the index in the combination technique, whose value is trivial to compute, see below. In formulas, Delta^ii = prod_{n=1}^N ( U_n^{ii_n} - U_n^{ii_n-1}) where U_n^{i_n} is the quadrature/interpolation operator along direction n at level i_n. The Delta^ii can be expressed as linear combination of tensorized U_n operators: Delta^ii = sum_{kk in K} c_kk prod_n U_n^{kk_n} where c_kk = (-1)^sum(ii - kk); and I = sortrows(K), while c_kk is not returned For instance Delta^[1 2] = (U_1^1 -U_1^0) * (U_2^2 -U_2^1) = U_1^1 * U_2^2 - U_1^1 * U_2^1 - U_1^0 * U_2^2 + U_1^0 * U_2^1 and delta_to_combitec([1, 2]): ```
0 1 0 2 1 1 1 2
` Of course whenever ii_n = 0 for some n, we should not take the difference ( U_n^{ii_n} - U_n^{ii_n-1}); delta_to_combitec does this too: delta_to_combitec([1, 1, 2]): `0 0 1 0 0 2 0 1 1 0 1 2 1 0 1 1 0 2 1 1 1 1 1 2
` but delta_to_combitec([1, 0, 2]): `0 0 1 0 0 2 1 0 1 1 0 2
- Parameters:
- iiarray_like
Multi-index (row-vector) describing a delta operator in the sparse grids construction (0-based indexing).
- Returns:
- Indarray
Set of corresponding quadrature/interpolation operators (lexicosorted).
- sgpykit.src.detect_insufficient_tolerance(pts, tol)[source]
Check if the given tolerance is sufficient to detect identical points.
For a matrix of points (one per row, as in mysortrows or lookup_merge_and_diff), computes an approximation of the support of the set of point in each direction (as max - min coord in each dir) and compares it with tol. If they are “same-sized” then tol is too large and a warning is thrown.
- Parameters:
- ptsnumpy.ndarray
Matrix of points, with each row representing a point.
- tolfloat
Tolerance value to check.
- Returns:
- bool
True if the tolerance is insufficient, False otherwise.
- sgpykit.src.find_lexicographic(lookfor, I, nocheck=None)[source]
Find specific rows of a matrix that is sorted lexicographically.
- Parameters:
- lookforarray_like
The row vector to look for among the rows of I.
- Iarray_like
The matrix to search in, assumed to be sorted lexicographically.
- nocheckstr, optional
If ‘nocheck’, the function does not check whether I is lexicographically sorted. This can be useful for speed purposes. Default is None.
- Returns:
- foundbool
True if the row vector is found, False otherwise.
- posint or None
The row number of the found row vector, i.e., lookfor == I[pos, :]. If not found, pos is None.
- iterint
The number of iterations performed during the binary search.
Notes
The function performs a preliminary check whether I is actually lexicographically sorted. If nocheck is ‘nocheck’, this check is skipped. The function uses a binary search algorithm, which guarantees a cost of ~log(nb_idx).
- sgpykit.src.find_lexicographic_tol(lookfor, I, tol=1e-14)[source]
Find specific rows of a matrix that is sorted lexicographically up to TOL.
Finds a specific row vector in a matrix that is sorted lexicographically up to a given tolerance. The function uses binary search to efficiently locate the row.
- Parameters:
- lookforarray_like
The row vector to search for in the matrix.
- Indarray
The matrix to search in, assumed to be sorted lexicographically.
- tolfloat, optional
The tolerance for testing equality between lookfor and rows of I. Default is 1e-14.
- Returns:
- foundbool
True if lookfor is found in I within the given tolerance, False otherwise.
- posint or list
The row number of lookfor in I if found, otherwise an empty list.
- iterint
The number of iterations performed during the binary search.
Notes
The function does not perform a preliminary check whether I is actually lexicographically sorted. The binary search guarantees a cost of ~log(nb_idx).
Examples
>>> I,_ = sg.multiidx_box_set([4, 2], 1) >>> noise = 1e-13 * np.random.randn(*I.shape) >>> Inoisy = I + noise >>> print(sg.find_lexicographic_tol([4, 2], Inoisy, 1e-12)) # Should return True >>> print(sg.find_lexicographic_tol([4, 2], Inoisy, 1e-14)) # Should return False
- sgpykit.src.generate_pattern(m)[source]
Generate a pattern matrix for the Cartesian product of sequences.
This function generates a matrix that can be used to create the Cartesian product of sequences {1, 2, …, m1} x {1, 2, …, m2} x … x {1, 2, …, mN}.
- Parameters:
- marray_like
Input array of integers representing the lengths of the sequences.
- Returns:
- patternndarray
Matrix of indices for the Cartesian product. The shape is (N, prod(m)), where N is the length of m.
Notes
The function expects MATLAB 1-based indexing and returns 0-based indexing.
The algorithm works one direction at a time, generating the n-th row of the pattern by repeating a base vector q times.
Examples
>>> generate_pattern([3, 2, 2]) array([[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]], dtype=uint8)
- sgpykit.src.lookup_merge_and_diff(pts_list, pts_list_old, tol=1e-14)[source]
Identify points to compute, recycle, and discard between two sparse grids.
This function compares two sets of points (from new and old sparse grids) and categorizes them based on their presence in both grids, using a specified tolerance to determine equality. It is used in adaptive sparse grid algorithms to efficiently manage point evaluations.
- Parameters:
- pts_listnumpy.ndarray
Array of points from the new sparse grid (shape: N x d, where N is the number of points and d is the dimensionality).
- pts_list_oldnumpy.ndarray
Array of points from the old sparse grid (shape: N_old x d).
- tolfloat, optional
Tolerance for considering two points equal (default is 1e-14).
- Returns:
- tocomp_listnumpy.ndarray
Indices of points in pts_list that need to be evaluated (not present in old grid).
- recycle_listnumpy.ndarray
Indices of points in pts_list that can be recycled from old grid.
- recycle_list_oldnumpy.ndarray
Corresponding indices in pts_list_old for recycled points.
- discard_listnumpy.ndarray
Indices of points in pts_list_old that are no longer in the new grid.
Notes
The function uses lexicographic sorting with tolerance to identify matching points.
For non-nested grids, some points from the old grid may be discarded.
The function performs several sanity checks to ensure correctness.
- sgpykit.src.mysortrows(A, tol=1e-14)[source]
Sort the rows of a matrix in lexicographic order with a tolerance.
Given a matrix A of real numbers, sorts the rows in lexicographic order. Entries that differ less than Tol are treated as equal (default Tol is 1e-14).
- Parameters:
- Aarray_like
Input matrix to be sorted.
- tolfloat, optional
Tolerance used to identify coincident entries (default 1e-14).
- Returns:
- Bndarray
Sorted matrix.
- idxndarray
Index vector such that A[idx,:] = B.
- sgpykit.src.plot_idx_status(G, I, idx_bin, idx)[source]
Plot the status of a two-dimensional adaptive sparse grid.
This function visualizes the indices used in the construction of a two-dimensional adaptive sparse grid. It plots four sets of points: - G: set of indices used to build the sparse grid - I: set of indices whose neighbors have been explored - idx_bin: set of indices whose neighbors have not been explored - idx: next index to be considered
- Parameters:
- Gnumpy.ndarray
Array of shape (n, 2) containing the indices used to build the sparse grid.
- Inumpy.ndarray
Array of shape (m, 2) containing the indices whose neighbors have been explored.
- idx_binnumpy.ndarray
Array of shape (p, 2) containing the indices whose neighbors have not been explored.
- idxnumpy.ndarray
Array of shape (2,) containing the next index to be considered.
- Returns:
- None
- sgpykit.src.tensor_grid(N, m, knots)[source]
Generate a tensor grid and compute the corresponding weights.
This function creates a tensor grid in N dimensions with M=[m1, m2, …, mN] points in each direction. The knots can be specified either as a cell array of functions (one for each dimension) or as a single function to be used for all dimensions.
- Parameters:
- Nint
Number of dimensions.
- marray_like
Number of points in each dimension.
- knotscallable or array_like of callables
Function(s) to generate the knots in each direction. If a single function is provided, it is replicated for all dimensions. Each function should have the signature x, w = knots_function(m).
- Returns:
- SStruct
A structure containing the tensor grid information: - knots : ndarray
Vector containing the tensor grid knots.
- weightsndarray
Vector containing the corresponding weights.
- sizeint
Size of the tensor grid, equal to the product of m.
- knots_per_dimlist
List of N components, each containing the set of 1D knots used to build the tensor grid.
- mndarray
Input vector m, where m[i] is the length of knots_per_dim[i].