quimb.tensor.tensor_3d

Classes and algorithms related to 3D tensor networks.

Attributes

Classes

oset

An ordered set which stores elements as the keys of dict (ordered as of

Tensor

A labelled, tagged n-dimensional array. The index labels are used

TensorNetworkGen

A tensor network which notionally has a single tensor per 'site',

TensorNetworkGenVector

A tensor network which notionally has a single tensor and outer index

Rotator3D

Object for rotating coordinates and various contraction functions so

TensorNetwork3D

Mixin class for tensor networks with a cubic lattice three-dimensional

TensorNetwork3DVector

Mixin class for a 3D square lattice vector TN, i.e. one with a single

TensorNetwork3DFlat

Mixin class for a 3D square lattice tensor network with a single tensor

PEPS3D

Projected Entangled Pair States object (3D).

Functions

check_opt(name, value, valid)

Check whether value takes one of valid options, and raise an

ensure_dict(x)

Make sure x is a dict, creating an empty one if x is None.

pairwise(iterable)

Iterate over each pair of neighbours in iterable.

randn([shape, dtype, scale, loc, num_threads, seed, dist])

Fast multithreaded generation of random normally distributed data.

seed_rand(seed)

See the random number generators, by instantiating a new set of bit

bonds(t1, t2)

Getting any indices connecting the Tensor(s) or TensorNetwork(s) t1

bonds_size(t1, t2)

Get the size of the bonds linking tensors or tensor networks t1 and

rand_uuid([base])

Return a guaranteed unique, shortish identifier, optional appended

tags_to_oset(tags)

Parse a tags argument into an ordered set.

gen_3d_bonds(Lx, Ly, Lz[, steppers, coo_filter, cyclic])

Convenience function for tiling pairs of bond coordinates on a 3D

gen_3d_plaquette(coo0, steps)

Generate a plaquette at site coo0 by stepping first in steps and

gen_3d_plaquettes(Lx, Ly, Lz[, tiling])

Generate a tiling of plaquettes in a cubic 3D lattice.

gen_3d_strings(Lx, Ly, Lz)

Generate all length-wise strings in a cubic 3D lattice.

parse_boundary_sequence(sequence)

is_lone_coo(where)

Check if where has been specified as a single coordinate triplet.

calc_cell_sizes(coo_groups[, autogroup])

cell_to_sites(p)

Turn a cell ((i0, j0, k0), (di, dj, dk)) into the sites it contains.

sites_to_cell(sites)

Get the minimum covering cell for sites.

calc_cell_map(cells)

Module Contents

quimb.tensor.tensor_3d.check_opt(name, value, valid)[source]

Check whether value takes one of valid options, and raise an informative error if not.

quimb.tensor.tensor_3d.ensure_dict(x)[source]

Make sure x is a dict, creating an empty one if x is None.

quimb.tensor.tensor_3d.pairwise(iterable)[source]

Iterate over each pair of neighbours in iterable.

quimb.tensor.tensor_3d.randn(shape=(), dtype=float, scale=1.0, loc=0.0, num_threads=None, seed=None, dist='normal')[source]

Fast multithreaded generation of random normally distributed data.

Parameters:
  • shape (tuple[int]) – The shape of the output random array.

  • dtype ({'complex128', 'float64', 'complex64' 'float32'}, optional) – The data-type of the output array.

  • scale (float, optional) – A multiplicative scale for the random numbers.

  • loc (float, optional) – An additive location for the random numbers.

  • num_threads (int, optional) – How many threads to use. If None, decide automatically.

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate.

quimb.tensor.tensor_3d.seed_rand(seed)[source]

See the random number generators, by instantiating a new set of bit generators with a ‘seed sequence’.

quimb.tensor.tensor_3d.bonds(t1, t2)[source]

Getting any indices connecting the Tensor(s) or TensorNetwork(s) t1 and t2.

quimb.tensor.tensor_3d.bonds_size(t1, t2)[source]

Get the size of the bonds linking tensors or tensor networks t1 and t2.

class quimb.tensor.tensor_3d.oset(it=())[source]

An ordered set which stores elements as the keys of dict (ordered as of python 3.6). ‘A few times’ slower than using a set directly for small sizes, but makes everything deterministic.

__slots__ = ('_d',)
classmethod _from_dict(d)[source]
classmethod from_dict(d)[source]

Public method makes sure to copy incoming dictionary.

copy()[source]
__deepcopy__(memo)[source]
add(k)[source]
discard(k)[source]
remove(k)[source]
clear()[source]
update(*others)[source]
union(*others)[source]
intersection_update(*others)[source]
intersection(*others)[source]
difference_update(*others)[source]
difference(*others)[source]
popleft()[source]
popright()[source]
pop[source]
__eq__(other)[source]

Return self==value.

__or__(other)[source]
__ior__(other)[source]
__and__(other)[source]
__iand__(other)[source]
__sub__(other)[source]
__isub__(other)[source]
__len__()[source]
__iter__()[source]
__contains__(x)[source]
__repr__()[source]

Return repr(self).

quimb.tensor.tensor_3d.rand_uuid(base='')[source]

Return a guaranteed unique, shortish identifier, optional appended to base.

Examples

>>> rand_uuid()
'_2e1dae1b'
>>> rand_uuid('virt-bond')
'virt-bond_bf342e68'
quimb.tensor.tensor_3d.tags_to_oset(tags)[source]

Parse a tags argument into an ordered set.

class quimb.tensor.tensor_3d.Tensor(data=1.0, inds=(), tags=None, left_inds=None)[source]

A labelled, tagged n-dimensional array. The index labels are used instead of axis numbers to identify dimensions, and are preserved through operations. The tags are used to identify the tensor within networks, and are combined when tensors are contracted together.

Parameters:
  • data (numpy.ndarray) – The n-dimensional data.

  • inds (sequence of str) – The index labels for each dimension. Must match the number of dimensions of data.

  • tags (sequence of str, optional) – Tags with which to identify and group this tensor. These will be converted into a oset.

  • left_inds (sequence of str, optional) – Which, if any, indices to group as ‘left’ indices of an effective matrix. This can be useful, for example, when automatically applying unitary constraints to impose a certain flow on a tensor network but at the atomistic (Tensor) level.

Examples

Basic construction:

>>> from quimb import randn
>>> from quimb.tensor import Tensor
>>> X = Tensor(randn((2, 3, 4)), inds=['a', 'b', 'c'], tags={'X'})
>>> Y = Tensor(randn((3, 4, 5)), inds=['b', 'c', 'd'], tags={'Y'})

Indices are automatically aligned, and tags combined, when contracting:

>>> X @ Y
Tensor(shape=(2, 5), inds=('a', 'd'), tags={'Y', 'X'})
__slots__ = ('_data', '_inds', '_tags', '_left_inds', '_owners')
_set_data(data)[source]
_set_inds(inds)[source]
_set_tags(tags)[source]
_set_left_inds(left_inds)[source]
get_params()[source]

A simple function that returns the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.

set_params(params)[source]

A simple function that sets the ‘parameters’ of the underlying data array. This is mainly for providing an interface for ‘structured’ arrays e.g. with block sparsity to interact with optimization.

copy(deep=False, virtual=False)[source]

Copy this tensor.

Note

By default (deep=False), the underlying array will not be copied.

Parameters:
  • deep (bool, optional) – Whether to copy the underlying data as well.

  • virtual (bool, optional) – To conveniently mimic the behaviour of taking a virtual copy of tensor network, this simply returns self.

__copy__[source]
property data
property inds
property tags
property left_inds
check()[source]

Do some basic diagnostics on this tensor, raising errors if something is wrong.

property owners
add_owner(tn, tid)[source]

Add tn as owner of this Tensor - it’s tag and ind maps will be updated whenever this tensor is retagged or reindexed.

remove_owner(tn)[source]

Remove TensorNetwork tn as an owner of this Tensor.

check_owners()[source]

Check if this tensor is ‘owned’ by any alive TensorNetworks. Also trim any weakrefs to dead TensorNetworks.

_apply_function(fn)[source]
modify(**kwargs)[source]

Overwrite the data of this tensor in place.

Parameters:
  • data (array, optional) – New data.

  • apply (callable, optional) – A function to apply to the current data. If data is also given this is applied subsequently.

  • inds (sequence of str, optional) – New tuple of indices.

  • tags (sequence of str, optional) – New tags.

  • left_inds (sequence of str, optional) – New grouping of indices to be ‘on the left’.

apply_to_arrays(fn)[source]

Apply the function fn to the underlying data array(s). This is meant for changing how the raw arrays are backed (e.g. converting between dtypes or libraries) but not their ‘numerical meaning’.

isel(selectors, inplace=False)[source]

Select specific values for some dimensions/indices of this tensor, thereby removing them. Analogous to X[:, :, 3, :, :] with arrays. The indices to select from can be specified either by integer, in which case the correspoding index is removed, or by a slice.

Parameters:
  • selectors (dict[str, int], dict[str, slice]) – Mapping of index(es) to which value to take.

  • inplace (bool, optional) – Whether to select inplace or not.

Return type:

Tensor

Examples

>>> T = rand_tensor((2, 3, 4), inds=('a', 'b', 'c'))
>>> T.isel({'b': -1})
Tensor(shape=(2, 4), inds=('a', 'c'), tags=())

See also

TensorNetwork.isel

isel_[source]
add_tag(tag)[source]

Add a tag or multiple tags to this tensor. Unlike self.tags.add this also updates any TensorNetwork objects viewing this Tensor.

expand_ind(ind, size, mode=None, rand_strength=None, rand_dist='normal')[source]

Inplace increase the size of the dimension of ind, the new array entries will be filled with zeros by default.

Parameters:
  • name (str) – Name of the index to expand.

  • size (int, optional) – Size of the expanded index.

  • mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If 'zeros' then fill with zeros, if 'repeat' then repeatedly tile the existing entries. If 'random' then fill with random entries drawn from rand_dist, multiplied by rand_strength. If None then select from zeros or random depening on non-zero rand_strength.

  • rand_strength (float, optional) – If mode='random', a multiplicative scale for the random entries, defaulting to 1.0. If mode is None then supplying a non-zero value here triggers mode='random'.

  • rand_dist ({'normal', 'uniform', 'exp'}, optional) – If mode='random', the distribution to draw the random entries from.

new_ind(name, size=1, axis=0, mode=None, rand_strength=None, rand_dist='normal')[source]

Inplace add a new index - a named dimension. If size is specified to be greater than one then the new array entries will be filled with zeros.

Parameters:
  • name (str) – Name of the new index.

  • size (int, optional) – Size of the new index.

  • axis (int, optional) – Position of the new index.

  • mode ({None, 'zeros', 'repeat', 'random'}, optional) – How to fill any new array entries. If 'zeros' then fill with zeros, if 'repeat' then repeatedly tile the existing entries. If 'random' then fill with random entries drawn from rand_dist, multiplied by rand_strength. If None then select from zeros or random depening on non-zero rand_strength.

  • rand_strength (float, optional) – If mode='random', a multiplicative scale for the random entries, defaulting to 1.0. If mode is None then supplying a non-zero value here triggers mode='random'.

  • rand_dist ({'normal', 'uniform', 'exp'}, optional) – If mode='random', the distribution to draw the random entries from.

new_bond[source]
new_ind_with_identity(name, left_inds, right_inds, axis=0)[source]

Inplace add a new index, where the newly stacked array entries form the identity from left_inds to right_inds. Selecting 0 or 1 for the new index name thus is like ‘turning off’ this tensor if viewed as an operator.

Parameters:
  • name (str) – Name of the new index.

  • left_inds (tuple[str]) – Names of the indices forming the left hand side of the operator.

  • right_inds (tuple[str]) – Names of the indices forming the right hand side of the operator. The dimensions of these must match those of left_inds.

  • axis (int, optional) – Position of the new index.

new_ind_pair_with_identity(new_left_ind, new_right_ind, d, inplace=False)[source]

Expand this tensor with two new indices of size d, by taking an (outer) tensor product with the identity operator. The two new indices are added as axes at the start of the tensor.

Parameters:
  • new_left_ind (str) – Name of the new left index.

  • new_right_ind (str) – Name of the new right index.

  • d (int) – Size of the new indices.

  • inplace (bool, optional) – Whether to perform the expansion inplace.

Return type:

Tensor

new_ind_pair_with_identity_[source]
conj(inplace=False)[source]

Conjugate this tensors data (does nothing to indices).

conj_[source]
property H
Conjugate this tensors data (does nothing to indices).
property shape
The size of each dimension.
property ndim
The number of dimensions.
property size
The total number of array elements.
property dtype
The data type of the array elements.
property backend
The backend inferred from the data.
iscomplex()[source]
astype(dtype, inplace=False)[source]

Change the type of this tensor to dtype.

astype_[source]
max_dim()[source]

Return the maximum size of any dimension, or 1 if scalar.

ind_size(ind)[source]

Return the size of dimension corresponding to ind.

inds_size(inds)[source]

Return the total size of dimensions corresponding to inds.

shared_bond_size(other)[source]

Get the total size of the shared index(es) with other.

inner_inds()[source]

Get all indices that appear on two or more tensors.

transpose(*output_inds, inplace=False)[source]

Transpose this tensor - permuting the order of both the data and the indices. This operation is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.

Note to compute the tranditional ‘transpose’ of an operator within a contraction for example, you would just use reindexing not this.

Parameters:
  • output_inds (sequence of str) – The desired output sequence of indices.

  • inplace (bool, optional) – Perform the tranposition inplace.

Returns:

tt – The transposed tensor.

Return type:

Tensor

transpose_[source]
transpose_like(other, inplace=False)[source]

Transpose this tensor to match the indices of other, allowing for one index to be different. E.g. if self.inds = ('a', 'b', 'c', 'x') and other.inds = ('b', 'a', 'd', 'c') then ‘x’ will be aligned with ‘d’ and the output inds will be ('b', 'a', 'x', 'c')

Parameters:
  • other (Tensor) – The tensor to match.

  • inplace (bool, optional) – Perform the tranposition inplace.

Returns:

tt – The transposed tensor.

Return type:

Tensor

See also

transpose

transpose_like_[source]
moveindex(ind, axis, inplace=False)[source]

Move the index ind to position axis. Like transpose, this permutes the order of both the data and the indices and is mainly for ensuring a certain data layout since for most operations the specific order of indices doesn’t matter.

Parameters:
  • ind (str) – The index to move.

  • axis (int) – The new position to move ind to. Can be negative.

  • inplace (bool, optional) – Whether to perform the move inplace or not.

Return type:

Tensor

moveindex_[source]
item()[source]

Return the scalar value of this tensor, if it has a single element.

trace(left_inds, right_inds, preserve_tensor=False, inplace=False)[source]

Trace index or indices left_inds with right_inds, removing them.

Parameters:
  • left_inds (str or sequence of str) – The left indices to trace, order matching right_inds.

  • right_inds (str or sequence of str) – The right indices to trace, order matching left_inds.

  • preserve_tensor (bool, optional) – If True, a tensor will be returned even if no indices remain.

  • inplace (bool, optional) – Perform the trace inplace.

Returns:

z

Return type:

Tensor or scalar

sum_reduce(ind, inplace=False)[source]

Sum over index ind, removing it from this tensor.

Parameters:
  • ind (str) – The index to sum over.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

Tensor

sum_reduce_[source]
vector_reduce(ind, v, inplace=False)[source]

Contract the vector v with the index ind of this tensor, removing it.

Parameters:
  • ind (str) – The index to contract.

  • v (array_like) – The vector to contract with.

  • inplace (bool, optional) – Whether to perform the reduction inplace.

Return type:

Tensor

vector_reduce_[source]
collapse_repeated(inplace=False)[source]

Take the diagonals of any repeated indices, such that each index only appears once.

collapse_repeated_[source]
contract(*others, output_inds=None, **opts)[source]
direct_product(other, sum_inds=(), inplace=False)[source]
direct_product_[source]
split(*args, **kwargs)[source]
compute_reduced_factor(side, left_inds, right_inds, **split_opts)[source]
distance(other, **contract_opts)[source]
distance_normalized[source]
gate(G, ind, preserve_inds=True, inplace=False)[source]

Gate this tensor - contract a matrix into one of its indices without changing its indices. Unlike contract, G is a raw array and the tensor remains with the same set of indices.

Parameters:
  • G (2D array_like) – The matrix to gate the tensor index with.

  • ind (str) – Which index to apply the gate to.

Return type:

Tensor

Examples

Create a random tensor of 4 qubits:

>>> t = qtn.rand_tensor(
...    shape=[2, 2, 2, 2],
...    inds=['k0', 'k1', 'k2', 'k3'],
... )

Create another tensor with an X gate applied to qubit 2:

>>> Gt = t.gate(qu.pauli('X'), 'k2')

The contraction of these two tensors is now the expectation of that operator:

>>> t.H @ Gt
-4.108910576149794
gate_[source]
singular_values(left_inds, method='svd')[source]

Return the singular values associated with splitting this tensor according to left_inds.

Parameters:
  • left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.

  • method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.

Returns:

The singular values.

Return type:

1d-array

entropy(left_inds, method='svd')[source]

Return the entropy associated with splitting this tensor according to left_inds.

Parameters:
  • left_inds (sequence of str) – A subset of this tensors indices that defines ‘left’.

  • method ({'svd', 'eig'}) – Whether to use the SVD or eigenvalue decomposition to get the singular values.

Return type:

float

retag(retag_map, inplace=False)[source]

Rename the tags of this tensor, optionally, in-place.

Parameters:
  • retag_map (dict-like) – Mapping of pairs {old_tag: new_tag, ...}.

  • inplace (bool, optional) – If False (the default), a copy of this tensor with the changed tags will be returned.

retag_[source]
reindex(index_map, inplace=False)[source]

Rename the indices of this tensor, optionally in-place.

Parameters:
  • index_map (dict-like) – Mapping of pairs {old_ind: new_ind, ...}.

  • inplace (bool, optional) – If False (the default), a copy of this tensor with the changed inds will be returned.

reindex_[source]
fuse(fuse_map, inplace=False)[source]

Combine groups of indices into single indices.

Parameters:

fuse_map (dict_like or sequence of tuples.) – Mapping like: {new_ind: sequence of existing inds, ...} or an ordered mapping like [(new_ind_1, old_inds_1), ...] in which case the output tensor’s fused inds will be ordered. In both cases the new indices are created at the minimum axis of any of the indices that will be fused.

Returns:

The transposed, reshaped and re-labeled tensor.

Return type:

Tensor

fuse_[source]
unfuse(unfuse_map, shape_map, inplace=False)[source]

Reshape single indices into groups of multiple indices

Parameters:
  • unfuse_map (dict_like or sequence of tuples.) – Mapping like: {existing_ind: sequence of new inds, ...} or an ordered mapping like [(old_ind_1, new_inds_1), ...] in which case the output tensor’s new inds will be ordered. In both cases the new indices are created at the old index’s position of the tensor’s shape

  • shape_map (dict_like or sequence of tuples) – Mapping like: {old_ind: new_ind_sizes, ...} or an ordered mapping like [(old_ind_1, new_ind_sizes_1), ...].

Returns:

The transposed, reshaped and re-labeled tensor

Return type:

Tensor

unfuse_[source]
to_dense(*inds_seq, to_qarray=False)[source]

Convert this Tensor into an dense array, with a single dimension for each of inds in inds_seqs. E.g. to convert several sites into a density matrix: T.to_dense(('k0', 'k1'), ('b0', 'b1')).

to_qarray[source]
squeeze(include=None, exclude=None, inplace=False)[source]

Drop any singlet dimensions from this tensor.

Parameters:
  • inplace (bool, optional) – Whether modify the original or return a new tensor.

  • include (sequence of str, optional) – Only squeeze dimensions with indices in this list.

  • exclude (sequence of str, optional) – Squeeze all dimensions except those with indices in this list.

  • inplace – Whether to perform the squeeze inplace or not.

Return type:

Tensor

squeeze_[source]
largest_element()[source]

Return the largest element, in terms of absolute magnitude, of this tensor.

idxmin(f=None)[source]

Get the index configuration of the minimum element of this tensor, optionally applying f first.

Parameters:

f (callable or str, optional) – If a callable, apply this function to the tensor data before finding the minimum element. If a string, apply autoray.do(f, data).

Returns:

Mapping of index names to their values at the minimum element.

Return type:

dict[str, int]

idxmax(f=None)[source]

Get the index configuration of the maximum element of this tensor, optionally applying f first.

Parameters:

f (callable or str, optional) – If a callable, apply this function to the tensor data before finding the maximum element. If a string, apply autoray.do(f, data).

Returns:

Mapping of index names to their values at the maximum element.

Return type:

dict[str, int]

norm()[source]

Frobenius norm of this tensor:

\[\|t\|_F = \sqrt{\mathrm{Tr} \left(t^{\dagger} t\right)}\]

where the trace is taken over all indices. Equivalent to the square root of the sum of squared singular values across any partition.

normalize(inplace=False)[source]
normalize_[source]
symmetrize(ind1, ind2, inplace=False)[source]

Hermitian symmetrize this tensor for indices ind1 and ind2. I.e. T = (T + T.conj().T) / 2, where the transpose is taken only over the specified indices.

symmetrize_[source]
isometrize(left_inds=None, method='qr', inplace=False)[source]

Make this tensor unitary (or isometric) with respect to left_inds. The underlying method is set by method.

Parameters:
  • left_inds (sequence of str) – The indices to group together and treat as the left hand side of a matrix.

  • method (str, optional) –

    The method used to generate the isometry. The options are:

    • ”qr”: use the Q factor of the QR decomposition of x with the constraint that the diagonal of R is positive.

    • ”svd”: uses U @ VH of the SVD decomposition of x. This is useful for finding the ‘closest’ isometric matrix to x, 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 completing x with zeros if it is rectangular. This is a good parametrization for optimization, but more expensive for non-square x.

    • ”cayley”: use the Cayley transform of x - dag(x), first completing x with 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-square x.

    • ”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_householder package. 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.

  • inplace (bool, optional) – Whether to perform the unitization inplace.

Return type:

Tensor

isometrize_[source]
unitize[source]
unitize_
randomize(dtype=None, inplace=False, **randn_opts)[source]

Randomize the entries of this tensor.

Parameters:
  • dtype ({None, str}, optional) – The data type of the random entries. If left as the default None, then the data type of the current array will be used.

  • inplace (bool, optional) – Whether to perform the randomization inplace, by default False.

  • randn_opts – Supplied to randn().

Return type:

Tensor

randomize_[source]
flip(ind, inplace=False)[source]

Reverse the axis on this tensor corresponding to ind. Like performing e.g. X[:, :, ::-1, :].

flip_[source]
multiply_index_diagonal(ind, x, inplace=False)[source]

Multiply this tensor by 1D array x as if it were a diagonal tensor being contracted into index ind.

multiply_index_diagonal_[source]
almost_equals(other, **kwargs)[source]

Check if this tensor is almost the same as another.

drop_tags(tags=None)[source]

Drop certain tags, defaulting to all, from this tensor.

bonds(other)[source]

Return a tuple of the shared indices between this tensor and other.

filter_bonds(other)[source]

Sort this tensor’s indices into a list of those that it shares and doesn’t share with another tensor.

Parameters:

other (Tensor) – The other tensor.

Returns:

shared, unshared – The shared and unshared indices.

Return type:

(tuple[str], tuple[str])

__imul__(other)[source]
__itruediv__(other)[source]
__and__(other)[source]

Combine with another Tensor or TensorNetwork into a new TensorNetwork.

__or__(other)[source]

Combine virtually (no copies made) with another Tensor or TensorNetwork into a new TensorNetwork.

__matmul__(other)[source]

Explicitly contract with another tensor. Avoids some slight overhead of calling the full tensor_contract().

negate(inplace=False)[source]

Negate this tensor.

negate_[source]
__neg__()[source]

Negate this tensor.

as_network(virtual=True)[source]

Return a TensorNetwork with only this tensor.

draw(*args, **kwargs)[source]

Plot a graph of this tensor and its indices.

graph[source]
visualize[source]
__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
_repr_info()[source]

General info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_extra()[source]

General detailed info to show in various reprs. Sublasses can add more relevant info to this dict.

_repr_info_str(normal=True, extra=False)[source]

Render the general info as a string.

_repr_html_()[source]

Render this Tensor as HTML, for Jupyter notebooks.

__str__()[source]

Return str(self).

__repr__()[source]

Return repr(self).

class quimb.tensor.tensor_3d.TensorNetworkGen(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: quimb.tensor.tensor_core.TensorNetwork

A tensor network which notionally has a single tensor per ‘site’, though these could be labelled arbitrarily could also be linked in an arbitrary geometry by bonds.

_NDIMS = 1
_EXTRA_PROPS = ('_sites', '_site_tag_id')
_compatible_arbgeom(other)[source]

Check whether self and other represent the same set of sites and are tagged equivalently.

combine(other, *, virtual=False, check_collisions=True)[source]

Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a TensorNetworkGen instance.

Parameters:
  • other (TensorNetworkGen or TensorNetwork) – The other tensor network to combine with.

  • virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (False, the default), or view them as virtual (True).

  • check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If True (the default), any inner indices that clash will be mangled.

Return type:

TensorNetworkGen or TensorNetwork

property nsites
The total number of sites.
gen_site_coos()[source]

Generate the coordinates of all sites, same as self.sites.

property sites
Tuple of the possible sites in this tensor network.
_get_site_set()[source]

The set of all sites.

gen_sites_present()[source]

Generate the sites which are currently present (e.g. if a local view of a larger tensor network), based on whether their tags are present.

Examples

>>> tn = qtn.TN3D_rand(4, 4, 4, 2)
>>> tn_sub = tn.select_local('I1,2,3', max_distance=1)
>>> list(tn_sub.gen_sites_present())
[(0, 2, 3), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 3)]
property site_tag_id
The string specifier for tagging each site of this tensor network.
site_tag(site)[source]

The name of the tag specifiying the tensor at site.

retag_sites(new_id, where=None, inplace=False)[source]

Modify the site tags for all or some tensors in this tensor network (without changing the site_tag_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “S{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to retag in place.

property site_tags
All of the site tags.
property site_tags_present
All of the site tags still present in this tensor network.
retag_all(new_id, inplace=False)[source]

Retag all sites and change the site_tag_id.

retag_all_[source]
_get_site_tag_set()[source]

The oset of all site tags.

filter_valid_site_tags(tags)[source]

Get the valid site tags from tags.

maybe_convert_coo(x)[source]

Check if x is a valid site and convert to the corresponding site tag if so, else return x.

gen_tags_from_coos(coos)[source]

Generate the site tags corresponding to the given coordinates.

_get_tids_from_tags(tags, which='all')[source]

This is the function that lets coordinates such as site be used for many ‘tag’ based functions.

reset_cached_properties()[source]

Reset any cached properties, one should call this when changing the actual geometry of a TN inplace, for example.

align(*args, inplace=False, **kwargs)[source]
align_[source]
__add__(other)[source]
__sub__(other)[source]
__iadd__(other)[source]
__isub__(other)[source]
class quimb.tensor.tensor_3d.TensorNetworkGenVector(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetworkGen

A tensor network which notionally has a single tensor and outer index per ‘site’, though these could be labelled arbitrarily and could also be linked in an arbitrary geometry by bonds.

_EXTRA_PROPS = ('_sites', '_site_tag_id', '_site_ind_id')
property site_ind_id
The string specifier for the physical indices.
site_ind(site)[source]
property site_inds
Return a tuple of all site indices.
property site_inds_present
All of the site inds still present in this tensor network.
reset_cached_properties()[source]

Reset any cached properties, one should call this when changing the actual geometry of a TN inplace, for example.

reindex_sites(new_id, where=None, inplace=False)[source]

Modify the site indices for all or some tensors in this vector tensor network (without changing the site_ind_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “ket{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

reindex_sites_[source]
reindex_all(new_id, inplace=False)[source]

Reindex all physical sites and change the site_ind_id.

reindex_all_[source]
gen_inds_from_coos(coos)[source]

Generate the site inds corresponding to the given coordinates.

phys_dim(site=None)[source]

Get the physical dimension of site, defaulting to the first site if not specified.

to_dense(*inds_seq, to_qarray=False, to_ket=None, **contract_opts)[source]

Contract this tensor network ‘vector’ into a dense array. By default, turn into a ‘ket’ qarray, i.e. column vector of shape (d, 1).

Parameters:
  • inds_seq (sequence of sequences of str) – How to group the site indices into the dense array. By default, use a single group ordered like sites, but only containing those sites which are still present.

  • to_qarray (bool) – Whether to turn the dense array into a qarray, if the backend would otherwise be 'numpy'.

  • to_ket (None or str) – Whether to reshape the dense array into a ket (shape (d, 1) array). If None (default), do this only if the inds_seq is not supplied.

  • contract_opts – Options to pass to contract().

Return type:

array

to_qarray[source]
gate_with_op_lazy(A, transpose=False, inplace=False, **kwargs)[source]

Act lazily with the operator tensor network A, which should have matching structure, on this vector/state tensor network, like A @ x. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

\[| x \rangle \rightarrow A | x \rangle\]

or (if transpose=True):

\[| x \rangle \rightarrow A^T | x \rangle\]
Parameters:
  • A (TensorNetworkGenOperator) – The operator tensor network to gate with, or apply to this tensor network.

  • transpose (bool, optional) – Whether to contract the lower or upper indices of A with the site indices of x. If False (the default), the lower indices of A will be contracted with the site indices of x, if True the upper indices of A will be contracted with the site indices of x, which is like applying A.T @ x.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on this tensor network.

Return type:

TensorNetworkGenVector

gate_with_op_lazy_[source]
gate(G, where, contract=False, tags=None, propagate_tags=False, info=None, inplace=False, **compress_opts)[source]

Apply a gate to this vector tensor network at sites where. This is essentially a wrapper around gate_inds() apart from where can be specified as a list of sites, and tags can be optionally, intelligently propagated to the new gate tensor.

\[| \psi \rangle \rightarrow G_\mathrm{where} | \psi \rangle\]
Parameters:
  • G (array_ike) – The gate array to apply, should match or be factorable into the shape (*phys_dims, *phys_dims).

  • where (node or sequence[node]) – The sites to apply the gate to.

  • contract ({False, True, 'split', 'reduce-split', 'split-gate',) – ‘swap-split-gate’, ‘auto-split-gate’}, optional How to apply the gate, see gate_inds().

  • tags (str or sequence of str, optional) – Tags to add to the new gate tensor.

  • propagate_tags ({False, True, 'register', 'sites'}, optional) –

    Whether to propagate tags to the new gate tensor:

    - False: no tags are propagated
    - True: all tags are propagated
    - 'register': only site tags corresponding to ``where`` are
      added.
    - 'sites': all site tags on the current sites are propgated,
      resulting in a lightcone like tagging.
    

  • info (None or dict, optional) – Used to store extra optional information such as the singular values if not absorbed.

  • inplace (bool, optional) – Whether to perform the gate operation inplace on the tensor network or not.

  • compress_opts – Supplied to tensor_split() for any contract methods that involve splitting. Ignored otherwise.

Return type:

TensorNetworkGenVector

See also

TensorNetwork.gate_inds

gate_[source]
gate_simple_(G, where, gauges, renorm=True, **gate_opts)[source]

Apply a gate to this vector tensor network at sites where, using simple update style gauging of the tensors first, as supplied in gauges. The new singular values for the bond are reinserted into gauges.

Parameters:
  • G (array_like) – The gate to be applied.

  • where (node or sequence[node]) – The sites to apply the gate to.

  • gauges (dict[str, array_like]) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.

  • renorm (bool, optional) – Whether to renormalise the singular after the gate is applied, before reinserting them into gauges.

gate_fit_local_(G, where, max_distance=0, fillin=0, gauges=None, **fit_opts)[source]
local_expectation_cluster(G, where, normalized=True, max_distance=0, fillin=False, gauges=None, optimize='auto', max_bond=None, rehearse=False, **contract_opts)[source]

Approximately compute a single local expectation value of the gate G at sites where, either treating the environment beyond max_distance as the identity, or using simple update style bond gauges as supplied in gauges.

This selects a local neighbourhood of tensors up to distance max_distance away from where, then traces over dangling bonds after potentially inserting the bond gauges, to form an approximate version of the reduced density matrix.

\[\langle \psi | G | \psi \rangle \approx \frac{ \mathrm{Tr} [ G \tilde{\rho}_\mathrm{where} ] }{ \mathrm{Tr} [ \tilde{\rho}_\mathrm{where} ] }\]

assuming normalized==True.

Parameters:
  • G (array_like) – The gate to compute the expecation of.

  • where (node or sequence[node]) – The sites to compute the expectation at.

  • normalized (bool, optional) – Whether to locally normalize the result, i.e. divide by the expectation value of the identity.

  • max_distance (int, optional) – The maximum graph distance to include tensors neighboring where when computing the expectation. The default 0 means only the tensors at sites where are used.

  • fillin (bool or int, optional) – When selecting the local tensors, whether and how many times to ‘fill-in’ corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See select_local().

  • gauges (dict[str, array_like], optional) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the local tensors.

  • max_bond (None or int, optional) – If specified, use compressed contraction.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

Returns:

expectation

Return type:

float

local_expectation_simple[source]
compute_local_expectation_cluster(terms, *, max_distance=0, fillin=False, normalized=True, gauges=None, optimize='auto', max_bond=None, return_all=False, rehearse=False, executor=None, progbar=False, **contract_opts)[source]

Compute all local expectations of the given terms, either treating the environment beyond max_distance as the identity, or using simple update style bond gauges as supplied in gauges.

This selects a local neighbourhood of tensors up to distance max_distance away from each term’s sites, then traces over dangling bonds after potentially inserting the bond gauges, to form an approximate version of the reduced density matrix.

\[\sum_\mathrm{i} \langle \psi | G_\mathrm{i} | \psi \rangle \approx \sum_\mathrm{i} \frac{ \mathrm{Tr} [ G_\mathrm{i} \tilde{\rho}_\mathrm{i} ] }{ \mathrm{Tr} [ \tilde{\rho}_\mathrm{i} ] }\]

assuming normalized==True.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • max_distance (int, optional) – The maximum graph distance to include tensors neighboring each term’s sites when computing the expectation. The default 0 means only the tensors at sites of each term are used.

  • fillin (bool or int, optional) – When selecting the local tensors, whether and how many times to ‘fill-in’ corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See select_local().

  • normalized (bool, optional) – Whether to locally normalize the result, i.e. divide by the expectation value of the identity. This implies that a different normalization factor is used for each term.

  • gauges (dict[str, array_like], optional) – The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the local tensors.

  • max_bond (None or int, optional) – If specified, use compressed contraction.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_opts – Supplied to contract().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]

compute_local_expectation_simple[source]
local_expectation_exact(G, where, optimize='auto-hq', normalized=True, rehearse=False, **contract_opts)[source]

Compute the local expectation of operator G at site(s) where by exactly contracting the full overlap tensor network.

compute_local_expectation_exact(terms, optimize='auto-hq', *, normalized=True, return_all=False, rehearse=False, executor=None, progbar=False, **contract_opts)[source]

Compute the local expectations of many operators, by exactly contracting the full overlap tensor network.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, when exactly contracting the full tensor network.

  • normalized (bool, optional) – Whether to normalize the result.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_opts – Supplied to contract().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]

partial_trace(keep, max_bond, optimize, flatten=True, reduce=False, normalized=True, symmetrized='auto', rehearse=False, method='contract_compressed', **contract_compressed_opts)[source]

Partially trace this tensor network state, keeping only the sites in keep, using compressed contraction.

Parameters:
  • keep (iterable of hashable) – The sites to keep.

  • max_bond (int) – The maximum bond dimensions to use while compressed contracting.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction.

  • flatten ({False, True, 'all'}, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually improved. If 'all' also flatten the tensors in keep.

  • reduce (bool, optional) – Whether to first ‘pull’ the physical indices off their respective tensors using QR reduction. Experimental.

  • normalized (bool, optional) – Whether to normalize the reduced density matrix at the end.

  • symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computation or not:

    - False: perform the computation.
    - 'tn': return the tensor network without running the path
      optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree``..
    - True: run the path optimizer and return the ``PathInfo``.
    

  • contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to contract_compressed().

Returns:

rho – The reduce density matrix of sites in keep.

Return type:

array_like

local_expectation(G, where, max_bond, optimize, flatten=True, normalized=True, symmetrized='auto', reduce=False, rehearse=False, **contract_compressed_opts)[source]

Compute the local expectation of operator G at site(s) where by approximately contracting the full overlap tensor network.

Parameters:
  • G (array_like) – The local operator to compute the expectation of.

  • where (node or sequence of nodes) – The sites to compute the expectation for.

  • max_bond (int) – The maximum bond dimensions to use while compressed contracting.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction.

  • method ({'rho', 'rho-reduced'}, optional) – The method to use to compute the expectation value.

  • flatten (bool, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually much improved.

  • normalized (bool, optional) – If computing via partial_trace, whether to normalize the reduced density matrix at the end.

  • symmetrized ({'auto', True, False}, optional) – If computing via partial_trace, whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computation or not:

    - False: perform the computation.
    - 'tn': return the tensor network without running the path
      optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree``..
    - True: run the path optimizer and return the ``PathInfo``.
    

  • contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to contract_compressed().

Returns:

expec

Return type:

float

compute_local_expectation(terms, max_bond, optimize, *, flatten=True, normalized=True, symmetrized='auto', reduce=False, return_all=False, rehearse=False, executor=None, progbar=False, **contract_compressed_opts)[source]

Compute the local expectations of many local operators, by approximately contracting the full overlap tensor network.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • max_bond (int) – The maximum bond dimension to use during contraction.

  • optimize (str or PathOptimizer) – The compressed contraction path optimizer to use.

  • method ({'rho', 'rho-reduced'}, optional) –

    The method to use to compute the expectation value.

    • ’rho’: compute the expectation value via the reduced density matrix.

    • ’rho-reduced’: compute the expectation value via the reduced density matrix, having reduced the physical indices onto the bonds first.

  • flatten (bool, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy can often be much improved.

  • normalized (bool, optional) – Whether to locally normalize the result.

  • symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation. If rehease is not False, this is ignored and a dict is always returned.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_compressed_opts – Supplied to contract_compressed().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]

compute_local_expectation_rehearse[source]
compute_local_expectation_tn[source]
quimb.tensor.tensor_3d.gen_3d_bonds(Lx, Ly, Lz, steppers=None, coo_filter=None, cyclic=False)[source]

Convenience function for tiling pairs of bond coordinates on a 3D lattice given a function like lambda i, j, k: (i + 1, j + 1, k + 1).

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • steppers (callable or sequence of callable) – Function(s) that take args (i, j, k) and generate another coordinate, thus defining a bond. Only valid steps are taken. If not given, defaults to nearest neighbor bonds.

  • coo_filter (callable) – Function that takes args (i, j, k) and only returns True if this is to be a valid starting coordinate.

Yields:

bond (tuple[tuple[int, int, int], tuple[int, int, int]]) – A pair of coordinates.

Examples

Generate nearest neighbor bonds:

>>> for bond in gen_3d_bonds(2, 2, 2, [lambda i, j, k: (i + 1, j, k),
...                                    lambda i, j, k: (i, j + 1, k),
...                                    lambda i, j, k: (i, j, k + 1)]):
...     print(bond)
((0, 0, 0), (1, 0, 0))
((0, 0, 0), (0, 1, 0))
((0, 0, 0), (0, 0, 1))
((0, 0, 1), (1, 0, 1))
((0, 0, 1), (0, 1, 1))
((0, 1, 0), (1, 1, 0))
((0, 1, 0), (0, 1, 1))
((0, 1, 1), (1, 1, 1))
((1, 0, 0), (1, 1, 0))
((1, 0, 0), (1, 0, 1))
((1, 0, 1), (1, 1, 1))
((1, 1, 0), (1, 1, 1))
quimb.tensor.tensor_3d.gen_3d_plaquette(coo0, steps)[source]

Generate a plaquette at site coo0 by stepping first in steps and then the reverse steps.

Parameters:
  • coo0 (tuple) – The coordinate of the first site in the plaquette.

  • steps (tuple) – The steps to take to generate the plaquette. Each element should be one of ('x+', 'x-', 'y+', 'y-', 'z+', 'z-').

Yields:

coo (tuple) – The coordinates of the sites in the plaquette, including the last site which will be the same as the first.

quimb.tensor.tensor_3d.gen_3d_plaquettes(Lx, Ly, Lz, tiling='1')[source]

Generate a tiling of plaquettes in a cubic 3D lattice.

Parameters:
  • Lx (int) – The length of the lattice in the x direction.

  • Ly (int) – The length of the lattice in the y direction.

  • Lz (int) – The length of the lattice in the z direction.

  • tiling ({'1', '2', '4', 'full'}) –

    The tiling to use:

    • ’1’: plaquettes in a sparse checkerboard pattern, such that each edge

      is covered by a maximum of one plaquette.

    • ’2’: less sparse checkerboard pattern, such that each edge is

      covered by a maximum of two plaquettes.

    • ’4’ or ‘full’: dense tiling of plaquettes. All bulk edges will

      be covered four times.

Yields:

plaquette (tuple[tuple[int]]) – The coordinates of the sites in each plaquette, including the last site which will be the same as the first.

quimb.tensor.tensor_3d.gen_3d_strings(Lx, Ly, Lz)[source]

Generate all length-wise strings in a cubic 3D lattice.

class quimb.tensor.tensor_3d.Rotator3D(tn, xrange, yrange, zrange, from_which)[source]

Object for rotating coordinates and various contraction functions so that the core algorithms only have to written once, but nor does the actual TN have to be modified.

property sweep_other
cyclic_x()
cyclic_y()
cyclic_z()
get_jnext(j)[source]
get_knext(k)[source]
quimb.tensor.tensor_3d._canonize_plane_opts
quimb.tensor.tensor_3d._compress_plane_opts
quimb.tensor.tensor_3d.BOUNDARY_SEQUENCE_MAP
quimb.tensor.tensor_3d.parse_boundary_sequence(sequence)[source]
class quimb.tensor.tensor_3d.TensorNetwork3D(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: quimb.tensor.tensor_arbgeom.TensorNetworkGen

Mixin class for tensor networks with a cubic lattice three-dimensional structure.

_NDIMS = 3
_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz')
_compatible_3d(other)[source]

Check whether self and other are compatible 3D tensor networks such that they can remain a 3D tensor network when combined.

combine(other, *, virtual=False, check_collisions=True)[source]

Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a TensorNetwork3D instance.

Parameters:
  • other (TensorNetwork3D or TensorNetwork) – The other tensor network to combine with.

  • virtual (bool, optional) – Whether the new tensor network should copy all the incoming tensors (False, the default), or view them as virtual (True).

  • check_collisions (bool, optional) – Whether to check for index collisions between the two tensor networks before combining them. If True (the default), any inner indices that clash will be mangled.

Return type:

TensorNetwork3D or TensorNetwork

property Lx
The number of x-slices.
property Ly
The number of y-slices.
property Lz
The number of z-slices.
property nsites
The total number of sites.
site_tag(i, j=None, k=None)[source]

The name of the tag specifiying the tensor at site (i, j, k).

property x_tag_id
The string specifier for tagging each x-slice of this 3D TN.
x_tag(i)[source]
property x_tags
A tuple of all of the ``Lx`` different x-slice tags.
property y_tag_id
The string specifier for tagging each y-slice of this 3D TN.
y_tag(j)[source]
property y_tags
A tuple of all of the ``Ly`` different y-slice tags.
property z_tag_id
The string specifier for tagging each z-slice of this 3D TN.
z_tag(k)[source]
property z_tags
A tuple of all of the ``Lz`` different z-slice tags.
maybe_convert_coo(coo)[source]

Check if coo is a tuple of three ints and convert to the corresponding site tag if so.

_get_tids_from_tags(tags, which='all')[source]

This is the function that lets coordinates such as (i, j, k) be used for many ‘tag’ based functions.

gen_site_coos()[source]

Generate coordinates for all the sites in this 3D TN.

gen_bond_coos()[source]

Generate pairs of coordinates for all the bonds in this 3D TN.

valid_coo(coo, xrange=None, yrange=None, zrange=None)[source]

Check whether coo is in-bounds.

Parameters:
  • coo ((int, int, int), optional) – The coordinates to check.

  • xrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • yrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • zrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

Return type:

bool

get_ranges_present()[source]

Return the range of site coordinates present in this TN.

Returns:

xrange, yrange, zrange – The minimum and maximum site coordinates present in each direction.

Return type:

tuple[tuple[int, int]]

Examples

>>> tn = qtn.TN3D_rand(4, 4, 4, 2)
>>> tn_sub = tn.select_local('I1,2,3', max_distance=1)
>>> tn_sub.get_ranges_present()
((0, 2), (1, 3), (2, 3))
is_cyclic_x(j=None, k=None, imin=None, imax=None)[source]

Check if the x dimension is cyclic (periodic), specifically whether a bond exists between (imin, j, k) and (imax, j, k), with default values of imin = 0 and imax = Lx - 1, and j and k the center of the lattice. If imin and imax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

is_cyclic_y(k=None, i=None, jmin=None, jmax=None)[source]

Check if the y dimension is cyclic (periodic), specifically whether a bond exists between (i, jmin, k) and (i, jmax, k), with default values of jmin = 0 and jmax = Ly - 1, and i and k the center of the lattice. If jmin and jmax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

is_cyclic_z(i=None, j=None, kmin=None, kmax=None)[source]

Check if the z dimension is cyclic (periodic), specifically whether a bond exists between (i, j, kmin) and (i, j, kmax), with default values of kmin = 0 and kmax = Lz - 1, and i and j the center of the lattice. If kmin and kmax are adjacent then this is considered False, since there is no ‘extra’ connectivity.

__getitem__(key)[source]

Key based tensor selection, checking for integer based shortcut.

_repr_info()[source]

General info to show in various reprs. Sublasses can add more relevant info to this dict.

flatten(fuse_multibonds=True, inplace=False)[source]

Contract all tensors corresponding to each site into one.

flatten_[source]
gen_pairs(xrange=None, yrange=None, zrange=None, xreverse=False, yreverse=False, zreverse=False, coordinate_order='xyz', xstep=None, ystep=None, zstep=None, stepping_order='xyz', step_only=None)[source]

Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order.

Parameters:
  • xrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • yrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • zrange ((int, int), optional) – The range of allowed values for the x, y, and z coordinates.

  • xreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.

  • yreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.

  • zreverse (bool, optional) – Whether to reverse the order of the x, y, and z sweeps.

  • coordinate_order (str, optional) – The order in which to sweep the x, y, and z coordinates. Earlier dimensions will change slower. If the corresponding range has size 1 then that dimension doesn’t need to be specified.

  • xstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse, yreverse, and zreverse respectively.

  • ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse, yreverse, and zreverse respectively.

  • zstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow xreverse, yreverse, and zreverse respectively.

  • stepping_order (str, optional) – The order in which to step the x, y, and z coordinates to generate bonds. Does not need to include all dimensions.

  • step_only (int, optional) – Only perform the ith steps in stepping_order, used to interleave canonizing and compressing for example.

Yields:

coo_a, coo_b (((int, int, int), (int, int, int)))

canonize_plane(xrange, yrange, zrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts)[source]

Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.

compress_plane(xrange, yrange, zrange, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None, **gen_pair_opts)[source]

Compress every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.

_contract_boundary_core_via_2d(xrange, yrange, zrange, from_which, max_bond, cutoff=1e-10, method='local-early', layer_tags=None, **compress_opts)[source]
_contract_boundary_core(xrange, yrange, zrange, from_which, max_bond, cutoff=1e-10, canonize=True, canonize_interleave=True, layer_tags=None, compress_late=True, equalize_norms=False, compress_opts=None, canonize_opts=None)[source]
_contract_boundary_projector(xrange, yrange, zrange, from_which, max_bond=None, cutoff=1e-10, canonize=False, layer_tags=None, lazy=False, equalize_norms=False, optimize='auto-hq', compress_opts=None, canonize_opts=None)[source]
contract_boundary_from(xrange, yrange, zrange, from_which, max_bond=None, *, cutoff=1e-10, mode='peps', equalize_norms=False, compress_opts=None, canonize_opts=None, inplace=False, **contract_boundary_opts)[source]

Unified entrypoint for contracting any rectangular patch of tensors from any direction, with any boundary method.

contract_boundary_from_[source]
_contract_interleaved_boundary_sequence(*, contract_boundary_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, canonize=False, canonize_opts=None, final_contract=True, final_contract_opts=None, optimize='auto-hq', progbar=False, inplace=False)[source]

Unified handler for performing iterleaved contractions in a sequence of inwards boundary directions.

contract_boundary(max_bond=None, *, cutoff=1e-10, mode='peps', canonize=True, compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, final_contract=True, final_contract_opts=None, optimize='auto-hq', progbar=False, inplace=False, **contract_boundary_opts)[source]
contract_boundary_[source]
contract_ctmrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, lazy=False, mode='projector', compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **contract_boundary_opts)[source]
contract_ctmrg_[source]
_compute_plane_envs(xrange, yrange, zrange, from_which, envs=None, storage_factory=None, **contract_boundary_opts)[source]

Compute all ‘plane’ environments for the cube given by xrange, yrange, zrange, with direction given by from_which.

_maybe_compute_cell_env(key, envs=None, storage_factory=None, boundary_order=None, **contract_boundary_opts)[source]

Recursively compute the necessary 2D, 1D, and 0D environments.

coarse_grain_hotrg(direction, max_bond=None, cutoff=1e-10, lazy=False, equalize_norms=False, optimize='auto-hq', compress_opts=None, inplace=False)[source]

Coarse grain this tensor network in direction using HOTRG. This inserts oblique projectors between tensor pairs and then optionally contracts them into new sites for form a lattice half the size.

Parameters:
  • direction ({'x', 'y', 'z'}) – The direction to coarse grain in.

  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • equalize_norms (bool, optional) – Whether to equalize the norms of the tensors in the coarse grained lattice.

  • optimize (str, optional) – The optimization method to use when contracting the coarse grained lattice, if lazy=False.

  • compress_opts (None or dict, optional) – Supplied to insert_compressor_between_regions().

  • inplace (bool, optional) – Whether to perform the coarse graining in place.

Returns:

The coarse grained tensor network, with size halved in direction.

Return type:

TensorNetwork2D

See also

contract_hotrg, insert_compressor_between_regions

coarse_grain_hotrg_[source]
contract_hotrg(max_bond=None, cutoff=1e-10, canonize=False, canonize_opts=None, sequence=('x', 'y', 'z'), max_separation=1, max_unfinished=1, lazy=False, equalize_norms=False, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **coarse_grain_opts)[source]

Contract this tensor network using the finite version of HOTRG. See https://arxiv.org/abs/1201.1144v4 and https://arxiv.org/abs/1905.02351 for the more optimal computaton of the projectors used here. The TN is contracted sequentially in sequence directions by inserting oblique projectors between tensor pairs, and then optionally contracting these new effective sites. The algorithm stops when only one direction has a length larger than 2, and thus exact contraction can be used.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.

  • cutoff (float, optional) – The cutoff for the singular values of the projector pairs.

  • sequence (tuple of str, optional) – The directions to contract in. Default is to contract in all directions.

  • max_separation (int, optional) – The maximum distance between sides (i.e. length - 1) of the tensor network before that direction is considered finished.

  • max_unfinished (int, optional) – The maximum number of directions that can be unfinished (i.e. are still longer than max_separation + 1) before the coarse graining terminates.

  • lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.

  • equalize_norms (bool or float, optional) – Whether to equalize the norms of the tensors in the tensor network after each coarse graining step.

  • final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the coarse graining contractions.

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), optimize defaults to 'auto-hq'.

  • inplace (bool, optional) – Whether to perform the coarse graining in place.

  • coarse_grain_opts – Additional options to pass to coarse_grain_hotrg().

Returns:

The contracted tensor network, which will have no more than one directino of length > 2.

Return type:

TensorNetwork3D

See also

coarse_grain_hotrg, insert_compressor_between_regions

contract_hotrg_[source]
quimb.tensor.tensor_3d.is_lone_coo(where)[source]

Check if where has been specified as a single coordinate triplet.

quimb.tensor.tensor_3d.calc_cell_sizes(coo_groups, autogroup=True)[source]
quimb.tensor.tensor_3d.cell_to_sites(p)[source]

Turn a cell ((i0, j0, k0), (di, dj, dk)) into the sites it contains.

Examples

>>> cell_to_sites([(3, 4), (2, 2)])
((3, 4), (3, 5), (4, 4), (4, 5))
quimb.tensor.tensor_3d.sites_to_cell(sites)[source]

Get the minimum covering cell for sites.

Examples

>>> sites_to_cell([(1, 3, 3), (2, 2, 4)])
((1, 2, 3) , (2, 2, 2))
quimb.tensor.tensor_3d.calc_cell_map(cells)[source]
class quimb.tensor.tensor_3d.TensorNetwork3DVector(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetwork3D, quimb.tensor.tensor_arbgeom.TensorNetworkGenVector

Mixin class for a 3D square lattice vector TN, i.e. one with a single physical index per site.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz', '_site_ind_id')
site_ind(i, j=None, k=None)[source]
reindex_sites(new_id, where=None, inplace=False)[source]

Modify the site indices for all or some tensors in this vector tensor network (without changing the site_ind_id).

Parameters:
  • new_id (str) – A string with a format placeholder to accept a site, e.g. “ket{}”.

  • where (None or sequence) – Which sites to update the index labels on. If None (default) all sites.

  • inplace (bool) – Whether to reindex in place.

phys_dim(i=None, j=None, k=None)[source]

Get the size of the physical indices / a specific physical index.

gate(G, where, contract=False, tags=None, info=None, inplace=False, **compress_opts)[source]

Apply a gate G to sites where, preserving the outer site inds.

gate_[source]
class quimb.tensor.tensor_3d.TensorNetwork3DFlat(ts=(), *, virtual=False, check_collisions=True)[source]

Bases: TensorNetwork3D

Mixin class for a 3D square lattice tensor network with a single tensor per site, for example, both PEPS and PEPOs.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz')
bond(coo1, coo2)[source]

Get the name of the index defining the bond between sites at coo1 and coo2.

bond_size(coo1, coo2)[source]

Return the size of the bond between sites at coo1 and coo2.

class quimb.tensor.tensor_3d.PEPS3D(arrays, *, shape='urfdlbp', tags=None, site_ind_id='k{},{},{}', site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', **tn_opts)[source]

Bases: TensorNetwork3DVector, TensorNetwork3DFlat

Projected Entangled Pair States object (3D).

Parameters:
  • arrays (sequence of sequence of sequence of array) – The core tensor data arrays.

  • shape (str, optional) – Which order the dimensions of the arrays are stored in, the default 'urfdlbp' stands for (‘up’, ‘right’, ‘front’, down’, ‘left’, ‘behind’, ‘physical’) meaning (x+, y+, z+, x-, y-, z-, physical) respectively. Arrays on the edge of lattice are assumed to be missing the corresponding dimension.

  • tags (set[str], optional) – Extra global tags to add to the tensor network.

  • site_ind_id (str, optional) – String specifier for naming convention of site indices.

  • site_tag_id (str, optional) – String specifier for naming convention of site tags.

  • x_tag_id (str, optional) – String specifier for naming convention of x-slice tags.

  • y_tag_id (str, optional) – String specifier for naming convention of y-slice tags.

  • z_tag_id (str, optional) – String specifier for naming convention of z-slice tags.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz', '_site_ind_id')
permute_arrays(shape='urfdlbp')[source]

Permute the indices of each tensor in this PEPS3D to match shape. This doesn’t change how the overall object interacts with other tensor networks but may be useful for extracting the underlying arrays consistently. This is an inplace operation.

Parameters:

shape (str, optional) – A permutation of 'lrp' specifying the desired order of the left, right, and physical indices respectively.

classmethod from_fill_fn(fill_fn, Lx, Ly, Lz, bond_dim, phys_dim=2, cyclic=False, shape='urfdlbp', **peps3d_opts)[source]

Create a 3D PEPS from a filling function with signature fill_fn(shape).

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • bond_dim (int) – The bond dimension.

  • phys_dim (int, optional) – The physical index dimension.

  • shape (str, optional) – How to layout the indices of the tensors, the default is (up, right, front, down, left, back, phys) == 'urfdlbp'. This is the order of the shape supplied to the filling function.

  • peps_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

classmethod empty(Lx, Ly, Lz, bond_dim, phys_dim=2, like='numpy', **peps3d_opts)[source]

Create an empty 3D PEPS.

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • peps3d_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

classmethod ones(Lx, Ly, Lz, bond_dim, phys_dim=2, like='numpy', **peps3d_opts)[source]

Create a 3D PEPS whose tensors are filled with ones.

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • peps3d_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

classmethod rand(Lx, Ly, Lz, bond_dim, phys_dim=2, dist='normal', loc=0.0, dtype='float64', seed=None, **peps3d_opts)[source]

Create a random (un-normalized) 3D PEPS.

Parameters:
  • Lx (int) – The number of x-slices.

  • Ly (int) – The number of y-slices.

  • Lz (int) – The number of z-slices.

  • bond_dim (int) – The bond dimension.

  • physical (int, optional) – The physical index dimension.

  • dtype (dtype, optional) – The dtype to create the arrays with, default is real double.

  • seed (int, optional) – A random seed.

  • peps_opts – Supplied to PEPS3D.

Returns:

psi

Return type:

PEPS3D

partial_trace_cluster(keep, max_bond=None, *, cutoff=1e-10, max_distance=0, fillin=0, gauges=False, flatten=False, normalized=True, symmetrized='auto', get=None, **contract_boundary_opts)[source]
partial_trace(keep, max_bond=None, *, cutoff=1e-10, canonize=True, flatten=False, normalized=True, symmetrized='auto', envs=None, storage_factory=None, boundary_order=None, contract_cell_optimize='auto-hq', contract_cell_method='boundary', contract_cell_opts=None, get=None, **contract_boundary_opts)[source]

Partially trace this tensor network state, keeping only the sites in keep, using compressed contraction.

Parameters:
  • keep (iterable of hashable) – The sites to keep.

  • max_bond (int) – The maximum bond dimensions to use while compressed contracting.

  • optimize (str or PathOptimizer, optional) – The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction.

  • flatten ({False, True, 'all'}, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually improved. If 'all' also flatten the tensors in keep.

  • reduce (bool, optional) – Whether to first ‘pull’ the physical indices off their respective tensors using QR reduction. Experimental.

  • normalized (bool, optional) – Whether to normalize the reduced density matrix at the end.

  • symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computation or not:

    - False: perform the computation.
    - 'tn': return the tensor network without running the path
      optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree``..
    - True: run the path optimizer and return the ``PathInfo``.
    

  • contract_compressed_opts (dict, optional) – Additional keyword arguments to pass to contract_compressed().

Returns:

rho – The reduce density matrix of sites in keep.

Return type:

array_like

compute_local_expectation(terms, max_bond=None, *, cutoff=1e-10, canonize=True, flatten=False, normalized=True, symmetrized='auto', return_all=False, envs=None, storage_factory=None, progbar=False, **contract_boundary_opts)[source]

Compute the local expectations of many local operators, by approximately contracting the full overlap tensor network.

Parameters:
  • terms (dict[node or (node, node), array_like]) – The terms to compute the expectation of, with keys being the sites and values being the local operators.

  • max_bond (int) – The maximum bond dimension to use during contraction.

  • optimize (str or PathOptimizer) – The compressed contraction path optimizer to use.

  • method ({'rho', 'rho-reduced'}, optional) –

    The method to use to compute the expectation value.

    • ’rho’: compute the expectation value via the reduced density matrix.

    • ’rho-reduced’: compute the expectation value via the reduced density matrix, having reduced the physical indices onto the bonds first.

  • flatten (bool, optional) – Whether to force ‘flattening’ (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy can often be much improved.

  • normalized (bool, optional) – Whether to locally normalize the result.

  • symmetrized ({'auto', True, False}, optional) – Whether to symmetrize the reduced density matrix at the end. This should be unecessary if flatten is set to True.

  • return_all (bool, optional) – Whether to return all results, or just the summed expectation. If rehease is not False, this is ignored and a dict is always returned.

  • rehearse ({False, 'tn', 'tree', True}, optional) –

    Whether to perform the computations or not:

    - False: perform the computation.
    - 'tn': return the tensor networks of each local expectation,
      without running the path optimizer.
    - 'tree': run the path optimizer and return the
      ``cotengra.ContractonTree`` for each local expectation.
    - True: run the path optimizer and return the ``PathInfo`` for
      each local expectation.
    

  • executor (Executor, optional) – If supplied compute the terms in parallel using this executor.

  • progbar (bool, optional) – Whether to show a progress bar.

  • contract_compressed_opts – Supplied to contract_compressed().

Returns:

expecs – If return_all==False, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term’s location to the expectation value.

Return type:

float or dict[node or (node, node), float]