Welcome to TensorToolbox’s documentation!¶
Contents:
-
TensorToolbox.core.
idxunfold
(dlist, idxs)[source]¶ Find the index corresponding to the unfolded (flat) version of a tensor
Parameters: - dlist (list,int) – list of integers containing the dimensions of the tensor
- idxs (list,int) – tensor index
Returns: index for the flatten tensor
-
TensorToolbox.core.
idxfold
(dlist, idx)[source]¶ Find the index corresponding to the folded version of a tensor from the flatten version
Parameters: - dlist (list,int) – list of integers containing the dimensions of the tensor
- idx (int) – tensor flatten index
Returns: list of int – the index for the folded version
Note: this routine can be used to get the indexes of a TTmat from indices of a matkron (matrix obtained using np.kron): (i,j) in N^d x N^d -> ((i_1,..,i_d),(j_1,..,j_d)) in (N x .. x N) x (N x .. x N)
-
TensorToolbox.core.
expand_idxs
(idxs_in, shape, full_shape, fix_dims=[], fix_idxs=None)[source]¶ From a tuple of indicies, apply all the unslicing transformations necessary in order to extract values from a tensor.
Parameters: - idxs_in (tuple) – indexing tuple. The admissible slicing format is the same used in np.ndarray.
- shape (tuple) – shape of the tensor
- full_shape (tuple) – full shape of the tensor
- fix_dims (list) – whether there are dimensions which had been fixed and need to be added.
- fix_idxs (list) – fixed idxs for each fixed dimension.
Returns: tuple
(lidxs,list_idx,slice_idx,out_shape,transpose_list_shape)
.lidxs
is an iterator of the indices.list_idx
andslice_idx
are the list of dimensions containing lists and the dimensions containing slices.out_shape
is a tuple containing the shape of the output tensor.transpose_list_shape
is a flag indicating whether the output format need to be transposed (behaving accordingly to np.ndarray).
-
TensorToolbox.core.
matkron_to_mattensor
(A, nrows, ncols)[source]¶ This function reshapes a 2D-matrix obtained as kron product of len(nrows)==len(ncols) matrices, to a len(nrows)-tensor that can be used as input for the TTmat constructor. Applies the Van Loan-Pitsianis reordering of the matrix elements.
Parameters: - A (ndarray) – 2-dimensional matrix
- nrows,ncols (list,int) – number of rows and number of columns of the original matrices used for the kron product
-
TensorToolbox.core.
mat_to_tt_idxs
(rowidxs, colidxs, nrows, ncols)[source]¶ Mapping from the multidimensional matrix indexing to the tt matrix indexing
(rowidxs,colidxs) = ((i_1,...,i_d),(j_1,...,j_d)) -> (l_1,...,l_d)
Parameters: - rowidxs,colidxs (tuple,int) – list of row and column indicies. len(rowidxs) == len(colidxs)
- nrows,ncols (tuple,int) – dimensions of matrices
Returns: tuple,int indices in the tt format
-
TensorToolbox.core.
tt_to_mat_idxs
(idxs, nrows, ncols)[source]¶ Mapping from the tt matrix indexing to the multidimensional matrix indexing
(l_1,...,l_d) -> (rowidxs,colidxs) = ((i_1,...,i_d),(j_1,...,j_d))Parameters: - idxs (tuple,int) – list of tt indicies. len(idxs) == len(nrows) == len(ncols)
- nrows,ncols (tuple,int) – dimensions of matrices
Returns: (rowidxs,colidxs) = ((i_1,..,i_d),(j_1,..,j_d)) indices in the matrix indexing
-
TensorToolbox.core.
maxvol
(A, delta=0.01, maxit=100)[source]¶ Find the rxr submatrix of maximal volume in A(nxr), n>=r
Parameters: Returns: (I,AsqInv,it)
whereI
is the list or rows of A forming the matrix with maximal volume,AsqInv
is the inverse of the matrix with maximal volume andit
is the number of iterations to convergenceRaises: raise exception if the dimension of A is r>n or if A is singular
Raises: ConvergenceError if convergence is not reached in maxit iterations
-
TensorToolbox.core.
lowrankapprox
(A, r, Jinit=None, delta=1e-05, maxit=100, maxvoleps=0.01, maxvolit=100)[source]¶ Given a matrix A nxm, find the maximum volume submatrix with rank r<n,m.
Parameters: - A (ndarray) – two dimensional array with dimension nxm
- r (int) – rank of the maxvol submatrix
- Jinit (list) – list of integers containing the r starting columns. If
None
then pick them randomly. - delta (float) – accuracy parameter
- maxit (int) – maximum number of iterations in the lowrankapprox routine
- maxvoleps (float) – accuracy parameter for each usage of the maxvol algorithm
Parma int maxvolit: maximum number of iterations in the maxvol routine
Returns: (I,J,AsqInv,it)
whereI
andJ
are the list of rows and columns of A that compose the submatrix of maximal volume,AsqInv
is the inverse of such matrix andit
is the number of iteration to convergence
-
TensorToolbox.core.
load
(filename, load_data=True)[source]¶ Used to load TensorToolbox data.
Parameters:
-
TensorToolbox.core.
ttcross_store
(path, TW, TTapp)[source]¶ Used to store the computed values of a TTcross approximation. Usually needed when the single function evaluation is demanding or when we need to restart TTcross later on.
Parameters: - path (string) – path pointing to the location where to store the data
- TW (TensorWrapper) – Tensor wrapper used to build the ttcross approximation. TW.get_data(), TW.get_X() and TW.get_params() will be stored.
- TTapp (TTvec) – TTcross approximation. TTapp.ttcross.Jinit will be stored.
Deprecated since version 0.3.0: Use the objects’ methods
store()
.
-
TensorToolbox.core.
to_v_0_3_0
(filename)[source]¶ Used to upgrade the storage version from version <0.3.0 to version 0.3.0
Parameters: filename (string) – path to the filename. This must be the main filename with no extension.
-
class
TensorToolbox.core.
TensorWrapper
(f, X, params=None, W=None, Q=None, twtype='array', data=None, dtype=<type 'object'>, store_file='', store_object=None, store_freq=None, store_overwrite=False, empty=False, maxprocs=None, marshal_f=True)[source]¶ A tensor wrapper is a data structure W that given a multi-dimensional scalar function f(X,params), and a set of coordinates {{x1}_i1,{x2}_i2,..,{xd}_id} indexed by the multi index {i1,..,id}, let you access f(x1_i1,..,xd_id) by W[i1,..,id]. The function evaluations are performed “as needed” and stored for future accesses.
Parameters: - f – multi-dimensional scalar function of type f(x,params), x being a list.
- X (list) – list of arrays with coordinates for each dimension
- params (tuple) – parameters to be passed to function f
- W (list) – list of arrays with weights for each dimension
- Q (int) – power to which round all the dimensions to.
- twtype (string) – ‘array’ values are stored whenever computed, ‘view’ values are never stored and function f is always called
- data (dict) – initialization data of the Tensor Wrapper (already computed entries)
- dtype (type) – type of output to be expected from f
- store_file (str) – file where to store the data
- store_object (object) – a storable object that must be stored in place of the TensorWrapper
- store_freq (bool) – how frequently to store the TensorWrapper (seconds)
- store_overwrite (bool) – whether to overwrite pre-existing files.
- empty (bool) – Creates an instance without initializing it. All the content can be initialized using the
setstate()
function. - maxprocs (int) – Number of processors to be used in the function evaluation (MPI)
- marshal_f (bool) – whether to marshal the function or not
-
fix_indices
(idxs, dims)[source]¶ Fix some of the indices in the tensor wrapper and reshape/resize it accordingly. The internal storage of the data is still done with respect to the global indices, but once some indices are fixed, the TensorWrapper can be accessed using just the remaining free indices.
Parameters:
-
get_full_ndim
()[source]¶ Always returns the ndim of the reshaped tensor tensor with no fixed indices
-
get_full_shape
()[source]¶ Always returns the shape of the reshaped tensor tensor with no fixed indices
-
get_full_size
()[source]¶ Always returns the size of the reshaped tensor tensor with no fixed indices
-
get_q_shape
()[source]¶ Always returns the shape of the tensor rounded to the next power of Q if Q!=None. Otherwise returns the shape of the underlying tensor.
-
global_to_q
(idxs)[source]¶ This operation is undefined because one global idx can point to many q indices
-
q_to_global
(idxs)[source]¶ This is a non-injective function from the q indices to the global indices
-
set_active_weights
(flag)[source]¶ Set whether to use the weights or not.
Parameters: flag (bool) – If True
the items returned by the Tensor Wrapper will be weighted according to the weights provided at construction time. IfFalse
the original values of the function will be returned.
-
class
TensorToolbox.core.
TTvec
(A, store_location='', store_object=None, store_freq=1, store_overwrite=False, multidim_point=None)[source]¶ Constructor of multidimensional tensor in Tensor Train format [1]_
Parameters: - A (Candecomp,ndarray,TT,TensorWrapper) – Available input formats are Candecomp, full tensor in numpy.ndarray, Tensor Train structure (list of cores), or a Tensor Wrapper.
- store_location (string) – Store computed values during construction on the specified file path. The stored values are ttcross_Jinit and the values used in the TensorWrapper. This permits a restart from already computed values. If empty string nothing is done. (method==’ttcross’)
- store_object (string) – Object to be stored (default are the tensor wrapper and ttcross_Jinit)
- store_freq (int) – storage frequency.
store_freq==1
stores intermediate values at every iteration. The program stores data everystore_freq
internal iterations. Ifstore_object
is a SpectralTensorTrain, thenstore_freq
determines the number of seconds every which to store values. - multidim_point (int) – If the object A returns a multidimensional array, then this can be used to define which point to apply ttcross to.
[1] Oseledets, I. (2011). Tensor-train decomposition. SIAM Journal on Scientific Computing, 33(5), 2295–2317. Retrieved from http://epubs.siam.org/doi/pdf/10.1137/090752286 [2] Oseledets, I., and Tyrtyshnikov, E. (2010). TT-cross approximation for multidimensional arrays. Linear Algebra and Its Applications, 432(1), 70-88. doi:10.1016/j.laa.2009.07.024 [3] Savostyanov, D., and Oseledets, I. (2011). Fast adaptive interpolation of multi-dimensional arrays in tensor train format. The 2011 International Workshop on Multidimensional (nD) Systems, 1–8. doi:10.1109/nDS.2011.6076873 [4] Savostyanov, D. (2013). Quasioptimality of maximum-volume cross interpolation of tensors. arXiv Preprint arXiv:1305.1818, c, 1–23. Retrieved from http://arxiv.org/abs/1305.1818 -
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None)[source]¶ Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
get_data_F_norm
()[source]¶ Used to get the Frobeniuos norm of the underlying data. This needs to be redefined in QTTvec in order to get the Frobeniuous norm of the real tensor.
-
get_ttdmrg_real_subtensor
(C, idx)[source]¶ Used to get the real subtensor of the underlying data. This needs to be redefined in QTTvec in order to get the subtensor of the real tensor.
-
inner_ttcross
(rs, Jinit, delta, maxit, mv_eps, mv_maxit, store_init=True)[source]¶ Construct a TT representation of A using TT cross
Parameters:
-
interpolate
(Ms=None, eps=1e-08, is_sparse=None)[source]¶ Interpolates the values of the TTvec at arbitrary points, using the interpolation matrices ``Ms’‘.
Parameters: Returns: TTvec interpolation
Return type: TTvec
>>> from DABISpectralToolbox import DABISpectral1D as S1D >>> Ms = [ S1D.LinearInterpolationMatrix(X[i],XI[i]) for i in range(d) ] >>> is_sparse = [True]*d >>> TTapproxI = TTapprox.interpolate(Ms,eps=1e-8,is_sparse=is_sparse)
-
project
(Vs=None, Ws=None, eps=1e-08, is_sparse=None)[source]¶ Project the TTvec onto a set of basis provided, using the Generalized Vandermonde matrices ``Vs’’ and weights ``Ws’‘.
Parameters: - Vs (list) – list of generalized Vandermonde matrices for each dimension. Ms[i].shape[1] == self.shape()[i]
- Ws (list) – list of weights for each dimension. Ws[i].shape[0] == self.shape()[i]
- eps (float) – tolerance with which to perform the rounding after interpolation
- is_sparse (list) – is_sparse[i] is a bool indicating whether Ms[i] is sparse or not. If ‘None’ all matrices are non sparse
Returns: TTvec containting the Fourier coefficients
Return type: TTvec
>>> from DABISpectralToolbox import DABISpectral1D as S1D >>> P = S1D.Poly1D(S1D.JACOBI,(0,0)) >>> x,w = S1D.Quadrature(10,S1D.GAUSS) >>> X = [x]*d >>> W = [w]*d >>> # Compute here the TTapprox at points X >>> TTapprox = TTvec(....) >>> # Project >>> Vs = [ P.GradVandermonde1D(x,10,0,norm=False) ] * d >>> is_sparse = [False]*d >>> TTfourier = TTapprox.project(Vs,W,eps=1e-8,is_sparse=is_sparse)
-
ttcross
(eps, rs, Jinit, delta, maxit, mv_eps, mv_maxit, fix_rank=False)[source]¶ Construct a TT representation of A using TT cross. This routine manage the outer loops for incremental ttcross or passes everything to ttcross if rs are specified.
Parameters: - eps (float) – tolerance with which to perform the TT-rounding and check the rank accuracy
- rs (list) – list of upper ranks (A.ndim)
- Jinit (list) – list (A.ndim-1) of lists of init indices
- delta (float) – TT-cross accuracy
- maxit (int) – maximum number of iterations for ttcross
- mv_eps (float) – MaxVol accuracy
- mv_maxit (int) – maximum number of iterations for MaxVol
- fix_rank (bool) – Whether the rank is allowed to increase
-
ttdmrg
(eps, Jinit, maxit, mv_eps, mv_maxit, kickrank=None, cross=False, store_init=True, loop_detection=False)[source]¶ Construct a TT representation of A using TT-Density matrix renormalization group
Parameters: - eps (float) – Frobenious tolerance of the approximation
- Jinit (list) – listo (A.ndim-1) of lists of init indices
- maxit (int) – maximum number of iterations of the ttdmrg
- mv_eps (float) – MaxVol accuracy
- mv_maxit (int) – maximum number of iterations for MaxVol
- kickrank (int) – rank overshooting
- cross (bool) – if True it uses ttcross for the supercores. If False it uses plain SVD.
- store_init (bool) – whether to store the initial indices used (restarting from the same indices will lead to the same construction).
- loop_detection (bool) – whether to check for loops. (Never occurred that we needed it)
-
ttdmrgcross
(eps, Jinit, maxit, mv_eps, mv_maxit, kickrank=None, store_init=True, loop_detection=False)[source]¶ Construct a TT representation of A using TT-Density matrix renormalization group
Parameters: - eps (float) – Frobenious tolerance of the approximation
- Jinit (list) – listo (A.ndim-1) of lists of init indices
- maxit (int) – maximum number of iterations of the ttdmrg
- mv_eps (float) – MaxVol accuracy
- mv_maxit (int) – maximum number of iterations for MaxVol
- kickrank (int) – rank overshooting
- cross (bool) – if True it uses ttcross for the supercores. If False it uses plain SVD.
- store_init (bool) – whether to store the initial indices used (restarting from the same indices will lead to the same construction).
- loop_detection (bool) – whether to check for loops. (Never occurred that we needed it)
-
TensorToolbox.core.
randvec
(d, N)[source]¶ Returns the rank-1 multidimensional random vector in Tensor Train format
- Args:
- d (int): number of dimensions N (int or list): If int then uniform sizes are used for all the dimensions, if list of int then len(N) == d and each dimension will use different size
- Returns:
- TTvec The rank-1 multidim random vector in Tensor Train format
-
TensorToolbox.core.
zerosvec
(d, N)[source]¶ Returns the rank-1 multidimensional vector of zeros in Tensor Train format
- Args:
- d (int): number of dimensions N (int or list): If int then uniform sizes are used for all the dimensions, if list of int then len(N) == d and each dimension will use different size
- Returns:
- TTvec The rank-1 multidim vector of zeros in Tensor Train format
-
class
TensorToolbox.core.
WTTvec
(A, W, store_location='', store_object=None, store_freq=1, store_overwrite=False, multidim_point=None)[source]¶ Constructor of multidimensional tensor in Weighted Tensor Train format [1]_
Parameters: - A (Candecomp,ndarray,TT,TensorWrapper) – Available input formats are Candecomp, full tensor in numpy.ndarray, Tensor Train structure (list of cores), or a Tensor Wrapper.
- W (list) – list of 1-dimensional ndarray containing the weights for each dimension.
- store_location (string) – Store computed values during construction on the specified file path. The stored values are ttcross_Jinit and the values used in the TensorWrapper. This permits a restart from already computed values. If empty string nothing is done. (method==’ttcross’)
- store_object (string) – Object to be stored (default are the tensor wrapper and ttcross_Jinit)
- store_freq (int) – storage frequency.
store_freq==1
stores intermediate values at every iteration. The program stores data everystore_freq
internal iterations. Ifstore_object
is a SpectralTensorTrain, thenstore_freq
determines the number of seconds every which to store values. - multidim_point (int) – If the object A returns a multidimensional array, then this can be used to define which point to apply ttcross to.
-
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None)[source]¶ Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
class
TensorToolbox.core.
TTmat
(A, nrows, ncols, is_sparse=None, sparse_ranks=None, store_location='', store_object=None, store_freq=1, store_overwrite=False)[source]¶ Constructor of multidimensional matrix in Tensor Train format
Parameters: - A (Candecomp,ndarray,TT) – Available input formats are Candecomp, full tensor in numpy.ndarray, Tensor Train structure (list of cores), list of sparse matrices of sizes (r_{i-1}*r_{i}*nrows x ncols) (used for fast dot product - limited support for other functionalities)
- nrows (list,int) – If int then the row size will be the same in all dimensions, if list then len(nrows) == len(self.TT) (numer of cores) and row size will change for each dimension.
- ncols (list,int) – If int then the column size will be the same in all dimensions, if list then len(ncols) == len(self.TT) (numer of cores) and column size will change for each dimension.
- is_sparse (bool) – [default == False] if True it uses sparsity to accelerate some computations
- sparse_ranks (list) – [default==None] mandatory argument when A is a list of sparse matrices. It contains integers listing the TT-ranks of the matrix.
Note
the method __getitem__ is not overwritten, thus the indices used to access the tensor refer to the flatten versions of the matrices composing the matrix tensor.
-
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=2)[source]¶ Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
TensorToolbox.core.
eye
(d, N)[source]¶ Returns the multidimensional identity operator in Tensor Train format
- Args:
- d (int): number of dimensions N (int or list): If int then uniform sizes are used for all the dimensions, if list of int then len(N) == d and each dimension will use different size
- Returns:
- TTmat The multidim identity matrix in Tensor Train format
- Note:
- TODO: improve construction avoiding passage through Candecomp
-
TensorToolbox.core.
randmat
(d, nrows, ncols)[source]¶ Returns the rank-1 multidimensional random matrix in Tensor Train format
- Args:
- d (int): number of dimensions nrows (int or list): If int then uniform sizes are used for all the dimensions, if list of int then len(nrows) == d and each dimension will use different size ncols (int or list): If int then uniform sizes are used for all the dimensions, if list of int then len(ncols) == d and each dimension will use different size
- Returns:
- TTmat The rank-1 multidim random matrix in Tensor Train format
-
class
TensorToolbox.core.
QTTvec
(A, global_shape=None, base=2, store_location='', store_object=None, store_freq=1, store_overwrite=False, multidim_point=None)[source]¶ Constructor of multidimensional tensor in Quantics Tensor Train format
Parameters: -
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None)[source]¶ Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
get_ttdmrg_real_subtensor
(C, idxs)[source]¶ Used to get the Frobeniuos norm of a subtensor of the underlying data.
Parameters: - C (np.ndarray) – Extracted 4-d tensor with shape len(l_idx) x n x m x len(r_idx)
- idxs (list) – List of tuples of the form (l_idx, slice, slice, r_idx)
Return np.ndarray Creal: 1-d array containing the filtered values belonging to the real tensor
-
interpolate
(Ms=None, eps=1e-08, is_sparse=None)[source]¶ Interpolates the values of the QTTvec at arbitrary points, using the interpolation matrices ``Ms’‘.
Parameters: - Ms (list) – list of interpolation matrices for each dimension. Ms[i].shape[1] == self.shape()[i]
- eps (float) – tolerance with which to perform the rounding after interpolation
- is_sparse (list) – is_sparse[i] is a bool indicating whether Ms[i] is sparse or not. If ‘None’ all matrices are non sparse [sparsity is not exploited]
Returns: QTTvec interpolation
Return type: QTTvec
>>> from DABISpectralToolbox import DABISpectral1D as S1D >>> Ms = [ S1D.LinearInterpolationMatrix(X[i],XI[i]) for i in range(d) ] >>> is_sparse = [True]*d >>> TTapproxI = TTapprox.interpolate(Ms,eps=1e-8,is_sparse=is_sparse)
-
project
(Vs=None, Ws=None, eps=1e-08, is_sparse=None)[source]¶ Project the QTTvec onto a set of basis provided, using the Generalized Vandermonde matrices ``Vs’’ and weights ``Ws’‘.
Parameters: - Vs (list) – list of generalized Vandermonde matrices for each dimension. Ms[i].shape[1] == self.shape()[i]
- Ws (list) – list of weights for each dimension. Ws[i].shape[0] == self.shape()[i]
- eps (float) – tolerance with which to perform the rounding after interpolation
- is_sparse (list) – is_sparse[i] is a bool indicating whether Ms[i] is sparse or not. If ‘None’ all matrices are non sparse [sparsity is not exploited]
Returns: TTvec containting the Fourier coefficients
Return type: TTvec
>>> from DABISpectralToolbox import DABISpectral1D as S1D >>> P = S1D.Poly1D(S1D.JACOBI,(0,0)) >>> x,w = S1D.Quadrature(10,S1D.GAUSS) >>> X = [x]*d >>> W = [w]*d >>> # Compute here the TTapprox at points X >>> TTapprox = QTTvec(....) >>> # Project >>> Vs = [ P.GradVandermonde1D(x,10,0,norm=False) ] * d >>> is_sparse = [False]*d >>> TTfourier = TTapprox.project(Vs,W,eps=1e-8,is_sparse=is_sparse)
-
-
TensorToolbox.core.
QTTzerosvec
(d, N, base)[source]¶ Returns the rank-1 multidimensional vector of zeros in Quantics Tensor Train format
- Args:
- d (int): number of dimensions N (int or list): If int then uniform sizes are used for all the dimensions, if list of int then len(N) == d and each dimension will use different size base (int): QTT base
- Returns:
- QTTvec The rank-1 multidim vector of zeros in Tensor Train format
-
class
TensorToolbox.core.
QTTmat
(A, base, nrows, ncols, is_sparse=None, store_location='', store_object=None, store_freq=1, store_overwrite=False)[source]¶ Constructor of multidimensional matrix in Quantics Tensor Train format
Parameters: - A (ndarray,TT) – Available input formats are full tensor in numpy.ndarray, Tensor Train structure (list of cores). If input is ndarray, then it must be in mattensor format (see aux.py)
- base (int) – folding base for QTT representation
- nrows (int) – If int then the row size will be the same in all dimensions, if list then len(nrows) == len(self.TT) (numer of cores) and row size will change for each dimension.
- ncols (int) – If int then the column size will be the same in all dimensions, if list then len(ncols) == len(self.TT) (numer of cores) and column size will change for each dimension.
-
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=2)[source]¶ Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
class
TensorToolbox.core.
STT
(f, grids, params, range_dim=0, marshal_f=True, surrogateONOFF=False, surrogate_type=None, orders=None, orderAdapt=None, eps=0.0001, method='ttdmrg', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None, store_location='', store_overwrite=False, store_freq=0)[source]¶ Constructor of the Spectral Tensor Train approximation. Given a function
f(x,theta,params):(Is, It) -> R
withdim(Is)=n
anddim(It)=d
, construct an approximation ofg(theta,params): It -> h_t(Is)
. For exampleIs
could be the discretization of a spatial dimension, andIt
some parameter space, so thatf(x,theta,params)
describes a scalar field depending some parameters that vary inIt
. Theparams
in the definition off
can be constants used by the function or othere objects that must be passed to the function definition.Parameters: - f (function) – multidimensional function to be approximated with format
f(x,theta,params)
- grids (list) – this is a list with
len(grids)=dim(Is)+dim(It)
which can contain: a) 1-dimensional numpy.array of points discretizing the i-th dimension, b) a tuple(PolyType,QuadType,PolyParams,span)
wherePolyType
is one of the polynomials available inSpectralToolbox.Spectral1D
andQuadType
is one of the quadrature rules associated to the selected polynomial andPolyParams
are the parameters for the selected polynomial.span
is a tuple defining the left and right end for dimension i (Example:(-3,np.inf)
) c) a tuple(QuadType,span)
whereQuadType
is one of the quadrature rules available inSpectralToolbox.Spectral1D
without the selection of a particular polynomial type, andspan
is defined as above. - params (object) – any list of parameters to be passed to the function
f
- range_dim (int) – define the dimension of the spatial dimension
Is
. For functionalsf(theta,params)
,dim(Is)=0
. For scalar fileds in 3D,dim(Is)=3
. - marshal_f (bool) – whether to marshal the function f or not. For MPI support, the function f must be marshalable (does this adverb exists??).
- surrogateONOFF (bool) – whether to construct the surrogate or not
- surrogate_type (str) – whether the surrogate will be an interpolating surrogate (
TensorTrain.LINEAR_INTERPOLATION
orTensorTrain.LAGRANGE_INTERPOLATION
) or a projection surrogate (TensorTrain.PROJECTION
) - orders (list) – polynomial orders for each dimension if
TensorTrain.PROJECTION
is used. IforderAdapt==True
then theorders
are starting orders that can be increased as needed by the construction algorithm. If this parameter is not provided butorderAdapt==True
, then the starting order is 1 for all the dimensions. - orderAdapt (bool) – whether the order is fixed or not.
- stt_store_location (str) – path to a file where function evaluations can be stored and used in order to restart the construction.
- stt_store_overwrite (bool) – whether to overwrite pre-existing files
- stt_store_freq (int) – storage frequency. Determines every how many seconds the state is stored.
stt_store_freq==0
stores every time it is possible. - empty (bool) – Creates an instance without initializing it. All the content can be initialized using the
setstate()
function.
Note
For a description of the remaining parameters see
TTvec
.-
__call__
(x_in, verbose=False)[source]¶ Evaluate the surrogate on points
x_in
Parameters: x_in (np.ndarray) – 1 or 2 dimensional array of points in the parameter space where to evaluate the function. In 2 dimensions, each row is an entry, i.e. x_in.shape[1] == self.param_dim
Returns: an array with dimension equal to the space dimension ( range_dim
) plus one. IfA
is the returned vector andrange_dim=2
, thenA[i,:,:]
is the value of the surrogate forx_in[i,:]
- f (function) – multidimensional function to be approximated with format
-
class
TensorToolbox.core.
SQTT
(f, grids, params, range_dim=0, marshal_f=True, base=2, surrogateONOFF=False, surrogate_type=None, orders=None, orderAdapt=None, eps=0.0001, method='ttdmrg', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None, store_location='', store_overwrite=False, store_freq=0)[source]¶ Constructor of the Spectral Quantics Tensor Train approximation. Given a function
f(x,theta,params):(Is, It) -> R
withdim(Is)=n
anddim(It)=d
, construct an approximation ofg(theta,params): It -> h_t(Is)
. For exampleIs
could be the discretization of a spatial dimension, andIt
some parameter space, so thatf(x,theta,params)
describes a scalar field depending some parameters that vary inIt
. Theparams
in the definition off
can be constants used by the function or othere objects that must be passed to the function definition.Parameters: - f (function) – multidimensional function to be approximated with format
f(x,theta,params)
- grids (list) – this is a list with
len(grids)=dim(Is)+dim(It)
which can contain: a) 1-dimensional numpy.array of points discretizing the i-th dimension, b) a tuple(PolyType,QuadType,PolyParams,span)
wherePolyType
is one of the polynomials available inSpectralToolbox.Spectral1D
andQuadType
is one of the quadrature rules associated to the selected polynomial andPolyParams
are the parameters for the selected polynomial.span
is a tuple defining the left and right end for dimension i (Example:(-3,np.inf)
) c) a tuple(QuadType,span)
whereQuadType
is one of the quadrature rules available inSpectralToolbox.Spectral1D
without the selection of a particular polynomial type, andspan
is defined as above. - params (object) – any list of parameters to be passed to the function
f
- range_dim (int) – define the dimension of the spatial dimension
Is
. For functionalsf(theta,params)
,dim(Is)=0
. For scalar fileds in 3D,dim(Is)=3
. - marshal_f (bool) – whether to marshal the function f or not. For MPI support, the function f must be marshalable (does this adverb exists??).
- base (int) –
base
parameter for Quantics Tensor Train - surrogateONOFF (bool) – whether to construct the surrogate or not
- surrogate_type (str) – whether the surrogate will be an interpolating surrogate (
TensorTrain.LINEAR_INTERPOLATION
orTensorTrain.LAGRANGE_INTERPOLATION
) or a projection surrogate (TensorTrain.PROJECTION
) - orders (list) – polynomial orders for each dimension if
TensorTrain.PROJECTION
is used. IforderAdapt==True
then theorders
are starting orders that can be increased as needed by the construction algorithm. If this parameter is not provided butorderAdapt==True
, then the starting order is 1 for all the dimensions. - orderAdapt (bool) – whether the order is fixed or not.
- stt_store_location (str) – path to a file where function evaluations can be stored and used in order to restart the construction.
- stt_store_overwrite (bool) – whether to overwrite pre-existing files
- stt_store_freq (int) – storage frequency. Determines every how many seconds the state is stored.
stt_store_freq==0
stores every time it is possible. - empty (bool) – Creates an instance without initializing it. All the content can be initialized using the
setstate()
function.
Note
For a description of the remaining parameters see
TTvec
.-
__getitem__
()¶
-
__call__
(x_in, verbose=False)¶ Evaluate the surrogate on points
x_in
Parameters: x_in (np.ndarray) – 1 or 2 dimensional array of points in the parameter space where to evaluate the function. In 2 dimensions, each row is an entry, i.e. x_in.shape[1] == self.param_dim
Returns: an array with dimension equal to the space dimension ( range_dim
) plus one. IfA
is the returned vector andrange_dim=2
, thenA[i,:,:]
is the value of the surrogate forx_in[i,:]
- f (function) – multidimensional function to be approximated with format
-
class
TensorToolbox.core.
TTvec
(A, store_location='', store_object=None, store_freq=1, store_overwrite=False, multidim_point=None)[source] Constructor of multidimensional tensor in Tensor Train format [1]_
Parameters: - A (Candecomp,ndarray,TT,TensorWrapper) – Available input formats are Candecomp, full tensor in numpy.ndarray, Tensor Train structure (list of cores), or a Tensor Wrapper.
- store_location (string) – Store computed values during construction on the specified file path. The stored values are ttcross_Jinit and the values used in the TensorWrapper. This permits a restart from already computed values. If empty string nothing is done. (method==’ttcross’)
- store_object (string) – Object to be stored (default are the tensor wrapper and ttcross_Jinit)
- store_freq (int) – storage frequency.
store_freq==1
stores intermediate values at every iteration. The program stores data everystore_freq
internal iterations. Ifstore_object
is a SpectralTensorTrain, thenstore_freq
determines the number of seconds every which to store values. - multidim_point (int) – If the object A returns a multidimensional array, then this can be used to define which point to apply ttcross to.
[1] Oseledets, I. (2011). Tensor-train decomposition. SIAM Journal on Scientific Computing, 33(5), 2295–2317. Retrieved from http://epubs.siam.org/doi/pdf/10.1137/090752286 [2] Oseledets, I., and Tyrtyshnikov, E. (2010). TT-cross approximation for multidimensional arrays. Linear Algebra and Its Applications, 432(1), 70-88. doi:10.1016/j.laa.2009.07.024 [3] Savostyanov, D., and Oseledets, I. (2011). Fast adaptive interpolation of multi-dimensional arrays in tensor train format. The 2011 International Workshop on Multidimensional (nD) Systems, 1–8. doi:10.1109/nDS.2011.6076873 [4] Savostyanov, D. (2013). Quasioptimality of maximum-volume cross interpolation of tensors. arXiv Preprint arXiv:1305.1818, c, 1–23. Retrieved from http://arxiv.org/abs/1305.1818 -
__getitem__
(idxs)[source]
-
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None)[source] Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
get_data_F_norm
()[source] Used to get the Frobeniuos norm of the underlying data. This needs to be redefined in QTTvec in order to get the Frobeniuous norm of the real tensor.
-
get_ttdmrg_real_subtensor
(C, idx)[source] Used to get the real subtensor of the underlying data. This needs to be redefined in QTTvec in order to get the subtensor of the real tensor.
-
inner_ttcross
(rs, Jinit, delta, maxit, mv_eps, mv_maxit, store_init=True)[source] Construct a TT representation of A using TT cross
Parameters:
-
interpolate
(Ms=None, eps=1e-08, is_sparse=None)[source] Interpolates the values of the TTvec at arbitrary points, using the interpolation matrices ``Ms’‘.
Parameters: Returns: TTvec interpolation
Return type: TTvec
>>> from DABISpectralToolbox import DABISpectral1D as S1D >>> Ms = [ S1D.LinearInterpolationMatrix(X[i],XI[i]) for i in range(d) ] >>> is_sparse = [True]*d >>> TTapproxI = TTapprox.interpolate(Ms,eps=1e-8,is_sparse=is_sparse)
-
project
(Vs=None, Ws=None, eps=1e-08, is_sparse=None)[source] Project the TTvec onto a set of basis provided, using the Generalized Vandermonde matrices ``Vs’’ and weights ``Ws’‘.
Parameters: - Vs (list) – list of generalized Vandermonde matrices for each dimension. Ms[i].shape[1] == self.shape()[i]
- Ws (list) – list of weights for each dimension. Ws[i].shape[0] == self.shape()[i]
- eps (float) – tolerance with which to perform the rounding after interpolation
- is_sparse (list) – is_sparse[i] is a bool indicating whether Ms[i] is sparse or not. If ‘None’ all matrices are non sparse
Returns: TTvec containting the Fourier coefficients
Return type: TTvec
>>> from DABISpectralToolbox import DABISpectral1D as S1D >>> P = S1D.Poly1D(S1D.JACOBI,(0,0)) >>> x,w = S1D.Quadrature(10,S1D.GAUSS) >>> X = [x]*d >>> W = [w]*d >>> # Compute here the TTapprox at points X >>> TTapprox = TTvec(....) >>> # Project >>> Vs = [ P.GradVandermonde1D(x,10,0,norm=False) ] * d >>> is_sparse = [False]*d >>> TTfourier = TTapprox.project(Vs,W,eps=1e-8,is_sparse=is_sparse)
-
rounding
(eps)[source] TT-rounding
-
rounding2
(eps)[source] TT-rounding
-
shape
()[source] Returns the shape of the tensor represented
-
ttcross
(eps, rs, Jinit, delta, maxit, mv_eps, mv_maxit, fix_rank=False)[source] Construct a TT representation of A using TT cross. This routine manage the outer loops for incremental ttcross or passes everything to ttcross if rs are specified.
Parameters: - eps (float) – tolerance with which to perform the TT-rounding and check the rank accuracy
- rs (list) – list of upper ranks (A.ndim)
- Jinit (list) – list (A.ndim-1) of lists of init indices
- delta (float) – TT-cross accuracy
- maxit (int) – maximum number of iterations for ttcross
- mv_eps (float) – MaxVol accuracy
- mv_maxit (int) – maximum number of iterations for MaxVol
- fix_rank (bool) – Whether the rank is allowed to increase
-
ttdmrg
(eps, Jinit, maxit, mv_eps, mv_maxit, kickrank=None, cross=False, store_init=True, loop_detection=False)[source] Construct a TT representation of A using TT-Density matrix renormalization group
Parameters: - eps (float) – Frobenious tolerance of the approximation
- Jinit (list) – listo (A.ndim-1) of lists of init indices
- maxit (int) – maximum number of iterations of the ttdmrg
- mv_eps (float) – MaxVol accuracy
- mv_maxit (int) – maximum number of iterations for MaxVol
- kickrank (int) – rank overshooting
- cross (bool) – if True it uses ttcross for the supercores. If False it uses plain SVD.
- store_init (bool) – whether to store the initial indices used (restarting from the same indices will lead to the same construction).
- loop_detection (bool) – whether to check for loops. (Never occurred that we needed it)
-
ttdmrgcross
(eps, Jinit, maxit, mv_eps, mv_maxit, kickrank=None, store_init=True, loop_detection=False)[source] Construct a TT representation of A using TT-Density matrix renormalization group
Parameters: - eps (float) – Frobenious tolerance of the approximation
- Jinit (list) – listo (A.ndim-1) of lists of init indices
- maxit (int) – maximum number of iterations of the ttdmrg
- mv_eps (float) – MaxVol accuracy
- mv_maxit (int) – maximum number of iterations for MaxVol
- kickrank (int) – rank overshooting
- cross (bool) – if True it uses ttcross for the supercores. If False it uses plain SVD.
- store_init (bool) – whether to store the initial indices used (restarting from the same indices will lead to the same construction).
- loop_detection (bool) – whether to check for loops. (Never occurred that we needed it)
-
class
TensorToolbox.core.
TTmat
(A, nrows, ncols, is_sparse=None, sparse_ranks=None, store_location='', store_object=None, store_freq=1, store_overwrite=False)[source] Constructor of multidimensional matrix in Tensor Train format
Parameters: - A (Candecomp,ndarray,TT) – Available input formats are Candecomp, full tensor in numpy.ndarray, Tensor Train structure (list of cores), list of sparse matrices of sizes (r_{i-1}*r_{i}*nrows x ncols) (used for fast dot product - limited support for other functionalities)
- nrows (list,int) – If int then the row size will be the same in all dimensions, if list then len(nrows) == len(self.TT) (numer of cores) and row size will change for each dimension.
- ncols (list,int) – If int then the column size will be the same in all dimensions, if list then len(ncols) == len(self.TT) (numer of cores) and column size will change for each dimension.
- is_sparse (bool) – [default == False] if True it uses sparsity to accelerate some computations
- sparse_ranks (list) – [default==None] mandatory argument when A is a list of sparse matrices. It contains integers listing the TT-ranks of the matrix.
Note
the method __getitem__ is not overwritten, thus the indices used to access the tensor refer to the flatten versions of the matrices composing the matrix tensor.
-
build
(eps=1e-10, method='svd', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=2)[source] Common interface for the construction of the approximation.
Parameters: - eps (float) – [default == 1e-10] For method==’svd’: precision with which to approximate the input tensor. For method==’ttcross’: TT-rounding tolerance for rank-check.
- method (string) – ‘svd’ use singular value decomposition to construct the TT representation [1]_, ‘ttcross’ use low rank skeleton approximation to construct the TT representation [2]_, ‘ttdmrg’ uses Tensor Train Renormalization Cross to construct the TT representation [3]_ [4]_, ‘ttdmrgcross’ uses ‘ttdmrg’ with ‘ttcross’ approximation of supercores
- rs (list) – list of integer ranks of different cores. If
None
then the incremental TTcross approach will be used. (method==’ttcross’) - fix_rank (bool) – determines whether the rank is allowed to be increased (method==’ttcross’)
- Jinit (list) – list of list of integers containing the r starting columns in the lowrankapprox routine for each core. If
None
then pick them randomly. (method==’ttcross’) - delta (float) – accuracy parameter in the TT-cross routine (method==’ttcross’). It is the relative error in Frobenious norm between two successive iterations.
- maxit (int) – maximum number of iterations in the lowrankapprox routine (method==’ttcross’)
- mv_eps (float) – accuracy parameter for each usage of the maxvol algorithm (method==’ttcross’)
- mv_maxit (int) – maximum number of iterations in the maxvol routine (method==’ttcross’)
- fix_rank – Whether the rank is allowed to increase
- kickrank (int) – rank overshooting for ‘ttdmrg’
-
class
TensorToolbox.core.
STT
(f, grids, params, range_dim=0, marshal_f=True, surrogateONOFF=False, surrogate_type=None, orders=None, orderAdapt=None, eps=0.0001, method='ttdmrg', rs=None, fix_rank=False, Jinit=None, delta=0.0001, maxit=100, mv_eps=1e-06, mv_maxit=100, kickrank=None, store_location='', store_overwrite=False, store_freq=0)[source] Constructor of the Spectral Tensor Train approximation. Given a function
f(x,theta,params):(Is, It) -> R
withdim(Is)=n
anddim(It)=d
, construct an approximation ofg(theta,params): It -> h_t(Is)
. For exampleIs
could be the discretization of a spatial dimension, andIt
some parameter space, so thatf(x,theta,params)
describes a scalar field depending some parameters that vary inIt
. Theparams
in the definition off
can be constants used by the function or othere objects that must be passed to the function definition.Parameters: - f (function) – multidimensional function to be approximated with format
f(x,theta,params)
- grids (list) – this is a list with
len(grids)=dim(Is)+dim(It)
which can contain: a) 1-dimensional numpy.array of points discretizing the i-th dimension, b) a tuple(PolyType,QuadType,PolyParams,span)
wherePolyType
is one of the polynomials available inSpectralToolbox.Spectral1D
andQuadType
is one of the quadrature rules associated to the selected polynomial andPolyParams
are the parameters for the selected polynomial.span
is a tuple defining the left and right end for dimension i (Example:(-3,np.inf)
) c) a tuple(QuadType,span)
whereQuadType
is one of the quadrature rules available inSpectralToolbox.Spectral1D
without the selection of a particular polynomial type, andspan
is defined as above. - params (object) – any list of parameters to be passed to the function
f
- range_dim (int) – define the dimension of the spatial dimension
Is
. For functionalsf(theta,params)
,dim(Is)=0
. For scalar fileds in 3D,dim(Is)=3
. - marshal_f (bool) – whether to marshal the function f or not. For MPI support, the function f must be marshalable (does this adverb exists??).
- surrogateONOFF (bool) – whether to construct the surrogate or not
- surrogate_type (str) – whether the surrogate will be an interpolating surrogate (
TensorTrain.LINEAR_INTERPOLATION
orTensorTrain.LAGRANGE_INTERPOLATION
) or a projection surrogate (TensorTrain.PROJECTION
) - orders (list) – polynomial orders for each dimension if
TensorTrain.PROJECTION
is used. IforderAdapt==True
then theorders
are starting orders that can be increased as needed by the construction algorithm. If this parameter is not provided butorderAdapt==True
, then the starting order is 1 for all the dimensions. - orderAdapt (bool) – whether the order is fixed or not.
- stt_store_location (str) – path to a file where function evaluations can be stored and used in order to restart the construction.
- stt_store_overwrite (bool) – whether to overwrite pre-existing files
- stt_store_freq (int) – storage frequency. Determines every how many seconds the state is stored.
stt_store_freq==0
stores every time it is possible. - empty (bool) – Creates an instance without initializing it. All the content can be initialized using the
setstate()
function.
Note
For a description of the remaining parameters see
TTvec
.-
__getitem__
()[source]
-
__call__
(x_in, verbose=False)[source] Evaluate the surrogate on points
x_in
Parameters: x_in (np.ndarray) – 1 or 2 dimensional array of points in the parameter space where to evaluate the function. In 2 dimensions, each row is an entry, i.e. x_in.shape[1] == self.param_dim
Returns: an array with dimension equal to the space dimension ( range_dim
) plus one. IfA
is the returned vector andrange_dim=2
, thenA[i,:,:]
is the value of the surrogate forx_in[i,:]
-
integrate
()[source] Compute the integral of the approximated function
Returns: an array with dimension equal to the space dimension ( range_dim
), containing the value of the integral.
-
prepare_TTapprox
(force_redo=False)[source] Prepares the TTapprox from the generic_approx
- f (function) – multidimensional function to be approximated with format
-
TensorToolbox.multilinalg.
mul
(A, B)[source]¶ - If A,B are TTvec/TTmat -> Hadamard product of two TT tensors
- If A TTvec/TTmat and B scalar -> multiplication by scalar
-
TensorToolbox.multilinalg.
kron
(A, B)[source]¶ Kron product between two tensors in TT format. Complexity: O(1)
-
TensorToolbox.multilinalg.
contraction
(A, U)[source]¶ Multidimensional contraction of tensor A with vectors in list U. Complexity: O(dnr^2)
- Syntax:
W = contraction(A,U)
Parameters: - A – Tensor in some form
- U – list of vectors of dimensions n_k for performing the contraction
-
TensorToolbox.multilinalg.
norm
(A, ord='fro', round_eps=1e-10, eps=0.0001, maxit=1000, pow_guess=None, info=False)[source]¶ Compute the norm of tensor A.
- Syntax:
w = norm(A,[ord])
Parameters: - A – Tensor in some form
- ord – Specifies the type of norm that needs to be computed. Available norms are: the Frobenius norm: ‘fro’. If the input tensor is a WeightedTensorTrainVec, then this takes the Frobenious norm of the weighted TT, i.e. the continuos norm defined by the weights.
-
TensorToolbox.multilinalg.
sd
(A, b, x0=None, eps=1e-08, maxit=1000, eps_round=1e-10, ext_info=False)[source]¶ Solves the system \(Ax=b\) using the Steepest Descent method in Tensor Train format.
Parameters: - A (TTmat) – Tensor train matrix
- b (TTvec/ndarray) – Right hand side
- x0 (TTvec/ndarray) – [default ==
TensorToolbox.core.zerosvec()
] initial guess of solutionx
- eps (float) – [default == 1e-8] stop criteria
- maxit (int) – [default == 1000] maximum number of iterations
- eps_round (float) – [default == 1e-10] accuracy for Tensor Train rounding operations
- ext_info (bool) – [default == False] whehter of not to have additional info returned
Returns: tuple
(x,conv,info)
x
(TTvec): solution of the linear system if converged or last iterate if not convergedconv
(bool): True -> converged, False -> Not converged / Zero Inner Product execeptioninfo
(dict):iter
-> total number of iterations;r
-> last residual in TT format;res
-> residual history
-
TensorToolbox.multilinalg.
cg
(A, b, x0=None, eps=1e-08, maxit=1000, eps_round=1e-10, ext_info=False)[source]¶ Solves the system \(Ax=b\) using the Conjugate Gradient method in Tensor Train format.
Parameters: - A (TTmat) – Tensor train matrix
- b (TTvec/ndarray) – Right hand side
- x0 (TTvec/ndarray) – [default ==
TensorToolbox.core.zerosvec()
] initial guess of solutionx
- eps (float) – [default == 1e-8] stop criteria for Bi-CGSTAB iterations
- maxit (int) – [default == 1000] maximum number of iterations for Bi-CGSTAB
- eps_round (float) – [default == 1e-10] accuracy for Tensor Train rounding operations
- ext_info (bool) – [default == False] whehter of not to have additional info returned
Returns: tuple
(x,conv,info)
x
(TTvec): solution of the linear system if converged or last iterate if not convergedconv
(bool): True -> converged, False -> Not converged / Zero Inner Product execeptioninfo
(dict):iter
-> total number of iterations;r
-> last residual in TT format;res
-> residual history
-
TensorToolbox.multilinalg.
bicgstab
(A, b, x0=None, eps=1e-08, maxit=1000, eps_round=1e-10, ext_info=False)[source]¶ Solves the system \(Ax=b\) using the Bi-Conjugate Gradient Stabilized method using Tensor Train format.
Parameters: - A (TTmat) – Tensor train matrix
- b (TTvec) – Right hand side
- x0 (TTvec) – [default ==
TensorToolbox.core.zerosvec()
] initial guess of solutionx
- eps (float) – [default == 1e-8] stop criteria for Bi-CGSTAB iterations
- maxit (int) – [default == 1000] maximum number of iterations for Bi-CGSTAB
- eps_round (float) – [default == 1e-10] accuracy for Tensor Train rounding operations
- ext_info (bool) – [default == False] whehter of not to have additional info returned
Returns: tuple
(x,conv,info)
x
(TTvec): solution of the linear system if converged or last iterate if not convergedconv
(bool): True -> converged, False -> Not converged / Zero Inner Product execeptioninfo
(dict):iter
-> total number of iterations;r
-> last residual in TT format;rho
-> last value of dot(r0,r) must be bigger than np.spacing(1);r0v
-> last value of dot(r0,v) must be bigger than np.spacing(1)
-
TensorToolbox.multilinalg.
gmres
(A, b, x0=None, eps=1e-08, maxit=1000, restart=1000, eps_round=1e-10, ext_info=False)[source]¶ Solves the system \(Ax=b\) using the Generalized Minimum Residual method with Modified Gram-Schmidt iterations using Tensor Train format.
Parameters: - A (TTmat) – Tensor train matrix
- b (TTvec) – Right hand side
- x0 (TTvec) – [default ==
TensorToolbox.core.zerosvec()
] initial guess of solutionx
- eps (float) – [default == 1e-8] stop criteria for GMRES iterations
- maxit (int) – [default == 1000] maximum number of iterations for GMRES
- restart (int) – [default == 1000] restart constant for GMRES (nothing is implemented to retain information, i.e. Hessemberg and Krylov space are reset)
- eps_round (float) – [default == 1e-10] accuracy for Tensor Train rounding operations
- ext_info (bool) – [default == False] whehter of not to have additional info returned
Returns: tuple
(x,conv,info)
x
(TTvec): solution of the linear system if converged or last iterate if not convergedconv
(bool): True -> converged, False -> Not converged / Zero Inner Product execeptioninfo
(dict):iter
-> total number of iterations;TT_r
-> last residual in TT format;res
-> norm of last residual;err
-> residual history per iteration
Note: not optimized for symmetric A