quimb.tensor.tnag.core

Classes and algorithms related to arbitrary geometry tensor networks.

Attributes

Classes

LatticeBondMap

Helper for creating consistent lattice bond indices.

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, *[, which, ...])

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

tensor_network_ag_gate_simple(self, G, where, gauges)

Apply a gate to this tensor network at sites where, using

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

gloop_remove_dangling(sites, neighbors[, where])

Given cluster sites and edges given by the neighbors

sloop_remove_dangling(path, neighbor_inds, where_tids)

_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_sloop_expand(tn, *args, **kwargs)

Define as function for pickleability.

_tn_local_expectation_gloop_expand(tn, *args, **kwargs)

Define as function for pickleability.

_combine_expansion_expectations(expecs, counts, norms)

Module Contents

quimb.tensor.tnag.core.get_coordinate_formatter(ndims)[source]
quimb.tensor.tnag.core.prod(xs)[source]

Product of all elements in xs.

class quimb.tensor.tnag.core.LatticeBondMap(Lx, Ly, Lz=None)[source]

Helper for creating consistent lattice bond indices.

Coordinates should be supplied without manually wrapping periodic boundaries. Any coordinate just outside the lattice is interpreted as a periodic bond, which keeps length-1 and length-2 periodic bonds distinct from ordinary in-lattice nearest-neighbor bonds.

Call with return_seen=True to return (bond, seen) where seen indicates whether the same lattice bond had already been requested. Useful if you only want to do something to one side of a bond.

shape
ndim
_ix
wrap(*coos)[source]
_key(cooa, coob)[source]
__call__(cooa, coob, *, return_seen=False)[source]
quimb.tensor.tnag.core.tensor_network_align(*tns: TensorNetworkGen, ind_ids=None, trace=False, inplace=False)[source]

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.tnag.core.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)[source]

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 reindex the operator tensor network A inplace, a minor performance gain if you don’t need to use A afterwards.

  • 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.tnag.core.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)[source]

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.tnag.core.create_lazy_edge_map(tn: TensorNetworkGen, site_tags=None)[source]

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.tnag.core.tensor_network_ag_sum(tna: TensorNetworkGen, tnb: TensorNetworkGen, site_tags=None, negate=False, compress=False, inplace=False, **compress_opts)[source]

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.tnag.core.tensor_network_ag_gate(self: TensorNetworkGenVector | TensorNetworkGenOperator, G, where, *, which=None, contract=False, tags=None, tags_upper=None, tags_lower=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 tensor_network_gate_inds() or tensor_network_gate_sandwich_inds() apart from where is specified as a list of sites, and tags can be optionally, intelligently propagated to the new gate tensor(s).

For a ‘vector’ tensor network, this is like:

\[| \psi \rangle \rightarrow G_\mathrm{where} | \psi \rangle\]

For an ‘operator’ tensor network, the default sandwich mode is like:

\[X \rightarrow G_\mathrm{where} X G_\mathrm{where}^\dagger\]

Or if which is “upper” like:

\[X \rightarrow G_\mathrm{where} X\]

Or if which is “lower” like:

\[X \rightarrow X G_\mathrm{where}^T\]
Parameters:
  • G (array_like) – 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.

  • which ({None, 'sandwich', 'upper', 'lower'}, optional) –

    What indices to apply the gate to.

    • None: apply to site indices if tn is a ‘vector’, else apply to both upper and lower indices (‘sandwich’) if tn is an ‘operator’.

    • "site": apply to the site indices, tn must be a ‘vector’.

    • "sandwich" or “both”: apply to both upper (ket-like) and lower (bra-like) indices like G @ A @ Gdag, tn must be an ‘operator’.

    • "upper": apply to the upper (ket-like) indices like G @ A, tn must be an ‘operator’.

    • "lower": apply to the lower (bra-like) indices like A @ G.T, tn must be an ‘operator’.

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

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

  • tags_upper (str or sequence of str, optional) – If which is “sandwich” or “upper”, tags to add to the upper gate tensor(s) only.

  • tags_lower (str or sequence of str, optional) – If which is “sandwich” or “lower”, tags to add to the lower gate tensor(s) only.

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

    What tags to propagate from the target sites to the new gate tensor(s):

    • False: no tags are propagated

    • True: all tags are propagated

    • 'register': if the gate itself is being split, for each part of the attached gate, only propagate the site tag of the site it is attached to / ‘sits above’.

    • 'sites': all site tags on the current sites are propagated, 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 or TensorNetworkGenOperator

See also

TensorNetwork.gate_inds

quimb.tensor.tnag.core.tensor_network_ag_gate_simple(self: TensorNetworkGenVector | TensorNetworkGenOperator, G, where, gauges, renorm=True, smudge=1e-12, power=1.0, info=None, inplace=False, **gate_opts)[source]

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

Parameters:
  • G (array_like) – 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.

  • gauges (dict[str, array_like]) – The store of gauge bonds, the keys being indices and the values being the vectors. Only keys 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 tensor_network_gate_inds().

class quimb.tensor.tnag.core.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.

has_site(site)[source]

Whether site is a valid site of this tensor network. The generic implementation tests membership in the full site set; structured subclasses (1D, 2D, 3D) override this with a cheap bounds check. Unhashable inputs return False.

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.

_get_tid_to_site_map()[source]

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

select_sites(sites, virtual=True, with_exponent=False)[source]

Select a sub-tensor network containing only the given sites. This is a simple wrapper that generates the relevant tags and calls self.select_any.

Parameters:
  • sites (sequence[hashable]) – The sites to select.

  • virtual (bool, optional) – Whether the returned tensor network views the same tensors (the default) or takes copies (virtual=False) from self.

  • with_exponent (bool, optional) – Whether to propagate the current exponent to the selected sub tensor network.

Return type:

TensorNetworkGen

bond(coo1, coo2)[source]

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)[source]

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()[source]

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

get_site_neighbor_map()[source]

Get a mapping from each site to its neighbors.

gen_gloops_sites(max_size=None, sites=None, grow_from='all', num_joins=1, join_overlap=2)[source]

Generate sets of sites that represent ‘generalized loops’ where every node is connected to at least two other loop nodes. This is a simple wrapper around gen_gloops() that works with the sites rather than tids.

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

  • sites (None or sequence[hashable]) – If supplied, only consider loops containing these sites.

  • grow_from ({'all', 'any', 'alldangle', 'anydangle'}, optional) – Only if sites is specified, this determines how to filter loops. If ‘all’, only yield loops containing all of the sites in sites, if ‘any’, yield loops containing any of the sites in sites. If ‘alldangle’ or ‘anydangle’, the sites are allowed to be dangling, i.e. 1-degree connected. This is useful for computing local expectations where the operator insertion breaks the loop assumption locally.

  • num_joins (int, optional) – If larger than 1, repeatedly generate larger loops by joining together the initial set (individually those with size up to max_size) of generalized loops. Each join combines loops that overlap on at least join_overlap sites.

  • join_overlap ({1, 2}, optional) – When joining loops together, the minimum number of overlapping sites they much share. 1 allows merging on a single site, 2 requires sharing a bond, which leads to fewer but ‘denser’ loops.

Yields:

tuple[hashable]

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]
flatten(fuse_multibonds=True, inplace=False, **contract_opts)[source]

Contract all tensors at each site together, yielding a single tensor per site. By default, any multibonds between flattened sites will also be fused together.

Parameters:
  • fuse_multibonds (bool, optional) – Whether to fuse any multibonds that are created by this process. Defaults to True.

  • inplace (bool, optional) – Whether to modify this tensor network inplace, or return a new one. Defaults to False.

Return type:

TensorNetworkGen

flatten_[source]
normalize_simple(gauges, **contract_opts)[source]

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.

get_local_sloops(*, where=None, sloops=None, num_joins=1, intersect=False, grow_from='all', strict_size=False, info=None)[source]

Parse the sloops argument to get the relevant simple loops for the given where sites. If sloops is an integer, auto generate loops locally, otherwise filter the given loops to only include those relevant to where. Simple loops are loops where each site is connected to exactly two other sites.

get_local_gloops(*, tids=None, where=None, gloops=None, grow_from='all', num_joins=1, strict_size=False, info=None)[source]

Parse the gloops argument to get the relevant generalized loops for the given where sites. If gloops is an integer, auto generate loops locally, otherwise filter the given loops to only include those relevant to where.

An example loop with where=(“A”, “B”), for grow_from='all':

 |   |
-o---o-
 |   |
-A---B-
 |   |

Setting grow_from='any' in would also generates loops like:

 |   |
-o---o-
 |   |   |
-o---A---B-
 |   |   |

where only site A is part of the original, generating loop, but both A and B are part of the returned cluster. For "alldangle" the same cluster would be generated but its size would be considered 5.

Parameters:
  • tids (sequence[int], optional) – The tensor ids to consider. Either this or where must be supplied.

  • where (sequence[hashable], optional) – The sites to consider. Either this or tids must be supplied.

  • info (dict) – A dictionary to store information across different calls.

  • gloops (None, int, or sequence of sequence of hashable, optional) – The gloops to consider. If None, auto generate local gloops up to the smallest non-trivial cluster size. If an integer, generate gloops locally with up to that size. If a sequence of sequences, use those gloops.

  • grow_from ({"all", "any"}, optional) – Whether to generate gloops that originally contain all or just any of the target sites in where. The base sites are always included in all returned gloops, even if they were not part of the supplied or auto-generated cluster.

Return type:

tuple[frozenset[hashable]]

quimb.tensor.tnag.core.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)[source]
quimb.tensor.tnag.core.gloop_remove_dangling(sites, neighbors, where=())[source]

Given cluster sites and edges given by the neighbors mapping, remove all sites that are not connected to at least two other sites, reducing it in this way to a generalised loop.

Parameters:
  • sites (sequence[hashable]) – The sites in the original cluster.

  • neighbors (dict[hashable, sequence[hashable]]) – The neighbors of each site.

  • where (sequence[hashable], optional) – The sites to keep, even if they are dangling.

Return type:

frozenset[hashable]

quimb.tensor.tnag.core.sloop_remove_dangling(path, neighbor_inds, where_tids)[source]
quimb.tensor.tnag.core._VALID_GATE_PROPAGATE
quimb.tensor.tnag.core._LAZY_GATE_CONTRACT
class quimb.tensor.tnag.core.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, inplace_op=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.

  • inplace_op (bool, optional) – Whether to reindex the operator tensor network A inplace, a minor performance gain if you don’t need to use A afterwards.

Return type:

TensorNetworkGenVector

gate_with_op_lazy_[source]
gate[source]
gate_[source]
gate_simple[source]
gate_simple_[source]
gate_fit_local_(G, where, max_distance=1, mode='graphdistance', fillin=False, gauges=None, connect_path=True, **fit_opts)[source]

Apply gate G to sites where by directly fitting a local patch of tensors, optionally gauging the boudary of this local patch first.

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

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

  • max_distance (int, optional) – The maximum distance from where to select tensors up to.

  • mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing where, of size up to max_distance, ensuring no dangling tensors.

  • fillin (bool or int, optional) – Whether to fill in the local patch with additional tensors, or not. fillin tensors are those connected by two or more bonds to the original local patch, the process is repeated int(fillin) times.

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

  • connect_path (bool, optional) – If the sites in ``where `` are a non-adjacent pair, whether to set the initial patch as a path that connects them.

  • fit_opts – Supplied to fit().

make_reduced_density_matrix(where, allow_dangling=True, bra_ind_id='b{}', mangle_append='*', layer_tags=('KET', 'BRA'))[source]

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)[source]

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)[source]

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)[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]

get_cluster(where, gauges=None, max_distance=0, mode='graphdistance', fillin=0, grow_from='all', smudge=1e-12, power=1.0)[source]

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 their direct neighbors, etc.

  • mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing where, of size up to max_distance, ensuring no dangling tensors.

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

  • grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tagged tensors, or just any of them (generating a larger region).

  • 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, mode='graphdistance', fillin=0, grow_from='all', smudge=1e-12, power=1.0, get='matrix', rehearse=False, **contract_opts)[source]

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.

  • mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing where, of size up to max_distance, ensuring no dangling tensors.

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

  • grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tagged tensors, or just any of them (generating a larger region).

  • 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, mode='graphdistance', fillin=False, grow_from='all', gauges=None, smudge=0.0, power=1.0, 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, 1 includes there direct neighbors, etc.

  • mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing where, of size up to max_distance, ensuring no dangling tensors.

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

  • grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tagged tensors, or just any of them (generating a larger region).

  • 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, mode='graphdistance', fillin=False, grow_from='all', 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 where when computing the expectation. The default 0 means only the tensors at sites where are used, 1 includes there direct neighbors, etc.

  • mode ({'graphdistance', 'loopunion'}, optional) – How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing where, of size up to max_distance, ensuring no dangling tensors.

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

  • grow_from ({"all", "any"}, optional) – If mode is ‘loopunion’, whether each loop should contain all of the initial tagged tensors, or just any of them (generating a larger region).

  • 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_sloop_expand(G, where, sloops=None, gauges=None, *, num_joins=1, grow_from='all', strict_size=False, intersect=False, autocomplete=True, autoreduce=True, combine='prod', normalized=True, info=None, optimize='auto', tn_cache_maxsize=512, progbar=False, **contract_opts)[source]

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.

  • sloops (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, and 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.

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

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

  • tn_cache_maxsize (int, optional) – The maximum size of the cache for the locally gauged tensor networks used in computing the local expectations.

  • contract_opts – Supplied to contract().

Returns:

expec

Return type:

scalar

compute_local_expectation_sloop_expand(terms, sloops=None, gauges=None, *, num_joins=1, grow_from='all', strict_size=False, intersect=False, autocomplete=True, autoreduce=True, combine='prod', normalized=True, info=None, return_all=False, optimize='auto', executor=None, progbar=False, **contract_opts)[source]
local_expectation_gloop_expand(G, where, gloops=None, gauges=None, combine='prod', normalized=True, autocomplete=True, autoreduce=True, grow_from='all', num_joins=1, strict_size=False, optimize='auto', info=None, tn_cache_maxsize=512, progbar=False, **contract_opts)[source]

Compute the expectation of operator G at site(s) where by expanding the expectation in terms of generalized 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.

  • gloops (None, int, or sequence[sequence[node]], optional) – The generalized loops to use. If an integer, generate loops up to and including this size. If None the maximum loop size is set as the smallest non-trivial loop found. If an explicit set of loops is given, only these loops are considered.

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

  • combine ({"prod", "sum"}, optional) – How to combine the local expectations of each cluster.

  • normalized (bool, "prod", "local" or "separate", "global", optional) –

    Whether and how to normalize the result.

    • True: uses “prod” if combine=”prod”, “local” if combine=”sum”.

    • ”prod”: shorthand for combine="prod" and normalized=True.

    • ”local”: each cluster within a term is normalized separately.

    • ”separate”: the expectation and normalization are computed separately and then combined for each term.

  • autocomplete (bool, optional) – Whether to automatically complete the local region graph by adding all required intersecting regions automatically.

  • autoreduce (bool, optional) – Whether to reduce any clusters with dangling bonds (which can still be generated as intersecting regions of loops) to generalized loops with dangling bonds removed. Should only be used at a BP fixed point.

  • grow_from ({"all", "any"}, optional) – If auto generating loops, whether generate only those which contain all sites in the term, or just any. The loops generated by “any” are a superset of those generated by “all”, giving a more accuracte estimate.

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

  • tn_cache_maxsize (int, optional) – The maximum size of the cache for the locally gauged tensor networks used in computing the local expectations.

  • contract_opts – Supplied to contract().

Returns:

expec

Return type:

scalar

norm_gloop_expand(gloops=None, autocomplete=False, autoreduce=True, gauges=None, optimize='auto', progbar=False, **contract_opts)[source]

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

compute_local_expectation_gloop_expand(terms, gloops=None, *, gauges=None, combine='prod', normalized=True, autocomplete=True, autoreduce=True, grow_from='all', strict_size=False, optimize='auto', info=None, return_all=False, executor=None, progbar=False, **contract_opts)[source]

Contract many local expectations using generalized loop expansion.

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

  • gloops (None, int, or sequence[sequence[node]], optional) – The generalized loops to use. If an integer, generate loops up to and including this size. If None the maximum loop size is set as the smallest non-trivial loop found. If an explicit set of loops is given, only these loops are considered.

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

  • combine ({"prod", "sum"}, optional) – How to combine the local expectations of each cluster.

  • normalized (bool, "prod", "local" or "separate", "global", optional) –

    Whether and how to normalize the result.

    • True: uses “prod” if combine=”prod”, “local” if combine=”sum”.

    • ”prod”: shorthand for combine="prod" and normalized=True.

    • ”local”: each cluster within a term is normalized separately.

    • ”separate”: the expectation and normalization are computed separately and then combined for each term.

    • ”global”: a single normalization factor is computed and used for all terms.

  • autocomplete (bool, optional) – Whether to automatically complete the local region graph by adding all required intersecting regions automatically.

  • autoreduce (bool, optional) – Whether to reduce any clusters with dangling bonds (which can still be generated as intersecting regions of loops) to generalized loops with dangling bonds removed. Should only be used at a BP fixed point.

  • grow_from ({"all", "any"}, optional) – If auto generating loops, whether generate only those which contain all sites in the term, or just any. The loops generated by “any” are a superset of those generated by “all”, giving a more accuracte estimate.

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

  • return_all (bool, optional) – Whether to return all results, or just the summed 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 tuple[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]
sample_configuration_cluster(gauges=None, max_distance=0, fillin=0, max_iterations=100, tol=5e-06, optimize='auto-hq', seed=None)[source]

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.tnag.core.TensorNetworkGenOperator(ts=(), *, virtual=False, check_collisions=True)[source]

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 (ket-like) and the ‘lower’ indices on the right (bra-like).

_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)[source]

Get the upper physical index name of site. By convention these are the ‘ket-like’ indices that would appear on the left of a dense matrix representation.

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

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_[source]
property upper_inds

Return a tuple of all upper indices. By convention these are the ‘ket-like’ indices that would appear on the left of a dense matrix representation.

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)[source]

Get the lower physical index name of site. By convention these are the ‘bra-like’ indices that would appear on the right of a dense matrix representation.

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

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_[source]
property lower_inds

Return a tuple of all lower indices. By convention these are the ‘bra-like’ indices that would appear on the right of a dense matrix representation.

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)[source]

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[source]
phys_dim(site=None, which='upper')[source]

Get the physical dimension of site.

gate[source]
gate_[source]
gate_sandwich[source]
gate_sandwich_[source]
gate_upper[source]
gate_upper_[source]
gate_lower[source]
gate_lower_[source]
gate_simple[source]
gate_simple_[source]
gate_upper_with_op_lazy(A, transpose=False, inplace=False)[source]

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_[source]
gate_lower_with_op_lazy(A, transpose=False, inplace=False)[source]

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_[source]
gate_sandwich_with_op_lazy(A, inplace=False)[source]

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_[source]
apply(other, compress=False, contract=True, inplace=False, **compress_opts)[source]

Act with this operator tensor network on another operator or vector tensor network (other), returning a new tensor network with the same structure/outer indices as other.

For a vector (TensorNetworkGenVector):

       | | | | | | | | | | | | | | | | | |
 self: A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A
       | | | | | | | | | | | | | | | | | |
other: x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x

                       -->

       | | | | | | | | | | | | | | | | | |   <- other.site_ind_id
  out: y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y=y

For an operator (TensorNetworkGenOperator):

       | | | | | | | | | | | | | | | | | |
 self: A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A-A
       | | | | | | | | | | | | | | | | | |
other: B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B-B
       | | | | | | | | | | | | | | | | | |

                       -->

       | | | | | | | | | | | | | | | | | |   <- other.upper_ind_id
  out: C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C=C
       | | | | | | | | | | | | | | | | | |   <- other.lower_ind_id
Parameters:
  • other (TensorNetworkGenOperator or TensorNetworkGenVector) – The tensor network to act on.

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

  • contract (bool, optional) – Whether to contract the tensors at each site after applying.

  • inplace (bool, optional) – Whether to act in place on this operator (self, the one that is acting) rather than on other (the one being acted on). The returned tensor network always has the same outer structure as other; with inplace=True the tensors and indices of self are consumed (reused without copying) into the result, so self should not be used afterwards. other is always left untouched.

  • compress_opts – Supplied to the compress method of the resulting tensor network.

Returns:

Same type as other.

Return type:

TensorNetworkGenOperator or TensorNetworkGenVector

apply_[source]
dot[source]
trace(left_inds=None, right_inds=None, **contract_opts)[source]

Take the trace of this operator tensor network by contracting the upper and lower physical indices on each currently present site.

Parameters:
  • left_inds (sequence of str, optional) – The ‘left’ (upper / ket-like) indices to trace over. If not given, defaults to the upper index at each present site.

  • right_inds (sequence of str, optional) – The ‘right’ (lower / bra-like) indices to trace over. If not given, defaults to the lower index at each present site.

  • contract_opts – Supplied to contract_tags().

partial_transpose(sysa, inplace=False)[source]

Perform a partial transpose on this operator tensor network, by swapping the upper and lower physical indices on the sites in sysa.

Since sites here may be arbitrary hashable objects (e.g. int, (i, j) tuples, strings, …), sysa is treated as a single site if it is itself a valid site of this tensor network, and as an iterable of sites otherwise.

Parameters:
  • sysa (site or sequence of sites) – The site(s) to transpose the physical indices on. A single hashable site is auto-wrapped; anything else is treated as an iterable of sites.

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

Return type:

TensorNetworkGenOperator

partial_transpose_[source]
quimb.tensor.tnag.core._handle_rehearse(rehearse, tn: quimb.tensor.tensor_core.TensorNetwork, optimize, **kwargs)[source]
quimb.tensor.tnag.core._compute_expecs_maybe_in_parallel(fn, tn, terms, return_all=False, executor=None, progbar=False, **kwargs)[source]

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

quimb.tensor.tnag.core._tn_local_expectation(tn: TensorNetworkGenVector, *args, **kwargs)[source]

Define as function for pickleability.

quimb.tensor.tnag.core._tn_local_expectation_cluster(tn: TensorNetworkGenVector, *args, **kwargs)[source]

Define as function for pickleability.

quimb.tensor.tnag.core._tn_local_expectation_exact(tn: TensorNetworkGenVector, *args, **kwargs)[source]

Define as function for pickleability.

quimb.tensor.tnag.core._tn_local_expectation_sloop_expand(tn: TensorNetworkGenVector, *args, **kwargs)[source]

Define as function for pickleability.

quimb.tensor.tnag.core._tn_local_expectation_gloop_expand(tn: TensorNetworkGenVector, *args, **kwargs)[source]

Define as function for pickleability.

quimb.tensor.tnag.core._combine_expansion_expectations(expecs, counts, norms, combine='prod', normalized=True)[source]