quimb.tensor.decomp¶
Functions for decomposing and projecting matrices, purely at the level of
arrays (rather than wrapped as Tensors). The includes the main entry point
array_split, which dispatches to a registered split driver based on the
method.
Attributes¶
Functions¶
|
Split a 2D array (or batch of 2D arrays) into left and right factors |
|
Compute the singular values of a 2D array without forming the full |
|
|
|
Parse the method and absorb options. Possibly resolve "auto" settings |
|
Automatically select method and absorb, convert defaults and settings to |
|
Based on split method and absorb mode, determine whether the left and |
|
Decorator to register functions which can decompose a matrix, and sets |
|
Decorator to register functions which can compute the singular values of |
|
|
|
Compute |
|
|
|
Right-multiplication a matrix by a vector representing a diagonal. |
|
|
|
Right-multiplication of a matrix by a vector representing an inverse |
|
|
|
Left-multiplication a matrix by a vector representing a diagonal. |
|
|
|
Left-multiplication of a matrix by a vector representing an inverse |
|
|
|
Get the 'sign' of |
|
|
|
|
|
|
|
|
|
Give full SVD decomposion result |
|
Singular value decomposition of raw 2d array |
|
Find the number of singular values to keep of |
|
Find the normalization constant for |
|
Accelerated version of |
|
Accelerated version of |
|
Numpy version of |
|
|
|
SVD-decomposition, but return singular values only. |
|
Compute an SVD from eigenvectors of the Gram matrix, |
|
Singular value decomposition of raw 2d array |
|
Compute an SVD from eigenvectors of the Gram matrix using Numba. |
|
SVD-split via eigen-decomposition, with optional dynamic truncation. |
|
|
|
Compute singular values from Gram matrix eigenvalues using Numba. |
|
Compute a low-rank SVD from random projections. Limit rank with |
|
|
|
|
|
SVD-like decomposition using hermitian eigen-decomposition, only works |
|
SVD-decomposition, using hermitian eigen-decomposition, only works if |
|
|
|
QR-decomposition, with stabilized R factor. |
|
|
|
|
|
|
|
|
|
|
|
Cholesky decomposition, only works if |
|
|
|
|
|
Compute QR or LQ factors from the Gram matrix using Cholesky. |
|
Compute QR or LQ factors. Try two passes of Cholesky QR for large, |
|
Choose the number of singular values to target. |
|
SVD-decomposition using iterative methods. Allows the |
|
SVD-decomposition using interpolative matrix random methods. Allows the |
|
|
|
SVD-decomposition using randomized methods (due to Halko). Allows the |
|
SVD-decomposition using iterative hermitian eigen decomp, thus assuming |
|
LU-decomposition with optional truncation. |
|
Polar decomposition of |
|
Polar decomposition of |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Perform isometrization using the QR decomposition. |
|
Perform isometrization using the SVD decomposition. |
|
Perform isometrization using anti-symmetric matrix exponentiation. |
|
Perform isometrization using an anti-symmetric Cayley transform. |
|
Perform isometrization explicitly using the modified Gram Schmidt |
|
Isometrize |
|
|
Generate an isometric (or unitary if square) / orthogonal matrix from |
|
Given the square, |
|
Compute the oblique projectors for two reduced factor matrices that |
|
Given 4D environment tensor of a bond, iteratively compute projectors |
Module Contents¶
- quimb.tensor.decomp.array_split(x, method='auto', absorb='auto', max_bond=None, cutoff='auto', cutoff_mode='rel', renorm=None, info=None, **kwargs)[source]¶
Split a 2D array (or batch of 2D arrays) into left and right factors (and possibly singular values) using a matrix decomposition. This is the main array-level entry point, dispatching to a registered split driver based on
method, withabsorbcontrolling the output form of the decomposition, andmax_bond,cutoffand others controlling static and dynamic truncation respectively.- Parameters:
x (array_like) – The array or batch of arrays to split, of shape
(..., m, n).method (str, optional) –
The decomposition method to use:
'auto': use the default method based onabsorband whether truncation is requested viamax_bondand/orcutoff.
The five main methods are:
'svd': full SVD, allowing all truncation options.'svd:eig': full SVD via eigendecomposition, allowing all truncation options. This can be faster than the standard SVD, but loses some precision.'svd:rand': low-rank SVD via randomized projection, allowing static and non-cumulative dynamic truncation.'qr': QR decomposition, by default left factor is isometric.'qr:cholesky': QR decomposition via Cholesky factorization, by default left factor is isometric. This can be faster than the standard QR, but can lose orthogonality.
These methods can skip work based on the factors requested by
absorb. Other methods are:'lq': LQ decomposition, right factor is isometric. Alias formethod='qr'withabsorb='left'.'qr:auto': try two passes of Cholesky QR for large, tall, narrow matrices. Use'qr'for other shapes, if Cholesky QR fails, or if it loses too much orthogonality.'eigh': full eigen-decomposition, array must be hermitian.'eigsh': iterative eigen-decomposition, array must be hermitian.'svds': iterative SVD, allows truncation.'isvd': iterative SVD using interpolative methods, allows truncation (seescipy.linalg.interpolative).'rsvd': randomized iterative SVD with truncation (alternative implementation).'lu': full LU decomposition, allows truncation. Favors sparsity but is not rank optimal.'polar_right': polar decomposition asA = U @ P.'polar_left': polar decomposition asA = P @ U.'cholesky': cholesky decomposition, array must be positive definite.
absorb (str or None, optional) –
Which factors to return and where to absorb singular or eigenvalues. Common options are:
'auto': use the method’s default absorb mode.'both'/'Usq,sqVH': absorbsqrt(s)into both factors.'left'/'Us,VH': absorbsinto the left factor, leaving the right factor isometric (LQ-like).'right'/'U,sVH': absorbsinto the right factor, leaving the left factor isometric (QR-like).None/'U,s,VH': returnsunabsorbed.
Additional options for returning partial results (e.g. only one factor, unrequested factors returned as
None):'lorthog'/'U': return only the left isometric factor.'rorthog'/'VH': return only the right isometric factor.'lfactor'/'Us': return only the left factor withsabsorbed (the L in an LQ decomposition).'rfactor'/'sVH': return only the right factor withsabsorbed (the R in a QR decomposition).'s': return only the singular values.
Unrequested factors are returned as
None.max_bond (int or None, optional) – The maximum bond dimension (number of singular values) to keep.
Nonemeans no limit.cutoff (float or "auto", optional) – Threshold for discarding singular values, only used by methods that support dynamic truncation. With
"auto", use1e-10for exact rank-revealing methods and no cutoff for randomized SVD.cutoff_mode ({"rel", "rsum2", "rsum1", "abs", "sum2", "sum1"}, optional) –
How to interpret
cutoffwhen discarding singular values:'rel': values less thancutoff * s[0]discarded.'rsum2': sum squared of values discarded must be less thancutofftimes the total sum of squared values.'rsum1': sum of values discarded must be less thancutofftimes the total sum of values.'abs': values less thancutoffdiscarded.'sum2': sum squared of values discarded must be< cutoff.'sum1': sum values discarded must be< cutoff.
For batched arrays,
'abs'and'rel'use one threshold and retain the smallest common bond dimension that keeps every required singular value. Cumulative modes are not supported for batched arrays.renorm (int or bool, optional) – Whether to renormalize the kept singular values to maintain the Frobenius or nuclear norm.
0orFalsemeans no renormalization.Trueuses power 1 forsum1/rsum1and power 2 otherwise.info (dict or None, optional) – If a dict is passed, store truncation info in the dict. Currently only supports the key ‘error’ for the truncation error, which is only computed if
method in {"svd", "svd:eig"}.**kwargs – Additional keyword arguments passed to the underlying split driver.
- Returns:
left (array or None) – The left factor, or
Noneif not requested byabsorb.s (array or None) – The singular/eigen values, or
Noneif absorbed into the factors.right (array or None) – The right factor, or
Noneif not requested byabsorb.
- quimb.tensor.decomp.array_svals(x, method='svd', **kwargs)[source]¶
Compute the singular values of a 2D array without forming the full decomposition, using a registered singular value driver.
- Parameters:
x (array_like) – The 2D array whose singular values to compute.
method (str, optional) – The method to use. Must have a registered singular value driver (e.g.
'svd'or'svd:eig').**kwargs – Additional keyword arguments passed to the underlying driver.
- Returns:
s – The singular values in descending order.
- Return type:
- quimb.tensor.decomp.get_U_s_VH = None¶
- quimb.tensor.decomp.get_s = 2¶
- quimb.tensor.decomp.get_Usq = -12¶
- quimb.tensor.decomp.get_VH = -11¶
- quimb.tensor.decomp.get_Us = -10¶
- quimb.tensor.decomp.get_Us_VH = -1¶
- quimb.tensor.decomp.get_Usq_sqVH = 0¶
- quimb.tensor.decomp.get_U_sVH = 1¶
- quimb.tensor.decomp.get_U = 10¶
- quimb.tensor.decomp.get_sVH = 11¶
- quimb.tensor.decomp.get_sqVH = 12¶
- quimb.tensor.decomp._ABSORB_MAP¶
- quimb.tensor.decomp._ABSORB_TRANSPOSE_MAP¶
- quimb.tensor.decomp._RETURNS_LEFT_ABSORBS¶
- quimb.tensor.decomp._RETURNS_RIGHT_ABSORBS¶
- quimb.tensor.decomp.cutoff_mode_abs = 1¶
- quimb.tensor.decomp.cutoff_mode_rel = 2¶
- quimb.tensor.decomp.cutoff_mode_sum2 = 3¶
- quimb.tensor.decomp.cutoff_mode_rsum2 = 4¶
- quimb.tensor.decomp.cutoff_mode_sum1 = 5¶
- quimb.tensor.decomp.cutoff_mode_rsum1 = 6¶
- quimb.tensor.decomp._CUTOFF_MODE_MAP¶
- quimb.tensor.decomp._MAX_BOND_LOOKUP¶
- quimb.tensor.decomp._CUTOFF_LOOKUP¶
- quimb.tensor.decomp._RENORM_LOOKUP¶
- quimb.tensor.decomp.parse_method_absorb(method='auto', absorb='auto', truncation=True)[source]¶
Parse the method and absorb options. Possibly resolve “auto” settings to defaults, and convert from string aliases to numeric codes.
- quimb.tensor.decomp.parse_split_opts(method='auto', absorb='auto', max_bond=None, cutoff='auto', cutoff_mode='rel', renorm=None)[source]¶
Automatically select method and absorb, convert defaults and settings to numeric type for numba, and only supply valid options for given method.
- quimb.tensor.decomp.parse_split_left_right_isom(method='auto', absorb='auto')[source]¶
Based on split method and absorb mode, determine whether the left and right factors are isometric, and can be marked as such.
- quimb.tensor.decomp._SPLIT_FNS¶
- quimb.tensor.decomp._SPLIT_VALUES_FNS¶
- quimb.tensor.decomp._DENSE_ONLY_METHODS¶
- quimb.tensor.decomp._DEFAULT_ABSORB¶
- quimb.tensor.decomp.register_split_driver(name, sparse=False, default_absorb=get_Usq_sqVH)[source]¶
Decorator to register functions which can decompose a matrix, and sets various flags specifying its capabilities and thus which options are valid to supply in
array_split.- Parameters:
name (str) – The name of the method, corresponding to the
methodargument ofarray_split.truncation ({"none", "static", "dynamic"}, optional) – Whether the method can handle truncation, and if so, whether it can only handle static truncation (i.e. max_bond) or dynamic truncation as well (i.e. cutoff and cutoff_mode).
sparse (bool, optional) – Whether the method can handle sparse arrays directly.
- quimb.tensor.decomp.register_svals_driver(name)[source]¶
Decorator to register functions which can compute the singular values of a matrix without computing the full decomposition, which is used in
array_svals.- Parameters:
name (str) – The name of the method, corresponding to the
methodargument ofarray_svals.
- quimb.tensor.decomp.safe_inverse(x, cutoff=None, power=1.0)[source]¶
Compute
x**-powerelementwise, damping entries at or belowcutoffso that (near) zeros map to zero rather than infinity. The damped formx / (x**(power + 1) + cutoff**(power + 1))is smooth, and thus gradient friendly, with a finite derivative at zero, and matchesx**-powerto relative accuracy(cutoff / x)**(power + 1).- Parameters:
x (array_like) – The values to invert, assumed non-negative, e.g. singular values. The last axis is the vector axis, any others are treated as batch dims.
cutoff (float or None, optional) – The scale below which to damp entries towards zero. If
None, takemax(x) * eps, the smallest scale resolvable given the largest entry.power (float, optional) – The (positive) power to invert to, e.g.
0.5for an inverse square root. Note the damping is always relative toxitself, notx**power.
- Return type:
array_like
- quimb.tensor.decomp.rdmul(x, d)[source]¶
Right-multiplication a matrix by a vector representing a diagonal.
- quimb.tensor.decomp.rddiv(x, d)[source]¶
Right-multiplication of a matrix by a vector representing an inverse diagonal.
- quimb.tensor.decomp.ldmul(d, x)[source]¶
Left-multiplication a matrix by a vector representing a diagonal.
- quimb.tensor.decomp.lddiv(d, x)[source]¶
Left-multiplication of a matrix by a vector representing an inverse diagonal.
- quimb.tensor.decomp.sgn(x)[source]¶
Get the ‘sign’ of
x, such thatx / sgn(x)is real and non-negative.
- quimb.tensor.decomp._trim_and_renorm_svd_result(U, s, VH, cutoff=-1.0, cutoff_mode=cutoff_mode_rsum2, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, use_abs=False, info=None, xp=None)[source]¶
Give full SVD decomposion result
U,s,VH, optionally trim, renormalize, and absorb the singular values. Seesvd_truncatedfor details.
- quimb.tensor.decomp.svd_truncated(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, info=None, **kwargs)[source]¶
Singular value decomposition of raw 2d array
x, with optional truncation based on max_bond and/or dynamically on cutoff.- Parameters:
x (array_like) – The 2D array or batch of 2D arrays to decompose.
cutoff (float, optional) – Singular value cutoff threshold, if
cutoff <= 0.0, then onlymax_bondis used.cutoff_mode ({1, 2, 3, 4, 5, 6}, optional) –
How to perform the truncation based on
cutoff:1 / ‘abs’: trim values below
cutoff2 / ‘rel’: trim values below
s[0] * cutoff3 / ‘sum2’: trim s.t.
sum(s_trim**2) < cutoff.4 / ‘rsum2’: trim s.t.
sum(s_trim**2) < sum(s**2) * cutoff.5 / ‘sum1’: trim s.t.
sum(s_trim**1) < cutoff.6 / ‘rsum1’: trim s.t.
sum(s_trim**1) < sum(s**1) * cutoff.
max_bond (int, optional) – An explicit maximum bond dimension, use -1 for none.
absorb (int or None, optional) – How to absorb the singular values, as a pre-converted numeric code (
get_Us_VH=-1: left,get_Usq_sqVH=0: both,get_U_sVH=1: right,None: return separately). Usearray_splitwith string aliases (e.g.'left','both','right',None) for a friendlier interface.renorm (int, optional) – Whether to renormalize the kept singular values.
0means no renormalization,1maintains the trace norm,2maintains the Frobenius norm.info (dict or None, optional) – If a dict is passed, store truncation info in the dict. Currently only supports the key ‘error’ for the truncation error.
- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp._compute_number_svals_to_keep_numba(s, cutoff, cutoff_mode)[source]¶
Find the number of singular values to keep of
sgivencutoffandcutoff_mode.
- quimb.tensor.decomp._compute_svals_renorm_factor_numba(s, n_chi, renorm)[source]¶
Find the normalization constant for
ssuch that the new sum squared of then_chilargest values equals the sum squared of all the old ones.
- quimb.tensor.decomp._trim_and_renorm_svd_result_numba(U, s, VH, cutoff, cutoff_mode, max_bond, absorb, renorm, use_abs=False, calc_error=False)[source]¶
Accelerated version of
_trim_and_renorm_svd_result.
- quimb.tensor.decomp.svd_truncated_numba(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, calc_error=False)[source]¶
Accelerated version of
svd_truncatedfor numpy arrays.
- quimb.tensor.decomp.svd_truncated_numpy(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, info=None)[source]¶
Numpy version of
svd_truncated, trying the accelerated version first, then falling back to the more stable scipy version.
- quimb.tensor.decomp.svd_truncated_lazy(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
- quimb.tensor.decomp.svd_via_eig(x, absorb=None, max_bond=-1, descending=True, right=None)[source]¶
Compute an SVD from eigenvectors of the Gram matrix,
xdag @ xorx @ xdag, wherexdagis the conjugate transpose ofx. Limit rank withmax_bond. Skip work based on the factors requested byabsorb.- Parameters:
x (array_like) – Input must have shape
(..., m, n).absorb (str or None, optional) –
Which factors to return and where to absorb singular values:
None/'U,s,VH': returnsas the middle element of the 3-tuple, unabsorbed.'both'/'Usq,sqVH': absorbsqrt(s)into both factors.'left'/'Us,VH': absorbsinto the left factor, leaving the right factor isometric (LQ-like).'right'/'U,sVH': absorbsinto the right factor, leaving the left factor isometric (QR-like).'lorthog'/'U': return only the left isometric factor.'rorthog'/'VH': return only the right isometric factor.'lfactor'/'Us': return only the left factor withsabsorbed (the L in an LQ decomposition).'rfactor'/'sVH': return only the right factor withsabsorbed (the R in a QR decomposition).'s': return only the singular values.
max_bond (int, optional) – Maximum number of singular values to keep. Use -1 for no limit.
descending (bool, optional) – Return singular values in descending order. Default is True.
right (bool, optional) – Use
xdag @ xif True, orx @ xdagif False. With None, choose the smaller Gram matrix. For square matrices, choose fromabsorb.
- Returns:
U (array or None) – Left singular vectors, possibly with
sabsorbed, orNoneif not requested.s (array or None) – Singular values, or
Noneif not requested.VH (array or None) – Right singular vectors, possibly with
sabsorbed, orNoneif not requested.
- quimb.tensor.decomp.svd_via_eig_truncated(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, info=None)[source]¶
Singular value decomposition of raw 2d array
x, via hermitian eigen-decomposition of the Gram matrix, with optional truncation based on max_bond and/or dynamically on cutoff.- Parameters:
x (array-like) – The 2D array or batch of 2D arrays to decompose.
cutoff (float, optional) – Singular value cutoff threshold, if
cutoff <= 0.0, then onlymax_bondis used.cutoff_mode ({1, 2, 3, 4, 5, 6}, optional) –
How to perform the truncation based on
cutoff:1 / ‘abs’: trim values below
cutoff2 / ‘rel’: trim values below
s[0] * cutoff3 / ‘sum2’: trim s.t.
sum(s_trim**2) < cutoff.4 / ‘rsum2’: trim s.t.
sum(s_trim**2) < sum(s**2) * cutoff.5 / ‘sum1’: trim s.t.
sum(s_trim**1) < cutoff.6 / ‘rsum1’: trim s.t.
sum(s_trim**1) < sum(s**1) * cutoff.
max_bond (int, optional) – An explicit maximum bond dimension, use -1 for none.
absorb (int or None, optional) – How to absorb the singular values, as a pre-converted numeric code (
get_Us_VH=-1: left,get_Usq_sqVH=0: both,get_U_sVH=1: right,None: return separately). Usearray_splitwith string aliases (e.g.'left','both','right',None) for a friendlier interface.renorm (int, optional) – Whether to renormalize the kept singular values.
0means no renormalization,1maintains the trace norm,2maintains the Frobenius norm.info (dict or None, optional) – If a dict is passed, store truncation info in the dict. Currently only supports the key ‘error’ for the truncation error.
- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp._svd_via_eig_numba(x, absorb=get_U_s_VH, max_bond=-1, descending=True, right=None)[source]¶
Compute an SVD from eigenvectors of the Gram matrix using Numba. Limit rank with
max_bond. Skip work based on the factors requested byabsorb.- Parameters:
x (array_like) – Input must be a 2D NumPy array.
absorb (int or None, optional) – Numeric code for the factors to return and singular values to absorb.
max_bond (int, optional) – Maximum number of singular values to keep. Use -1 for no limit.
descending (bool, optional) – Return singular values in descending order. Default is True.
right (bool or None, optional) – Use
x.conj().T @ xif True, orx @ x.conj().Tif False. With None, choose the smaller Gram matrix. For square matrices, choose fromabsorb.
- Returns:
U (array or None)
s (array or None)
VH (array or None)
- quimb.tensor.decomp._svd_via_eig_truncated_numba(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, calc_error=False)[source]¶
SVD-split via eigen-decomposition, with optional dynamic truncation. Uses
_svd_via_eig_numbashortcuts when the full spectrum is not needed.
- quimb.tensor.decomp.svd_via_eig_truncated_numpy(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, info=None)[source]¶
- quimb.tensor.decomp.svdvals_eig(x)[source]¶
Compute singular values from Gram matrix eigenvalues using Numba.
xmust be a 2D NumPy array.
- quimb.tensor.decomp.svd_rand_truncated(x, max_bond, cutoff=0.0, cutoff_mode=cutoff_mode_rel, absorb=get_Usq_sqVH, oversample=10, num_iterations=2, method_lorthog='qr', method_reduced='svd', right=None, lorthog_opts=None, reduced_opts=None, seed=None, noise_dist='normal')[source]¶
Compute a low-rank SVD from random projections. Limit rank with
max_bond. Optionally discard small singular values withcutoff. Only absolute and relative cutoffs are supported.- Parameters:
x (array_like) – Input must have shape
(..., m, n).max_bond (int) – Maximum number of singular values to keep. Use
Noneor a negative value for no limit. Keeping all values removes the benefit of a low-rank sketch.cutoff (float, optional) – Absolute or relative threshold for discarding singular values from the sketched spectrum. Disabled by default.
cutoff_mode ({1, 2, "abs", "rel"}, optional) – How to interpret
cutoff."abs"discards values belowcutoffand"rel"discards values belowcutoff * s[0]. Cumulative modes require the full spectrum and are not supported.absorb (str or None, optional) –
Which factors to return and where to absorb singular values:
None/'U,s,VH': returnsas the middle element of the 3-tuple, unabsorbed.'both'/'Usq,sqVH': absorbsqrt(s)into both factors.'left'/'Us,VH': absorbsinto the left factor, leaving the right factor isometric (LQ-like).'right'/'U,sVH': absorbsinto the right factor, leaving the left factor isometric (QR-like).'lorthog'/'U': return only the left isometric factor.'rorthog'/'VH': return only the right isometric factor.'lfactor'/'Us': return only the left factor withsabsorbed (the L in an LQ decomposition).'rfactor'/'sVH': return only the right factor withsabsorbed (the R in a QR decomposition).'s': return only the singular values.
oversample (int, optional) – Extra dimensions for the random sketch to improve accuracy, default 10.
num_iterations (int, optional) – Number of power iterations to improve accuracy, default 2.
method_lorthog (str, optional) – Decomposition used to form an orthonormal basis for the random sketch, e.g.
'qr','svd:eig'or'svd'. Default is'qr'.method_reduced (str, optional) – Decomposition used for the reduced matrix, e.g.
'svd'or'svd:eig'. Default is'svd'.right (bool, optional) – Sketch from the right if True, or the left if False. With None, choose from
absorbto avoid a reduced SVD where possible. Otherwise, sketch from the right for tall matrices, or the left for wide ones.lorthog_opts (dict or None, optional) – Extra options for the decomposition set by
method_lorthog.reduced_opts (dict or None, optional) – Extra options for the decomposition set by
method_reduced.seed (int, Generator or None, optional) – Random seed or existing generator for reproducibility.
noise_dist ({"normal", "rademacher"}, optional) – Distribution used to generate the random sketch.
- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp.eigh_truncated(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, positive=0, shift=False)[source]¶
SVD-like decomposition using hermitian eigen-decomposition, only works if
xis hermitian.- Parameters:
x (array_like) – The 2D array or batch of 2D arrays to decompose.
cutoff (float, optional) – Singular value cutoff threshold, if
cutoff <= 0.0, then onlymax_bondis used.cutoff_mode ({1, 2, 3, 4, 5, 6}, optional) –
How to perform the truncation based on
cutoff:1 / ‘abs’: trim values below
cutoff2 / ‘rel’: trim values below
s[0] * cutoff3 / ‘sum2’: trim s.t.
sum(s_trim**2) < cutoff.4 / ‘rsum2’: trim s.t.
sum(s_trim**2) < sum(s**2) * cutoff.5 / ‘sum1’: trim s.t.
sum(s_trim**1) < cutoff.6 / ‘rsum1’: trim s.t.
sum(s_trim**1) < sum(s**1) * cutoff.
max_bond (int, optional) – An explicit maximum bond dimension, use -1 for none.
absorb (int or None, optional) – How to absorb the singular values, as a pre-converted numeric code (
get_Us_VH=-1: left,get_Usq_sqVH=0: both,get_U_sVH=1: right,None: return separately). Usearray_splitwith string aliases (e.g.'left','both','right',None) for a friendlier interface.renorm (int, optional) – Whether to renormalize the kept singular values.
0means no renormalization,1maintains the trace norm,2maintains the Frobenius norm.positive (bool, optional) – Whether to assume the operator is positive semi-definite.
shift (bool or float, optional) –
Whether to add a small shift to the diagonal of
xfor regularization. The valid options are:True: addtrace(x) * epsto the diagonal ofx, whereepsis the machine epsilon for the dtype ofx.False: never add a shift.float: use the provided value as a relative shift, i.e. add
shift * trace(x)to the diagonal ofx.
- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp.eigh_truncated_numba(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, positive=0, shift=0.0)[source]¶
SVD-decomposition, using hermitian eigen-decomposition, only works if
xis hermitian.
- quimb.tensor.decomp.eigh_truncated_numpy(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0, positive=0, shift=False)[source]¶
- quimb.tensor.decomp.qr_stabilized(x, absorb=get_U_sVH, stabilized=True, **kwargs)[source]¶
QR-decomposition, with stabilized R factor.
- Parameters:
x (array_like) – The 2D array or batch of 2D arrays to decompose.
absorb (str or int, optional) –
What form to compute / where to ‘absorb’ the singular values:
"right"/'U,sVH': usual QR decomposition."lorthog"/"U": just the left isometric factor (Q)."rfactor"/"sVH": just the right factor (R)."left"/'Us,VH': LQ-like decomposition."lfactor"/"Us": just the left factor (L) of LQ."rorthog"/"VH": just the right isometric factor (Q) of LQ.
stabilized (bool, optional) – Whether to stabilize the diagonal of R by setting its phase to 1 and absorbing the phase into Q. This can improve the numerical stability of gradients for example.
kwargs – Extra kwargs to pass to the underlying QR function.
- Returns:
left (array_like) – The left isometric factor (Q).
s (None)
right (array_like) – The right upper triangular factor (R).
- quimb.tensor.decomp.cholesky_regularized(x, absorb=get_Usq_sqVH, shift=True)[source]¶
Cholesky decomposition, only works if
xis positive definite. Theshiftparameter controls optional regularization for close to singular matrices.- Parameters:
x (array_like) – The 2D array or batch of 2D arrays to decompose.
absorb (int, optional) –
How to absorb the factors. The valid options are:
"both"orget_Usq_sqVH: return (L, None, L^H)"lsqrt"orget_Usq: return (L, None, None)"rsqrt"orget_sqVH: return (None, None, L^H)
shift ("auto", bool or float, optional) –
Whether to add a small shift to the diagonal of
xfor regularization. The valid options are:True: always add a small shift computed as above."auto": try without shift, if it fails, then add a small shift computed astrace(x) * eps,epsis the machine epsilon for the dtype ofx.False: never add a shift, just try the Cholesky decomposition directly.float: use the provided value as a relative shift, i.e. add
shift * trace(x)to the diagonal ofx.
- Returns:
left (array_like or None) – The lower triangular Cholesky factor (L).
s (None)
right (array_like or None) – The conjugate transpose of L (L^H).
- quimb.tensor.decomp.qr_via_cholesky(x, absorb=get_Us_VH, shift=True, solve_triangular=True, passes=1, tol_orthog=None)[source]¶
Compute QR or LQ factors from the Gram matrix using Cholesky. This can be faster for tall, narrow matrices. Ill-conditioned inputs can lose orthogonality. Additional passes can restore it.
- Parameters:
x (array_like) – Input must have shape
(..., m, n). For QR,mshould be at leastn. For LQ,nshould be at leastm.absorb (str or int, optional) – Use
'right'for QR or'left'for LQ. To return one factor, use'lorthog'or'rorthog'for the left or right isometry, or'lfactor'or'rfactor'for the left or right triangular factor.shift ("auto", bool or float, optional) –
Shift added to the Gram matrix diagonal in each pass. Here
epsis machine epsilon for the dtype, andtraceis the Gram matrix trace.True: addtrace * eps."auto": try without a shift, then addtrace * epsif it fails.False: do not add a shift.float: add
shift * trace. Negative values useepsinstead ofshift.
solve_triangular (bool, optional) – Use a triangular solve if True, or a general solve if False.
passes (int, optional) –
Positive number of orthogonalization passes. Each new pass orthogonalizes the previous result. Two passes (CholeskyQR2) can give orthogonality to machine precision for condition numbers up to about
1 / sqrt(eps). Three passes withshiftcan handle full-rank inputs with condition numbers close to1 / eps. Hereepsis machine epsilon.For rank-deficient inputs, regularization can preserve reconstruction. It does not ensure orthogonality. Use
'qr'or'qr:auto'when orthogonality is required.tol_orthog (float, optional) – Before each pass after the first, check the previous result’s Gram matrix. Raise
ValueErrorif its distance from the identity is at least this value. The distance is the Frobenius norm over the whole batch. Large errors can stop the next pass restoring orthogonality. None skips this check.
- Returns:
left (array_like or None) – Left factor, or
Noneif not requested.s (None)
right (array_like or None) – Right factor, or
Noneif not requested.
- Raises:
TypeError – If
passesis not an integer.ValueError – If
passesis not positive, or the Gram matrix error is at leasttol_orthog.
- quimb.tensor.decomp.qr_auto(x, absorb=get_U_sVH, stabilized=True, min_aspect=8, min_work=2**20)[source]¶
Compute QR or LQ factors. Try two passes of Cholesky QR for large, narrow matrices. Use
qr_stabilized()for other shapes, if Cholesky QR fails, or if the first pass loses too much orthogonality.- Parameters:
x (array_like) – Input must have shape
(..., m, n).absorb (str or int, optional) – Use
'right'for QR or'left'for LQ. To return one factor, use'lorthog'or'rorthog'for the left or right isometry, or'lfactor'or'rfactor'for the left or right triangular factor.stabilized (bool, optional) – Make the triangular factor’s diagonal real and nonnegative when using
qr_stabilized(). Cholesky QR already gives positive diagonals.min_aspect (float, optional) – Minimum aspect ratio for Cholesky QR. For QR, require
m >= min_aspect * n. For LQ, swapmandn.min_work (int, optional) – Minimum
m * n**2for Cholesky QR. For LQ, swapmandn. Below this, standard QR is used, as the extra calls cost more than they save.
- Returns:
left (array_like or None) – Left factor, or
Noneif not requested.s (None)
right (array_like or None) – Right factor, or
Noneif not requested.
- quimb.tensor.decomp._choose_k(x, cutoff, max_bond)[source]¶
Choose the number of singular values to target.
- quimb.tensor.decomp.svds(x, cutoff=0.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
SVD-decomposition using iterative methods. Allows the computation of only a certain number of singular values, e.g. max_bond, from the get-go, and is thus more efficient. Can also supply
scipy.sparse.linalg.LinearOperator.- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp.isvd(x, cutoff=0.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
SVD-decomposition using interpolative matrix random methods. Allows the computation of only a certain number of singular values, e.g. max_bond, from the get-go, and is thus more efficient. Can also supply
scipy.sparse.linalg.LinearOperator.- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp._rsvd_numpy(x, cutoff=0.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
- quimb.tensor.decomp.rsvd(x, cutoff=0.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
SVD-decomposition using randomized methods (due to Halko). Allows the computation of only a certain number of singular values, e.g. max_bond, from the get-go, and is thus more efficient. Can also supply
scipy.sparse.linalg.LinearOperator.- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp.eigsh(x, cutoff=0.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
SVD-decomposition using iterative hermitian eigen decomp, thus assuming that
xis hermitian. Allows the computation of only a certain number of singular values, e.g. max_bond, from the get-go, and is thus more efficient. Can also supplyscipy.sparse.linalg.LinearOperator.- Returns:
left (array_like or None)
s (array_like or None)
right (array_like or None)
- quimb.tensor.decomp.lu_truncated(x, cutoff=-1.0, cutoff_mode=cutoff_mode_rel, max_bond=-1, absorb=get_Usq_sqVH, renorm=0)[source]¶
LU-decomposition with optional truncation.
- Returns:
left (array_like) – The permuted lower triangular factor (PL).
s (None)
right (array_like) – The upper triangular factor (U).
- quimb.tensor.decomp.polar_right(x)[source]¶
Polar decomposition of
xas x = U @ P, where U is unitary and P is positive semidefinite.- Returns:
left (array_like) – The unitary factor (U).
s (None)
right (array_like) – The positive semidefinite factor (P).
- quimb.tensor.decomp.polar_left(x)[source]¶
Polar decomposition of
xas x = P @ U, where U is unitary and P is positive semidefinite.- Returns:
left (array_like) – The positive semidefinite factor (P).
s (None)
right (array_like) – The unitary factor (U).
- quimb.tensor.decomp._similarity_compress_fns¶
- quimb.tensor.decomp.isometrize_exp(x)[source]¶
Perform isometrization using anti-symmetric matrix exponentiation.
\[U_A = \exp \left( X - X^\dagger \right)\]If
xis rectangular it is completed with zeros first.
- quimb.tensor.decomp.isometrize_cayley(x)[source]¶
Perform isometrization using an anti-symmetric Cayley transform.
\[U_A = (I + \dfrac{A}{2})(I - \dfrac{A}{2})^{-1}\]where \(A = X - X^\dagger\). If
xis rectangular it is completed with zeros first.
- quimb.tensor.decomp.isometrize_modified_gram_schmidt(A)[source]¶
Perform isometrization explicitly using the modified Gram Schmidt procedure (this is slow but a useful reference).
- quimb.tensor.decomp.isometrize_torch_householder(x)[source]¶
Isometrize
xusing the Householder reflection method, as implemented by thetorch_householderpackage.
- quimb.tensor.decomp._ISOMETRIZE_METHODS¶
- quimb.tensor.decomp.isometrize(x, method='qr')[source]¶
Generate an isometric (or unitary if square) / orthogonal matrix from array
x.- Parameters:
x (array) – The matrix to project into isometrix form.
method (str, optional) –
The method used to generate the isometry. The options are:
”qr”: use the Q factor of the QR decomposition of
xwith the constraint that the diagonal ofRis positive.”svd”: uses
U @ VHof the SVD decomposition ofx. This is useful for finding the ‘closest’ isometric matrix tox, such as when it has been expanded with noise etc. But is less stable for differentiation / optimization.”exp”: use the matrix exponential of
x - dag(x), first completingxwith zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-squarex.”cayley”: use the Cayley transform of
x - dag(x), first completingxwith zeros if it is rectangular. This is a good parametrization for optimization (one the few compatible with HIPS/autograd e.g.), but more expensive for non-squarex.”householder”: use the Householder reflection method directly. This requires that the backend implements “linalg.householder_product”.
”torch_householder”: use the Householder reflection method directly, using the
torch_householderpackage. This requires that the package is installed and that the backend is"torch". This is generally the best parametrizing method for “torch” if available.”mgs”: use a python implementation of the modified Gram Schmidt method directly. This is slow if not compiled but a useful reference.
Not all backends support all methods or differentiating through all methods.
- Returns:
Q – The isometrization / orthogonalization of
x.- Return type:
- quimb.tensor.decomp.squared_op_to_reduced_factor(x2, dl, dr, right=True, method='eigh', **kwargs)[source]¶
Given the square,
x2, of an operatorx, compute either the left or right reduced factor matrix of the unsquared operatorxwith original shape(dl, dr).If
right=True, compute the right factor,s @ Vdag, assumingx2is given asx2 = dag(x) @ x = V @ s^2 @ Vdag, otherwise compute the left factor,U @ s, assumingx2 = x @ dag(x) = U @ s^2 @ Udag.- Parameters:
x2 (array) – The squared operator, either
dag(x) @ xorx @ dag(x).dl (int) – The original left dimension of the unsquared operator
x.dr (int) – The original right dimension of the unsquared operator
x.right (bool, optional) – Whether to compute the right factor (
s @ Vdag) or left factor (U @ s).method (str, optional) – The method to use for the decomposition.
kwargs – Additional keyword arguments to pass to the decomposition method. For example
shiftfor thecholeskyandeighmethods.
- Returns:
factor – The reduced factor matrix of the unsquared operator
x.- Return type:
- quimb.tensor.decomp.compute_oblique_projectors(Rl, Rr, max_bond=None, cutoff=0.0, absorb='both', cutoff_mode='rsum2', method='svd', **compress_opts)[source]¶
Compute the oblique projectors for two reduced factor matrices that describe a gauge on a bond. Concretely, assuming that
RlandRrare the reduced factor matrices for local operatorA, such that:\[A = Q_L R_L R_R Q_R\]with
Q_LandQ_Risometric matrices, then the optimal inner truncation is given by:\[A' = Q_L R_L P_L P_R R_R Q_R\]The bond can also be left as several unfused axes, which can avoid alignment issues with block sparse arrays.
- Parameters:
Rl (array) – The left reduced factor, with its outer axis first and then one or more bond axes.
Rr (array) – The right reduced factor, with the bond axes first, in the same order as for
Rl, and then its outer axis.max_bond (int, optional) – The maximum bond dimension to compress to.
cutoff (float, optional) – The singular value cutoff to use.
absorb (str or None, optional) –
Where to absorb the effective singular values into the projectors. The options are:
'both'/'Usq,sqVH': absorbsqrt(s)into both projectors.'left'/'Us,VH': absorbsinto the left projector, leaving the right projector isometric (LQ-like).'right'/'U,sVH': absorbsinto the right projector, leaving the left projector isometric (QR-like).None/'U,s,VH': returnsas a separate middle element.
cutoff_mode (str, optional) – The cutoff mode to use when applying the cutoff.
method (str, optional) – The method to use for the SVD decomposition when computing the projectors.
compress_opts – Additional keyword arguments to pass to the SVD decomposition method.
- Returns:
Pl (array) – The left oblique projector, with the bond axes of
Rrand then the new bond.Pr (array) – The right oblique projector, with the new bond and then the bond axes of
Rl.
- quimb.tensor.decomp.compute_bondenv_projectors(E, max_bond, cutoff=0.0, absorb='both', max_iterations=100, tol=1e-10, solver='solve', solver_maxiter=4, prenormalize=False, condition=True, enforce_pos=True, pos_smudge=1e-10, init='svd', info=None)[source]¶
Given 4D environment tensor of a bond, iteratively compute projectors that compress the bond dimension to max_bond, minimizing the distance in terms of frobenius norm. If absorb!=”both” and cutoff!=0.0 then a final truncated SVD is also performed on the final projector pair.
N.B. This is experimental and not working for e.g. fermions yet.
- Parameters:
E (array) – The 4D environment tensor of a bond. The dimensions should be arranged as (ket-left, ket-right, bra-left, bra-right).
max_bond (int) – The maximum bond dimension to compress to.
cutoff (float, optional) – The singular value cutoff to use.
absorb (str or None, optional) –
Where to absorb the effective singular values into the projectors:
'both'/'Usq,sqVH': absorbsqrt(s)into both projectors.'left'/'Us,VH': absorbsinto the left projector, leaving the right projector isometric (LQ-like).'right'/'U,sVH': absorbsinto the right projector, leaving the left projector isometric (QR-like).None/'U,s,VH': returnsas a separate middle element.
max_iterations (int, optional) – The maximum number of iterations to use when fitting the projectors.
tol (float, optional) – The target tolerance to reach when fitting the projectors.
solver ({'solve', None, str}, optional) – The solver to use inside the fitting loop. If None will use a custom conjugate gradient method. Else can be any of the iterative solvers supported by
scipy.sparse.linalgsuch as ‘gmres’, ‘bicgstab’, etc.solver_maxiter (int, optional) – The maximum number of iterations to use for the inner solver, i.e. per fitting step, only for iterative solver args.
prenormalize (bool, optional) – Whether to prenormalize the environment tensor such that its full contraction before compression is 1. Recommended for stability when the normalization does not matter.
condition (bool or "iso", optional) – Whether to condition the projectors after each fitting step. If
True, their norms will be simply matched. If"iso", then they are gauged each time such that the previous tensor is isometric. Recommended for stability.enforce_pos (bool, optional) – Whether to enforce the environment tensor to be positive semi-definite by symmetrizing and clipping negative eigenvalues. Recommended for stability.
pos_smudge (float, optional) – The value to clip negative eigenvalues to when enforcing positivity, relative to the largest eigenvalue.
init ({'svd', 'eigh', 'random', 'reduced'}, optional) –
How to initialize the compression projectors. The options are:
’svd’: use a truncated SVD of the environment tensor with the bra bond traced out.
’eigh’: use a similarity compression of the environment tensor with the bra bond traced out.
’random’: use random projectors.
’reduced’: split the environment into bra and ket parts, then canonize one half left and right to get the reduced factors.
info (dict, optional) – If provided, will store information about the fitting process here. The keys ‘iterations’ and ‘distance’ will contain the final number of iterations and distance reached respectively.
- Returns:
Pl (array) – The left projector.
Pr (array) – The right projector.