quimb.tensor.tensor_arbgeom

Classes and algorithms related to arbitrary geometry tensor networks.

Attributes

Classes

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

TensorNetworkGenOperator

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

Functions

get_coordinate_formatter(ndims)

prod(xs)

Product of all elements in xs.

tensor_network_align(*tns[, ind_ids, trace, inplace])

Align an arbitrary number of tensor networks in a stack-like geometry:

tensor_network_apply_op_vec(A, x[, which_A, contract, ...])

Apply a general a general tensor network representing an operator (has

tensor_network_apply_op_op(A, B[, which_A, which_B, ...])

Apply the operator (has upper and lower site inds) represented by tensor

create_lazy_edge_map(tn[, site_tags])

Given a tensor network, where each tensor is in exactly one group or

tensor_network_ag_sum(tna, tnb[, site_tags, negate, ...])

Add two tensor networks with arbitrary, but matching, geometries. They

tensor_network_ag_gate(self, G, where[, contract, ...])

Apply a gate to this vector tensor network at sites where. This is

gauge_product_boundary_vector(tn, tags[, which, ...])

region_remove_dangling(sites, neighbors[, where])

_handle_rehearse(rehearse, tn, optimize, **kwargs)

_compute_expecs_maybe_in_parallel(fn, tn, terms[, ...])

Unified helper function for the various methods that compute many

_tn_local_expectation(tn, *args, **kwargs)

Define as function for pickleability.

_tn_local_expectation_cluster(tn, *args, **kwargs)

Define as function for pickleability.

_tn_local_expectation_exact(tn, *args, **kwargs)

Define as function for pickleability.

_tn_local_expectation_loop_expansion(tn, *args, **kwargs)

Define as function for pickleability.

_tn_local_expectation_cluster_expansion(tn, *args, ...)

Define as function for pickleability.

Module Contents

quimb.tensor.tensor_arbgeom.get_coordinate_formatter(ndims)
quimb.tensor.tensor_arbgeom.prod(xs)

Product of all elements in xs.

quimb.tensor.tensor_arbgeom.tensor_network_align(*tns: TensorNetworkGen, ind_ids=None, trace=False, inplace=False)

Align an arbitrary number of tensor networks in a stack-like geometry:

a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a
| | | | | | | | | | | | | | | | | | <- ind_ids[0] (defaults to 1st id)
b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b
| | | | | | | | | | | | | | | | | | <- ind_ids[1]
               ...
| | | | | | | | | | | | | | | | | | <- ind_ids[-2]
y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y
| | | | | | | | | | | | | | | | | | <- ind_ids[-1]
z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z
Parameters:
  • tns (sequence of TensorNetwork) – The TNs to align, should be structured and either effective ‘vectors’ (have a site_ind_id) or ‘operators’ (have a up_ind_id and lower_ind_id).

  • ind_ids (None, or sequence of str) – String with format specifiers to id each level of sites with. Will be automatically generated like (tns[0].site_ind_id, "__ind_a{}__", "__ind_b{}__", ...) if not given.

  • inplace (bool) – Whether to modify the input tensor networks inplace.

Returns:

tns_aligned

Return type:

sequence of TensorNetwork

quimb.tensor.tensor_arbgeom.tensor_network_apply_op_vec(A: TensorNetworkGenOperator, x: TensorNetworkGenVector, which_A='lower', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts)

Apply a general a general tensor network representing an operator (has upper_ind_id and lower_ind_id) to a tensor network representing a vector (has site_ind_id), by contracting each pair of tensors at each site then compressing the resulting tensor network. How the compression takes place is determined by the type of tensor network passed in. The returned tensor network has the same site indices as x, and it is the lower_ind_id of A that is contracted.

This is like performing A.to_dense() @ x.to_dense(), or the transpose thereof, depending on the value of which_A.

Parameters:
  • A (TensorNetworkGenOperator) – The tensor network representing the operator.

  • x (TensorNetworkGenVector) – The tensor network representing the vector.

  • which_A ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of A with the site indices of x.

  • contract (bool) – Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site.

  • fuse_multibonds (bool) – If contract=True, whether to fuse any multibonds after contracting the tensors at each site.

  • compress (bool) – Whether to compress the resulting tensor network.

  • inplace (bool) – Whether to modify x, the input vector tensor network inplace.

  • inplace_A (bool) – Whether to modify A, the operator tensor network inplace.

  • compress_opts – Options to pass to tn.compress, where tn is the resulting tensor network, if compress=True.

Returns:

The same type as x.

Return type:

TensorNetworkGenVector

quimb.tensor.tensor_arbgeom.tensor_network_apply_op_op(A: TensorNetworkGenOperator, B: TensorNetworkGenOperator, which_A='lower', which_B='upper', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts)

Apply the operator (has upper and lower site inds) represented by tensor network A to the operator represented by tensor network B. The resulting tensor network has the same upper and lower indices as B. Optionally contract the tensors at each site, fuse any multibonds, and compress the resulting tensor network.

This is like performing A.to_dense() @ B.to_dense(), or various combinations of tranposes thereof, depending on the values of which_A and which_B.

Parameters:
  • A (TensorNetworkGenOperator) – The tensor network representing the operator to apply.

  • B (TensorNetworkGenOperator) – The tensor network representing the target operator.

  • which_A ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of A.

  • which_B ({"lower", "upper"}, optional) – Whether to contract the lower or upper indices of B.

  • contract (bool) – Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site.

  • fuse_multibonds (bool) – If contract=True, whether to fuse any multibonds after contracting the tensors at each site.

  • compress (bool) – Whether to compress the resulting tensor network.

  • inplace (bool) – Whether to modify B, the target tensor network inplace.

  • inplace_A (bool) – Whether to modify A, the applied operator tensor network inplace.

  • compress_opts – Options to pass to tn.compress, where tn is the resulting tensor network, if compress=True.

Returns:

The same type as B.

Return type:

TensorNetworkGenOperator

quimb.tensor.tensor_arbgeom.create_lazy_edge_map(tn: TensorNetworkGen, site_tags=None)

Given a tensor network, where each tensor is in exactly one group or ‘site’, compute which sites are connected to each other, without checking each pair.

Parameters:
  • tn (TensorNetwork) – The tensor network to analyze.

  • site_tags (None or sequence of str, optional) – Which tags to consider as ‘sites’, by default uses tn.site_tags.

Returns:

  • edges (dict[tuple[str, str], list[str]]) – Each key is a sorted pair of tags, which are connected, and the value is a list of the indices connecting them.

  • neighbors (dict[str, list[str]]) – For each site tag, the other site tags it is connected to.

quimb.tensor.tensor_arbgeom.tensor_network_ag_sum(tna: TensorNetworkGen, tnb: TensorNetworkGen, site_tags=None, negate=False, compress=False, inplace=False, **compress_opts)

Add two tensor networks with arbitrary, but matching, geometries. They should have the same site tags, with a single tensor per site and sites connected by a single index only (but the name of this index can differ in the two TNs).

Parameters:
  • tna (TensorNetworkGen) – The first tensor network to add.

  • tnb (TensorNetworkGen) – The second tensor network to add.

  • site_tags (None or sequence of str, optional) – Which tags to consider as ‘sites’, by default uses tna.site_tags.

  • negate (bool, optional) – Whether to negate the second tensor network before adding.

  • compress (bool, optional) – Whether to compress the resulting tensor network, by calling the compress method with the given options.

  • inplace (bool, optional) – Whether to modify the first tensor network inplace.

Returns:

The resulting tensor network.

Return type:

TensorNetworkGen

quimb.tensor.tensor_arbgeom.tensor_network_ag_gate(self: TensorNetworkGen, G, where, contract=False, tags=None, propagate_tags=False, which=None, info=None, inplace=False, **compress_opts)

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

class quimb.tensor.tensor_arbgeom.TensorNetworkGen(ts=(), *, virtual=False, check_collisions=True)

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)

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

combine(other, *, virtual=False, check_collisions=True)

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()

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

property sites

Tuple of the possible sites in this tensor network.

_get_site_set()

The set of all sites.

gen_sites_present()

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)

The name of the tag specifiying the tensor at site.

retag_sites(new_id, where=None, inplace=False)

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)

Retag all sites and change the site_tag_id.

retag_all_
_get_site_tag_set()

The oset of all site tags.

filter_valid_site_tags(tags)

Get the valid site tags from tags.

maybe_convert_coo(x)

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

gen_tags_from_coos(coos)

Generate the site tags corresponding to the given coordinates.

_get_tids_from_tags(tags, which='all')

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

_get_tid_to_site_map()

Get a mapping from low level tensor id to the site it represents, assuming there is a single tensor per site.

bond(coo1, coo2)

Get the name of the index defining the bond between sites at coo1 and coo2. This will error if there is not exactly one bond between the sites.

Parameters:
  • coo1 (hashable or str) – The first site, or site tag.

  • coo2 (hashable or str) – The second site, or site tag.

Return type:

str

bond_size(coo1, coo2)

Return the (combined) size of the bond(s) between sites at coo1 and coo2.

Parameters:
  • coo1 (hashable or str) – The first site, or site tag.

  • coo2 (hashable or str) – The second site, or site tag.

Return type:

int

gen_bond_coos()

Generate the coordinates (pairs of sites) of all bonds.

get_site_neighbor_map()

Get a mapping from each site to its neighbors.

gen_regions_sites(max_region_size=None, sites=None)

Generate sets of sites that represent ‘regions’ where every node is connected to at least two other region nodes. This is a simple wrapper around TensorNewtork.gen_regions that works with the sites rather than tids.

Parameters:
  • max_region_size (None or int) – Set the maximum number of tensors that can appear in a region. If None, wait until any valid region is found and set that as the maximum size.

  • tags (None or sequence of str) – If supplied, only consider regions containing these tids.

Yields:

tuple[hashable]

reset_cached_properties()

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

align(*args, inplace=False, **kwargs)
align_
__add__(other)
__sub__(other)
__iadd__(other)
__isub__(other)
normalize_simple(gauges, **contract_opts)

Normalize this network using simple local gauges. After calling this, any tree-like sub network gauged with gauges will have 2-norm 1. Inplace operation on both the tensor network and gauges.

Parameters:

gauges (dict[str, array_like]) – The gauges to normalize with.

quimb.tensor.tensor_arbgeom.gauge_product_boundary_vector(tn, tags, which='all', max_bond=1, smudge=1e-06, canonize_distance=0, select_local_distance=None, select_local_opts=None, **contract_around_opts)
quimb.tensor.tensor_arbgeom.region_remove_dangling(sites, neighbors, where=())
quimb.tensor.tensor_arbgeom._VALID_GATE_PROPAGATE
quimb.tensor.tensor_arbgeom._LAZY_GATE_CONTRACT
class quimb.tensor.tensor_arbgeom.TensorNetworkGenVector(ts=(), *, virtual=False, check_collisions=True)

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)
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()

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)

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_
reindex_all(new_id, inplace=False)

Reindex all physical sites and change the site_ind_id.

reindex_all_
gen_inds_from_coos(coos)

Generate the site inds corresponding to the given coordinates.

phys_dim(site=None)

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)

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
gate_with_op_lazy(A, transpose=False, inplace=False, **kwargs)

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_
gate
gate_
gate_simple_(G, where, gauges, renorm=True, smudge=1e-12, power=1.0, **gate_opts)

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.

  • smudge (float, optional) – A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues.

  • power (float, optional) – The power to raise the singular values to before multiplying them in and inverting them.

  • gate_opts – Supplied to gate_inds().

gate_fit_local_(G, where, max_distance=0, fillin=0, gauges=None, **fit_opts)
make_reduced_density_matrix(where, allow_dangling=True, bra_ind_id='b{}', mangle_append='*', layer_tags=('KET', 'BRA'))

Form the tensor network representation of the reduced density matrix, taking special care to handle potential hyper inner and outer indices.

Parameters:
  • where (node or sequence[node]) – The sites to keep.

  • allow_dangling (bool, optional) – Whether to allow dangling indices in the resulting density matrix. These are non-physical indices, that usually result from having cut a region of the tensor network.

  • bra_ind_id (str, optional) – The string format to use for the bra indices.

  • mangle_append (str, optional) – The string to append to indices that are not traced out.

  • layer_tags (tuple of str, optional) – The tags to apply to the ket and bra tensor network layers.

partial_trace_exact(where, optimize='auto-hq', normalized=True, rehearse=False, get='matrix', **contract_opts)

Compute the reduced density matrix at sites where by exactly contracting the full overlap tensor network.

Parameters:
  • where (sequence[node]) – The sites to keep.

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

  • normalized (bool or "return", optional) – Whether to normalize the result. If “return”, return the norm separately.

  • rehearse (bool, optional) – Whether to perform the computation or not, if True return a rehearsal info dict.

  • get ({'matrix', 'array', 'tensor'}, optional) – Whether to return the result as a dense array, the data itself, or a tensor network.

Return type:

array or Tensor or dict or (array, float), (Tensor, float)

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

Compute the local expectation of operator G at sites where by exactly contracting the full overlap tensor network.

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

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

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

  • normalized (bool or "return", optional) – Whether to normalize the result. If “return”, return the norm separately.

  • rehearse (bool, optional) – Whether to perform the computation or not, if True return a rehearsal info dict.

  • contract_opts – Supplied to contract().

Return type:

float or (float, float)

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

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]

get_cluster(where, gauges=None, max_distance=0, fillin=0, smudge=1e-12, power=1.0)

Get the wavefunction cluster tensor network for the sites surrounding where, potentially gauging the region with the simple update style bond gauges in gauges.

Parameters:
  • where (sequence[node]) – The sites around which to form the cluster.

  • 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.

  • 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, 1 includes there direct neighbors, etc.

  • 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().

  • smudge (float, optional) – A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues.

  • power (float, optional) – The power to raise the singular values to before multiplying them in and inverting them.

Return type:

TensorNetworkGenVector

partial_trace_cluster(where, gauges=None, optimize='auto-hq', normalized=True, max_distance=0, fillin=0, smudge=1e-12, power=1.0, get='matrix', rehearse=False, **contract_opts)

Compute the approximate reduced density matrix at sites where by contracting a local cluster of tensors, potentially gauging the region with the simple update style bond gauges in gauges.

Parameters:
  • where (sequence[node]) – The sites to keep.

  • 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.

  • normalized (bool or "return", optional) – Whether to normalize the result. If “return”, return the norm separately.

  • 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, 1 includes there direct neighbors, etc.

  • 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().

  • smudge (float, optional) – A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues.

  • power (float, optional) – The power to raise the singular values to before multiplying them in and inverting them.

  • get ({'matrix', 'array', 'tensor'}, optional) – Whether to return the result as a fused matrix (i.e. always 2D), unfused array, or still labeled Tensor.

  • rehearse (bool, optional) – Whether to perform the computation or not, if True return a rehearsal info dict.

  • contract_opts – Supplied to contract().

local_expectation_cluster(G, where, normalized=True, max_distance=0, fillin=False, gauges=None, smudge=0.0, power=1.0, optimize='auto', max_bond=None, rehearse=False, **contract_opts)

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, 1 includes there direct neighbors, etc.

  • 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
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)

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 where when computing the expectation. The default 0 means only the tensors at sites where are used, 1 includes there direct neighbors, etc.

  • 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
local_expectation_loop_expansion(G, where, loops=None, gauges=None, normalized=True, optimize='auto', intersect=False, use_all_starting_paths=False, info=None, progbar=False, **contract_opts)

Compute the expectation of operator G at site(s) where by expanding the expectation in terms of loops of tensors.

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

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

  • loops (None or sequence[NetworkPath], optional) – The loops to use. If an integer, all loops up to and including that length will be used if the loop passes through all sites in where. If None the maximum loop length is set as the shortest loop found. If an explicit set of loops is given, only these loops are considered, but only if they pass through all sites in where. intersect is ignored.

  • 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 gauged.

  • normalized (bool or "local", optional) – Whether to normalize the result. If “local” each loop term is normalized separately. If True each term is normalized using a loop expansion estimate of the norm. If False no normalization is performed.

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

  • info (dict, optional) – A dictionary to store intermediate results in to avoid recomputing them. This is useful when computing various expectations with different sets of loops. This should only be reused when both the tensor network and gauges remain the same.

  • intersect (bool, optional) – If loops is not an explicit set of loops, whether to consider self intersecting loops in the search for loops passing through where.

  • contract_opts – Supplied to contract().

Returns:

expec

Return type:

scalar

compute_local_expectation_loop_expansion(terms, loops=None, *, gauges=None, normalized=True, optimize='auto', info=None, intersect=False, return_all=False, executor=None, progbar=False, **contract_opts)
local_expectation_cluster_expansion(G, where, clusters=None, gauges=None, normalized=True, autocomplete=True, autoreduce=True, optimize='auto', info=None, **contract_opts)

Compute the expectation of operator G at site(s) where by expanding the expectation in terms of clusters of tensors.

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

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

  • clusters (None or sequence[sequence[node]], optional) – The clusters to use. If an integer, all cluster up to and including that size will be used if the cluster contains all sites in where. If None the maximum cluster size is set as the smallest non-trivial cluster (2-connected subgraph) found. If an explicit set of clusters is given, only these clusters are considered, but only if they contain all sites in where.

  • 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 gauged.

  • normalized (bool or "local", optional) – Whether to normalize the result. If “local” each cluster term is normalized separately. If True each term is normalized using a loop expansion estimate of the norm. If False no normalization is performed.

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

  • info (dict, optional) – A dictionary to store intermediate results in to avoid recomputing them. This is useful when computing various expectations with different sets of loops. This should only be reused when both the tensor network and gauges remain the same.

  • contract_opts – Supplied to contract().

Returns:

expec

Return type:

scalar

norm_cluster_expansion(clusters=None, autocomplete=False, autoreduce=True, gauges=None, optimize='auto', progbar=False, **contract_opts)

Compute the norm of this tensor network by expanding it in terms of clusters of tensors.

compute_local_expectation_cluster_expansion(terms, clusters=None, *, gauges=None, normalized=True, autocomplete=True, optimize='auto', info=None, return_all=False, executor=None, progbar=False, **contract_opts)
partial_trace(keep, max_bond, optimize, flatten=True, reduce=False, normalized=True, symmetrized='auto', rehearse=False, method='contract_compressed', **contract_compressed_opts)

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)

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)

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
compute_local_expectation_tn
sample_configuration_cluster(gauges=None, max_distance=0, fillin=0, max_iterations=100, tol=5e-06, optimize='auto-hq', seed=None)

Sample a configuration for this state using the simple update or cluster style environement approximation. The algorithms proceeds as a decimation:

  1. Compute every remaining site’s local density matrix.

  2. The site with the largest bias is sampled.

  3. The site is projected into this sampled local config.

  4. The state is regauged given the projection.

  5. Repeat until all sites are sampled.

Parameters:
  • 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 gauged.

  • max_distance (int, optional) – The maximum distance to consider when computing the local density matrix for each site. Zero meaning on the site itself, 1 meaning the site and its immediate neighbors, etc.

  • 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().

  • max_iterations (int, optional) – The maximum number of iterations to perform when gauging the state.

  • tol (float, optional) – The tolerance to converge to when gauging the state.

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

  • seed (None, int or np.random.Generator, optional) – A random seed or random number generator to use.

Returns:

  • config (dict[Node, int]) – The sampled configuration.

  • omega (float) – The probability of the sampled configuration in terms of the approximate distribution induced by the cluster scheme.

class quimb.tensor.tensor_arbgeom.TensorNetworkGenOperator(ts=(), *, virtual=False, check_collisions=True)

Bases: TensorNetworkGen

A tensor network which notionally has a single tensor and two outer indices per ‘site’, though these could be labelled arbitrarily and could also be linked in an arbitrary geometry by bonds. By convention, if converted to a dense matrix, the ‘upper’ indices would be on the left and the ‘lower’ indices on the right.

_EXTRA_PROPS = ('_sites', '_site_tag_id', '_upper_ind_id', '_lower_ind_id')
property upper_ind_id

The string specifier for the upper phyiscal indices.

upper_ind(site)

Get the upper physical index name of site.

reindex_upper_sites(new_id, where=None, inplace=False)

Modify the upper site indices for all or some tensors in this operator tensor network (without changing the upper_ind_id).

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

  • 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_upper_sites_
property upper_inds

Return a tuple of all upper indices.

property upper_inds_present

Return a tuple of all upper indices still present in the tensor network.

property lower_ind_id

The string specifier for the lower phyiscal indices.

lower_ind(site)

Get the lower physical index name of site.

reindex_lower_sites(new_id, where=None, inplace=False)

Modify the lower site indices for all or some tensors in this operator tensor network (without changing the lower_ind_id).

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

  • 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_lower_sites_
property lower_inds

Return a tuple of all lower indices.

property lower_inds_present

Return a tuple of all lower indices still present in the tensor network.

to_dense(*inds_seq, to_qarray=False, **contract_opts)

Contract this tensor network ‘operator’ into a dense array.

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'.

  • contract_opts – Options to pass to contract().

Return type:

array

to_qarray
phys_dim(site=None, which='upper')

Get the physical dimension of site.

gate_upper
gate_upper_
gate_lower
gate_lower_
gate_upper_with_op_lazy(A, transpose=False, inplace=False)

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

\[B \rightarrow A B\]

or (if transpose=True):

\[B \rightarrow A^T B\]
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 upper indices of B. If False (the default), the lower indices of A will be contracted with the upper indices of B, if True the upper indices of A will be contracted with the upper indices of B, which is like applying the transpose first.

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

Return type:

TensorNetworkGenOperator

gate_upper_with_op_lazy_
gate_lower_with_op_lazy(A, transpose=False, inplace=False)

Act lazily ‘from the right’ with the operator tensor network A, which should have matching structure, on this operator tensor network (B), like B @ A. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

\[B \rightarrow B A\]

or (if transpose=True):

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

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

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

Return type:

TensorNetworkGenOperator

gate_lower_with_op_lazy_
gate_sandwich_with_op_lazy(A, inplace=False)

Act lazily with the operator tensor network A, which should have matching structure, on this operator tensor network (B), like \(B \rightarrow A B A^\dagger\). The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted.

Parameters:
  • A (TensorNetworkGenOperator) – The operator tensor network to gate with, or apply to this tensor network.

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

Return type:

TensorNetworkGenOperator

gate_sandwich_with_op_lazy_
quimb.tensor.tensor_arbgeom._handle_rehearse(rehearse, tn: quimb.tensor.tensor_core.TensorNetwork, optimize, **kwargs)
quimb.tensor.tensor_arbgeom._compute_expecs_maybe_in_parallel(fn, tn, terms, return_all=False, executor=None, progbar=False, **kwargs)

Unified helper function for the various methods that compute many expectations, possibly in parallel, possibly with a progress bar.

quimb.tensor.tensor_arbgeom._tn_local_expectation(tn: TensorNetworkGenVector, *args, **kwargs)

Define as function for pickleability.

quimb.tensor.tensor_arbgeom._tn_local_expectation_cluster(tn: TensorNetworkGenVector, *args, **kwargs)

Define as function for pickleability.

quimb.tensor.tensor_arbgeom._tn_local_expectation_exact(tn: TensorNetworkGenVector, *args, **kwargs)

Define as function for pickleability.

quimb.tensor.tensor_arbgeom._tn_local_expectation_loop_expansion(tn, *args, **kwargs)

Define as function for pickleability.

quimb.tensor.tensor_arbgeom._tn_local_expectation_cluster_expansion(tn, *args, **kwargs)

Define as function for pickleability.