pytreenet.util package

This module provides various utility functions.

This includes custom exceptions fitting into the TTN concepts, tensor splitting methods, and general python utility functions.

Submodules

pytreenet.util.std_utils module

Some useful tools that do not fit into any other category.

pytreenet.util.std_utils.compare_lists_by_value(list1: List, list2: List) bool

Compare, if two lists have the same elements.

Parameters:
  • list1 (List) – The first list.

  • list2 (List) – The second list.

Returns:

Whether the two lists have the same elements.

Return type:

bool

pytreenet.util.std_utils.copy_object(obj: Any, deep=True) Any

Copy an object.

Shortens the commonly used if-else statement for copying objects to distinguish between deep and shallow copies.

Parameters:
  • obj (Any) – The object to copy.

  • deep (bool, optional) – Whether to perform a deep copy. Defaults to True.

Returns:

The copied object.

Return type:

Any

pytreenet.util.std_utils.fast_exp_action(exponent: ndarray, vector: ndarray, mode: str = 'fastest') ndarray

Perform the action of the exponentiation of a matrix on a vector.

Different modes can be choosen to perform the action. The fastest mode is the default mode. The modes are:

  • “expm”: Use the scipy expm function.

  • “eigsh”: Use the scipy eigsh function. Only valid for hermitian matrices.

  • “chebyshev”: Use the scipy expm_multiply function.

  • “sparse”: Use the scipy sparse expm function. Only valid for sparse

    matrices.

  • “none”: Do not perform any action.

Parameters:
  • exponent (np.ndarray) – The exponent in matrix form.

  • vector (np.ndarray) – The input vector in vector form.

  • mode (str, optional) – The mode to use. Defaults to “fastest”.

Raises:

NotImplementedError – If an unimplemented mode is used.

Returns:

The result of the exponentiation and multiplication.

exp(exponent) @ vector.

Return type:

np.ndarray

pytreenet.util.std_utils.sort_dictionary(dictionary: Dict) Dict

Sort a dictionary by its values.

Parameters:

dictionary (Dict) – The dictionary to sort.

Returns:

The sorted dictionary.

Return type:

Dict

pytreenet.util.tensor_splitting module

Functions that decompose a tensor.

The functions in this module are used to decompose a tensor into two or more tensors. The QR decomposition and the singular value decomposition are the most common decompositions used in tensor networks and implemented. While the QR-Decomposition is faster, the SVD allows for a truncation of the bond dimension, by discarding sufficiently small singular values.

class pytreenet.util.tensor_splitting.ContractionMode(value)

Bases: Enum

Which tensor the singular values are contracted into.

VCONTR: Contracts the singular values with the V tensor. UCONTR: Contracts the singular values with the U tensor. EQUAL: Contracts the squareroot of the singular values with each tensor.

EQUAL = 'equal'
UCONTR = 'ucontr'
VCONTR = 'vcontr'
class pytreenet.util.tensor_splitting.SVDParameters(max_bond_dim: int = 100, rel_tol: float = 0.01, total_tol: float = 1e-15, renorm: bool = True)

Bases: object

Holds all the parameters required for a truncated singular value decomposition.

max_bond_dim

The maximum bond dimension allowed between nodes. Defaults to 100.

Type:

int, optional

rel_tol

singular values s for which (s / largest singular value) < rel_tol are truncated. Defaults to 0.01.

Type:

float, optional

total_tol

singular values s for which s < total_tol are truncated. Defaults to 1e-15.

Type:

float, optional

renorm

If True, the truncated singular value vector is scaled to have the same norm as the original vector. Defaults to True.

Type:

bool, optional

check_truncation_parameters()

Checks if the truncation parameters are valid.

The maximum bond dimension has to be a positive integer or infinity. The relative tolerance has to be positive or -infinity. The total tolerance has to be positive or -infinity.

max_bond_dim: int = 100
rel_tol: float = 0.01
renorm: bool = True
total_tol: float = 1e-15
class pytreenet.util.tensor_splitting.SplitMode(value)

Bases: Enum

Different modes on how to deal with the dimensions of a decomposed tensor.

Decompositions are not unique, but differ in how to deal with the dimension of the new created bond. In principle one can increase the dimension as much as is desired, by adding zero vectors to the resulting tensors.

FULL: The resulting tensor has the keeps the inout dimension of the

original tensor.

REDUCED: The resulting tensor has the minimum dimension between the

input and output tensor. This means there are no zero vectors added. This is the default mode of numpy.

KEEP: One of the resulting tensors has the same shape as the input tensor,

if only one leg is split of from the rest.

FULL = 'full'
KEEP = 'keep'
REDUCED = 'reduced'
numpy_qr_mode() str

Returns the string required in the numpy QR decomposition.

numpy_svd_mode() bool

Returns the numpy SVD mode required.

A numpy SVD has to be told, if it should return the full or reduced matrices by using a boolean.

pytreenet.util.tensor_splitting.contr_truncated_svd_splitting(tensor: ndarray, u_legs: Tuple[int, ...], v_legs: Tuple[int, ...], contr_mode: ContractionMode = ContractionMode.VCONTR, svd_params: SVDParameters = SVDParameters(max_bond_dim=100, rel_tol=0.01, total_tol=1e-15, renorm=True)) Tuple[ndarray, ndarray]
Performs a truncated singular value decomposition, but the singular values

are contracted with the V tensor.

Parameters:
  • tensor (np.ndarray) – Tensor on which the svd is to be performed.

  • u_legs (Tuple[int]) – Legs of tensor that are to be associated to U after the SVD.

  • v_legs (Tuple[int]) – Legs of tensor that are to be associated to V after the SVD.

  • contr_mode (ContractionMode) – Determines how the singular values are contracted into the other tensors.

  • svd_params (SVDParameters) – Parameters for the truncation of the

pytreenet.util.tensor_splitting.renormalise_singular_values(s: ndarray, new_s: ndarray) ndarray

Renormalises a truncated singular value vector.

The vector is scaled to have the same norm as the original vector.

Parameters:
  • s (np.ndarray) – The original vector of singular values.

  • new_s (np.ndarray) – The truncated vector of singular values.

Returns:

The renormalised vector new_s.

Return type:

np.ndarray

pytreenet.util.tensor_splitting.tensor_qr_decomposition(tensor: ndarray, q_legs: Tuple[int, ...], r_legs: Tuple[int, ...], mode: SplitMode = SplitMode.REDUCED) Tuple[ndarray, ndarray]

Computes the QR decomposition of a tensor with respect to the given legs.

Parameters:
  • tensor (np.ndarray) – Tensor on which the QR-decomp is to applied.

  • q_legs (Tuple[int]) – Legs of tensor that should be associated to the Q tensor after QR-decomposition.

  • r_legs (Tuple[int]) – Legs of tensor that should be associated to the R tensor after QR-decomposition.

  • mode (SplitMode, optional) – Reduced returns a QR deocomposition with minimum dimension between Q and R. Full returns the decomposition with dimension between Q and R as the output dimension of Q. Keep causes Q to have the same shape as the input tensor. Defaults to SplitMode.REDUCED.

Returns:

(Q, R):

      |2                             |1
    __|_      r_legs = (1, )       __|_        ____
   |    |     q_legs = (0,2)      |    |      | R  |
___|    |___  -------------->  ___| Q  |______|____|____
0  |____|  1                   0  |____| 2   0        1

Return type:

Tuple[np.ndarray,np.ndarray]

pytreenet.util.tensor_splitting.tensor_svd(tensor: ndarray, u_legs: Tuple[int, ...], v_legs: Tuple[int, ...], mode: SplitMode = SplitMode.REDUCED) Tuple[ndarray, ndarray, ndarray]

Perform a singular value decomposition on a tensor.

Parameters:
  • tensor (np.ndarray) – Tensor on which the svd is to be performed.

  • u_legs (Tuple[int]) – Legs of tensor that are to be associated to U after the SVD.

  • v_legs (Tuple[int]) – Legs of tensor that are to be associated to V after the SVD.

  • mode (SplitMode, optional) – Determines if the full or reduced matrices u and vh obtained by the SVD are returned. The default is SplitMode.REDUCED.

Returns:

(U, S, V), where S is the

vector of singular values and U and V are tensors equivalent to an isometry:

      |2                             |1
    __|_      v_legs = (1, )       __|_        ____        ____
   |    |     q_legs = (0,2)      |    |      |  S |      |    |
___|    |___  -------------->  ___|  U |______|____|______| Vh |____1
0  |____|  1                   0  |____| 2   0       1  0 |____|

Return type:

Tuple[np.ndarray,np.ndarray,np.ndarray]

pytreenet.util.tensor_splitting.truncate_singular_values(s: ndarray, svd_params: SVDParameters) Tuple[ndarray, ndarray]

Truncates the singular values of a tensor given as a vector.

Parameters:
  • s (np.ndarray) – Vector of singular values sorted in descending order.

  • svd_params (SVDParameters) – Parameters for the truncation of the singular values.

Returns:

(new_s, s_trunc), where is is the

shortened vector of singular values and s_trunc is a vector of the truncated singular values.

Return type:

Tuple[np.ndarray,np.ndarray]

pytreenet.util.tensor_splitting.truncated_tensor_svd(tensor: ndarray, u_legs: Tuple[int, ...], v_legs: Tuple[int, ...], svd_params: SVDParameters) Tuple[ndarray, ndarray, ndarray]

Performs a singular value decomposition of a tensor including truncation.

This means some of the singular values are discarded and the resulting tensors are truncated to the new bond dimension.

Parameters:
  • tensor (np.ndarray) – Tensor on which the svd is to be performed.

  • u_legs (Tuple[int]) – Legs of tensor that are to be associated to U after the SVD.

  • v_legs (Tuple[int]) – Legs of tensor that are to be associated to V after the SVD.

  • svd_params (SVDParameters) – Parameters for the truncation of the singular values.

Returns:

(U, S, V), where U and V are

the truncated tensors and S are the singular values:

      |2                             |1
    __|_      v_legs = (1, )       __|_        ____        ____
   |    |     q_legs = (0,2)      |    |      |  S |      |    |
___|    |___  -------------->  ___|  U |______|____|______| Vh |____1
0  |____|  1                   0  |____| 2   0       1  0 |____|

Return type:

Tuple[np.ndarray,np.ndarray,np.ndarray]

pytreenet.util.tensor_util module

Helpful functions that work with the tensors of the tensor nodes.

These functions transform a given tensor independent of the overall tensor network structure.

pytreenet.util.tensor_util.compute_transfer_tensor(tensor: ndarray, contr_indices: Tuple[int, ...] | int) ndarray

Computes the tranfer tensor of the given tensor.

The transfer tensor is the tensor that is obtained by contracting the tensor with its conjugate along the given indices.

Parameters:
  • tensor (np.ndarray) – The tensor to compute the transfer tensor for.

  • contr_indices (Union[Tuple[int], int]) – The indices of the legs of the tensor to be contracted.

Returns:

The transfer tensor, i.e.:

    ____          ____
   |    |__oi1___|    |
___| A  |__oi2___| A* |____
   |____|        |____|

Return type:

np.ndarray

pytreenet.util.tensor_util.tensor_matricisation_half(tensor: ndarray) ndarray

Turns a tensor into a matrix combining half the legs into input atn output.

More specifically the tensor is matricized by combining the first half of the legs to the input leg of the matrix and the second half of the legs to the output leg.

Parameters:

tensor (np.ndarray) – Tensor to be matricized.

Returns:

The resulting matrix.

Return type:

np.ndarray

pytreenet.util.tensor_util.tensor_matricization(tensor: ndarray, output_legs: Tuple[int, ...], input_legs: Tuple[int, ...], correctly_ordered: bool = False) ndarray

Turns a tensor into a matrix.

This is done by combining the legs defined as output into one big output leg and the legs defined as input into one big input leg. The order of the legs is kept, i.e. the dimensions when viewed as a tensor product have the same order as the legs defined in the lists.

Parameters:
  • tensor (np.ndarray) – Tensor to be matricized.

  • output_legs (Tuple[int]) – The tensor legs which are to be combined to be the matrix’ output leg (First index).

  • input_legs (Tuple[int]) – The tensor legs which are to be combined to be the matrix’ input leg (Second index).

  • correctly_ordered (bool, optional) – If true it is assumed, the tensor does not need to be transposed, i.e. this should be activated if the tensor already has the correct order of legs. Defaults to False.

Returns:

The resulting matrix.

Return type:

np.ndarray

pytreenet.util.tensor_util.tensor_multidot(tensor: ndarray, other_tensors: List[ndarray], main_legs: List[int], other_legs: List[int]) ndarray

For a given tensor, perform multiple tensor contractions at once.

The tensor is contracted with multiple other tensors. The legs for each for each contraction should be at the same position as the corresponding tensor in the list of tensors.

Parameters:
  • tensor (np.ndarray) – Tensor to be mutliplied with other tensors.

  • other_tensors (List[np.ndarray]) – The tensors that should be contracted with tensor.

  • main_legs (List[int]) – The legs of tensor which are connected to the tensors in other_tensors.

  • other_legs (List[int]) – The legs of the tensors in other_tensors which are connected to tensor.

Returns:

The resulting tensor

Return type:

np.ndarray

pytreenet.util.tensor_util.transpose_tensor_by_leg_list(tensor: ndarray, first_legs: List[int], last_legs: List[int]) ndarray

Transposes a tensor according to two lists of legs.

The legs in the first_legs list will become the first legs of the new tensor and the legs in the secon dlist will become the last legs of the new tensor.

Parameters:
  • tensor (np.ndarray) – Tensor to be transposed.

  • first_legs (List[int]) – Leg indices that are to become the first legs of the new tensor.

  • last_legs (List[int]) – Leg indices that are to become the last legs of the new tensor.

Returns:

New tensor that is the transposed input tensor:

_____       (0,2)       _____

___| |___ (1,3) ___| |___ 0 | | 1 ----> 0 | | 2 ___| |___ ___| |___ 2 |_____| 3 1 |_____| 3

Return type:

np.ndarray

pytreenet.util.ttn_exceptions module

Exceptinos specific to tensor networks and common checks.

This module contains exceptions that are specific to tensor networks. This concerns the connectivity of nodes in a tree tensor network (TTN) with the NoConnectionException and the compatibility of two TTNs with the NotCompatibleException.

Checks are commonly done for parameters of tensor network algorithms.

exception pytreenet.util.ttn_exceptions.NoConnectionException

Bases: Exception

Raised when tensors of two nodes in a tree supposed to interact directly but the nodes are not actually connected.

exception pytreenet.util.ttn_exceptions.NotCompatibleException

Bases: Exception

Raised when compatibility of two TTN is checked, but not fulfilled.

pytreenet.util.ttn_exceptions.non_negativity_check(value: int | float, name: str | None = None, errstr: str | None = None)

Check if a given value is non-negative, i.e >=0.

Parameters:
  • value (Union[int,float]) – The value to check.

  • name (Union[str,None], optional) – A name of the value that is checked, will be inserted into a default error string. Defaults to None.

  • errstr (Union[None,str], optional) – An individual error string that overrides the default error string. Defaults to None.

pytreenet.util.ttn_exceptions.positivity_check(value: int | float, name: str | None = None, errstr: str | None = None)

Check if a given value is positive.

Parameters:
  • value (Union[int,float]) – The value to check.

  • name (Union[str,None], optional) – A name of the value that is checked, will be inserted into a default error string. Defaults to None.

  • errstr (Union[None,str], optional) – An individual error string that overrides the default error string. Defaults to None.