quimb.tensor.tn3d.core

Classes and algorithms related to 3D tensor networks.

Attributes

Classes

Rotator3D

Map coordinates and contraction functions between lattice directions.

TensorNetwork3D

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

TensorNetwork3DVector

Mixin for 3D cubic-lattice vector tensor networks.

TensorNetwork3DFlat

Mixin for 3D cubic-lattice tensor networks with one tensor per site.

PEPS3D

A 3D projected entangled-pair state.

Functions

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

Generate pairs of bond coordinates on a 3D lattice given a function like

gen_3d_plaquette(coo0, steps)

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

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

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

gen_3d_strings(Lx, Ly, Lz)

Generate all straight strings that span a cubic 3D lattice.

parse_boundary_sequence(sequence)

is_lone_coo(where)

Check whether where is one coordinate triplet.

calc_cell_sizes(coo_groups[, autogroup])

cell_to_sites(p)

Return the sites in a rectangular cell.

sites_to_cell(sites)

Return the smallest rectangular cell that contains sites.

calc_cell_map(cells)

Module Contents

quimb.tensor.tn3d.core.gen_3d_bonds(Lx, Ly, Lz, steppers=None, coo_filter=None, cyclic=False)[source]

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

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

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

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

  • steppers (callable or sequence of callable, optional) – One or more functions that map (i, j, k) to a second coordinate. Each valid pair of coordinates defines a bond. The default functions generate nearest-neighbor bonds.

  • coo_filter (callable, optional) – A function that returns True when (i, j, k) is a valid starting coordinate. The default accepts every coordinate.

  • cyclic (bool or tuple[bool, bool, bool], optional) – Whether the lattice is cyclic in the x, y, and z directions.

Yields:

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

Examples

Generate nearest neighbor bonds:

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

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

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

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

Yields:

coo (tuple) – The coordinates of the plaquette sites. The last coordinate equals the first coordinate.

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

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

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

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

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

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

    The tiling to use:

    • ’1’: plaquettes in a sparse checkerboard pattern, such that each edge is covered by a maximum of one plaquette.

    • ’2’: less sparse checkerboard pattern, such that each edge is covered by a maximum of two plaquettes.

    • ’4’ or ‘full’: dense tiling of plaquettes. Each bulk edge is covered four times.

Yields:

plaquette (tuple[tuple[int]]) – The coordinates of each plaquette. The last coordinate equals the first coordinate.

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

Generate all straight strings that span a cubic 3D lattice.

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

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

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

Yields:

string (tuple[tuple[int, int, int], …]) – The coordinates of a string that spans one lattice direction.

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

Map coordinates and contraction functions between lattice directions.

This mapping lets the core algorithms operate without modifying the tensor network.

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

Bases: quimb.tensor.tnag.core.TensorNetworkGen

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

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

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

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

Combine this tensor network with another tensor network.

Return a TensorNetwork3D instance when the inputs are compatible.

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

  • virtual (bool, optional) – If False, copy the tensors from both inputs. If True, reference the input tensors as virtual tensors.

  • check_collisions (bool, optional) – Whether to check for index collisions before combining the tensor networks. If True, rename conflicting inner indices.

Returns:

The combined tensor network.

Return type:

TensorNetwork3D or TensorNetwork

property Lx

The number of x-slices.

property Ly

The number of y-slices.

property Lz

The number of z-slices.

property nsites

The total number of sites.

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

Return the tag for a site.

Parameters:
  • i (int or tuple[int, int, int]) – The x-coordinate, or all three coordinates as a tuple.

  • j (int, optional) – The y-coordinate. Required when i is not a coordinate tuple.

  • k (int, optional) – The z-coordinate. Required when i is not a coordinate tuple.

Returns:

The site tag.

Return type:

str

property x_tag_id

The format string for x-slice tags.

x_tag(i)[source]
property x_tags

A tuple of all of the Lx different x-slice tags.

property y_tag_id

The format string for y-slice tags.

y_tag(j)[source]
property y_tags

A tuple of all of the Ly different y-slice tags.

property z_tag_id

The format string for z-slice tags.

z_tag(k)[source]
property z_tags

A tuple of all of the Lz different z-slice tags.

maybe_convert_coo(coo)[source]

Convert a coordinate triplet to its site tag.

Parameters:

coo (object) – The value to convert.

Returns:

The site tag, or the unchanged input if it is not a coordinate triplet.

Return type:

str or object

has_site(site)[source]

Check whether a value is a valid site coordinate.

Parameters:

site (object) – The value to check.

Returns:

Whether site is an integer coordinate within the lattice bounds.

Return type:

bool

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

Support coordinates in methods that select tensors by tag.

gen_site_coos()[source]

Generate coordinates for all the sites in this 3D tensor network.

gen_bond_coos()[source]

Generate coordinate pairs for all bonds in this tensor network.

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

Check whether coo is in-bounds.

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

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

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

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

Return type:

bool

get_ranges_present()[source]

Return the range of site coordinates in this tensor network.

Returns:

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

Return type:

tuple[tuple[int, int]]

Examples

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

Check for a periodic bond in the x direction.

Parameters:
  • j (int, optional) – The y- and z-coordinates. Each default is at the lattice center.

  • k (int, optional) – The y- and z-coordinates. Each default is at the lattice center.

  • imin (int, optional) – The x-coordinates. The defaults are 0 and Lx - 1.

  • imax (int, optional) – The x-coordinates. The defaults are 0 and Lx - 1.

Returns:

Whether a bond connects (imin, j, k) and (imax, j, k). The result is False when imin and imax are adjacent.

Return type:

bool

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

Check for a periodic bond in the y direction.

Parameters:
  • k (int, optional) – The z- and x-coordinates. Each default is at the lattice center.

  • i (int, optional) – The z- and x-coordinates. Each default is at the lattice center.

  • jmin (int, optional) – The y-coordinates. The defaults are 0 and Ly - 1.

  • jmax (int, optional) – The y-coordinates. The defaults are 0 and Ly - 1.

Returns:

Whether a bond connects (i, jmin, k) and (i, jmax, k). The result is False when jmin and jmax are adjacent.

Return type:

bool

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

Check for a periodic bond in the z direction.

Parameters:
  • i (int, optional) – The x- and y-coordinates. Each default is at the lattice center.

  • j (int, optional) – The x- and y-coordinates. Each default is at the lattice center.

  • kmin (int, optional) – The z-coordinates. The defaults are 0 and Lz - 1.

  • kmax (int, optional) – The z-coordinates. The defaults are 0 and Lz - 1.

Returns:

Whether a bond connects (i, j, kmin) and (i, j, kmax). The result is False when kmin and kmax are adjacent.

Return type:

bool

__getitem__(key)[source]

Key based tensor selection, checking for integer based shortcut.

_repr_info()[source]

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

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

Contract all tensors at each site into one tensor per site.

By default, also fuse multiple bonds between flattened sites.

Parameters:
  • fuse_multibonds (bool, optional) – Whether to fuse multiple bonds created by flattening.

  • inplace (bool, optional) – Whether to modify this tensor network in place.

Returns:

The flattened tensor network.

Return type:

TensorNetwork3DFlat

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

Generate coordinate pairs for bonds in a lattice range.

Parameters:
  • xrange (tuple[int, int], optional) – The inclusive coordinate ranges. The full lattice range is the default.

  • yrange (tuple[int, int], optional) – The inclusive coordinate ranges. The full lattice range is the default.

  • zrange (tuple[int, int], optional) – The inclusive coordinate ranges. The full lattice range is the default.

  • xreverse (bool, optional) – Whether to reverse each coordinate sweep.

  • yreverse (bool, optional) – Whether to reverse each coordinate sweep.

  • zreverse (bool, optional) – Whether to reverse each coordinate sweep.

  • coordinate_order (str, optional) – The coordinate sweep order. Earlier coordinates change more slowly. A direction can be omitted only when its range has length one.

  • xstep (int, optional) – The step in each bond direction. Each default follows the corresponding reverse option.

  • ystep (int, optional) – The step in each bond direction. Each default follows the corresponding reverse option.

  • zstep (int, optional) – The step in each bond direction. Each default follows the corresponding reverse option.

  • stepping_order (str, optional) – The order in which to generate bond directions.

  • step_only (int, optional) – Generate only the direction at this position in stepping_order.

Yields:

coo_a, coo_b (tuple[int, int, int]) – The coordinates at the ends of each bond.

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

Canonize tensor pairs in a lattice range.

Parameters:
  • xrange (tuple[int, int]) – The inclusive coordinate ranges.

  • yrange (tuple[int, int]) – The inclusive coordinate ranges.

  • zrange (tuple[int, int]) – The inclusive coordinate ranges.

  • equalize_norms (bool or float, optional) – The norm-equalization option passed to canonize_between().

  • canonize_opts (dict, optional) – Additional options passed to canonize_between().

  • gen_pair_opts – Additional options passed to gen_pairs().

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

Compress tensor pairs in a lattice range.

Parameters:
  • xrange (tuple[int, int]) – The inclusive coordinate ranges.

  • yrange (tuple[int, int]) – The inclusive coordinate ranges.

  • zrange (tuple[int, int]) – The inclusive coordinate ranges.

  • max_bond (int, optional) – The maximum bond dimension after compression.

  • cutoff (float, optional) – The singular-value cutoff.

  • equalize_norms (bool or float, optional) – The norm-equalization option passed to compress_between().

  • compress_opts (dict, optional) – Additional options passed to compress_between().

  • gen_pair_opts – Additional options passed to gen_pairs().

_contract_boundary_core_via_2d(xrange, yrange, zrange, from_which, max_bond, cutoff=1e-10, method='local-early', layer_tags=None, **compress_opts)[source]
_contract_boundary_core(xrange, yrange, zrange, from_which, max_bond, cutoff=1e-10, canonize=True, canonize_interleave=True, layer_tags=None, compress_late=True, equalize_norms=False, compress_opts=None, canonize_opts=None)[source]

Core function for the ‘peps’ mode boundary contraction, which eagerly contracts two layers of tensors, then compresses all the bonds, possibly interleaving canonization between e.g. each direction of compression sweep.

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

Contract a rectangular region from one boundary.

Parameters:
  • xrange (tuple[int, int]) – The inclusive bounds of the region.

  • yrange (tuple[int, int]) – The inclusive bounds of the region.

  • zrange (tuple[int, int]) – The inclusive bounds of the region.

  • from_which ({'xmin', 'xmax', 'ymin', 'ymax', 'zmin', 'zmax'}) – The boundary from which to contract.

  • max_bond (int, optional) – The maximum bond dimension after compression.

  • cutoff (float, optional) – The singular-value cutoff.

  • mode (str, optional) – The boundary-compression method.

  • equalize_norms (bool or float, optional) – Whether to equalize tensor norms during contraction.

  • compress_opts (dict, optional) – Additional options for compression.

  • inplace (bool, optional) – Whether to modify this tensor network in place.

  • contract_boundary_opts – Additional options for the selected boundary-contraction method.

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

Unified handler for performing interleaved contractions in a sequence of inward boundary directions.

contract_boundary(max_bond=None, *, cutoff=1e-10, mode='peps', canonize=True, compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, strip_exponent=False, equalize_norms='auto', final_contract=True, final_contract_opts=None, optimize='auto-hq', progbar=False, inplace=False, **contract_boundary_opts)[source]

Contract this 3D tensor network by sweeping a sequence of the 2D boundaries inward.

Parameters:
  • max_bond (int, optional) – The maximum bond dimension. If None, use only the cutoff for compression. A finite value is recommended for networks with loops.

  • cutoff (float, optional) – The cutoff to use when compressing the bonds.

  • mode ({"peps", "projector3d", "l2bp3d", "projector", "l2bp",) –

    “local-early”, “local-late”, “su”, …}, optional The mode to use for the contraction:

    • ”peps” : eagerly contract two layers of tensors, then compress all bonds, possibly interleaving canonization between. This is a mode specific to 3D.

    • ”projector3d” : use CTMRG/HOTRG boundary projectors inserted between layers to compress lazily. This mode is specific to 3D.

    • ”l2bp3d” : use lazy 2-norm belief propagation compression to insert projectors between layers. This mode is specific to 3D.

    • ”projector”, “l2bp”, “local-early”, “local-late”, “su” : use any ‘arbitrary’ geometry compression mode (see quimb.tensor.tnag.compress) to compress the boundary.

  • canonize (bool, optional) – Whether to perform canonization/gauging while compressing. What this means depends on the mode.

  • compress_opts (dict, optional) – Low-level options to pass to the individual compression routine.

  • sequence (tuple[str, ...], optional) – The boundary sequence. The default contains all three directions. The allowed values are "xmin", "xmax", "ymin", "ymax", "zmin", and "zmax". The sequence is applied cyclically.

  • xmin (int, optional) – The initial boundaries to start contracting from. By default these are chosen as the outermost boundaries which contain tensors.

  • xmax (int, optional) – The initial boundaries to start contracting from. By default these are chosen as the outermost boundaries which contain tensors.

  • ymin (int, optional) – The initial boundaries to start contracting from. By default these are chosen as the outermost boundaries which contain tensors.

  • ymax (int, optional) – The initial boundaries to start contracting from. By default these are chosen as the outermost boundaries which contain tensors.

  • zmin (int, optional) – The initial boundaries to start contracting from. By default these are chosen as the outermost boundaries which contain tensors.

  • zmax (int, optional) – The initial boundaries to start contracting from. By default these are chosen as the outermost boundaries which contain tensors.

  • max_separation (int, optional) – The maximum separation to contract the boundaries to. By default this is 1, meaning that the contraction stops when two opposing boundaries are adjacent.

  • max_unfinished (int, optional) – The maximum number of directions that can remain unfinished before the contraction stops.

  • around (((int, int, int), ...), optional) – A set of coordinates to contract around. The contraction stops when all coordinates are within the current boundaries.

  • strip_exponent (bool, optional) – Whether to strip an overall exponent, log10, from the final contraction result. If True, a tuple of (scalar, exponent) is returned instead of a single scalar.

  • equalize_norms (bool, float, or "auto", optional) – Whether to keep tensor norms similar during contraction and store the base-10 logarithm of the overall scale in tn.exponent. By default, "auto" follows strip_exponent. A float specifies the target norm and is not redistributed at the end.

  • final_contract (bool, optional) – Whether to perform the final, exact contraction of the remaining tensors once the boundary contraction is finished. If around is specified, this is automatically set to False.

  • final_contract_opts (dict, optional) – Additional options to pass to the final contraction step.

  • optimize (str or list, optional) – The contraction path optimizer to use for the final contraction step, if performed. By default uses “auto-hq”.

  • progbar (bool, optional) – Whether to show a progress bar of the boundary contraction.

  • inplace (bool, optional) – Whether to perform the contraction in place or on a copy.

  • contract_boundary_opts – Additional options passed to contract_boundary_from().

contract_boundary_[source]
contract_peps_sweep(max_bond, cutoff=0.0, from_which=None, mode='peps', canonize=True, canonize_interleave=True, peps_opts=None, mps_opts=None, strip_exponent=False, equalize_norms='auto', progbar=False, inplace=False, **kwargs)[source]

Contract this 3D tensor network with a PEPS-to-MPS sweep.

First contract one lattice direction to produce a 2D tensor network. Then contract its rows and columns as matrix product states. This method is primarily a reference method.

Parameters:
  • max_bond (int) – The maximum bond dimension to allow during the contraction. By default the MPS bond dimension is set to twice this value.

  • cutoff (float, optional) – The cutoff to use when compressing the MPS.

  • from_which ({'xmin', 'xmax', 'ymin', 'ymax', 'zmin', 'zmax'}, optional) – Which direction to contract the PEPS from. By default the direction which requires the smallest area PEPS is chosen.

  • mode ({"peps", "projector", ...}, optional) – The boundary contraction method to use. See contract_boundary.

  • canonize (bool, optional) – Whether to perform canonization/gauging during the PEPS and MPS compression steps. By default applies to both. What this means depends on the mode.

  • canonize_interleave (bool, optional) – If mode=='peps', whether to interleave canonization and compression sweeps, or do all canonization then all compression.

  • peps_opts (dict, optional) – Additional options to pass to the PEPS compression steps.

  • mps_opts (dict, optional) – Additional options to pass to the MPS compression steps.

  • strip_exponent (bool, optional) – Whether to strip an overall exponent, log10, from the final contraction result. If True, a tuple of (scalar, exponent) is returned instead of a single scalar.

  • equalize_norms (bool, float, or "auto", optional) – Whether to keep tensor norms similar during contraction and store the base-10 logarithm of the overall scale in tn.exponent. By default, "auto" follows strip_exponent. A float specifies the target norm and is not redistributed at the end.

  • progbar (bool, optional) – Whether to show a progress bar of the boundary contraction.

  • inplace (bool, optional) – Whether to perform the contraction in place or on a copy.

  • kwargs – Additional options to pass to contract_boundary() for the PEPS compression steps.

contract_simple_sweep(max_bond, power=1.0, smudge=1e-12, max_iterations=5, equalize_norms=False, peps_opts=None, mps_opts=None, inplace=False)[source]
contract_ctmrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, lazy=False, mode='projector', sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, max_separation=1, max_unfinished=1, around=None, strip_exponent=False, equalize_norms='auto', optimize='auto-hq', contract_opts=None, reduce_opts=None, compress_opts=None, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **contract_boundary_opts)[source]

Contract this tensor network with finite 3D CTMRG.

See https://arxiv.org/abs/cond-mat/9507087. Insert oblique projectors between boundary pairs in each direction in sequence. Optionally contract these projectors into effective sites. Stop when enough directions have length at most max_separation + 1. Then contract the remaining tensor network exactly.

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

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

  • canonize (bool, optional) – Whether to canonize the boundary tensors before each contraction.

  • canonize_opts (None or dict, optional) – Additional options for canonization.

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

  • mode (str, optional) – The method to perform the boundary contraction. Defaults to 'projector'.

  • sequence (sequence of str, optional) – The boundaries from which to contract inward. The default contains all directions.

  • xmin (int, optional) – The initial bottom boundary row, defaults to 0.

  • xmax (int, optional) – The initial top boundary row, defaults to Lx - 1.

  • ymin (int, optional) – The initial left boundary column, defaults to 0.

  • ymax (int, optional) – The initial right boundary column, defaults to Ly - 1.

  • zmin (int, optional) – The initial front boundary layer, defaults to 0.

  • zmax (int, optional) – The initial back boundary layer, defaults to Lz - 1.

  • max_separation (int, optional) – A direction is complete when its boundaries are no farther apart than this value.

  • max_unfinished (int, optional) – The maximum number of directions that can be unfinished before the contraction terminates.

  • around (None or sequence of (int, int, int), optional) – Coordinates to preserve. Boundary contraction stops at the rectangular region that contains these coordinates.

  • strip_exponent (bool, optional) – Whether to strip an overall exponent, log10, from the final contraction result. If True, a tuple of (scalar, exponent) is returned instead of a single scalar.

  • equalize_norms (bool, float, or "auto", optional) – Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in tn.exponent. By default ("auto") this follows strip_exponent.

  • optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors. Note any value in contract_opts takes precedence over this.

  • contract_opts (dict, optional) – Explicit options for contracting the projectors to pass to to_dense(). Values set here take precedence over any defaults such as optimize.

  • reduce_opts (dict, optional) – Explicit options to pass to squared_op_to_reduced_factor(), for example method="cholesky". Values set here take precedence over any defaults.

  • compress_opts (dict, optional) – Explicit options to pass to compute_oblique_projectors(). Values set here take precedence over any defaults.

  • final_contract (bool, optional) – Whether to exactly contract the remaining tensor network after the boundary contraction.

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), if final_contract=True. Defaults to same as contract_opts.

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

  • inplace (bool, optional) – Whether to perform the boundary contraction in place.

  • contract_boundary_opts – Additional options to pass to contract_boundary_from().

Returns:

Either the fully contracted scalar (if final_contract=True and around=None) or the partially contracted tensor network.

Return type:

scalar or TensorNetwork3D

See also

contract_boundary_from, contract_hotrg, TensorNetwork.insert_compressor_between_regions

contract_ctmrg_[source]
_compute_plane_envs(xrange, yrange, zrange, from_which, envs=None, storage_factory=None, **contract_boundary_opts)[source]

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

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

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

coarse_grain_hotrg(direction, max_bond=None, cutoff=1e-10, canonize=False, canonize_opts=None, gauge_power=1.0, lazy=False, strip_exponent=False, equalize_norms='auto', optimize='auto-hq', contract_opts=None, reduce_opts=None, compress_opts=None, inplace=False)[source]

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

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

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

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

  • canonize (bool, optional) – Whether to canonize all tensors before computing projectors, via gauge_all_simple_().

  • canonize_opts (None or dict, optional) – Additional options to pass to gauge_all_simple_().

  • gauge_power (float, optional) – If canonize=True, the power to which to raise the computed bond gauge weights before computing the compressed projectors.

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

  • strip_exponent (bool, optional) – If True, enable norm equalization during the coarse graining.

  • equalize_norms (bool or "auto", optional) – Whether to equalize the norms of the tensors in the coarse grained lattice. By default ("auto") this follows strip_exponent.

  • optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors. Note any value in contract_opts takes precedence over this.

  • contract_opts (dict, optional) – Explicit options for contracting the projectors to pass to to_dense(). Values set here take precedence over any defaults such as optimize.

  • reduce_opts (dict, optional) – Explicit options to pass to squared_op_to_reduced_factor(), for example method="cholesky". Values set here take precedence over any defaults.

  • compress_opts (dict, optional) – Explicit options to pass to compute_oblique_projectors(). Values set here take precedence over any defaults.

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

Returns:

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

Return type:

TensorNetwork3D

See also

contract_hotrg, insert_compressor_between_regions

coarse_grain_hotrg_[source]
contract_hotrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, gauge_power=1.0, sequence=('x', 'y', 'z'), max_separation=1, max_unfinished=1, lazy=False, strip_exponent=False, equalize_norms='auto', optimize='auto-hq', contract_opts=None, reduce_opts=None, compress_opts=None, final_contract=True, final_contract_opts=None, progbar=False, inplace=False, **coarse_grain_opts)[source]

Contract this tensor network using the finite version of HOTRG. See https://arxiv.org/abs/1201.1144v4 and https://arxiv.org/abs/1905.02351 for the improved computation of the projectors used here. The tensor network is contracted sequentially in sequence directions by inserting oblique projectors between tensor pairs. It can then contract the projectors into new effective sites. The algorithm stops when at most one direction has length greater than 2. It then contracts exactly.

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

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

  • canonize (bool, optional) – Whether to canonize all tensors before computing projectors, via gauge_all_simple_().

  • canonize_opts (None or dict, optional) – Additional options to pass to gauge_all_simple_().

  • gauge_power (float, optional) – If canonize=True, the power to which to raise the computed bond gauge weights before computing the compressed projectors.

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

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

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

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

  • strip_exponent (bool, optional) – Whether to strip an overall exponent, log10, from the final contraction result. If True, a tuple of (scalar, exponent) is returned instead of a single scalar.

  • equalize_norms (bool, float, or "auto", optional) – Whether to equalize the norms of the tensors in the tensor network after each coarse graining step. By default ("auto") this follows strip_exponent.

  • optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors. Note any value in contract_opts takes precedence over this.

  • contract_opts (dict, optional) – Explicit options for contracting the projectors to pass to to_dense(). Values set here take precedence over any defaults such as optimize.

  • reduce_opts (dict, optional) – Explicit options to pass to squared_op_to_reduced_factor(), for example method="cholesky". Values set here take precedence over any defaults.

  • compress_opts (dict, optional) – Explicit options to pass to compute_oblique_projectors(). Values set here take precedence over any defaults.

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

  • final_contract_opts (None or dict, optional) – Options to pass to contract(), if final_contract=True. Defaults to same as contract_opts.

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

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

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

Returns:

The contracted tensor network. At most one direction has length greater than 2.

Return type:

TensorNetwork3D

See also

coarse_grain_hotrg, insert_compressor_between_regions

contract_hotrg_[source]
quimb.tensor.tn3d.core.is_lone_coo(where)[source]

Check whether where is one coordinate triplet.

Parameters:

where (sequence) – The value to check.

Returns:

Whether where is a coordinate triplet.

Return type:

bool

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

Return the sites in a rectangular cell.

Parameters:

p (tuple[tuple[int, int, int], tuple[int, int, int]]) – The cell origin and cell size.

Returns:

The sites in the cell.

Return type:

tuple[tuple[int, int, int], …]

Examples

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

Return the smallest rectangular cell that contains sites.

Parameters:

sites (iterable[tuple[int, int, int]]) – The site coordinates.

Returns:

The cell origin and cell size.

Return type:

tuple[tuple[int, int, int], tuple[int, int, int]]

Examples

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

Bases: TensorNetwork3D, quimb.tensor.tnag.core.TensorNetworkGenVector

Mixin for 3D cubic-lattice vector tensor networks.

Each site has one physical index.

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

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

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

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

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

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

Return the physical index dimension.

Parameters:
  • i (int, optional) – The coordinate of a physical index. If no complete coordinate is given, use the first physical index that remains in the tensor network.

  • j (int, optional) – The coordinate of a physical index. If no complete coordinate is given, use the first physical index that remains in the tensor network.

  • k (int, optional) – The coordinate of a physical index. If no complete coordinate is given, use the first physical index that remains in the tensor network.

Returns:

The physical index dimension.

Return type:

int

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

Apply a gate to one or more sites.

Parameters:
  • G (array_like) – The gate array.

  • where (tuple[int, int, int] or sequence of tuple[int, int, int]) – The site or sites on which to apply the gate.

  • contract (bool or str, optional) – How to contract and compress the gate. See gate_inds().

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

  • info (dict, optional) – A dictionary for optional contraction information.

  • inplace (bool, optional) – Whether to modify this tensor network in place.

  • compress_opts – Additional options passed to gate_inds().

Returns:

The tensor network after applying the gate.

Return type:

TensorNetwork3DVector

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

Bases: TensorNetwork3D

Mixin for 3D cubic-lattice tensor networks with one tensor per site.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz')
class quimb.tensor.tn3d.core.PEPS3D(arrays, *, shape='urfdlbp', tags=None, site_ind_id='k{},{},{}', site_tag_id='I{},{},{}', x_tag_id='X{}', y_tag_id='Y{}', z_tag_id='Z{}', cyclic=None, **tn_opts)[source]

Bases: TensorNetwork3DVector, TensorNetwork3DFlat

A 3D projected entangled-pair state.

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

  • shape (str, optional) – The index order in each array. The default "urfdlbp" means up, right, front, down, left, back, and physical. Boundary arrays omit dimensions for missing bonds.

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

  • site_ind_id (str, optional) – The format string for site indices.

  • site_tag_id (str, optional) – The format string for site tags.

  • x_tag_id (str, optional) – The format strings for slice tags.

  • y_tag_id (str, optional) – The format strings for slice tags.

  • z_tag_id (str, optional) – The format strings for slice tags.

  • cyclic (None, bool, or tuple[bool, bool, bool], optional) – Whether each lattice direction is cyclic. If None, infer the boundary conditions from the array shapes.

  • tn_opts – Additional options for TensorNetwork.

_EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_z_tag_id', '_Lx', '_Ly', '_Lz', '_site_ind_id')
_site_ind_id = 'k{},{},{}'
_site_tag_id = 'I{},{},{}'
_x_tag_id = 'X{}'
_y_tag_id = 'Y{}'
_z_tag_id = 'Z{}'
_Lx
_Ly
_Lz
permute_arrays(shape='urfdlbp')[source]

Permute each tensor to a specified index order.

This in-place operation changes only the array layout.

Parameters:

shape (str, optional) – A permutation of "urfdlbp" for the up, right, front, down, left, back, and physical indices.

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

Create a 3D PEPS from a filling function.

Parameters:
  • fill_fn (callable) – A function with signature fill_fn(shape) that returns a tensor array.

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

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

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

  • bond_dim (int) – The bond dimension.

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

  • cyclic (bool or tuple[bool, bool, bool], optional) – Whether the lattice is cyclic in each direction.

  • shape (str, optional) – The tensor index order. The default "urfdlbp" means up, right, front, down, left, back, and physical. This order determines the shape passed to fill_fn.

  • peps3d_opts – Additional options for PEPS3D.

Returns:

The new tensor network.

Return type:

PEPS3D

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

Create a 3D PEPS with zero-filled tensors.

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

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

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

  • bond_dim (int) – The bond dimension.

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

  • like (array_like or str, optional) – The array backend for the tensor data.

  • peps3d_opts – Additional options for PEPS3D.

Returns:

The new tensor network.

Return type:

PEPS3D

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

Create a 3D PEPS with one-filled tensors.

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

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

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

  • bond_dim (int) – The bond dimension.

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

  • like (array_like or str, optional) – The array backend for the tensor data.

  • peps3d_opts – Additional options for PEPS3D.

Returns:

The new tensor network.

Return type:

PEPS3D

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

Create a random, unnormalized 3D PEPS.

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

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

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

  • bond_dim (int) – The bond dimension.

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

  • dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – The random distribution.

  • loc (float, optional) – The additive offset for the random values.

  • dtype (dtype, optional) – The data type of the tensor arrays.

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

  • peps3d_opts – Additional options for PEPS3D.

Returns:

The new tensor network.

Return type:

PEPS3D

partial_trace_cluster(keep, max_bond=None, *, cutoff=1e-10, max_distance=0, fillin=0, gauges=False, flatten=False, normalized=True, symmetrized='auto', get=None, **contract_boundary_opts)[source]

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, relative to the largest gauge value, to add before multiplying the gauges in and inverting them.

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

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

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

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

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

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

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

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

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

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

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

    Whether to perform the computation or not:

    • False: perform the computation.

    • 'tn': return the tensor network without running the path optimizer.

    • 'tree': run the path optimizer and return the cotengra.ContractonTree..

    • True: run the path optimizer and return the PathInfo.

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

Returns:

rho – The reduce density matrix of sites in keep.

Return type:

array_like

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

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

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

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

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

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

    The method to use to compute the expectation value.

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

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

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

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

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

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

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

    Whether to perform the computations or not:

    • False: perform the computation.

    • 'tn': return the tensor networks of each local expectation, without running the path optimizer.

    • 'tree': run the path optimizer and return the cotengra.ContractonTree for each local expectation.

    • True: run the path optimizer and return the PathInfo for each local expectation.

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

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

  • contract_compressed_opts – Supplied to contract_compressed().

Returns:

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

Return type:

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