quimb.tensor.tn2d.core¶
Classes and algorithms related to 2D tensor networks.
Attributes¶
Classes¶
Object for rotating coordinates and various contraction functions so |
|
Mixin class for tensor networks with a square lattice two-dimensional |
|
Mixin class for a 2D square lattice vector TN, i.e. one with a single |
|
Mixin class for a 2D square lattice TN operator, i.e. one with both |
|
Mixin class for a 2D square lattice tensor network with a single tensor |
|
Projected Entangled Pair States object (2D): |
|
Projected Entangled Pair Operator object: |
Functions¶
|
|
|
Convenience function for tiling pairs of bond coordinates on a 2D |
|
Generate a plaquette at site |
|
Generate a tiling of plaquettes in a square 2D lattice. |
|
Generate all length-wise strings in a square 2D lattice. |
|
Ensure |
|
Read the boundary contraction method, including the deprecated |
|
Check whether |
|
|
|
|
|
Absorb the ket layer of the block's first plane into |
|
Yield environments for plaquettes |
|
|
|
Grow the block |
|
Use a module-level function for executor pickling. Ignore the term. |
|
Base function for printing a unicode schematic of flat 2D TNs. |
|
Find a sequence of plaquette blocksizes that will cover all the terms |
Turn a plaquette |
|
|
Generate a dictionary of all the coordinate pairs in |
|
Module Contents¶
- quimb.tensor.tn2d.core.gen_2d_bonds(Lx, Ly, steppers=None, coo_filter=None, cyclic=False)[source]¶
Convenience function for tiling pairs of bond coordinates on a 2D lattice given a function like
lambda i, j: (i + 1, j + 1).- Parameters:
Lx (int) – The number of rows.
Ly (int) – The number of columns.
steppers (callable or sequence of callable, optional) – Function(s) that take args
(i, j)and generate another coordinate, thus defining a bond. Only valid steps are taken. If not given, defaults to nearest neighbor bonds.coo_filter (callable) – Function that takes args
(i, j)and only returnsTrueif this is to be a valid starting coordinate.
- Yields:
bond (tuple[tuple[int, int], tuple[int, int]]) – A pair of coordinates.
Examples
Generate nearest neighbor bonds:
>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i, j + 1), >>> lambda i, j: (i + 1, j)]): >>> print(bond) ((0, 0), (0, 1)) ((0, 0), (1, 0)) ((0, 1), (1, 1)) ((1, 0), (1, 1))
Generate next nearest neighbor digonal bonds:
>>> for bond in gen_2d_bonds(2, 2, [lambda i, j: (i + 1, j + 1), >>> lambda i, j: (i + 1, j - 1)]): >>> print(bond) ((0, 0), (1, 1)) ((0, 1), (1, 0))
- quimb.tensor.tn2d.core.gen_2d_plaquette(coo0, steps)[source]¶
Generate a plaquette at site
coo0by stepping first instepsand then the reverse steps.- Parameters:
- Yields:
coo (tuple) – The coordinates of the sites in the plaquette, including the last site which will be the same as the first.
- quimb.tensor.tn2d.core.gen_2d_plaquettes(Lx, Ly, tiling)[source]¶
Generate a tiling of plaquettes in a square 2D lattice.
- Parameters:
Lx (int) – The length of the lattice in the x direction.
Ly (int) – The length of the lattice in the y direction.
tiling ({'1', '2', 'full'}) –
The tiling to use:
- ’1’: plaquettes in a checkerboard pattern, such that each edge
is covered by a maximum of one plaquette.
- ’2’ or ‘full’: dense tiling of plaquettes. All bulk edges will
be covered twice.
- Yields:
plaquette (tuple[tuple[int]]) – The coordinates of the sites in each plaquette, including the last site which will be the same as the first.
- quimb.tensor.tn2d.core.gen_2d_strings(Lx, Ly)[source]¶
Generate all length-wise strings in a square 2D lattice.
- class quimb.tensor.tn2d.core.Rotator2D(tn, xrange, yrange, from_which, stepsize=1)[source]¶
Object for rotating coordinates and various contraction functions so that the core algorithms only have to written once, but nor does the actual TN have to be modified.
- Parameters:
tn (TensorNetwork2D) – The tensor network to rotate coordinates for.
xrange (tuple[int, int]) – The range of x-coordinates to range over.
yrange (tuple[int, int]) – The range of y-coordinates to range over.
from_which ({'xmin', 'xmax', 'ymin', 'ymax'}) – The direction to sweep from.
stepsize (int, optional) – The step size to use when sweeping.
- tn¶
- xrange¶
- yrange¶
- from_which¶
- plane¶
- sweep_other()¶
- rotate(a, b)[source]¶
Rotate a pair such as a coordinate
(i, j)or a block size between the real and rotated frames. This is its own inverse.
- cyclic_x()¶
- cyclic_y()¶
- quimb.tensor.tn2d.core.BOUNDARY_SEQUENCE_VALID¶
- quimb.tensor.tn2d.core.BOUNDARY_SEQUENCE_MAP¶
- quimb.tensor.tn2d.core.parse_boundary_sequence(sequence)[source]¶
Ensure
sequenceis a tuple of boundary sequence strings from{'xmin', 'xmax', 'ymin', 'ymax'}
- class quimb.tensor.tn2d.core.TensorNetwork2D(ts=(), *, virtual=False, check_collisions=True)[source]¶
Bases:
quimb.tensor.tnag.core.TensorNetworkGenMixin class for tensor networks with a square lattice two-dimensional structure, indexed by
[{row},{column}]so that:'Y{j}' v i=Lx-1 ●──●──●──●──●──●── ──● | | | | | | | ... | | | | | | 'I{i},{j}' = 'I3,5' e.g. i=3 ●──●──●──●──●──●── | | | | | | | i=2 ●──●──●──●──●──●── ──● <== 'X{i}' | | | | | | ... | i=1 ●──●──●──●──●──●── ──● | | | | | | | i=0 ●──●──●──●──●──●── ──● j=0, 1, 2, 3, 4, 5 j=Ly-1This implies the following conventions:
the ‘up’ (x+) bond is coordinates
(i, j), (i + 1, j)the ‘down’ (x-) bond is coordinates
(i, j), (i - 1, j)the ‘right’ (y+) bond is coordinates
(i, j), (i, j + 1)the ‘left’ (y-) bond is coordinates
(i, j), (i, j - 1)
- _NDIMS = 2¶
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly')¶
- _compatible_2d(other)[source]¶
Check whether
selfandotherare compatible 2D tensor networks such that they can remain a 2D tensor network when combined.
- combine(other, *, virtual=False, check_collisions=True)[source]¶
Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a
TensorNetwork2Dinstance.- Parameters:
other (TensorNetwork2D 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:
- property Lx¶
The number of rows.
- property Ly¶
The number of columns.
- property nsites¶
The total number of sites.
- property x_tag_id¶
The string specifier for tagging each row of this 2D TN.
- property x_tags¶
A tuple of all of the
Lxdifferent row tags.
- row_tags¶
- property y_tag_id¶
The string specifier for tagging each column of this 2D TN.
- property y_tags¶
A tuple of all of the
Lydifferent column tags.
- col_tags¶
- maybe_convert_coo(x)[source]¶
Check if
xis a tuple of two ints and convert to the corresponding site tag if so.
- has_site(site)[source]¶
Whether
siteis a valid(i, j)coordinate of this 2D tensor network, with0 <= i < Lxand0 <= j < Ly.
- _get_tids_from_tags(tags, which='all')[source]¶
This is the function that lets coordinates such as
(i, j)be used for many ‘tag’ based functions.
- gen_horizontal_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i, j + 1)wherejis even, which thus don’t overlap at all.
- gen_horizontal_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i, j + 1)wherejis odd, which thus don’t overlap at all.
- gen_vertical_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j)whereiis even, which thus don’t overlap at all.
- gen_vertical_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j)whereiis odd, which thus don’t overlap at all.
- gen_diagonal_left_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j - 1)wherejis even, which thus don’t overlap at all.
- gen_diagonal_left_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j - 1)wherejis odd, which thus don’t overlap at all.
- gen_diagonal_right_even_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j + 1)whereiis even, which thus don’t overlap at all.
- gen_diagonal_right_odd_bond_coos()[source]¶
Generate all coordinate pairs like
(i, j), (i + 1, j + 1)whereiis odd, which thus don’t overlap at all.
- is_cyclic_x(j=None, imin=None, imax=None)[source]¶
Check if the x dimension is cyclic (periodic), specifically whether a bond exists between
(imin, j)and(imax, j), with default values ofimin = 0andimax = Lx - 1, andjat the center of the lattice. Ifiminandimaxare adjacent then this is considered False, since there is no ‘extra’ connectivity.
- is_cyclic_y(i=None, jmin=None, jmax=None)[source]¶
Check if the y dimension is cyclic (periodic), specifically whether a bond exists between
(i, jmin)and(i, jmax), with default values ofjmin = 0andjmax = Ly - 1, andiat the center of the lattice. Ifjminandjmaxare adjacent then this is considered False, since there is no ‘extra’ connectivity.
- _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) TensorNetwork2DFlat[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. If not already, the resulting tensor network will be promoted to a
TensorNetwork2DFlat.- Parameters:
- Return type:
- gen_pairs(xrange=None, yrange=None, xreverse=False, yreverse=False, coordinate_order='xy', xstep=None, ystep=None, stepping_order='xy', step_only=None)[source]¶
Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order.
- Parameters:
xrange ((int, int), optional) – The range of allowed values for the x and y coordinates.
yrange ((int, int), optional) – The range of allowed values for the x and y coordinates.
xreverse (bool, optional) – Whether to reverse the order of the x and y sweeps.
yreverse (bool, optional) – Whether to reverse the order of the x and y sweeps.
coordinate_order (str, optional) – The order in which to sweep the x and y coordinates. Earlier dimensions will change slower. If the corresponding range has size 1 then that dimension doesn’t need to be specified.
xstep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverseandyreverserespectively.ystep (int, optional) – When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow
xreverseandyreverserespectively.stepping_order (str, optional) – The order in which to step the x and y coordinates to generate bonds. Does not need to include all dimensions.
step_only (int, optional) – Only perform the ith steps in
stepping_order, used to interleave canonizing and compressing for example.
- Yields:
coo_a, coo_b (((int, int), (int, int)))
- canonize_plane(xrange, yrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts)[source]¶
Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.
- canonize_row(i, sweep, yrange=None, **canonize_opts)[source]¶
Canonize all or part of a row.
If
sweep == 'right'then:| | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ==> ─●──>──>──>──>──o──●─ row=i | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | . . . . jstart jstop jstart jstopIf
sweep == 'left'then:| | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ==> ─●──o──<──<──<──<──●─ row=i | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | . . . . jstop jstart jstop jstartDoes not yield an orthogonal form in the same way as in 1D.
- canonize_column(j, sweep, xrange=None, **canonize_opts)[source]¶
Canonize all or part of a column.
If
sweep='up'then:| | | | | | ─●──●──●─ ─●──●──●─ | | | | | | ─●──●──●─ ─●──o──●─ istop | | | ==> | | | ─●──●──●─ ─●──^──●─ | | | | | | ─●──●──●─ ─●──^──●─ istart | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | . . j jIf
sweep='down'then:| | | | | | ─●──●──●─ ─●──●──●─ | | | | | | ─●──●──●─ ─●──v──●─ istart | | | ==> | | | ─●──●──●─ ─●──v──●─ | | | | | | ─●──●──●─ ─●──o──●─ istop | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | . . j jDoes not yield an orthogonal form in the same way as in 1D.
- compress_plane(xrange, yrange, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None, **gen_pair_opts)[source]¶
Compress every pair of tensors within a subrange, optionally specifying a order to visit those pairs in.
- compress_row(i, sweep, yrange=None, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None)[source]¶
Compress all or part of a row.
If
sweep == 'right'then:| | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━━> ━●━━>──>──>──>──o━━●━ row=i | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | . . . . jstart jstop jstart jstopIf
sweep == 'left'then:| | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━━> ━●━━o──<──<──<──<━━●━ row=i | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | . . . . jstop jstart jstop jstartDoes not yield an orthogonal form in the same way as in 1D.
- Parameters:
i (int) – Which row to compress.
sweep ({'right', 'left'}) – Which direction to sweep in.
yrange (tuple[int, int] or None) – The range of columns to compress.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
compress_opts (None or dict, optional) – Supplied to
compress_between().
- compress_column(j, sweep, xrange=None, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None)[source]¶
Compress all or part of a column.
If
sweep='up'then:┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──o──●─ . ┃ ┃ ┃ ==> ┃ | ┃ . ─●──●──●─ ─●──^──●─ . xrange ┃ ┃ ┃ ┃ | ┃ . ─●──●──●─ ─●──^──●─ . ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ . . j jIf
sweep='down'then:┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──v──●─ . ┃ ┃ ┃ ==> ┃ | ┃ . ─●──●──●─ ─●──v──●─ . xrange ┃ ┃ ┃ ┃ | ┃ . ─●──●──●─ ─●──o──●─ . ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ . . j jDoes not yield an orthogonal form in the same way as in 1D.
- Parameters:
j (int) – Which column to compress.
sweep ({'up', 'down'}) – Which direction to sweep in.
xrange (None or (int, int), optional) – The range of rows to compress.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
compress_opts (None or dict, optional) – Supplied to
compress_between().
- _contract_boundary_core_via_1d(xrange, yrange, from_which, max_bond, cutoff=1e-10, method='dm', layer_tags=None, **compress_opts)[source]¶
- _contract_boundary_core(xrange, yrange, from_which, max_bond, cutoff=1e-10, canonize=True, layer_tags=None, compress_late=True, sweep_reverse=False, equalize_norms=False, compress_opts=None, canonize_opts=None)[source]¶
- _contract_boundary_full_bond(xrange, yrange, from_which, max_bond, cutoff=0.0, similarity_method=None, renorm=False, optimize='auto-hq', opposite_envs=None, equalize_norms=False, contract_boundary_opts=None, compress_opts=None)[source]¶
Contract the boundary of this 2D TN using the ‘full bond’ environment information obtained from a boundary contraction in the opposite direction.
- Parameters:
xrange ((int, int) or None, optional) – The range of rows to contract and compress.
yrange ((int, int)) – The range of columns to contract and compress.
from_which ({'xmin', 'ymin', 'xmax', 'ymax'}) – Which direction to contract the rectangular patch from.
max_bond (int) – The maximum boundary dimension, AKA ‘chi’. By default used for the opposite direction environment contraction as well.
cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction - only for the opposite direction environment contraction.
similarity_method ({'eigh', 'eig', 'svd', 'biorthog'}, optional) – Which similarity decomposition method to use to compress the full bond environment, a shortcut for
compress_opts=dict(method=...). By default'eigh'.renorm (bool, optional) – Whether to renormalize the isometric projection or not.
optimize (str or PathOptimize, optimize) – Contraction optimizer to use for the exact contractions.
opposite_envs (dict, optional) – If supplied, the opposite environments will be fetched or lazily computed into this dict depending on whether they are missing.
contract_boundary_opts – Other options given to the opposite direction environment contraction.
compress_opts (dict, optional) – Options supplied to
similarity_compress()when compressing each full bond environment.
- _contract_boundary_projector(xrange, yrange, from_which, max_bond=None, cutoff=1e-10, lazy=False, equalize_norms=False, optimize='auto-hq', contract_opts=None, reduce_opts=None, compress_opts=None)[source]¶
Contract the boundary of this 2D tensor network by explicitly computing and inserting explicit local projector tensors, which can optionally be left uncontracted. Multilayer networks are naturally supported.
- Parameters:
xrange (tuple) – The range of x indices to contract.
yrange (tuple) – The range of y indices to contract.
from_which ({'xmin', 'xmax', 'ymin', 'ymax'}) – From which boundary to contract.
max_bond (int, optional) – The maximum bond dimension to contract to. If
None(default), compression is left tocutoff.cutoff (float, optional) – The cutoff to use for boundary compression.
lazy (bool, optional) – Whether to leave the boundary tensors uncontracted. If
False(the default), the boundary tensors are contracted and the resulting boundary has a single tensor per site.equalize_norms (bool, optional) – Whether to actively absorb the norm of modified tensors into
self.exponent.optimize (str or PathOptimizer, optional) – The contract path optimization to use when forming the projector tensors.
contract_opts (dict, optional) – Explicit options for contracting the projectors to pass to
to_dense(). Values set here take precedence over any defaults such asoptimize.reduce_opts (dict, optional) – Explicit options to pass to
squared_op_to_reduced_factor(), for examplemethod="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.
See also
TensorNetwork.insert_compressor_between_regions
- contract_boundary_from(xrange, yrange, from_which, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]¶
Unified entrypoint for contracting any rectangular patch of tensors from any direction, with any boundary
method:'mps'(the default),'full-bond','projector2d'or any 1D compression method, seetensor_network_1d_compress().modeis a deprecated alias ofmethod. Forlayer_tags, seecontract_boundary().
- contract_boundary_from_xmin(xrange, yrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]¶
Contract a 2D tensor network inwards from the bottom, canonizing and compressing (left to right) along the way. If
layer_tags is Nonethis looks like:a) contract │ │ │ │ │ ●──●──●──●──● │ │ │ │ │ │ │ │ │ │ --> ●══●══●══●══● ●──●──●──●──● b) optionally canonicalize │ │ │ │ │ ●══●══<══<══< c) compress in opposite direction │ │ │ │ │ --> │ │ │ │ │ --> │ │ │ │ │ >──●══●══●══● --> >──>──●══●══● --> >──>──>──●══● . . --> . . --> . .
If
layer_tagsis supplied, each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:a) first flatten the outer boundary only │ ││ ││ ││ ││ │ │ ││ ││ ││ ││ │ ●─○●─○●─○●─○●─○ ●─○●─○●─○●─○●─○ │ ││ ││ ││ ││ │ ==> ╲│ ╲│ ╲│ ╲│ ╲│ ●─○●─○●─○●─○●─○ ●══●══●══●══● b) contract and compress a single layer only │ ││ ││ ││ ││ │ │ ○──○──○──○──○ │╱ │╱ │╱ │╱ │╱ ●══<══<══<══< c) contract and compress the next layer ╲│ ╲│ ╲│ ╲│ ╲│ >══>══>══>══●
- Parameters:
xrange ((int, int)) – The range of rows to compress (inclusive).
yrange ((int, int) or None, optional) – The range of columns to compress (inclusive), sweeping along with canonization and compression. Defaults to all columns.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between().inplace (bool, optional) – Whether to perform the contraction inplace or not.
- contract_boundary_from_xmax(xrange, yrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, inplace=False, sweep_reverse=False, compress_opts=None, **contract_boundary_opts)[source]¶
Contract a 2D tensor network inwards from the top, canonizing and compressing (right to left) along the way. If
layer_tags is Nonethis looks like:a) contract ●──●──●──●──● | | | | | --> ●══●══●══●══● ●──●──●──●──● | | | | | | | | | | b) optionally canonicalize ●══●══<══<══< | | | | | c) compress in opposite direction >──●══●══●══● --> >──>──●══●══● --> >──>──>──●══● | | | | | --> | | | | | --> | | | | | . . --> . . --> . .
If
layer_tagsis supplied, each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:a) first flatten the outer boundary only ●─○●─○●─○●─○●─○ ●══●══●══●══● │ ││ ││ ││ ││ │ ==> ╱│ ╱│ ╱│ ╱│ ╱│ ●─○●─○●─○●─○●─○ ●─○●─○●─○●─○●─○ │ ││ ││ ││ ││ │ │ ││ ││ ││ ││ │ b) contract and compress a single layer only ●══<══<══<══< │╲ │╲ │╲ │╲ │╲ │ ○──○──○──○──○ │ ││ ││ ││ ││ │ c) contract and compress the next layer ●══●══●══●══● ╱│ ╱│ ╱│ ╱│ ╱│
- Parameters:
xrange ((int, int)) – The range of rows to compress (inclusive).
yrange ((int, int) or None, optional) – The range of columns to compress (inclusive), sweeping along with canonization and compression. Defaults to all columns.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between().inplace (bool, optional) – Whether to perform the contraction inplace or not.
- contract_boundary_from_ymin(yrange, xrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]¶
Contract a 2D tensor network inwards from the left, canonizing and compressing (bottom to top) along the way. If
layer_tags is Nonethis looks like:a) contract ●──●── ●── │ │ ║ ●──●── ==> ●── │ │ ║ ●──●── ●── b) optionally canonicalize ●── v── ║ ║ ●── ==> v── ║ ║ ●── ●── c) compress in opposite direction v── ●── ║ │ v── ==> ^── ║ │ ●── ^──
If
layer_tagsis supplied, each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:a) first flatten the outer boundary only ○──○── ●──○── │╲ │╲ │╲ │╲ ●─○──○── ╰─●──○── ╲│╲╲│╲ ==> │╲╲│╲ ●─○──○── ╰─●──○── ╲│ ╲│ │ ╲│ ●──●── ╰──●── b) contract and compress a single layer only ○── ╱╱ ╲ ●─── ○── ╲ ╱╱ ╲ ^─── ○── ╲ ╱╱ ^───── c) contract and compress the next layer ●── │╲ ╰─●── │╲ ╰─●── │ ╰──- Parameters:
yrange ((int, int)) – The range of columns to compress (inclusive).
xrange ((int, int) or None, optional) – The range of rows to compress (inclusive), sweeping along with canonization and compression. Defaults to all rows.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between().inplace (bool, optional) – Whether to perform the contraction inplace or not.
- contract_boundary_from_ymax(yrange, xrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, sweep_reverse=False, compress_opts=None, inplace=False, **contract_boundary_opts)[source]¶
Contract a 2D tensor network inwards from the left, canonizing and compressing (top to bottom) along the way. If
layer_tags is Nonethis looks like:a) contract ──●──● ──● │ │ ║ ──●──● ==> ──● │ │ ║ ──●──● ──● b) optionally canonicalize ──● ──v ║ ║ ──● ==> ──v ║ ║ ──● ──● c) compress in opposite direction ──v ──● ║ │ ──v ==> ──^ ║ │ ──● ──^
If
layer_tagsis supplied, each layer is contracted in and compressed separately, resulting generally in a lower memory scaling. For two layer tags this looks like:a) first flatten the outer boundary only ──○──○ ──○──● ╱│ ╱│ ╱│ ╱│ ──○──○─● ──○──●─╯ ╱│╱╱│╱ ==> ╱│╱╱│ ──○──○─● ──○──●─╯ │╱ │╱ │╱ │ ──●──● ──●──╯ b) contract and compress a single layer only ──○ ╱ ╲╲ ──○────v ╱ ╲╲ ╱ ──○────v ╲╲ ╱ ─────● c) contract and compress the next layer ╲ ────v ╲ ╱ ────v ╲ ╱ ────●- Parameters:
yrange ((int, int)) – The range of columns to compress (inclusive).
xrange ((int, int) or None, optional) – The range of rows to compress (inclusive), sweeping along with canonization and compression. Defaults to all rows.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.sweep_reverse (bool, optional) – Which way to perform the compression sweep, which has an effect on which tensors end up being canonized. Setting this to true sweeps the compression from largest to smallest coordinates.
compress_opts (None or dict, optional) – Supplied to
compress_between().inplace (bool, optional) – Whether to perform the contraction inplace or not.
- _contract_interleaved_boundary_sequence(*, contract_boundary_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=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 iterleaved contractions in a sequence of inwards boundary directions.
- contract_boundary(max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, compress_opts=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, max_separation=1, max_unfinished=1, around=None, strip_exponent=False, equalize_norms='auto', final_contract=True, final_contract_opts=None, progbar=None, inplace=False, **contract_boundary_opts)[source]¶
Contract the boundary of this 2D tensor network inwards. By default, if contracting to a scalar, this contracts the two shortest opposing sides inwards. If around is specified, or depending on sequence, it can contract from in any sequence of directions, and in any order like so:
●──●──●──● ●──●──●──● ●──●──● │ │ │ │ │ │ │ │ ║ │ │ ●──●──●──● ●──●──●──● ^──●──● >══>══● >──v │ │ij│ │ ==> │ │ij│ │ ==> ║ij│ │ ==> │ij│ │ ==> │ij║ ●──●──●──● ●══<══<══< ^──<──< ^──<──< ^──< │ │ │ │ ●──●──●──●
Optionally from any or all of the boundary, in multiple layers, and stopping around a region. The default is to contract the boundary from the two shortest opposing sides.
- Parameters:
around (None or sequence of (int, int), optional) – If given, don’t contract the square of sites bounding these coordinates.
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary, can also be any of the generic 1D or arbgeom methods.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.compress_opts (None or dict, optional) – Other low level options to pass to
compress_between().sequence (sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which directions to cycle throught when performing the inwards contractions, i.e. from that direction. If
aroundis specified you will likely need all of these! Default is to contract from the two shortest opposing sides.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..max_separation (int, optional) – When any two sides become this far apart simply contract the remaining tensor network. If
aroundis given, also stop each side this many rows or columns from the target region. With0the boundaries absorb the edge rows or columns of the region, but leave at least two.max_unfinished (int, optional) – If
around is None, when this many sides are still not withinmax_separationsimply contract the remaining tensor network.around – If given, don’t contract the square of sites bounding 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 followsstrip_exponent.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(),optimizedefaults to'auto-hq'.progbar (bool, optional) – Whether to show a progress bar.
inplace (bool, optional) – Whether to perform the contraction in place or not.
contract_boundary_opts – Supplied to
contract_boundary_from(), including compression and canonization options.
- contract_mps_sweep(max_bond=None, *, cutoff=1e-10, canonize=True, direction=None, **contract_boundary_opts)[source]¶
Contract this 2D tensor network by sweeping an MPS across from one side to the other.
- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
direction ({'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which direction to sweep from. If
None(default) then the shortest boundary is chosen.contract_boundary_opts – Supplied to
contract_boundary_from(), including compression and canonization options.
- gen_block_environments(direction, blocks, max_bond, *, cyclic=None, compress_fn=None, schedule='auto', method=None, layer_tags=None, cutoff=None, canonize=True, optimize='auto-hq', equalize_norms=False, compress_opts=None, **compress_method_opts)[source]¶
Yield compressed row or column environments as they are ready. Keep cached environments only until their last use. See
gen_compressed_environments().- Parameters:
direction ({'x', 'y'}) – Compute environments for blocks of rows or columns respectively.
blocks (sequence of tuple[int, int]) – The
(start, size)blocks of rows or columns, which can have different sizes, all computed together in one sweep. Useall_blocks()to get every block of one size.max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cyclic (bool, optional) – Periodicity along
direction. By default infer it from the network.compress_fn ({None, 'ag', '1d', '2d'}, optional) – Which compression function to use along the other direction, see
gen_compressed_environments(). By default use ‘1d’ if the other direction is open, and ‘ag’ if it is periodic.schedule ({'auto', 'tree', 'cut', 'cutpair'}, optional) – Environment construction schedule, only relevant if
cyclic. By default use ‘tree’, which never compresses two environments together. The ‘cut’ schedule uses fewer compressions but combines two environments as its final step, which can be expensive in an approx contraction setting. The ‘cutpair’ schedule keeps these two environments separate.method (str or callable, optional) – The compression method, supplied to
compress_fn. By default use its own default method.layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted. Compress after each layer.cutoff (float, optional) – Compression cutoff. By default use the default of the compression function.
canonize (bool or str, optional) – Canonicalization option supplied to the compressor.
optimize (str, optional) – Contraction path optimizer supplied to the compressor.
equalize_norms (bool or float, optional) – Whether to equalize tensor norms after each compression.
compress_opts (dict, optional) – Additional options supplied to the compressor.
compress_method_opts – Additional options supplied to the compression method.
- Yields:
block (tuple[int, int]) – The
(start, size)block.environment (TensorNetwork) – The environment of
block, which also carries the original network’s.exponent.
- compute_block_environments(direction, blocks, max_bond, *, cutoff=None, method=None, **kwargs)[source]¶
Compute compressed row or column environments for blocks of rows or columns. See
gen_block_environments()for the options, and to process them one at a time.- Parameters:
direction ({'x', 'y'}) – Compute environments for blocks of rows or columns respectively.
blocks (sequence of tuple[int, int]) – The
(start, size)blocks of rows or columns.max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cutoff (float, optional) – Compression cutoff. By default use the default of the compression function.
method (str or callable, optional) – The compression method, see
gen_block_environments().kwargs – Supplied to
gen_block_environments().
- Returns:
The environment for each
(start, size)block.- Return type:
dict[tuple[int, int], TensorNetwork]
- compute_environments(from_which, xrange=None, yrange=None, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, dense=False, compress_opts=None, envs=None, equalize_norms=False, **contract_boundary_opts)[source]¶
Compute the 1D boundary tensor networks describing the environments of rows and columns.
- Parameters:
from_which ({'xmin', 'xmax', 'ymin', 'ymax'}) – Which boundary to compute the environments from.
xrange (tuple[int], optional) – The range of rows to compute the environments for.
yrange (tuple[int], optional) – The range of columns to compute the environments for.
max_bond (int, optional) – The maximum bond dimension of the environments.
cutoff (float, optional) – The cutoff for the singular values of the environments.
canonize (bool, optional) – Whether to canonicalize along each MPS environment before compressing.
method ({'mps', 'projector', 'full-bond', ...}, optional) – Which contraction method to use for the environments.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.dense (bool, optional) – Whether to use dense tensors for the environments.
compress_opts (dict, optional) – Other options to pass to
tensor_compress_bond().envs (dict, optional) – An existing dictionary to store the environments in.
equalize_norms (bool or float, optional) – Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in
tn.exponent. Note that the boundary tensor networks only accumulate new exponent generated by the contraction, if the original tensor network has a non-zero exponent, you may need to use it to get the correct overall scaling. For example:envs["xmin", i] | tn.select(tn.x_tag(i), with_exponent=True) | envs["xmax", i].contract_boundary_opts – Other options to pass to
contract_boundary_from().
- Returns:
envs – A dictionary of the environments, with keys of the form
(from_which, row_or_col_index).- Return type:
- compute_xmin_environments[source]¶
Compute the
self.Lx1D boundary tensor networks describing the lower environments of each row in this 2D tensor network. Seecompute_x_environments()for full details.
- compute_xmax_environments[source]¶
Compute the
self.Lx1D boundary tensor networks describing the upper environments of each row in this 2D tensor network. Seecompute_x_environments()for full details.
- compute_ymin_environments[source]¶
Compute the
self.Ly1D boundary tensor networks describing the left environments of each column in this 2D tensor network. Seecompute_y_environments()for full details.
- compute_ymax_environments[source]¶
Compute the
self.Ly1D boundary tensor networks describing the right environments of each column in this 2D tensor network. Seecompute_y_environments()for full details.
- compute_x_environments(max_bond=None, *, cutoff=1e-10, canonize=True, dense=False, method=None, layer_tags=None, compress_opts=None, envs=None, **contract_boundary_opts)[source]¶
Compute the
2 * self.Lx1D boundary tensor networks describing the lower and upper environments of each row in this 2D tensor network, assumed to represent the norm.The top or ‘xmax’ environment for row
iwill be a contraction of all rowsi + 1, i + 2, ...etc:●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━● ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲
The bottom or ‘xmin’ environment for row
iwill be a contraction of all rowsi - 1, i - 2, ...etc:╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●
Such that
envs['xmax', i] & self.select(self.x_tag(i)) & envs['xmin', i]would look like:●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━● ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o─o ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●
And be (an approximation of) the norm centered around row
i- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
dense (bool, optional) – If true, contract the boundary in as a single dense tensor.
method ({'mps', 'full-bond', ...}, optional) – How to perform the boundary compression.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.compress_opts (None or dict, optional) – Supplied to
compress_between().envs (dict, optional) – Supply an existing dictionary to store the environments in.
contract_boundary_opts – Supplied to
contract_boundary_from_xmin()andcontract_boundary_from_xmax().
- Returns:
x_envs – The two environment tensor networks of row
iwill be stored inx_envs['xmin', i]andx_envs['xmax', i].- Return type:
dict[(str, int), TensorNetwork]
- compute_y_environments(max_bond=None, *, cutoff=1e-10, canonize=True, dense=False, method=None, layer_tags=None, compress_opts=None, envs=None, **contract_boundary_opts)[source]¶
Compute the
2 * self.Ly1D boundary tensor networks describing the left (‘ymin’) and right (‘ymax’) environments of each column in this 2D tensor network, assumed to represent the norm.The left or ‘ymin’ environment for column
jwill be a contraction of all columnsj - 1, j - 2, ...etc:●< ┃ ●< ┃ ●< ┃ ●<
The right or ‘ymax’ environment for row
jwill be a contraction of all rowsj + 1, j + 2, ...etc:>● ┃ >● ┃ >● ┃ >●
Such that
envs['ymin', j] & self.select(self.y_tag(j)) & envs['ymax', j]would look like:╱o ●< o| >● ┃ |o ┃ ●< o| >● ┃ |o ┃ ●< o| >● ┃ |o ┃ ●< o╱ >●
And be (an approximation of) the norm centered around column
j- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
dense (bool, optional) – If true, contract the boundary in as a single dense tensor.
method ({'mps', 'full-bond', ...}, optional) – How to perform the boundary compression.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.compress_opts (None or dict, optional) – Supplied to
compress_between().contract_boundary_opts – Supplied to
contract_boundary_from_ymin()andcontract_boundary_from_ymax().
- Returns:
y_envs – The two environment tensor networks of column
jwill be stored iny_envs['ymin', j]andy_envs['ymax', j].- Return type:
dict[(str, int), TensorNetwork]
- _compute_plaquette_environments_x_first(x_bsz, y_bsz, max_bond=None, cutoff=1e-10, canonize=True, layer_tags=None, second_dense=None, x_envs=None, **compute_environment_opts)[source]¶
- _compute_plaquette_environments_y_first(x_bsz, y_bsz, max_bond=None, cutoff=1e-10, canonize=True, layer_tags=None, second_dense=None, y_envs=None, **compute_environment_opts)[source]¶
- compute_plaquette_environments(x_bsz=2, y_bsz=2, max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=None, first_contract=None, second_dense=None, compress_opts=None, **compute_environment_opts)[source]¶
Compute all environments like:
second_dense=False second_dense=True (& first_contract='columns') ●──● ╭───●───╮ ╱│ │╲ │ ╱ ╲ │ ●─. .─● ┬ ●─ . . ─● ┬ │ │ ┊ x_bsz │ │ ┊ x_bsz ●─. .─● ┴ ●─ . . ─● ┴ ╲│ │╱ │ ╲ ╱ │ ●──● ╰───●───╯ <--> <-> y_bsz y_bsz
Use two boundary contractions sweeps.
- Parameters:
x_bsz (int, optional) – The size of the plaquettes in the x-direction (number of rows).
y_bsz (int, optional) – The size of the plaquettes in the y-direction (number of columns).
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the boundary compression.
layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted.first_contract ({None, 'x', 'y'}, optional) – The environments can either be generated with initial sweeps in the row (‘x’) or column (‘y’) direction. Generally it makes sense to perform this approximate step in whichever is smaller (the default).
second_dense (None or bool, optional) – Whether to perform the second set of contraction sweeps (in the rotated direction from whichever
first_contractis) using a dense tensor or boundary method. By default this is only turned on if thebszin the corresponding direction is 1.compress_opts (None or dict, optional) – Supplied to
compress_between().compute_environment_opts – Supplied to
compute_y_environments()orcompute_x_environments().
- Returns:
The plaquette environments. The key is two tuples of ints, the startings coordinate of the plaquette being the first and the size of the plaquette being the second pair.
- Return type:
- compute_plaquette_environments_via_envs(x_bsz=2, y_bsz=2, *, max_bond, starts=None, cyclic=None, first_contract=None, schedule='auto', second_schedule='auto', second_dense=None, method=None, layer_tags=None, cutoff=None, canonize=True, optimize='auto-hq', equalize_norms=False, compress_opts=None, contract_opts=None, **compress_method_opts)[source]¶
Compute plaquette environments for open or periodic boundaries. Plaquettes can cross periodic boundaries. Compress in the first direction, then contract along each remaining strip. Use
second_denseto choose exact or compressed contraction along the strips.See
compute_plaquette_environments()for contraction from open boundaries.- Parameters:
x_bsz (int, optional) – Plaquette size in each direction.
y_bsz (int, optional) – Plaquette size in each direction.
max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.starts (sequence of tuple[int, int], optional) – The
(i, j)plaquette starts to compute. By default compute every valid start.cyclic (bool or tuple[bool, bool], optional) – Periodicity in each direction. By default infer it.
first_contract ({'x', 'y'}, optional) – Direction to contract approximately first.
schedule ({'auto', 'tree', 'cut', 'cutpair'}, optional) – Construction schedule of the approximate environments in the first direction, see
gen_block_environments().second_schedule ({'auto', 'tree', 'cut', 'cutpair'}, optional) – Schedule along each strip. By default use ‘cut’ for exact contraction and ‘tree’ for compressed contraction.
second_dense (bool, optional) – Whether to contract along each strip exactly. By default do so only for strips of width one. Compress wider strips.
method (str or callable, optional) – Compression method. By default use the compressor’s default for each direction. See
gen_compressed_environments().layer_tags (None or sequence of str, optional) – Tags identifying the layers, which are contracted one by one in this order. Use
Noneto contract all layers together. Booleans and integers are not accepted. Compress after each layer.cutoff (float, optional) – Compression cutoff. By default use the default of the compression function.
canonize (bool or str, optional) – Canonicalization option supplied to the compressor.
optimize (str, optional) – Contraction path optimizer supplied to the compressor, and the default for
contract_opts.equalize_norms (bool or float, optional) – Whether to equalize tensor norms after each compression.
compress_opts (dict, optional) – Additional options supplied to the compressor.
contract_opts (dict, optional) – Options for the exact contractions along each strip, see
second_dense.optimizeis the default path optimizer.compress_method_opts – Additional options supplied to the compression method.
- Returns:
Plaquette environments keyed by start and size.
- Return type:
- 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
directionusing HOTRG. This inserts oblique projectors between tensor pairs and then optionally contracts them into new sites for form a lattice half the size.- Parameters:
direction ({'x', 'y'}) – 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 when 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 followsstrip_exponent.optimize (str, optional) – The optimization method to use when contracting the coarse grained lattice, if
lazy=False.contract_opts (dict, optional) – Explicit options for contracting the projectors to pass to
to_dense(). Values set here take precedence over any defaults such asoptimize.reduce_opts (dict, optional) – Explicit options to pass to
squared_op_to_reduced_factor(), for examplemethod="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:
See also
contract_hotrg,TensorNetwork.insert_compressor_between_regions
- contract_hotrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, gauge_power=1.0, sequence=('x', 'y'), 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 more optimal computaton of the projectors used here. The TN is contracted sequentially in
sequencedirections by inserting oblique projectors between plaquettes, and then optionally contracting these new effective sites. The algorithm stops when only one direction has a length larger than 2, and thus exact contraction can be used.- Parameters:
max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.
cutoff (float, optional) – The cutoff for the singular values of the projector pairs.
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 when 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 all tensors after each contraction, gathering the overall scaling coefficient, log10, in
tn.exponent. By default ("auto") this followsstrip_exponent.optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors. Note any value in
contract_optswill take 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 asoptimize.reduce_opts (dict, optional) – Explicit options to pass to
squared_op_to_reduced_factor(), for examplemethod="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(), iffinal_contract=True. Defaults to same ascontract_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, which will have no more than one direction of length > 2.
- Return type:
See also
coarse_grain_hotrg,contract_ctmrg,TensorNetwork.insert_compressor_between_regions
- contract_ctmrg(max_bond=None, *, cutoff=1e-10, canonize=False, canonize_opts=None, lazy=False, method=None, sequence=None, xmin=None, xmax=None, ymin=None, ymax=None, max_separation=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 2D tensor network using the finite analog of the CTMRG algorithm - https://arxiv.org/abs/cond-mat/9507087. The TN is contracted sequentially in
sequencedirections by inserting oblique projectors between boundary pairs, and then optionally contracting these new effective sites. The algorithm stops when only one direction has a length larger than max_separation, and thus exact contraction can be used.- Parameters:
max_bond (int, optional) – The maximum bond dimension of the projector pairs inserted.
cutoff (float, optional) – The cutoff for the singular values of the projector pairs.
canonize (bool, optional) – Whether to canonize the boundary tensors before each contraction, via
gauge_all().canonize_opts (None or dict, optional) – Additional options to pass to
gauge_all().lazy (bool, optional) – Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them.
method (str, optional) – The method to perform the boundary contraction. Defaults to
'projector'.sequence (sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which directions to cycle throught when performing the inwards contractions, i.e. from that direction. If
aroundis specified you will likely need all of these! Default is to contract in 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..max_separation (int, optional) – When any two sides become this far apart simply contract the remaining tensor network. If
aroundis given, also stop each side this many rows or columns from the target region. With0the boundaries absorb the edge rows or columns of the region, but leave at least two.around (None or sequence of (int, int), optional) – If given, don’t contract the square of sites bounding 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 followsstrip_exponent.optimize (str or PathOptimizer, optional) – How to optimize the contraction of the projection tensors. Note any value in
contract_optswill take 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 asoptimize.reduce_opts (dict, optional) – Explicit options to pass to
squared_op_to_reduced_factor(), for examplemethod="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(), iffinal_contract=True. Defaults to same ascontract_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=Trueandaround=None) or the partially contracted tensor network.- Return type:
See also
contract_boundary_from,contract_hotrg,TensorNetwork.insert_compressor_between_regions
- quimb.tensor.tn2d.core._parse_boundary_method(method, opts, default='mps')[source]¶
Read the boundary contraction method, including the deprecated
modeoption inopts.
- quimb.tensor.tn2d.core._half_absorb_block_layers(tn, envl, envr, block_tags, layer_tags, compress_fn)[source]¶
Absorb the ket layer of the block’s first plane into
envl, and the bra layer of its last plane intoenvr. Return the two halves of the strip,envlwith the remaining ket layers, and the remaining bra layers withenvr. These keep any exponent the compression gave the environments. An empty environment leaves its layer unabsorbed.
- quimb.tensor.tn2d.core._gen_plaquette_environments_via_envs(tn, plaquettes, cyclic_x, cyclic_y, first_contract, second_schedule, contract_opts, environment_opts, second_dense=None, max_separation=1)[source]¶
Yield environments for plaquettes
((i, j), (x_bsz, y_bsz)). Plaquettes can differ in size and cross periodic boundaries.First compress along one direction to leave a narrow strip. Unless
first_contractis set, choose this direction for each plaquette. Share one sweep across all block sizes in each direction.Then contract along each strip. By default, contract strips of width one exactly and compress wider strips. Set
second_denseto choose explicitly.With
max_separation=0.5,envlabsorbs the first layer of the block’s first plane, andenvrthe last layer of its last plane, wherever these environments exist. A single periodic environment absorbs only the first layer of the first plane. Contract these strips exactly, and also yield the local sides of each layer at the plaquette. Otherwise yieldNonefor these.Schematically (from the side):
- max_separation=1: max_separation=0.5: max_separation=0:
┊ ┊ ┊ ┊
- KET-> ┏━━░──░━━┓ envl┏█──░┓ ┊ ┊
envl█ █envr ┃ ┃ envl█━━█envr
- BRA-> ┗━━░──░━━┛ ┗░──█┛envr ┊ ┊
┊ ┊ ┊ ┊ …. …. ….
plaquette
- quimb.tensor.tn2d.core._grow_1d_block(start, size, max_distance, L, cyclic)[source]¶
Grow the block
(start, size)bymax_distanceon each side, and return the new(start, size). If open, stop at the lattice edges. If periodic, the block can wrap past the boundary. If it would then reach allLsites, return each site once, splitting the extra sites evenly either side of the original block, with any odd one after it.
- quimb.tensor.tn2d.core._tn_partial_trace_cluster_boundary(tn, _, where, **kwargs)[source]¶
Use a module-level function for executor pickling. Ignore the term.
- class quimb.tensor.tn2d.core.TensorNetwork2DVector(ts=(), *, virtual=False, check_collisions=True)[source]¶
Bases:
TensorNetwork2D,quimb.tensor.tnag.core.TensorNetworkGenVectorMixin class for a 2D square lattice vector TN, i.e. one with a single physical index per site.
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_site_ind_id')¶
- 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).
- gate(G, where, contract=False, tags=None, propagate_tags='sites', inplace=False, info=None, **compress_opts)[source]¶
Apply the dense gate
G, maintaining the physical indices of this 2D vector tensor network.- Parameters:
G (array_like) – The gate array to apply, should match or be factorable into the shape
(phys_dim,) * (2 * len(where)).where (sequence of tuple[int, int] or tuple[int, int]) – Which site coordinates to apply the gate to.
contract ({'reduce-split', 'split', False, True}, optional) –
How to contract the gate into the 2D tensor network:
False: gate is added to network and nothing is contracted, tensor network structure is thus not maintained.
True: gate is contracted with all tensors involved, tensor network structure is thus only maintained if gate acts on a single site only.
’reduce-split’: factor the two physical indices into ‘R-factors’ using QR decompositions on the original site tensors, then contract the gate, split it and reabsorb each side. Much cheaper than
'split'.’split’: contract all involved tensors then split the result back into two.
The final two methods are relevant for two site gates only, for single site gates they use the
contract=Trueoption which also maintains the structure of the TN. See below for a pictorial description of each method.tags (str or sequence of str, optional) – Tags to add to the new gate tensor.
propagate_tags ({'sites', 'register', True, False}, optional) –
If
contract==False, which tags to propagate to the new gate tensor from the tensors it was applied to:If
'sites', then only propagate tags matching e.g. ‘I{},{}’ and ignore all others. I.e. assuming unitary gates just propagate the causal lightcone.If
'register', then only propagate tags matching the sites of where this gate was actually applied. I.e. ignore the lightcone, just keep track of which ‘registers’ the gate was applied to.If
False, propagate nothing.If
True, propagate all tags.
inplace (bool, optional) – Whether to perform the gate operation inplace on the tensor network or not.
info (None or dict, optional) – Used to store extra optional information such as the singular values if not absorbed.
compress_opts – Supplied to
tensor_split()for anycontractmethods that involve splitting. Ignored otherwise.
- Returns:
G_psi – The new 2D vector TN like
IIIGII @ psietc.- Return type:
Notes
The
contractoptions look like the following (for two site gates).contract=False:│ │ GGGGG │╱ │╱ ──●───●── ╱ ╱
contract=True:│╱ │╱ ──GGGGG── ╱ ╱
contract='split':│╱ │╱ │╱ │╱ ──GGGGG── ==> ──G┄┄┄G── ╱ ╱ ╱ ╱ <SVD>
contract='reduce-split':│ │ │ │ GGGGG GGG │ │ │╱ │╱ ==> ╱│ │ ╱ ==> ╱│ │ ╱ │╱ │╱ ──●───●── ──>─●─●─<── ──>─GGG─<── ==> ──G┄┄┄G── ╱ ╱ ╱ ╱ ╱ ╱ ╱ ╱ <QR> <LQ> <SVD>
For one site gates when one of the ‘split’ methods is supplied
contract=Trueis assumed.
- compute_norm(max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=('KET', 'BRA'), compress_opts=None, sequence=None, equalize_norms=False, progbar=None, **contract_opts)[source]¶
Compute the norm (squared) of this vector via boundary contraction.
- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary, can also be any of the generic 1D or arbgeom methods.
layer_tags (None, bool, int or tuple[str, str], optional) – Tags for the ket and bra layers, which are then contracted one by one in this order. Use
Trueor1for("KET", "BRA"), orFalse,0orNoneto contract both layers together.compress_opts (None or dict, optional) – Other low level options to pass to
compress_between().sequence (sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional) – Which directions to cycle throught when performing the inwards contractions, i.e. from that direction. If
aroundis specified you will likely need all of these! Default is to contract from the two shortest opposing sides.equalize_norms (bool or float, optional) – Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in
tn.exponent.progbar (bool, optional) – Whether to show a progress bar.
contract_opts – Additional options to pass to
contract_boundary().
- Return type:
- compute_partial_traces_boundary(wheres, max_bond, *, normalized=True, get='matrix', cutoff=None, canonize=True, method=None, layer_tags=('KET', 'BRA'), autogroup=True, contract_optimize='auto-hq', plaquette_envs=None, plaquette_map=None, progbar=False, **plaquette_env_options)[source]¶
Compute reduced density matrices using the boundary contraction plaquette environments of
compute_plaquette_environments(). Only for open boundaries.- Parameters:
wheres (sequence of coordinate or sequence of coordinates) – The site or sites to keep for each reduced density matrix, either a single coordinate
(i, j)or a pair of coordinates.max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.normalized (bool or "return", optional) – Normalize each reduced density matrix to unit trace. If “return”, give each as
(rho, trace)without dividing by the trace. Ignored ifget="tn", which returns the unnormalized network without a separate trace.get ({'matrix', 'array', 'tensor', 'tn'}, optional) – How to return each reduced density matrix, see
compute_partial_traces().cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction. By default
1e-10.canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary.
layer_tags (None, bool, int or tuple[str, str], optional) – Tags for the ket and bra layers, which are then contracted one by one in this order. Use
Trueor1for("KET", "BRA"), orFalse,0orNoneto contract both layers together.autogroup (bool, optional) – If
True(the default), group sites into horizontal and vertical sets to be computed separately (usually more efficient) if possible.contract_optimize (str, optional) – Contraction path finder to use for contracting each local reduced density matrix.
plaquette_envs (None or dict, optional) – Supply precomputed plaquette environments.
plaquette_map (None, dict, optional) – Supply the mapping of which plaquettes (denoted by
((x0, y0), (dx, dy))) to use for which coordinates, it will be calculated automatically otherwise.progbar (bool, optional) – Whether to show a progress bar, with one step per reduced density matrix.
plaquette_env_options – Supplied to
compute_plaquette_environments()to generate the plaquette environments.
- Returns:
The reduced density matrix for each
where, with sites in the order ofwhere.- Return type:
dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork]
- compute_partial_traces_via_envs(wheres, max_bond, *, normalized=True, get='matrix', autogroup=True, plaquette_sizes=None, cyclic=None, first_contract=None, schedule='auto', second_schedule='auto', second_dense=None, max_separation=1, method=None, layer_tags=('KET', 'BRA'), cutoff=None, canonize=True, optimize='auto-hq', equalize_norms=False, compress_opts=None, contract_opts=None, progbar=False, callback_rhos=None, **compress_method_opts)[source]¶
Compute reduced density matrices for open or periodic boundaries. Use compressed plaquette environments from
compute_plaquette_environments_via_envs(). Share one sweep across all plaquette sizes in each first direction, then contract along each remaining strip.- Parameters:
wheres (sequence of coordinate or sequence of coordinates) – The site or sites to keep for each reduced density matrix. Sites can cross either periodic boundary.
max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.normalized (bool or "return", optional) – Normalize each reduced density matrix to unit trace. If “return”, give each as
(rho, trace)without dividing by the trace. Ignored ifget="tn", which returns the unnormalized network without a separate trace.get ({'matrix', 'array', 'tensor', 'tn'}, optional) – How to return each reduced density matrix, see
compute_partial_traces().autogroup (bool, optional) –
Use larger requested plaquette sizes to cover smaller ones. For requested sizes {3x1, 2x1, 2x2, 1x2, 1x3},
autogroup=Trueuses {3x1, 2x2, 1x3}. Withautogroup=False, use 3x3 for all.For each set of sites, choose the smallest of these sizes that fits, by area. In this example, use 3x1 for the 2x1 sites and 1x3 for the 1x2 sites. Enlarge the rectangle around the sites to that size, keeping its start coordinate. At open boundaries, shift it inward if needed to fit the lattice. Reuse an environment when both the plaquette size and start match.
plaquette_sizes (sequence[tuple[int, int]], optional) – Plaquette sizes
(x_bsz, y_bsz)to use in place of those chosen byautogroup. Each set of sites must fit in one of them.cyclic (bool or tuple[bool, bool], optional) – Periodicity in each direction. By default infer it.
first_contract ({'x', 'y'}, optional) – Direction to compress first for all plaquettes. By default choose it per plaquette to keep the strip narrow, e.g. ‘x’ for 1x2 and ‘y’ for 2x1. This can require a sweep in each direction.
schedule ({'auto', 'tree', 'cut', 'cutpair'}, optional) – Construction schedule of the approximate environments in the first direction, see
gen_block_environments().second_schedule ({'auto', 'tree', 'cut', 'cutpair'}, optional) – Schedule along each strip. By default use ‘cut’ for exact contraction and ‘tree’ for compressed contraction.
second_dense (bool, optional) – Whether to contract along each strip exactly. By default do so only for strips of width one. Compress wider strips.
max_separation ({1, 0.5}, optional) –
How far to leave between the environments and kept sites. By default (1), they are left adjacent. If 0.5, with two
layer_tags, absorb the first layer of adjacent sites into the min-side env and the last layer into the max-side env, wherever these exist. A single periodic env connected to both sides absorbs only the first layer. The remaining strip is then contracted exactly, regardless ofsecond_dense. From the side:max_separation=1: max_separation=0.5: ┊ ┊ ┊ ┊ KET-> ┏━━░──░━━┓ envl┏█──░┓ envl█ █envr ┃ ┃ BRA-> ┗━━░──░━━┛ ┗░──█┛envr ┊ ┊ ┊ ┊ .... .... plaquettemethod (str or callable, optional) – Compression method. By default use the compressor’s default for each direction. See
gen_compressed_environments().layer_tags (None, bool, int or tuple[str, str], optional) – Tags for the ket and bra layers, which are then contracted one by one in this order. Use
Trueor1for("KET", "BRA"), orFalse,0orNoneto contract both layers together.cutoff (float, optional) – Compression cutoff. By default use the default of the compression function.
canonize (bool or str, optional) – Canonicalization option supplied to the compressor.
optimize (str, optional) – Contraction path optimizer supplied to the compressor, and the default for
contract_opts.equalize_norms (bool or float, optional) – Whether to equalize tensor norms after each compression.
compress_opts (dict, optional) – Additional options supplied to the compressor.
contract_opts (dict, optional) – Options for the exact contractions, of the environments along each strip if
second_dense, and of each reduced density matrix.optimizeis the default path optimizer.progbar (bool, optional) – Whether to show a progress bar, with one step per reduced density matrix.
callback_rhos (callable, optional) – If given, call
callback_rhos(rhos)with the new reduced density matrices of each plaquette as soon as they are ready, in the same form as the return value. Plaquettes finish in sweep order, not the order ofwheres. This can be used to save results during a long run.compress_method_opts – Additional options supplied to the compression method.
- Returns:
The reduced density matrix for each
where, with sites in the order ofwhere.- Return type:
dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork]
- partial_trace_cluster_boundary(keep, max_bond, *, max_distance=1, max_separation=1, gauges=None, cutoff=None, method=None, canonize=True, layer_tags=('KET', 'BRA'), first_contract=None, cyclic=None, normalized=True, get='matrix', smudge=1e-12, power=1.0, optimize='auto-hq', compress_opts=None, **contract_boundary_opts)[source]¶
Compute an approximate reduced density matrix from a local rectangular cluster. Grow the smallest rectangle containing
keepbymax_distancesites on each side. Insert simple update bondgaugesif supplied. Sweep one axis inward until at mostmax_separationrows or columns remain on each side of the kept sites. Contract the remaining network exactly. From the side:max_separation=1: max_separation=0.5: max_separation=0: ┊ ┊ ┊ ┊ KET-> ┏━━░──░━━┓ envl┏█──░┓ ┊ ┊ envl█ █envr ┃ ┃ envl█━━█envr BRA-> ┗━━░──░━━┛ ┗░──█┛envr ┊ ┊ ┊ ┊ ┊ ┊ .... .... .... plaquetteThe cluster can cross a periodic boundary. It is treated as an open network, so it supports the usual boundary compression methods, including 1D methods.
- Parameters:
keep (coordinate or sequence of coordinates) – Sites to keep. They can cross either periodic boundary.
max_bond (int or None) – Maximum boundary bond dimension, often called ‘chi’. Use
Noneto truncate using onlycutoff.max_distance (int, optional) – Number of sites to add on each side. Must be non-negative. Open boundaries clip the cluster to the lattice. If the cluster would cover a whole periodic direction, the two sides are cut.
max_separation (int or 0.5, optional) – How far to leave between the boundary and kept sites. By default (1), they are left adjacent. If 0, the boundaries also absorb the adjacent row (but not if this means joining envs). If 0.5, with two
layer_tags, absorb the first layer of adjacent sites into the min-side env and the last layer into the max-side env, wherever these exist.gauges (dict[str, array_like], optional) – Simple update bond gauges keyed by index. Only matching bonds receive a gauge.
cutoff (float, optional) – Singular value cutoff for boundary compression. Defaults to
1e-10.method ({'mps', 'full-bond', 'projector2d', ...}, optional) – Boundary compression method. Any 1D compression method is also accepted. Defaults to
'mps'.canonize (bool, optional) – Whether to canonize before compressing.
layer_tags (None, bool, int or tuple[str, str], optional) – Tags for the ket and bra layers, which are then contracted one by one in this order. Use
Trueor1for("KET", "BRA"), orFalse,0orNoneto contract both layers together.first_contract ({'x', 'y'}, optional) – Axis to sweep. By default, choose the one that leaves the narrowest strip.
cyclic (bool or tuple[bool, bool], optional) – Periodicity in each direction. By default, infer it.
normalized (bool or "return", optional) – Normalize to unit trace. If
"return", return(rho, trace)without dividing by the trace. Ignored forget="tn".get ({'matrix', 'array', 'tensor', 'tn'}, optional) – Return a matrix, array, tensor, or the uncontracted network.
'tn'returns the remaining strip without a separate trace.smudge (float, optional) – Value added to gauges before insertion, relative to the largest gauge value.
power (float, optional) – Power applied to gauges before insertion.
optimize (str or PathOptimizer, optional) – Path optimizer for the final contraction.
compress_opts (None or dict, optional) – Additional boundary compression options.
contract_boundary_opts – Additional options passed to
contract_boundary().
- Return type:
array or Tensor or TensorNetwork or (array, float) or (Tensor, float)
- compute_partial_traces_cluster_boundary(wheres, max_bond, *, max_distance=1, gauges=None, normalized=True, get='matrix', executor=None, progbar=False, **kwargs)[source]¶
Compute reduced density matrices for many sets of sites. Use a separate rectangular cluster for each set. See
partial_trace_cluster_boundary().- Parameters:
wheres (sequence of coordinate or sequence of coordinates) – Sites to keep for each reduced density matrix. Each set can cross either periodic boundary.
max_bond (int or None) – Maximum boundary bond dimension, often called ‘chi’. Use
Noneto truncate using onlycutoff.max_distance (int, optional) – Number of sites to add on each side. Must be non-negative.
gauges (dict[str, array_like], optional) – Simple update bond gauges keyed by index.
normalized (bool or "return", optional) – Normalize each reduced density matrix to unit trace. If
"return", return each as(rho, trace)without dividing by the trace. Ignored forget="tn".get ({'matrix', 'array', 'tensor', 'tn'}, optional) – Return each result as a matrix, array, tensor, or uncontracted network.
executor (Executor, optional) – Run the computations in parallel with this executor.
progbar (bool, optional) – Whether to show one progress step per reduced density matrix.
kwargs – Additional options for
partial_trace_cluster_boundary().
- Returns:
The reduced density matrix for each
where, with sites in the order ofwhere.- Return type:
dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork]
- compute_partial_traces(wheres, max_bond, *, cutoff=None, method=None, normalized=True, get='matrix', route=None, progbar=False, **kwargs)[source]¶
Compute many local reduced density matrices at once, each from the environment of a plaquette containing its sites.
- Parameters:
wheres (sequence of coordinate or sequence of coordinates) – The site or sites to keep for each reduced density matrix.
max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cutoff (float, optional) – The cutoff used when compressing the environments. By default use the default of the compression function, or
1e-10forroute='boundary'androute='cluster_boundary'.method (str or callable, optional) – Compression method for the selected route. By default, use that route’s default.
normalized (bool or "return", optional) – Normalize each reduced density matrix to unit trace. If “return”, give each as
(rho, trace)without dividing by the trace. Ignored ifget="tn", which returns the unnormalized network without a separate trace.get ({'matrix', 'array', 'tensor', 'tn'}, optional) –
How to return each reduced density matrix:
’matrix’: a dense matrix, with the ket sites fused into rows and the bra sites fused into columns.
’array’: the raw array, with one axis per ket site then one axis per bra site.
’tensor’: a
Tensorwith the ket and bra indices.’tn’: the uncontracted tensor network.
route ({None, 'boundary', 'envs', 'cluster_boundary'}, optional) –
How to compute each reduced density matrix. By default, use
'envs'if either direction is periodic and'boundary'otherwise.’boundary’: boundary contraction from each side, see
compute_partial_traces_boundary(). Only for open boundaries.’envs’: an approximate sweep in one direction, then sweeps along each strip in the other direction, see
compute_partial_traces_via_envs().’cluster_boundary’: contract a separate cluster around each set of sites, with optional simple update gauges, see
partial_trace_cluster_boundary().
progbar (bool, optional) – Whether to show a progress bar, with one step per reduced density matrix.
kwargs – Supplied to the method chosen by
route.
- Returns:
The reduced density matrix for each
where, with sites in the order ofwhere.- Return type:
dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork]
- partial_trace(keep, max_bond, *, cutoff=None, method=None, normalized=True, get='matrix', route=None, **kwargs)[source]¶
Compute the reduced density matrix of the sites
keep. Seecompute_partial_traces()for the options, and for many sets of sites at once.- Parameters:
keep (coordinate or sequence of coordinates) – The site or sites to keep.
max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cutoff (float, optional) – The cutoff used when compressing the environments. By default use the default of the compression function, or
1e-10forroute='boundary'androute='cluster_boundary'.method (str or callable, optional) – Compression method for the selected route. By default, use that route’s default.
normalized (bool or "return", optional) – Normalize the reduced density matrix to unit trace. If “return”, give
(rho, trace)without dividing by the trace. Ignored ifget="tn", which returns the unnormalized network without a separate trace.get ({'matrix', 'array', 'tensor', 'tn'}, optional) – How to return the reduced density matrix, see
compute_partial_traces().route ({None, 'boundary', 'envs', 'cluster_boundary'}, optional) – How to compute the plaquette environment, see
compute_partial_traces().kwargs – Supplied to
compute_partial_traces().
- Return type:
array or Tensor or TensorNetwork or (array, float) or (Tensor, float)
- compute_local_expectation_via_envs(terms, max_bond, *, cutoff=None, method=None, normalized=True, return_all=False, progbar=False, **kwargs)[source]¶
Compute many local expectations at once, as
tr(rho G)with each reduced density matrixrhofromcompute_partial_traces_via_envs(), for open or periodic boundaries.- Parameters:
terms (dict[coordinate or tuple[coordinate], array_like]) – The local terms to compute values for. Sites can cross either periodic boundary.
max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cutoff (float, optional) – Compression cutoff. By default use the default of the compression function.
method (str or callable, optional) – The compression method, see
compute_partial_traces_via_envs().normalized (bool or "return", optional) – Normalize each local reduced density matrix to unit trace. If “return” and
return_all=True, give each term as(expec, trace)without dividing by the trace.return_all (bool, optional) – Whether to return each expectation in
termsseparately or sum them all together (the default).progbar (bool, optional) – Whether to show a progress bar, with one step per reduced density matrix.
kwargs – Supplied to
compute_partial_traces_via_envs().
- Return type:
- compute_local_expectation_cluster_boundary(terms, max_bond, *, max_distance=1, gauges=None, cutoff=None, method=None, normalized=True, return_all=False, progbar=False, **kwargs)[source]¶
Compute local expectations as
tr(rho G). Form each reduced density matrixrhofrom a separate rectangular cluster. Seepartial_trace_cluster_boundary().- Parameters:
terms (dict[coordinate or tuple[coordinate], array_like]) – Local terms keyed by site or sites. Sites can cross either periodic boundary. Each term should be a matrix or an array with one axis per ket site, then one axis per bra site.
max_bond (int or None) – Maximum boundary bond dimension, often called ‘chi’. Use
Noneto truncate using onlycutoff.max_distance (int, optional) – Number of sites to add on each side. Must be non-negative.
gauges (dict[str, array_like], optional) – Simple update bond gauges keyed by index.
cutoff (float, optional) – Singular value cutoff for boundary compression. Defaults to
1e-10.method (str or callable, optional) – Boundary compression method. Defaults to
'mps'.normalized (bool or "return", optional) – Normalize each reduced density matrix to unit trace. If
"return"andreturn_all=True, return(expec, trace)for each term without dividing by the trace. If"return"andreturn_all=False, divide each value by its trace before summing.return_all (bool, optional) – Whether to return each expectation. By default, return their sum.
progbar (bool, optional) – Whether to show one progress step per reduced density matrix.
kwargs – Additional options for
compute_partial_traces_cluster_boundary().
- Return type:
- compute_local_expectation(terms, max_bond, *, cutoff=None, method=None, normalized=True, return_all=False, route=None, progbar=False, **kwargs)[source]¶
Compute local expectations as
tr(rho G), using reduced density matrices fromcompute_partial_traces(). Return their sum by default.By default normalize each expectation by its local trace, \(\langle O_i \rangle = Tr[\rho_p O_i] / Tr[\rho_p]\). This avoids a separate norm contraction and usually improves accuracy.
- Parameters:
terms (dict[coordinate or tuple[coordinate], array_like]) – Local operators keyed by site or sites. Use
(i, j)for one site or((i_a, j_a), (i_b, j_b), ...)for several. Each operator can be a matrix or an array with one axis per ket site followed by one per bra site.max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cutoff (float, optional) – The cutoff used when compressing the environments. By default use the default of the compression function, or
1e-10forroute='boundary'androute='cluster_boundary'.method (str or callable, optional) – Compression method for the selected route. By default, use that route’s default.
normalized (bool or "return", optional) – Normalize each local reduced density matrix to unit trace. If “return” and
return_all=True, give each term as(expec, trace)without dividing by the trace.return_all (bool, optional) – Whether to return each expectation in
termsseparately or sum them all together (the default).route ({None, 'boundary', 'envs', 'cluster_boundary'}, optional) – How to compute each reduced density matrix, see
compute_partial_traces(). By default use'envs'if either direction is periodic and'boundary'otherwise.progbar (bool, optional) – Whether to show a progress bar, with one step per reduced density matrix.
kwargs – Additional options for the selected route.
- Return type:
- local_expectation(G, where, max_bond, *, cutoff=None, method=None, normalized=True, route=None, **kwargs)[source]¶
Compute the local expectation
tr(rho G)of operatorGat siteswhere, withrhofrompartial_trace(). Seecompute_local_expectation()for many terms at once.- Parameters:
G (array_like) – The local operator, as a matrix or with one axis per ket site then one axis per bra site.
where (coordinate or sequence of coordinates) – The site or sites to compute the expectation at.
max_bond (int or None) – Maximum environment bond dimension, often called ‘chi’. Supply
Noneto truncate using onlycutoff. This is not recommended in 2D.cutoff (float, optional) – The cutoff used when compressing the environments. By default use the default of the compression function, or
1e-10forroute='boundary'androute='cluster_boundary'.method (str or callable, optional) – Compression method for the selected route. By default, use that route’s default.
normalized (bool or "return", optional) – Normalize the reduced density matrix to unit trace. If “return”, give
(expec, trace)without dividing by the trace.route ({None, 'boundary', 'envs', 'cluster_boundary'}, optional) – How to compute the reduced density matrix, see
compute_partial_traces().kwargs – Supplied to
compute_partial_traces().
- Return type:
- normalize(max_bond=None, *, cutoff=1e-10, canonize=True, method=None, layer_tags=('KET', 'BRA'), balance_bonds=False, equalize_norms=False, inplace=False, **contract_boundary_opts)[source]¶
Normalize this PEPS.
- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
canonize (bool, optional) – Whether to sweep one way with canonization before compressing.
method ({'mps', 'full-bond', ...}, optional) – How to perform the compression on the boundary.
layer_tags (None, bool, int or tuple[str, str], optional) – Tags for the ket and bra layers, which are then contracted one by one in this order. Use
Trueor1for("KET", "BRA"), orFalse,0orNoneto contract both layers together.balance_bonds (bool, optional) – Whether to balance the bonds after normalization, a form of conditioning.
equalize_norms (bool, optional) – Whether to set all the tensor norms to the same value after normalization, another form of conditioning.
inplace (bool, optional) – Whether to perform the normalization inplace or not.
contract_boundary_opts – Supplied to
contract_boundary(), by default, two layer contraction will be used.
- class quimb.tensor.tn2d.core.TensorNetwork2DOperator(ts=(), *, virtual=False, check_collisions=True)[source]¶
Bases:
TensorNetwork2D,quimb.tensor.tnag.core.TensorNetworkGenOperatorMixin class for a 2D square lattice TN operator, i.e. one with both ‘upper’ and ‘lower’ site (physical) indices.
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_upper_ind_id', '_lower_ind_id')¶
- reindex_lower_sites(new_id, where=None, inplace=False)[source]¶
Update the lower site index labels to a new string specifier.
- class quimb.tensor.tn2d.core.TensorNetwork2DFlat(ts=(), *, virtual=False, check_collisions=True)[source]¶
Bases:
TensorNetwork2DMixin class for a 2D square lattice tensor network with a single tensor per site, for example, both PEPS and PEPOs.
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly')¶
- expand_bond_dimension(new_bond_dim, inplace=True, bra=None, rand_strength=0.0)[source]¶
Increase the bond dimension of this flat, 2D, tensor network, padding the tensor data with either zeros or random entries.
- Parameters:
new_bond_dim (int) – The new dimension. If smaller or equal to the current bond dimension nothing will happend.
inplace (bool, optional) – Whether to expand in place (the default), or return a new TN.
bra (TensorNetwork2DFlat, optional) – Expand this TN with the same data also, assuming it to be the conjugate, bra, TN.
rand_strength (float, optional) – If greater than zero, pad the data arrays with gaussian noise of this strength.
- Returns:
tn
- Return type:
- compress(max_bond=None, cutoff=1e-10, equalize_norms=False, row_sweep='right', col_sweep='up', **compress_opts)[source]¶
Compress all bonds in this flat 2D tensor network.
- Parameters:
max_bond (int, optional) – The maximum boundary dimension, AKA ‘chi’. The default of
Nonemeans truncation is left purely tocutoffand is not recommended in 2D.cutoff (float, optional) – Cut-off value to used to truncate singular values in the boundary contraction.
compress_opts (None or dict, optional) – Supplied to
compress_between().
- class quimb.tensor.tn2d.core.PEPS(arrays, *, shape='urdlp', tags=None, site_ind_id='k{},{}', site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', **tn_opts)[source]¶
Bases:
TensorNetwork2DVector,TensorNetwork2DFlatProjected Entangled Pair States object (2D):
... │ │ │ │ │ │ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │ │ │ │ │ │ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │ │ │ │ │ │ ... ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │ │ │ │ │ │ ●────●────●────●────●────●── ╱ ╱ ╱ ╱ ╱ ╱
- Parameters:
arrays (sequence of sequence of array_like) – The core tensor data arrays.
shape (str, optional) – Which order the dimensions of the arrays are supplied in, the default
'urdlp'stands for (‘up’, ‘right’, ‘down’, ‘left’, ‘physical’). Arrays on the edge of lattice are assumed to be missing the corresponding dimension. Internally, the arrays are stored ‘urdlp’.tags (set[str], optional) – Extra global tags to add to the tensor network.
site_ind_id (str, optional) – String specifier for naming convention of site indices.
site_tag_id (str, optional) – String specifier for naming convention of site tags.
x_tag_id (str, optional) – String specifier for naming convention of row (‘x’) tags.
y_tag_id (str, optional) – String specifier for naming convention of column (‘y’) tags.
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_site_ind_id')¶
- _site_ind_id = 'k{},{}'¶
- _site_tag_id = 'I{},{}'¶
- _x_tag_id = 'X{}'¶
- _y_tag_id = 'Y{}'¶
- _Lx¶
- _Ly¶
- classmethod from_fill_fn(fill_fn, Lx, Ly, bond_dim, phys_dim=2, cyclic=False, shape='urdlp', **peps_opts)[source]¶
Create a 2D PEPS from a filling function with signature
fill_fn(shape).- Parameters:
Lx (int) – The number of rows.
Ly (int) – The number of columns.
bond_dim (int) – The bond dimension.
phys_dim (int, optional) – The physical index dimension.
cyclic (bool or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions.
shape (str, optional) – How to layout the indices of the tensors, the default is
(up, right, down, left, phys) == 'urdlp'. This is the order of the shape supplied to the filling function.peps_opts – Supplied to
PEPS.
- Returns:
psi
- Return type:
- classmethod empty(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]¶
Create an empty 2D PEPS.
- Parameters:
- Returns:
psi
- Return type:
See also
- classmethod ones(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]¶
Create a 2D PEPS whose tensors are filled with ones.
- Parameters:
- Returns:
psi
- Return type:
See also
- classmethod zeros(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts)[source]¶
Create a 2D PEPS whose tensors are filled with zeros.
- Parameters:
- Returns:
psi
- Return type:
See also
- classmethod rand(Lx, Ly, bond_dim, phys_dim=2, dist='normal', loc=0.0, scale=1.0, dtype='float64', seed=None, **peps_opts)[source]¶
Create a random (un-normalized) PEPS.
- Parameters:
Lx (int) – The number of rows.
Ly (int) – The number of columns.
bond_dim (int) – The bond dimension.
physical (int, optional) – The physical index dimension.
dist ({'normal', 'uniform', 'rademacher', 'exp'}, optional) – Type of random number to generate, defaults to ‘normal’.
loc (float, optional) – An additive offset to add to the random numbers.
dtype (dtype, optional) – The dtype to create the arrays with, default is real double.
seed (int, optional) – A random seed.
peps_opts – Supplied to
PEPS.
- Returns:
psi
- Return type:
See also
- classmethod product_state(site_map, cyclic=False, **peps_opts)[source]¶
Create a PEPS representing a product state, with explicit bonds of dimension 1 between sites.
- Parameters:
site_map (dict[tuple[int, int], array] or Sequence[Sequence[array]]) – A mapping of site coordinates to physical vectors, or a 2D array of physical vectors. Each vector being a single site state.
cyclic (bool or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions.
peps_opts – Supplied to
PEPS.
- Return type:
- class quimb.tensor.tn2d.core.PEPO(arrays, *, shape='urdlbk', tags=None, upper_ind_id='k{},{}', lower_ind_id='b{},{}', site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', cyclic=None, **tn_opts)[source]¶
Bases:
TensorNetwork2DOperator,TensorNetwork2DFlatProjected Entangled Pair Operator object:
... │╱ │╱ │╱ │╱ │╱ │╱ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │╱ │╱ │╱ │╱ │╱ │╱ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │╱ │╱ │╱ │╱ │╱ │╱ ... ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │╱ │╱ │╱ │╱ │╱ │╱ ●────●────●────●────●────●── ╱ ╱ ╱ ╱ ╱ ╱
- Parameters:
arrays (sequence of sequence of array) – The core tensor data arrays.
shape (str, optional) – What order the dimensions of the arrays are supplied in, the default
'urdlbk'stands for (‘up’ / x+, ‘right’ / y+, ‘down’ / x-, ‘left’ / y-, ‘bra’, ‘ket’). Arrays on the edge of lattice are assumed to be missing the corresponding dimension.tags (set[str], optional) – Extra global tags to add to the tensor network.
upper_ind_id (str, optional) – String specifier for naming convention of upper site indices.
lower_ind_id (str, optional) – String specifier for naming convention of lower site indices.
site_tag_id (str, optional) – String specifier for naming convention of site tags.
x_tag_id (str, optional) – String specifier for naming convention of row (‘x’) tags.
y_tag_id (str, optional) – String specifier for naming convention of column (‘y’) tags.
cyclic (None, bool, or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions. If
None(default), infer from the array shapes (requires any non-singleton bond dimension). Pass an explicitboolor(cyclic_x, cyclic_y)to override inference; this is needed when bond dimensions are 1 (shape inference then cannot detect cyclic boundaries).
- _EXTRA_PROPS = ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_upper_ind_id', '_lower_ind_id')¶
- _upper_ind_id = 'k{},{}'¶
- _lower_ind_id = 'b{},{}'¶
- _site_tag_id = 'I{},{}'¶
- _x_tag_id = 'X{}'¶
- _y_tag_id = 'Y{}'¶
- _Lx¶
- _Ly¶
- classmethod from_fill_fn(fill_fn, Lx, Ly, bond_dim, phys_dim=2, cyclic=False, shape='urdlbk', **pepo_opts)[source]¶
Create a PEPO and fill the tensor entries with a supplied function matching signature
fill_fn(shape) -> array.- Parameters:
fill_fn (callable) – A function that takes a shape tuple and returns a data array.
Lx (int) – The number of rows.
Ly (int) – The number of columns.
bond_dim (int) – The bond dimension.
phys_dim (int, optional) – The physical indices dimension.
cyclic (bool or tuple[bool, bool], optional) – Whether the lattice is cyclic in the x and y directions.
shape (str, optional) – How to layout the indices of the tensors, the default is
(up, right, down, left bra, ket) == 'urdlbk'.pepo_opts – Supplied to
PEPO.
- classmethod rand(Lx, Ly, bond_dim, phys_dim=2, herm=False, dist='normal', loc=0.0, scale=1.0, dtype='float64', seed=None, **pepo_opts)[source]¶
Create a random PEPO.
- Parameters:
Lx (int) – The number of rows.
Ly (int) – The number of columns.
bond_dim (int) – The bond dimension.
physical (int, optional) – The physical index dimension.
herm (bool, optional) – Whether to symmetrize the tensors across the physical bonds to make the overall operator hermitian.
dtype (dtype, optional) – The dtype to create the arrays with, default is real double.
seed (int, optional) – A random seed.
pepo_opts – Supplied to
PEPO.
- Returns:
X
- Return type:
- rand_herm¶
- classmethod zeros(Lx, Ly, bond_dim, phys_dim=2, dtype='float64', backend='numpy', **pepo_opts)[source]¶
Create a PEPO with all zero entries.
- Parameters:
Lx (int) – The number of rows.
Ly (int) – The number of columns.
bond_dim (int) – The bond dimension.
physical (int, optional) – The physical index dimension.
dtype (dtype, optional) – The dtype to create the arrays with, default is real double.
backend (str, optional) – Which backend to use, default is
'numpy'.pepo_opts – Supplied to
PEPO.
- quimb.tensor.tn2d.core.show_2d(tn_2d, show_lower=False, show_upper=False)[source]¶
Base function for printing a unicode schematic of flat 2D TNs.
- quimb.tensor.tn2d.core.calc_plaquette_sizes(coo_groups, autogroup=True)[source]¶
Find a sequence of plaquette blocksizes that will cover all the terms (coordinate pairs) in
pairs.- Parameters:
coo_groups (sequence of tuple[tuple[int]] or tuple[int]) – The sequence of 2D coordinates pairs describing terms. Each should either be a single 2D coordinate or a sequence of 2D coordinates.
autogroup (bool, optional) – Whether to return the minimal sequence of blocksizes that will cover all terms or merge them into a single
((x_bsz, y_bsz),).
- Returns:
bszs – Pairs of blocksizes.
- Return type:
Examples
Some nearest neighbour interactions:
>>> H2 = {None: qu.ham_heis(2)} >>> ham = qtn.LocalHam2D(10, 10, H2) >>> calc_plaquette_sizes(ham.terms.keys()) ((1, 2), (2, 1))
>>> calc_plaquette_sizes(ham.terms.keys(), autogroup=False) ((2, 2),)
If we add any next nearest neighbour interaction then we are going to need the (2, 2) blocksize in any case:
>>> H2[(1, 1), (2, 2)] = 0.5 * qu.ham_heis(2) >>> ham = qtn.LocalHam2D(10, 10, H2) >>> calc_plaquette_sizes(ham.terms.keys()) ((2, 2),)
If we add longer range interactions (non-diagonal next nearest) we again can benefit from multiple plaquette blocksizes:
>>> H2[(1, 1), (1, 3)] = 0.25 * qu.ham_heis(2) >>> H2[(1, 1), (3, 1)] = 0.25 * qu.ham_heis(2) >>> ham = qtn.LocalHam2D(10, 10, H2) >>> calc_plaquette_sizes(ham.terms.keys()) ((1, 3), (2, 2), (3, 1))
Or choose the plaquette blocksize that covers all terms:
>>> calc_plaquette_sizes(ham.terms.keys(), autogroup=False) ((3, 3),)
- quimb.tensor.tn2d.core.plaquette_to_sites(p)[source]¶
Turn a plaquette
((i0, j0), (di, dj))into the sites it contains.Examples
>>> plaquette_to_sites([(3, 4), (2, 2)]) ((3, 4), (3, 5), (4, 4), (4, 5))
- quimb.tensor.tn2d.core.calc_plaquette_map(plaquettes)[source]¶
Generate a dictionary of all the coordinate pairs in
plaquettesmapped to the ‘best’ (smallest) rectangular plaquette that contains them.Examples
Consider 4 sites, with one 2x2 plaquette and two vertical (2x1) and horizontal (1x2) plaquettes each:
>>> plaquettes = [ ... # 2x2 plaquette covering all sites ... ((0, 0), (2, 2)), ... # horizontal plaquettes ... ((0, 0), (1, 2)), ... ((1, 0), (1, 2)), ... # vertical plaquettes ... ((0, 0), (2, 1)), ... ((0, 1), (2, 1)), ... ]
>>> calc_plaquette_map(plaquettes) {((0, 0), (0, 1)): ((0, 0), (1, 2)), ((0, 0), (1, 0)): ((0, 0), (2, 1)), ((0, 0), (1, 1)): ((0, 0), (2, 2)), ((0, 1), (1, 0)): ((0, 0), (2, 2)), ((0, 1), (1, 1)): ((0, 1), (2, 1)), ((1, 0), (1, 1)): ((1, 0), (1, 2))}
Now every of the size coordinate pairs is mapped to one of the plaquettes, but to the smallest one that contains it. So the 2x2 plaquette (specified by
((0, 0), (2, 2))) would only used for diagonal terms here.