quimb.tensor.tn2d.core ====================== .. py:module:: quimb.tensor.tn2d.core .. autoapi-nested-parse:: Classes and algorithms related to 2D tensor networks. Attributes ---------- .. autoapisummary:: quimb.tensor.tn2d.core.BOUNDARY_SEQUENCE_VALID quimb.tensor.tn2d.core.BOUNDARY_SEQUENCE_MAP Classes ------- .. autoapisummary:: quimb.tensor.tn2d.core.Rotator2D quimb.tensor.tn2d.core.TensorNetwork2D quimb.tensor.tn2d.core.TensorNetwork2DVector quimb.tensor.tn2d.core.TensorNetwork2DOperator quimb.tensor.tn2d.core.TensorNetwork2DFlat quimb.tensor.tn2d.core.PEPS quimb.tensor.tn2d.core.PEPO Functions --------- .. autoapisummary:: quimb.tensor.tn2d.core.nearest_neighbors quimb.tensor.tn2d.core.gen_2d_bonds quimb.tensor.tn2d.core.gen_2d_plaquette quimb.tensor.tn2d.core.gen_2d_plaquettes quimb.tensor.tn2d.core.gen_2d_strings quimb.tensor.tn2d.core.parse_boundary_sequence quimb.tensor.tn2d.core._parse_boundary_method quimb.tensor.tn2d.core.is_lone_coo quimb.tensor.tn2d.core._normalize_2d_cyclic quimb.tensor.tn2d.core._choose_plaquette_first_contract quimb.tensor.tn2d.core._half_absorb_block_layers quimb.tensor.tn2d.core._gen_plaquette_environments_via_envs quimb.tensor.tn2d.core._find_plaquette quimb.tensor.tn2d.core._grow_1d_block quimb.tensor.tn2d.core._tn_partial_trace_cluster_boundary quimb.tensor.tn2d.core.show_2d quimb.tensor.tn2d.core.calc_plaquette_sizes quimb.tensor.tn2d.core.plaquette_to_sites quimb.tensor.tn2d.core.calc_plaquette_map quimb.tensor.tn2d.core.tensor_network_2d_distance Module Contents --------------- .. py:function:: nearest_neighbors(coo) .. py:function:: gen_2d_bonds(Lx, Ly, steppers=None, coo_filter=None, cyclic=False) Convenience function for tiling pairs of bond coordinates on a 2D lattice given a function like ``lambda i, j: (i + 1, j + 1)``. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param steppers: 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. :type steppers: callable or sequence of callable, optional :param coo_filter: Function that takes args ``(i, j)`` and only returns ``True`` if this is to be a valid starting coordinate. :type coo_filter: callable :Yields: **bond** (*tuple[tuple[int, int], tuple[int, int]]*) -- A pair of coordinates. .. rubric:: 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)) .. py:function:: gen_2d_plaquette(coo0, steps) Generate a plaquette at site ``coo0`` by stepping first in ``steps`` and then the reverse steps. :param coo0: The coordinate of the first site in the plaquette. :type coo0: tuple :param steps: The steps to take to generate the plaquette. Each element should be one of ``('x+', 'x-', 'y+', 'y-')``. :type steps: tuple :Yields: **coo** (*tuple*) -- The coordinates of the sites in the plaquette, including the last site which will be the same as the first. .. py:function:: gen_2d_plaquettes(Lx, Ly, tiling) Generate a tiling of plaquettes in a square 2D lattice. :param Lx: The length of the lattice in the x direction. :type Lx: int :param Ly: The length of the lattice in the y direction. :type Ly: int :param tiling: 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. :type tiling: {'1', '2', 'full'} :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. .. py:function:: gen_2d_strings(Lx, Ly) Generate all length-wise strings in a square 2D lattice. .. py:class:: Rotator2D(tn, xrange, yrange, from_which, stepsize=1) 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. :param tn: The tensor network to rotate coordinates for. :type tn: TensorNetwork2D :param xrange: The range of x-coordinates to range over. :type xrange: tuple[int, int] :param yrange: The range of y-coordinates to range over. :type yrange: tuple[int, int] :param from_which: The direction to sweep from. :type from_which: {'xmin', 'xmax', 'ymin', 'ymax'} :param stepsize: The step size to use when sweeping. :type stepsize: int, optional .. py:attribute:: tn .. py:attribute:: xrange .. py:attribute:: yrange .. py:attribute:: from_which .. py:attribute:: plane .. py:method:: sweep_other() .. py:method:: rotate(a, b) Rotate a pair such as a coordinate ``(i, j)`` or a block size between the real and rotated frames. This is its own inverse. .. py:method:: cyclic_x() .. py:method:: cyclic_y() .. py:method:: get_jnext(j) .. py:method:: get_opposite_env_fn() Get the function and location label for contracting boundaries in the opposite direction to main sweep. .. py:data:: BOUNDARY_SEQUENCE_VALID .. py:data:: BOUNDARY_SEQUENCE_MAP .. py:function:: parse_boundary_sequence(sequence) Ensure ``sequence`` is a tuple of boundary sequence strings from ``{'xmin', 'xmax', 'ymin', 'ymax'}`` .. py:class:: TensorNetwork2D(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`quimb.tensor.tnag.core.TensorNetworkGen` Mixin 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-1 This 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)`` .. py:attribute:: _NDIMS :value: 2 .. py:attribute:: _EXTRA_PROPS :value: ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly') .. py:method:: _compatible_2d(other) Check whether ``self`` and ``other`` are compatible 2D tensor networks such that they can remain a 2D tensor network when combined. .. py:method:: combine(other, *, virtual=False, check_collisions=True) Combine this tensor network with another, returning a new tensor network. If the two are compatible, cast the resulting tensor network to a :class:`TensorNetwork2D` instance. :param other: The other tensor network to combine with. :type other: TensorNetwork2D or TensorNetwork :param virtual: Whether the new tensor network should copy all the incoming tensors (``False``, the default), or view them as virtual (``True``). :type virtual: bool, optional :param check_collisions: 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. :type check_collisions: bool, optional :rtype: TensorNetwork2D or TensorNetwork .. py:property:: Lx The number of rows. .. py:property:: Ly The number of columns. .. py:property:: nsites The total number of sites. .. py:method:: site_tag(i, j=None) The name of the tag specifiying the tensor at site ``(i, j)``. .. py:property:: x_tag_id The string specifier for tagging each row of this 2D TN. .. py:method:: x_tag(i) .. py:property:: x_tags A tuple of all of the ``Lx`` different row tags. .. py:attribute:: row_tag .. py:attribute:: row_tags .. py:property:: y_tag_id The string specifier for tagging each column of this 2D TN. .. py:method:: y_tag(j) .. py:property:: y_tags A tuple of all of the ``Ly`` different column tags. .. py:attribute:: col_tag .. py:attribute:: col_tags .. py:method:: maybe_convert_coo(x) Check if ``x`` is a tuple of two ints and convert to the corresponding site tag if so. .. py:method:: has_site(site) Whether ``site`` is a valid ``(i, j)`` coordinate of this 2D tensor network, with ``0 <= i < Lx`` and ``0 <= j < Ly``. .. py:method:: _get_tids_from_tags(tags, which='all') This is the function that lets coordinates such as ``(i, j)`` be used for many 'tag' based functions. .. py:method:: gen_site_coos() Generate coordinates for all the sites in this 2D TN. .. py:method:: gen_bond_coos() Generate pairs of coordinates for all the bonds in this 2D TN. .. py:method:: gen_horizontal_bond_coos() Generate all coordinate pairs like ``(i, j), (i, j + 1)``. .. py:method:: gen_horizontal_even_bond_coos() Generate all coordinate pairs like ``(i, j), (i, j + 1)`` where ``j`` is even, which thus don't overlap at all. .. py:method:: gen_horizontal_odd_bond_coos() Generate all coordinate pairs like ``(i, j), (i, j + 1)`` where ``j`` is odd, which thus don't overlap at all. .. py:method:: gen_vertical_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j)``. .. py:method:: gen_vertical_even_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j)`` where ``i`` is even, which thus don't overlap at all. .. py:method:: gen_vertical_odd_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j)`` where ``i`` is odd, which thus don't overlap at all. .. py:method:: gen_diagonal_left_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j - 1)``. .. py:method:: gen_diagonal_left_even_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j - 1)`` where ``j`` is even, which thus don't overlap at all. .. py:method:: gen_diagonal_left_odd_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j - 1)`` where ``j`` is odd, which thus don't overlap at all. .. py:method:: gen_diagonal_right_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j + 1)``. .. py:method:: gen_diagonal_right_even_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j + 1)`` where ``i`` is even, which thus don't overlap at all. .. py:method:: gen_diagonal_right_odd_bond_coos() Generate all coordinate pairs like ``(i, j), (i + 1, j + 1)`` where ``i`` is odd, which thus don't overlap at all. .. py:method:: gen_diagonal_bond_coos() Generate all next nearest neighbor diagonal coordinate pairs. .. py:method:: valid_coo(coo, xrange=None, yrange=None) Check whether ``coo`` is in-bounds. :param coo: The coordinates to check. :type coo: (int, int, int), optional :param xrange: The range of allowed values for the x and y coordinates. :type xrange: (int, int), optional :param yrange: The range of allowed values for the x and y coordinates. :type yrange: (int, int), optional :rtype: bool .. py:method:: get_ranges_present() Return the range of site coordinates present in this TN. :returns: **xrange, yrange** -- The minimum and maximum site coordinates present in each direction. :rtype: tuple[tuple[int, int]] .. py:method:: is_cyclic_x(j=None, imin=None, imax=None) Check if the x dimension is cyclic (periodic), specifically whether a bond exists between ``(imin, j)`` and ``(imax, j)``, with default values of ``imin = 0`` and ``imax = Lx - 1``, and ``j`` at the center of the lattice. If ``imin`` and ``imax`` are adjacent then this is considered False, since there is no 'extra' connectivity. .. py:method:: is_cyclic_y(i=None, jmin=None, jmax=None) Check if the y dimension is cyclic (periodic), specifically whether a bond exists between ``(i, jmin)`` and ``(i, jmax)``, with default values of ``jmin = 0`` and ``jmax = Ly - 1``, and ``i`` at the center of the lattice. If ``jmin`` and ``jmax`` are adjacent then this is considered False, since there is no 'extra' connectivity. .. py:method:: __getitem__(key) Key based tensor selection, checking for integer based shortcut. .. py:method:: show() Print a unicode schematic of this 2D TN and its bond dimensions. .. py:method:: _repr_info() General info to show in various reprs. Sublasses can add more relevant info to this dict. .. py:method:: flatten(fuse_multibonds=True, inplace=False) -> TensorNetwork2DFlat 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 :class:`TensorNetwork2DFlat`. :param fuse_multibonds: Whether to fuse any multibonds that are created by this process. Defaults to ``True``. :type fuse_multibonds: bool, optional :param inplace: Whether to modify this tensor network inplace, or return a new one. Defaults to ``False``. :type inplace: bool, optional :rtype: TensorNetwork2DFlat .. py:attribute:: flatten_ .. py:method:: gen_pairs(xrange=None, yrange=None, xreverse=False, yreverse=False, coordinate_order='xy', xstep=None, ystep=None, stepping_order='xy', step_only=None) Helper function for generating pairs of cooordinates for all bonds within a certain range, optionally specifying an order. :param xrange: The range of allowed values for the x and y coordinates. :type xrange: (int, int), optional :param yrange: The range of allowed values for the x and y coordinates. :type yrange: (int, int), optional :param xreverse: Whether to reverse the order of the x and y sweeps. :type xreverse: bool, optional :param yreverse: Whether to reverse the order of the x and y sweeps. :type yreverse: bool, optional :param coordinate_order: 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. :type coordinate_order: str, optional :param xstep: When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow ``xreverse`` and ``yreverse`` respectively. :type xstep: int, optional :param ystep: When generating a bond, step in this direction to yield the neighboring coordinate. By default, these follow ``xreverse`` and ``yreverse`` respectively. :type ystep: int, optional :param stepping_order: The order in which to step the x and y coordinates to generate bonds. Does not need to include all dimensions. :type stepping_order: str, optional :param step_only: Only perform the ith steps in ``stepping_order``, used to interleave canonizing and compressing for example. :type step_only: int, optional :Yields: **coo_a, coo_b** (*((int, int), (int, int))*) .. py:method:: canonize_plane(xrange, yrange, equalize_norms=False, canonize_opts=None, **gen_pair_opts) Canonize every pair of tensors within a subrange, optionally specifying a order to visit those pairs in. .. py:method:: canonize_row(i, sweep, yrange=None, **canonize_opts) Canonize all or part of a row. If ``sweep == 'right'`` then:: | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ==> ─●──>──>──>──>──o──●─ row=i | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | . . . . jstart jstop jstart jstop If ``sweep == 'left'`` then:: | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ==> ─●──o──<──<──<──<──●─ row=i | | | | | | | | | | | | | | ─●──●──●──●──●──●──●─ ─●──●──●──●──●──●──●─ | | | | | | | | | | | | | | . . . . jstop jstart jstop jstart Does not yield an orthogonal form in the same way as in 1D. :param i: Which row to canonize. :type i: int :param sweep: Which direction to sweep in. :type sweep: {'right', 'left'} :param jstart: Starting column, defaults to whole row. :type jstart: int or None :param jstop: Stopping column, defaults to whole row. :type jstop: int or None :param canonize_opts: Supplied to ``canonize_between``. .. py:method:: canonize_column(j, sweep, xrange=None, **canonize_opts) Canonize all or part of a column. If ``sweep='up'`` then:: | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | ─●──●──●─ ─●──o──●─ istop | | | ==> | | | ─●──●──●─ ─●──^──●─ | | | | | | ─●──●──●─ ─●──^──●─ istart | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | . . j j If ``sweep='down'`` then:: | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | ─●──●──●─ ─●──v──●─ istart | | | ==> | | | ─●──●──●─ ─●──v──●─ | | | | | | ─●──●──●─ ─●──o──●─ istop | | | | | | ─●──●──●─ ─●──●──●─ | | | | | | . . j j Does not yield an orthogonal form in the same way as in 1D. :param j: Which column to canonize. :type j: int :param sweep: Which direction to sweep in. :type sweep: {'up', 'down'} :param xrange: The range of columns to canonize. :type xrange: None or (int, int), optional :param canonize_opts: Supplied to ``canonize_between``. .. py:method:: canonize_row_around(i, around=(0, 1)) .. py:method:: compress_plane(xrange, yrange, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None, **gen_pair_opts) Compress every pair of tensors within a subrange, optionally specifying a order to visit those pairs in. .. py:method:: compress_row(i, sweep, yrange=None, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None) Compress all or part of a row. If ``sweep == 'right'`` then:: | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━━> ━●━━>──>──>──>──o━━●━ row=i | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | . . . . jstart jstop jstart jstop If ``sweep == 'left'`` then:: | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━━> ━●━━o──<──<──<──<━━●━ row=i | | | | | | | | | | | | | | ━●━━●━━●━━●━━●━━●━━●━ ━●━━●━━●━━●━━●━━●━━●━ | | | | | | | | | | | | | | . . . . jstop jstart jstop jstart Does not yield an orthogonal form in the same way as in 1D. :param i: Which row to compress. :type i: int :param sweep: Which direction to sweep in. :type sweep: {'right', 'left'} :param yrange: The range of columns to compress. :type yrange: tuple[int, int] or None :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional .. py:method:: compress_column(j, sweep, xrange=None, max_bond=None, cutoff=1e-10, equalize_norms=False, compress_opts=None) Compress all or part of a column. If ``sweep='up'`` then:: ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──o──●─ . ┃ ┃ ┃ ==> ┃ | ┃ . ─●──●──●─ ─●──^──●─ . xrange ┃ ┃ ┃ ┃ | ┃ . ─●──●──●─ ─●──^──●─ . ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ . . j j If ``sweep='down'`` then:: ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──v──●─ . ┃ ┃ ┃ ==> ┃ | ┃ . ─●──●──●─ ─●──v──●─ . xrange ┃ ┃ ┃ ┃ | ┃ . ─●──●──●─ ─●──o──●─ . ┃ ┃ ┃ ┃ ┃ ┃ ─●──●──●─ ─●──●──●─ ┃ ┃ ┃ ┃ ┃ ┃ . . j j Does not yield an orthogonal form in the same way as in 1D. :param j: Which column to compress. :type j: int :param sweep: Which direction to sweep in. :type sweep: {'up', 'down'} :param xrange: The range of rows to compress. :type xrange: None or (int, int), optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional .. py:method:: _contract_boundary_core_via_1d(xrange, yrange, from_which, max_bond, cutoff=1e-10, method='dm', layer_tags=None, **compress_opts) .. py:method:: _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) .. py:method:: _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) Contract the boundary of this 2D TN using the 'full bond' environment information obtained from a boundary contraction in the opposite direction. :param xrange: The range of rows to contract and compress. :type xrange: (int, int) or None, optional :param yrange: The range of columns to contract and compress. :type yrange: (int, int) :param from_which: Which direction to contract the rectangular patch from. :type from_which: {'xmin', 'ymin', 'xmax', 'ymax'} :param max_bond: The maximum boundary dimension, AKA 'chi'. By default used for the opposite direction environment contraction as well. :type max_bond: int :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction - only for the opposite direction environment contraction. :type cutoff: float, optional :param similarity_method: Which similarity decomposition method to use to compress the full bond environment, a shortcut for ``compress_opts=dict(method=...)``. By default ``'eigh'``. :type similarity_method: {'eigh', 'eig', 'svd', 'biorthog'}, optional :param renorm: Whether to renormalize the isometric projection or not. :type renorm: bool, optional :param optimize: Contraction optimizer to use for the exact contractions. :type optimize: str or PathOptimize, optimize :param opposite_envs: If supplied, the opposite environments will be fetched or lazily computed into this dict depending on whether they are missing. :type opposite_envs: dict, optional :param contract_boundary_opts: Other options given to the opposite direction environment contraction. :param compress_opts: Options supplied to :func:`~quimb.tensor.decomp.similarity_compress` when compressing each full bond environment. :type compress_opts: dict, optional .. py:method:: _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) 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. :param xrange: The range of x indices to contract. :type xrange: tuple :param yrange: The range of y indices to contract. :type yrange: tuple :param from_which: From which boundary to contract. :type from_which: {'xmin', 'xmax', 'ymin', 'ymax'} :param max_bond: The maximum bond dimension to contract to. If ``None`` (default), compression is left to ``cutoff``. :type max_bond: int, optional :param cutoff: The cutoff to use for boundary compression. :type cutoff: float, optional :param lazy: 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. :type lazy: bool, optional :param equalize_norms: Whether to actively absorb the norm of modified tensors into ``self.exponent``. :type equalize_norms: bool, optional :param optimize: The contract path optimization to use when forming the projector tensors. :type optimize: str or PathOptimizer, optional :param contract_opts: Explicit options for contracting the projectors to pass to :meth:`~quimb.tensor.TensorNetwork.to_dense`. Values set here take precedence over any defaults such as ``optimize``. :type contract_opts: dict, optional :param reduce_opts: Explicit options to pass to :func:`squared_op_to_reduced_factor`, for example ``method="cholesky"``. Values set here take precedence over any defaults. :type reduce_opts: dict, optional :param compress_opts: Explicit options to pass to :func:`compute_oblique_projectors`. Values set here take precedence over any defaults. :type compress_opts: dict, optional .. seealso:: :py:obj:`TensorNetwork.insert_compressor_between_regions` .. py:method:: 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) 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, see :func:`~quimb.tensor.tn1d.compress.tensor_network_1d_compress`. ``mode`` is a deprecated alias of ``method``. For ``layer_tags``, see :meth:`contract_boundary`. .. py:attribute:: contract_boundary_from_ .. py:method:: 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) Contract a 2D tensor network inwards from the bottom, canonizing and compressing (left to right) along the way. If ``layer_tags is None`` this looks like:: a) contract │ │ │ │ │ ●──●──●──●──● │ │ │ │ │ │ │ │ │ │ --> ●══●══●══●══● ●──●──●──●──● b) optionally canonicalize │ │ │ │ │ ●══●══<══<══< c) compress in opposite direction │ │ │ │ │ --> │ │ │ │ │ --> │ │ │ │ │ >──●══●══●══● --> >──>──●══●══● --> >──>──>──●══● . . --> . . --> . . If ``layer_tags`` is 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 ╲│ ╲│ ╲│ ╲│ ╲│ >══>══>══>══● :param xrange: The range of rows to compress (inclusive). :type xrange: (int, int) :param yrange: The range of columns to compress (inclusive), sweeping along with canonization and compression. Defaults to all columns. :type yrange: (int, int) or None, optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param sweep_reverse: 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. :type sweep_reverse: bool, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param inplace: Whether to perform the contraction inplace or not. :type inplace: bool, optional .. seealso:: :py:obj:`contract_boundary_from_xmax`, :py:obj:`contract_boundary_from_ymin`, :py:obj:`contract_boundary_from_ymax` .. py:attribute:: contract_boundary_from_xmin_ .. py:method:: 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) Contract a 2D tensor network inwards from the top, canonizing and compressing (right to left) along the way. If ``layer_tags is None`` this looks like:: a) contract ●──●──●──●──● | | | | | --> ●══●══●══●══● ●──●──●──●──● | | | | | | | | | | b) optionally canonicalize ●══●══<══<══< | | | | | c) compress in opposite direction >──●══●══●══● --> >──>──●══●══● --> >──>──>──●══● | | | | | --> | | | | | --> | | | | | . . --> . . --> . . If ``layer_tags`` is 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 ●══●══●══●══● ╱│ ╱│ ╱│ ╱│ ╱│ :param xrange: The range of rows to compress (inclusive). :type xrange: (int, int) :param yrange: The range of columns to compress (inclusive), sweeping along with canonization and compression. Defaults to all columns. :type yrange: (int, int) or None, optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param sweep_reverse: 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. :type sweep_reverse: bool, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param inplace: Whether to perform the contraction inplace or not. :type inplace: bool, optional .. seealso:: :py:obj:`contract_boundary_from_xmin`, :py:obj:`contract_boundary_from_ymin`, :py:obj:`contract_boundary_from_ymax` .. py:attribute:: contract_boundary_from_xmax_ .. py:method:: 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) Contract a 2D tensor network inwards from the left, canonizing and compressing (bottom to top) along the way. If ``layer_tags is None`` this looks like:: a) contract ●──●── ●── │ │ ║ ●──●── ==> ●── │ │ ║ ●──●── ●── b) optionally canonicalize ●── v── ║ ║ ●── ==> v── ║ ║ ●── ●── c) compress in opposite direction v── ●── ║ │ v── ==> ^── ║ │ ●── ^── If ``layer_tags`` is 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 ●── │╲ ╰─●── │╲ ╰─●── │ ╰── :param yrange: The range of columns to compress (inclusive). :type yrange: (int, int) :param xrange: The range of rows to compress (inclusive), sweeping along with canonization and compression. Defaults to all rows. :type xrange: (int, int) or None, optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param sweep_reverse: 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. :type sweep_reverse: bool, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param inplace: Whether to perform the contraction inplace or not. :type inplace: bool, optional .. seealso:: :py:obj:`contract_boundary_from_xmin`, :py:obj:`contract_boundary_from_xmax`, :py:obj:`contract_boundary_from_ymax` .. py:attribute:: contract_boundary_from_ymin_ .. py:method:: 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) Contract a 2D tensor network inwards from the left, canonizing and compressing (top to bottom) along the way. If ``layer_tags is None`` this looks like:: a) contract ──●──● ──● │ │ ║ ──●──● ==> ──● │ │ ║ ──●──● ──● b) optionally canonicalize ──● ──v ║ ║ ──● ==> ──v ║ ║ ──● ──● c) compress in opposite direction ──v ──● ║ │ ──v ==> ──^ ║ │ ──● ──^ If ``layer_tags`` is 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 ╲ ╱ ────● :param yrange: The range of columns to compress (inclusive). :type yrange: (int, int) :param xrange: The range of rows to compress (inclusive), sweeping along with canonization and compression. Defaults to all rows. :type xrange: (int, int) or None, optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param sweep_reverse: 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. :type sweep_reverse: bool, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param inplace: Whether to perform the contraction inplace or not. :type inplace: bool, optional .. seealso:: :py:obj:`contract_boundary_from_xmin`, :py:obj:`contract_boundary_from_xmax`, :py:obj:`contract_boundary_from_ymin` .. py:attribute:: contract_boundary_from_ymax_ .. py:method:: _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) Unified handler for performing iterleaved contractions in a sequence of inwards boundary directions. .. py:method:: 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) 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. :param around: If given, don't contract the square of sites bounding these coordinates. :type around: None or sequence of (int, int), optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary, can also be any of the generic 1D or arbgeom methods. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param compress_opts: Other low level options to pass to :meth:`~quimb.tensor.tensor_core.TensorNetwork.compress_between`. :type compress_opts: None or dict, optional :param sequence: Which directions to cycle throught when performing the inwards contractions, i.e. *from* that direction. If ``around`` is specified you will likely need all of these! Default is to contract from the two shortest opposing sides. :type sequence: sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional :param xmin: The initial bottom boundary row, defaults to 0. :type xmin: int, optional :param xmax: The initial top boundary row, defaults to ``Lx - 1``. :type xmax: int, optional :param ymin: The initial left boundary column, defaults to 0. :type ymin: int, optional :param ymax: The initial right boundary column, defaults to ``Ly - 1``.. :type ymax: int, optional :param max_separation: When any two sides become this far apart simply contract the remaining tensor network. If ``around`` is given, also stop each side this many rows or columns from the target region. With ``0`` the boundaries absorb the edge rows or columns of the region, but leave at least two. :type max_separation: int, optional :param max_unfinished: If ``around is None``, when this many sides are still not within ``max_separation`` simply contract the remaining tensor network. :type max_unfinished: int, optional :param around: If given, don't contract the square of sites bounding these coordinates. :type around: None or sequence of (int, int), optional :param strip_exponent: 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. :type strip_exponent: bool, optional :param equalize_norms: Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in ``tn.exponent``. By default (``"auto"``) this follows ``strip_exponent``. :type equalize_norms: bool, float, or "auto", optional :param final_contract: Whether to exactly contract the remaining tensor network after the boundary contraction. :type final_contract: bool, optional :param final_contract_opts: Options to pass to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`, ``optimize`` defaults to ``'auto-hq'``. :type final_contract_opts: None or dict, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param inplace: Whether to perform the contraction in place or not. :type inplace: bool, optional :param contract_boundary_opts: Supplied to :meth:`contract_boundary_from`, including compression and canonization options. .. py:attribute:: contract_boundary_ .. py:method:: contract_mps_sweep(max_bond=None, *, cutoff=1e-10, canonize=True, direction=None, **contract_boundary_opts) Contract this 2D tensor network by sweeping an MPS across from one side to the other. :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param direction: Which direction to sweep from. If ``None`` (default) then the shortest boundary is chosen. :type direction: {'xmin', 'xmax', 'ymin', 'ymax'}, optional :param contract_boundary_opts: Supplied to :meth:`contract_boundary_from`, including compression and canonization options. .. py:attribute:: contract_mps_sweep_ .. py:method:: contract_full_bootstrap(n, *, optimize='auto-hq', **kwargs) .. py:method:: 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) Yield compressed row or column environments as they are ready. Keep cached environments only until their last use. See :func:`~quimb.tensor.environments.gen_compressed_environments`. :param direction: Compute environments for blocks of rows or columns respectively. :type direction: {'x', 'y'} :param blocks: The ``(start, size)`` blocks of rows or columns, which can have different sizes, all computed together in one sweep. Use :func:`~quimb.tensor.environments.all_blocks` to get every block of one size. :type blocks: sequence of tuple[int, int] :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cyclic: Periodicity along ``direction``. By default infer it from the network. :type cyclic: bool, optional :param compress_fn: Which compression function to use along the other direction, see :func:`~quimb.tensor.environments.gen_compressed_environments`. By default use '1d' if the other direction is open, and 'ag' if it is periodic. :type compress_fn: {None, 'ag', '1d', '2d'}, optional :param schedule: 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. :type schedule: {'auto', 'tree', 'cut', 'cutpair'}, optional :param method: The compression method, supplied to ``compress_fn``. By default use its own default method. :type method: str or callable, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. Compress after each layer. :type layer_tags: None or sequence of str, optional :param cutoff: Compression cutoff. By default use the default of the compression function. :type cutoff: float, optional :param canonize: Canonicalization option supplied to the compressor. :type canonize: bool or str, optional :param optimize: Contraction path optimizer supplied to the compressor. :type optimize: str, optional :param equalize_norms: Whether to equalize tensor norms after each compression. :type equalize_norms: bool or float, optional :param compress_opts: Additional options supplied to the compressor. :type compress_opts: dict, optional :param 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``. .. py:method:: compute_block_environments(direction, blocks, max_bond, *, cutoff=None, method=None, **kwargs) Compute compressed row or column environments for blocks of rows or columns. See :meth:`gen_block_environments` for the options, and to process them one at a time. :param direction: Compute environments for blocks of rows or columns respectively. :type direction: {'x', 'y'} :param blocks: The ``(start, size)`` blocks of rows or columns. :type blocks: sequence of tuple[int, int] :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cutoff: Compression cutoff. By default use the default of the compression function. :type cutoff: float, optional :param method: The compression method, see :meth:`gen_block_environments`. :type method: str or callable, optional :param kwargs: Supplied to :meth:`gen_block_environments`. :returns: The environment for each ``(start, size)`` block. :rtype: dict[tuple[int, int], TensorNetwork] .. py:method:: 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, check_zero=False, **contract_boundary_opts) Compute the 1D boundary tensor networks describing the environments of rows and columns. :param from_which: Which boundary to compute the environments from. :type from_which: {'xmin', 'xmax', 'ymin', 'ymax'} :param xrange: The range of rows to compute the environments for. :type xrange: tuple[int], optional :param yrange: The range of columns to compute the environments for. :type yrange: tuple[int], optional :param max_bond: The maximum bond dimension of the environments. :type max_bond: int, optional :param cutoff: The cutoff for the singular values of the environments. :type cutoff: float, optional :param canonize: Whether to canonicalize along each MPS environment before compressing. :type canonize: bool, optional :param method: Which contraction method to use for the environments. :type method: {'mps', 'projector', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param dense: Whether to use dense tensors for the environments. :type dense: bool, optional :param compress_opts: Other options to pass to :func:`~quimb.tensor.tensor_core.tensor_compress_bond`. :type compress_opts: dict, optional :param envs: An existing dictionary to store the environments in. :type envs: dict, optional :param equalize_norms: 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]``. :type equalize_norms: bool or float, optional :param check_zero: If ``True``, when equalizing norms, leave exactly zero boundary tensors as they are rather than giving ``nan``. Only used with ``dense=True``, not by the compressed boundary methods. Off by default to avoid data dependent branching when tracing and computing gradients etc. :type check_zero: bool, optional :param contract_boundary_opts: Other options to pass to :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary_from`. :returns: **envs** -- A dictionary of the environments, with keys of the form ``(from_which, row_or_col_index)``. :rtype: dict .. py:attribute:: compute_xmin_environments Compute the ``self.Lx`` 1D boundary tensor networks describing the lower environments of each row in this 2D tensor network. See :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.compute_x_environments` for full details. .. py:attribute:: compute_xmax_environments Compute the ``self.Lx`` 1D boundary tensor networks describing the upper environments of each row in this 2D tensor network. See :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.compute_x_environments` for full details. .. py:attribute:: compute_ymin_environments Compute the ``self.Ly`` 1D boundary tensor networks describing the left environments of each column in this 2D tensor network. See :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.compute_y_environments` for full details. .. py:attribute:: compute_ymax_environments Compute the ``self.Ly`` 1D boundary tensor networks describing the right environments of each column in this 2D tensor network. See :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.compute_y_environments` for full details. .. py:method:: 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) Compute the ``2 * self.Lx`` 1D 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 ``i`` will be a contraction of all rows ``i + 1, i + 2, ...`` etc:: ●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━●━━━● ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ ╱ ╲ The bottom or 'xmin' environment for row ``i`` will be a contraction of all rows ``i - 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`` :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param dense: If true, contract the boundary in as a single dense tensor. :type dense: bool, optional :param method: How to perform the boundary compression. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param envs: Supply an existing dictionary to store the environments in. :type envs: dict, optional :param contract_boundary_opts: Supplied to :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary_from_xmin` and :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary_from_xmax` . :returns: **x_envs** -- The two environment tensor networks of row ``i`` will be stored in ``x_envs['xmin', i]`` and ``x_envs['xmax', i]``. :rtype: dict[(str, int), TensorNetwork] .. py:method:: 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) Compute the ``2 * self.Ly`` 1D 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 ``j`` will be a contraction of all columns ``j - 1, j - 2, ...`` etc:: ●< ┃ ●< ┃ ●< ┃ ●< The right or 'ymax' environment for row ``j`` will be a contraction of all rows ``j + 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`` :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param dense: If true, contract the boundary in as a single dense tensor. :type dense: bool, optional :param method: How to perform the boundary compression. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param contract_boundary_opts: Supplied to :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary_from_ymin` and :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary_from_ymax` . :returns: **y_envs** -- The two environment tensor networks of column ``j`` will be stored in ``y_envs['ymin', j]`` and ``y_envs['ymax', j]``. :rtype: dict[(str, int), TensorNetwork] .. py:method:: _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) .. py:method:: _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) .. py:method:: 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) 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. :param x_bsz: The size of the plaquettes in the x-direction (number of rows). :type x_bsz: int, optional :param y_bsz: The size of the plaquettes in the y-direction (number of columns). :type y_bsz: int, optional :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the boundary compression. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. :type layer_tags: None or sequence of str, optional :param first_contract: 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). :type first_contract: {None, 'x', 'y'}, optional :param second_dense: Whether to perform the second set of contraction sweeps (in the rotated direction from whichever ``first_contract`` is) using a dense tensor or boundary method. By default this is only turned on if the ``bsz`` in the corresponding direction is 1. :type second_dense: None or bool, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional :param compute_environment_opts: Supplied to :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.compute_y_environments` or :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.compute_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. :rtype: dict[((int, int), (int, int)), TensorNetwork] .. py:method:: 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) 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_dense`` to choose exact or compressed contraction along the strips. See :meth:`compute_plaquette_environments` for contraction from open boundaries. :param x_bsz: Plaquette size in each direction. :type x_bsz: int, optional :param y_bsz: Plaquette size in each direction. :type y_bsz: int, optional :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param starts: The ``(i, j)`` plaquette starts to compute. By default compute every valid start. :type starts: sequence of tuple[int, int], optional :param cyclic: Periodicity in each direction. By default infer it. :type cyclic: bool or tuple[bool, bool], optional :param first_contract: Direction to contract approximately first. :type first_contract: {'x', 'y'}, optional :param schedule: Construction schedule of the approximate environments in the first direction, see :meth:`gen_block_environments`. :type schedule: {'auto', 'tree', 'cut', 'cutpair'}, optional :param second_schedule: Schedule along each strip. By default use 'cut' for exact contraction and 'tree' for compressed contraction. :type second_schedule: {'auto', 'tree', 'cut', 'cutpair'}, optional :param second_dense: Whether to contract along each strip exactly. By default do so only for strips of width one. Compress wider strips. :type second_dense: bool, optional :param method: Compression method. By default use the compressor's default for each direction. See :func:`~quimb.tensor.environments.gen_compressed_environments`. :type method: str or callable, optional :param layer_tags: Tags identifying the layers, which are contracted one by one in this order. Use ``None`` to contract all layers together. Booleans and integers are not accepted. Compress after each layer. :type layer_tags: None or sequence of str, optional :param cutoff: Compression cutoff. By default use the default of the compression function. :type cutoff: float, optional :param canonize: Canonicalization option supplied to the compressor. :type canonize: bool or str, optional :param optimize: Contraction path optimizer supplied to the compressor, and the default for ``contract_opts``. :type optimize: str, optional :param equalize_norms: Whether to equalize tensor norms after each compression. :type equalize_norms: bool or float, optional :param compress_opts: Additional options supplied to the compressor. :type compress_opts: dict, optional :param contract_opts: Options for the exact contractions along each strip, see ``second_dense``. ``optimize`` is the default path optimizer. :type contract_opts: dict, optional :param compress_method_opts: Additional options supplied to the compression method. :returns: Plaquette environments keyed by start and size. :rtype: dict[((int, int), (int, int)), TensorNetwork] .. py:method:: 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) Coarse grain this tensor network in ``direction`` using HOTRG. This inserts oblique projectors between tensor pairs and then optionally contracts them into new sites for form a lattice half the size. :param direction: The direction to coarse grain in. :type direction: {'x', 'y'} :param max_bond: The maximum bond dimension of the projector pairs inserted. :type max_bond: int, optional :param cutoff: The cutoff for the singular values of the projector pairs. :type cutoff: float, optional :param canonize: Whether to canonize all tensors before computing projectors, via :meth:`gauge_all_simple_`. :type canonize: bool, optional :param canonize_opts: Additional options to pass to :meth:`gauge_all_simple_`. :type canonize_opts: None or dict, optional :param gauge_power: If `canonize=True`, the power to which to raise the computed bond gauge weights when before computing the compressed projectors. :type gauge_power: float, optional :param lazy: Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them. :type lazy: bool, optional :param strip_exponent: If ``True``, enable norm equalization during the coarse graining. :type strip_exponent: bool, optional :param equalize_norms: Whether to equalize the norms of the tensors in the coarse grained lattice. By default (``"auto"``) this follows ``strip_exponent``. :type equalize_norms: bool or "auto", optional :param optimize: The optimization method to use when contracting the coarse grained lattice, if ``lazy=False``. :type optimize: str, optional :param contract_opts: Explicit options for contracting the projectors to pass to :meth:`~quimb.tensor.TensorNetwork.to_dense`. Values set here take precedence over any defaults such as ``optimize``. :type contract_opts: dict, optional :param reduce_opts: Explicit options to pass to :func:`squared_op_to_reduced_factor`, for example ``method="cholesky"``. Values set here take precedence over any defaults. :type reduce_opts: dict, optional :param compress_opts: Explicit options to pass to :func:`compute_oblique_projectors`. Values set here take precedence over any defaults. :type compress_opts: dict, optional :param inplace: Whether to perform the coarse graining in place. :type inplace: bool, optional :returns: The coarse grained tensor network, with size halved in ``direction``. :rtype: TensorNetwork2D .. seealso:: :py:obj:`contract_hotrg`, :py:obj:`TensorNetwork.insert_compressor_between_regions` .. py:attribute:: coarse_grain_hotrg_ .. py:method:: 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) Contract this tensor network using the finite version of HOTRG. See https://arxiv.org/abs/1201.1144v4 and https://arxiv.org/abs/1905.02351 for the more optimal computaton of the projectors used here. The TN is contracted sequentially in ``sequence`` directions by inserting oblique projectors between 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. :param max_bond: The maximum bond dimension of the projector pairs inserted. :type max_bond: int, optional :param cutoff: The cutoff for the singular values of the projector pairs. :type cutoff: float, optional :param canonize: Whether to canonize all tensors before computing projectors, via :meth:`gauge_all_simple_`. :type canonize: bool, optional :param canonize_opts: Additional options to pass to :meth:`gauge_all_simple_`. :type canonize_opts: None or dict, optional :param gauge_power: If `canonize=True`, the power to which to raise the computed bond gauge weights when before computing the compressed projectors. :type gauge_power: float, optional :param sequence: The directions to contract in. Default is to contract in all directions. :type sequence: tuple of str, optional :param max_separation: The maximum distance between sides (i.e. length - 1) of the tensor network before that direction is considered finished. :type max_separation: int, optional :param max_unfinished: The maximum number of directions that can be unfinished (i.e. are still longer than max_separation + 1) before the coarse graining terminates. :type max_unfinished: int, optional :param lazy: Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them. :type lazy: bool, optional :param strip_exponent: 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. :type strip_exponent: bool, optional :param equalize_norms: Whether to equalize the norms of all tensors after each contraction, gathering the overall scaling coefficient, log10, in ``tn.exponent``. By default (``"auto"``) this follows ``strip_exponent``. :type equalize_norms: bool, float, or "auto", optional :param optimize: How to optimize the contraction of the projection tensors. Note any value in ``contract_opts`` will take precedence over this. :type optimize: str or PathOptimizer, optional :param contract_opts: Explicit options for contracting the projectors to pass to :meth:`~quimb.tensor.TensorNetwork.to_dense`. Values set here take precedence over any defaults such as ``optimize``. :type contract_opts: dict, optional :param reduce_opts: Explicit options to pass to :func:`squared_op_to_reduced_factor`, for example ``method="cholesky"``. Values set here take precedence over any defaults. :type reduce_opts: dict, optional :param compress_opts: Explicit options to pass to :func:`compute_oblique_projectors`. Values set here take precedence over any defaults. :type compress_opts: dict, optional :param final_contract: Whether to exactly contract the remaining tensor network after the coarse graining contractions. :type final_contract: bool, optional :param final_contract_opts: Options to pass to :meth:`contract`, if ``final_contract=True``. Defaults to same as ``contract_opts``. :type final_contract_opts: None or dict, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param inplace: Whether to perform the coarse graining in place. :type inplace: bool, optional :param coarse_grain_opts: Additional options to pass to :meth:`coarse_grain_hotrg`. :returns: The contracted tensor network, which will have no more than one direction of length > 2. :rtype: TensorNetwork2D .. seealso:: :py:obj:`coarse_grain_hotrg`, :py:obj:`contract_ctmrg`, :py:obj:`TensorNetwork.insert_compressor_between_regions` .. py:attribute:: contract_hotrg_ .. py:method:: 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) 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 ``sequence`` directions 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. :param max_bond: The maximum bond dimension of the projector pairs inserted. :type max_bond: int, optional :param cutoff: The cutoff for the singular values of the projector pairs. :type cutoff: float, optional :param canonize: Whether to canonize the boundary tensors before each contraction, via :meth:`gauge_all`. :type canonize: bool, optional :param canonize_opts: Additional options to pass to :meth:`gauge_all`. :type canonize_opts: None or dict, optional :param lazy: Whether to contract the coarse graining projectors or leave them in the tensor network lazily. Default is to contract them. :type lazy: bool, optional :param method: The method to perform the boundary contraction. Defaults to ``'projector'``. :type method: str, optional :param sequence: Which directions to cycle throught when performing the inwards contractions, i.e. *from* that direction. If ``around`` is specified you will likely need all of these! Default is to contract in all directions. :type sequence: sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional :param xmin: The initial bottom boundary row, defaults to 0. :type xmin: int, optional :param xmax: The initial top boundary row, defaults to ``Lx - 1``. :type xmax: int, optional :param ymin: The initial left boundary column, defaults to 0. :type ymin: int, optional :param ymax: The initial right boundary column, defaults to ``Ly - 1``.. :type ymax: int, optional :param max_separation: When any two sides become this far apart simply contract the remaining tensor network. If ``around`` is given, also stop each side this many rows or columns from the target region. With ``0`` the boundaries absorb the edge rows or columns of the region, but leave at least two. :type max_separation: int, optional :param around: If given, don't contract the square of sites bounding these coordinates. :type around: None or sequence of (int, int), optional :param strip_exponent: 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. :type strip_exponent: bool, optional :param equalize_norms: Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in ``tn.exponent``. By default (``"auto"``) this follows ``strip_exponent``. :type equalize_norms: bool, float, or "auto", optional :param optimize: How to optimize the contraction of the projection tensors. Note any value in ``contract_opts`` will take precedence over this. :type optimize: str or PathOptimizer, optional :param contract_opts: Explicit options for contracting the projectors to pass to :meth:`~quimb.tensor.TensorNetwork.to_dense`. Values set here take precedence over any defaults such as ``optimize``. :type contract_opts: dict, optional :param reduce_opts: Explicit options to pass to :func:`squared_op_to_reduced_factor`, for example ``method="cholesky"``. Values set here take precedence over any defaults. :type reduce_opts: dict, optional :param compress_opts: Explicit options to pass to :func:`compute_oblique_projectors`. Values set here take precedence over any defaults. :type compress_opts: dict, optional :param final_contract: Whether to exactly contract the remaining tensor network after the boundary contraction. :type final_contract: bool, optional :param final_contract_opts: Options to pass to :meth:`contract`, if ``final_contract=True``. Defaults to same as ``contract_opts``. :type final_contract_opts: None or dict, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param inplace: Whether to perform the boundary contraction in place. :type inplace: bool, optional :param contract_boundary_opts: Additional options to pass to :meth:`contract_boundary_from`. :returns: Either the fully contracted scalar (if ``final_contract=True`` and ``around=None``) or the partially contracted tensor network. :rtype: scalar or TensorNetwork2D .. seealso:: :py:obj:`contract_boundary_from`, :py:obj:`contract_hotrg`, :py:obj:`TensorNetwork.insert_compressor_between_regions` .. py:attribute:: contract_ctmrg_ .. py:function:: _parse_boundary_method(method, opts, default='mps') Read the boundary contraction method, including the deprecated ``mode`` option in ``opts``. .. py:function:: is_lone_coo(where) Check whether ``where`` is a single coordinate pair. .. py:function:: _normalize_2d_cyclic(tn, cyclic) .. py:function:: _choose_plaquette_first_contract(tn, x_bsz, y_bsz, first_contract) .. py:function:: _half_absorb_block_layers(tn, envl, envr, block_tags, layer_tags, compress_fn) Absorb the ket layer of the block's first plane into ``envl``, and the bra layer of its last plane into ``envr``. Return the two halves of the strip, ``envl`` with the remaining ket layers, and the remaining bra layers with ``envr``. These keep any exponent the compression gave the environments. An empty environment leaves its layer unabsorbed. .. py:function:: _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) 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_contract`` is 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_dense`` to choose explicitly. With ``max_separation=0.5``, ``envl`` absorbs the first layer of the block's first plane, and ``envr`` the 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 yield ``None`` for these. Schematically (from the side): max_separation=1: max_separation=0.5: max_separation=0: ┊ ┊ ┊ ┊ KET-> ┏━━░──░━━┓ envl┏█──░┓ ┊ ┊ envl█ █envr ┃ ┃ envl█━━█envr BRA-> ┗━━░──░━━┛ ┗░──█┛envr ┊ ┊ ┊ ┊ ┊ ┊ .... .... .... plaquette .. py:function:: _find_plaquette(where, Lx, Ly, cyclic_x, cyclic_y) .. py:function:: _grow_1d_block(start, size, max_distance, L, cyclic) Grow the block ``(start, size)`` by ``max_distance`` on 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 all ``L`` sites, return each site once, splitting the extra sites evenly either side of the original block, with any odd one after it. .. py:function:: _tn_partial_trace_cluster_boundary(tn, _, where, **kwargs) Use a module-level function for executor pickling. Ignore the term. .. py:class:: TensorNetwork2DVector(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`TensorNetwork2D`, :py:obj:`quimb.tensor.tnag.core.TensorNetworkGenVector` Mixin class for a 2D square lattice vector TN, i.e. one with a single physical index per site. .. py:attribute:: _EXTRA_PROPS :value: ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_site_ind_id') .. py:method:: site_ind(i, j=None) Return the physical index of site ``(i, j)``. .. py:method:: reindex_sites(new_id, where=None, inplace=False) Modify the site indices for all or some tensors in this vector tensor network (without changing the ``site_ind_id``). :param new_id: A string with a format placeholder to accept a site, e.g. "ket{}". :type new_id: str :param where: Which sites to update the index labels on. If ``None`` (default) all sites. :type where: None or sequence :param inplace: Whether to reindex in place. :type inplace: bool .. py:attribute:: reindex_sites_ .. py:method:: phys_dim(i=None, j=None) Get the size of the physical indices / a specific physical index. .. py:method:: gate(G, where, contract=False, tags=None, propagate_tags='sites', inplace=False, info=None, **compress_opts) Apply the dense gate ``G``, maintaining the physical indices of this 2D vector tensor network. :param G: The gate array to apply, should match or be factorable into the shape ``(phys_dim,) * (2 * len(where))``. :type G: array_like :param where: Which site coordinates to apply the gate to. :type where: sequence of tuple[int, int] or tuple[int, int] :param contract: 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=True`` option which also maintains the structure of the TN. See below for a pictorial description of each method. :type contract: {'reduce-split', 'split', False, True}, optional :param tags: Tags to add to the new gate tensor. :type tags: str or sequence of str, optional :param propagate_tags: 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. :type propagate_tags: {'sites', 'register', True, False}, optional :param inplace: Whether to perform the gate operation inplace on the tensor network or not. :type inplace: bool, optional :param info: Used to store extra optional information such as the singular values if not absorbed. :type info: None or dict, optional :param compress_opts: Supplied to :func:`~quimb.tensor.tensor_core.tensor_split` for any ``contract`` methods that involve splitting. Ignored otherwise. :returns: **G_psi** -- The new 2D vector TN like ``IIIGII @ psi`` etc. :rtype: TensorNetwork2DVector .. rubric:: Notes The ``contract`` options look like the following (for two site gates). ``contract=False``:: │ │ GGGGG │╱ │╱ ──●───●── ╱ ╱ ``contract=True``:: │╱ │╱ ──GGGGG── ╱ ╱ ``contract='split'``:: │╱ │╱ │╱ │╱ ──GGGGG── ==> ──G┄┄┄G── ╱ ╱ ╱ ╱ ``contract='reduce-split'``:: │ │ │ │ GGGGG GGG │ │ │╱ │╱ ==> ╱│ │ ╱ ==> ╱│ │ ╱ │╱ │╱ ──●───●── ──>─●─●─<── ──>─GGG─<── ==> ──G┄┄┄G── ╱ ╱ ╱ ╱ ╱ ╱ ╱ ╱ For one site gates when one of the 'split' methods is supplied ``contract=True`` is assumed. .. py:attribute:: gate_ .. py:method:: 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) Compute the norm (squared) of this vector via boundary contraction. :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary, can also be any of the generic 1D or arbgeom methods. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags for the ket and bra layers, which are then contracted one by one in this order. Use ``True`` or ``1`` for ``("KET", "BRA")``, or ``False``, ``0`` or ``None`` to contract both layers together. :type layer_tags: None, bool, int or tuple[str, str], optional :param compress_opts: Other low level options to pass to :meth:`~quimb.tensor.tensor_core.TensorNetwork.compress_between`. :type compress_opts: None or dict, optional :param sequence: Which directions to cycle throught when performing the inwards contractions, i.e. *from* that direction. If ``around`` is specified you will likely need all of these! Default is to contract from the two shortest opposing sides. :type sequence: sequence of {'xmin', 'xmax', 'ymin', 'ymax'}, optional :param equalize_norms: Whether to equalize the norms of the boundary tensors after each contraction, gathering the overall scaling coefficient, log10, in ``tn.exponent``. :type equalize_norms: bool or float, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Additional options to pass to :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary`. :rtype: scalar .. py:method:: 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) Compute reduced density matrices using the boundary contraction plaquette environments of :meth:`compute_plaquette_environments`. Only for open boundaries. :param wheres: The site or sites to keep for each reduced density matrix, either a single coordinate ``(i, j)`` or a pair of coordinates. :type wheres: sequence of coordinate or sequence of coordinates :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param normalized: Normalize each reduced density matrix to unit trace. If "return", give each as ``(rho, trace)`` without dividing by the trace. Ignored if ``get="tn"``, which returns the unnormalized network without a separate trace. :type normalized: bool or "return", optional :param get: How to return each reduced density matrix, see :meth:`compute_partial_traces`. :type get: {'matrix', 'array', 'tensor', 'tn'}, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. By default ``1e-10``. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags for the ket and bra layers, which are then contracted one by one in this order. Use ``True`` or ``1`` for ``("KET", "BRA")``, or ``False``, ``0`` or ``None`` to contract both layers together. :type layer_tags: None, bool, int or tuple[str, str], optional :param autogroup: If ``True`` (the default), group sites into horizontal and vertical sets to be computed separately (usually more efficient) if possible. :type autogroup: bool, optional :param contract_optimize: Contraction path finder to use for contracting each local reduced density matrix. :type contract_optimize: str, optional :param plaquette_envs: Supply precomputed plaquette environments. :type plaquette_envs: None or dict, optional :param plaquette_map: Supply the mapping of which plaquettes (denoted by ``((x0, y0), (dx, dy))``) to use for which coordinates, it will be calculated automatically otherwise. :type plaquette_map: None, dict, optional :param progbar: Whether to show a progress bar, with one step per reduced density matrix. :type progbar: bool, optional :param plaquette_env_options: Supplied to :meth:`compute_plaquette_environments` to generate the plaquette environments. :returns: The reduced density matrix for each ``where``, with sites in the order of ``where``. :rtype: dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork] .. py:method:: 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) Compute reduced density matrices for open or periodic boundaries. Use compressed plaquette environments from :meth:`compute_plaquette_environments_via_envs`. Share one sweep across all plaquette sizes in each first direction, then contract along each remaining strip. :param wheres: The site or sites to keep for each reduced density matrix. Sites can cross either periodic boundary. :type wheres: sequence of coordinate or sequence of coordinates :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param normalized: Normalize each reduced density matrix to unit trace. If "return", give each as ``(rho, trace)`` without dividing by the trace. Ignored if ``get="tn"``, which returns the unnormalized network without a separate trace. :type normalized: bool or "return", optional :param get: How to return each reduced density matrix, see :meth:`compute_partial_traces`. :type get: {'matrix', 'array', 'tensor', 'tn'}, optional :param autogroup: Use larger requested plaquette sizes to cover smaller ones. For requested sizes {3x1, 2x1, 2x2, 1x2, 1x3}, ``autogroup=True`` uses {3x1, 2x2, 1x3}. With ``autogroup=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. :type autogroup: bool, optional :param plaquette_sizes: Plaquette sizes ``(x_bsz, y_bsz)`` to use in place of those chosen by ``autogroup``. Each set of sites must fit in one of them. :type plaquette_sizes: sequence[tuple[int, int]], optional :param cyclic: Periodicity in each direction. By default infer it. :type cyclic: bool or tuple[bool, bool], optional :param first_contract: 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. :type first_contract: {'x', 'y'}, optional :param schedule: Construction schedule of the approximate environments in the first direction, see :meth:`gen_block_environments`. :type schedule: {'auto', 'tree', 'cut', 'cutpair'}, optional :param second_schedule: Schedule along each strip. By default use 'cut' for exact contraction and 'tree' for compressed contraction. :type second_schedule: {'auto', 'tree', 'cut', 'cutpair'}, optional :param second_dense: Whether to contract along each strip exactly. By default do so only for strips of width one. Compress wider strips. :type second_dense: bool, optional :param max_separation: 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 of ``second_dense``. From the side:: max_separation=1: max_separation=0.5: ┊ ┊ ┊ ┊ KET-> ┏━━░──░━━┓ envl┏█──░┓ envl█ █envr ┃ ┃ BRA-> ┗━━░──░━━┛ ┗░──█┛envr ┊ ┊ ┊ ┊ .... .... plaquette :type max_separation: {1, 0.5}, optional :param method: Compression method. By default use the compressor's default for each direction. See :func:`~quimb.tensor.environments.gen_compressed_environments`. :type method: str or callable, optional :param layer_tags: Tags for the ket and bra layers, which are then contracted one by one in this order. Use ``True`` or ``1`` for ``("KET", "BRA")``, or ``False``, ``0`` or ``None`` to contract both layers together. :type layer_tags: None, bool, int or tuple[str, str], optional :param cutoff: Compression cutoff. By default use the default of the compression function. :type cutoff: float, optional :param canonize: Canonicalization option supplied to the compressor. :type canonize: bool or str, optional :param optimize: Contraction path optimizer supplied to the compressor, and the default for ``contract_opts``. :type optimize: str, optional :param equalize_norms: Whether to equalize tensor norms after each compression. :type equalize_norms: bool or float, optional :param compress_opts: Additional options supplied to the compressor. :type compress_opts: dict, optional :param contract_opts: Options for the exact contractions, of the environments along each strip if ``second_dense``, and of each reduced density matrix. ``optimize`` is the default path optimizer. :type contract_opts: dict, optional :param progbar: Whether to show a progress bar, with one step per reduced density matrix. :type progbar: bool, optional :param callback_rhos: 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 of ``wheres``. This can be used to save results during a long run. :type callback_rhos: callable, optional :param compress_method_opts: Additional options supplied to the compression method. :returns: The reduced density matrix for each ``where``, with sites in the order of ``where``. :rtype: dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork] .. py:method:: 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) Compute an approximate reduced density matrix from a local rectangular cluster. Grow the smallest rectangle containing ``keep`` by ``max_distance`` sites on each side. Insert simple update bond ``gauges`` if supplied. Sweep one axis inward until at most ``max_separation`` rows 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 ┊ ┊ ┊ ┊ ┊ ┊ .... .... .... plaquette The cluster can cross a periodic boundary. It is treated as an open network, so it supports the usual boundary compression methods, including 1D methods. :param keep: Sites to keep. They can cross either periodic boundary. :type keep: coordinate or sequence of coordinates :param max_bond: Maximum boundary bond dimension, often called 'chi'. Use ``None`` to truncate using only ``cutoff``. :type max_bond: int or None :param max_distance: 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. :type max_distance: int, optional :param max_separation: 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. :type max_separation: int or 0.5, optional :param gauges: Simple update bond gauges keyed by index. Only matching bonds receive a gauge. :type gauges: dict[str, array_like], optional :param cutoff: Singular value cutoff for boundary compression. Defaults to ``1e-10``. :type cutoff: float, optional :param method: Boundary compression method. Any 1D compression method is also accepted. Defaults to ``'mps'``. :type method: {'mps', 'full-bond', 'projector2d', ...}, optional :param canonize: Whether to canonize before compressing. :type canonize: bool, optional :param layer_tags: Tags for the ket and bra layers, which are then contracted one by one in this order. Use ``True`` or ``1`` for ``("KET", "BRA")``, or ``False``, ``0`` or ``None`` to contract both layers together. :type layer_tags: None, bool, int or tuple[str, str], optional :param first_contract: Axis to sweep. By default, choose the one that leaves the narrowest strip. :type first_contract: {'x', 'y'}, optional :param cyclic: Periodicity in each direction. By default, infer it. :type cyclic: bool or tuple[bool, bool], optional :param normalized: Normalize to unit trace. If ``"return"``, return ``(rho, trace)`` without dividing by the trace. Ignored for ``get="tn"``. :type normalized: bool or "return", optional :param get: Return a matrix, array, tensor, or the uncontracted network. ``'tn'`` returns the remaining strip without a separate trace. :type get: {'matrix', 'array', 'tensor', 'tn'}, optional :param smudge: Value added to gauges before insertion, relative to the largest gauge value. :type smudge: float, optional :param power: Power applied to gauges before insertion. :type power: float, optional :param optimize: Path optimizer for the final contraction. :type optimize: str or PathOptimizer, optional :param compress_opts: Additional boundary compression options. :type compress_opts: None or dict, optional :param contract_boundary_opts: Additional options passed to :meth:`contract_boundary`. :rtype: array or Tensor or TensorNetwork or (array, float) or (Tensor, float) .. py:method:: compute_partial_traces_cluster_boundary(wheres, max_bond, *, max_distance=1, gauges=None, normalized=True, get='matrix', executor=None, progbar=False, **kwargs) Compute reduced density matrices for many sets of sites. Use a separate rectangular cluster for each set. See :meth:`partial_trace_cluster_boundary`. :param wheres: Sites to keep for each reduced density matrix. Each set can cross either periodic boundary. :type wheres: sequence of coordinate or sequence of coordinates :param max_bond: Maximum boundary bond dimension, often called 'chi'. Use ``None`` to truncate using only ``cutoff``. :type max_bond: int or None :param max_distance: Number of sites to add on each side. Must be non-negative. :type max_distance: int, optional :param gauges: Simple update bond gauges keyed by index. :type gauges: dict[str, array_like], optional :param normalized: Normalize each reduced density matrix to unit trace. If ``"return"``, return each as ``(rho, trace)`` without dividing by the trace. Ignored for ``get="tn"``. :type normalized: bool or "return", optional :param get: Return each result as a matrix, array, tensor, or uncontracted network. :type get: {'matrix', 'array', 'tensor', 'tn'}, optional :param executor: Run the computations in parallel with this executor. :type executor: Executor, optional :param progbar: Whether to show one progress step per reduced density matrix. :type progbar: bool, optional :param kwargs: Additional options for :meth:`partial_trace_cluster_boundary`. :returns: The reduced density matrix for each ``where``, with sites in the order of ``where``. :rtype: dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork] .. py:method:: compute_partial_traces(wheres, max_bond, *, cutoff=None, method=None, normalized=True, get='matrix', route=None, progbar=False, **kwargs) Compute many local reduced density matrices at once, each from the environment of a plaquette containing its sites. :param wheres: The site or sites to keep for each reduced density matrix. :type wheres: sequence of coordinate or sequence of coordinates :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cutoff: The cutoff used when compressing the environments. By default use the default of the compression function, or ``1e-10`` for ``route='boundary'`` and ``route='cluster_boundary'``. :type cutoff: float, optional :param method: Compression method for the selected route. By default, use that route's default. :type method: str or callable, optional :param normalized: Normalize each reduced density matrix to unit trace. If "return", give each as ``(rho, trace)`` without dividing by the trace. Ignored if ``get="tn"``, which returns the unnormalized network without a separate trace. :type normalized: bool or "return", optional :param get: 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 :class:`~quimb.tensor.tensor_core.Tensor` with the ket and bra indices. - 'tn': the uncontracted tensor network. :type get: {'matrix', 'array', 'tensor', 'tn'}, optional :param route: 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 :meth:`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 :meth:`compute_partial_traces_via_envs`. - 'cluster_boundary': contract a separate cluster around each set of sites, with optional simple update gauges, see :meth:`partial_trace_cluster_boundary`. :type route: {None, 'boundary', 'envs', 'cluster_boundary'}, optional :param progbar: Whether to show a progress bar, with one step per reduced density matrix. :type progbar: bool, optional :param kwargs: Supplied to the method chosen by ``route``. :returns: The reduced density matrix for each ``where``, with sites in the order of ``where``. :rtype: dict[coordinate or tuple[coordinate], array or Tensor or TensorNetwork] .. py:method:: partial_trace(keep, max_bond, *, cutoff=None, method=None, normalized=True, get='matrix', route=None, **kwargs) Compute the reduced density matrix of the sites ``keep``. See :meth:`compute_partial_traces` for the options, and for many sets of sites at once. :param keep: The site or sites to keep. :type keep: coordinate or sequence of coordinates :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cutoff: The cutoff used when compressing the environments. By default use the default of the compression function, or ``1e-10`` for ``route='boundary'`` and ``route='cluster_boundary'``. :type cutoff: float, optional :param method: Compression method for the selected route. By default, use that route's default. :type method: str or callable, optional :param normalized: Normalize the reduced density matrix to unit trace. If "return", give ``(rho, trace)`` without dividing by the trace. Ignored if ``get="tn"``, which returns the unnormalized network without a separate trace. :type normalized: bool or "return", optional :param get: How to return the reduced density matrix, see :meth:`compute_partial_traces`. :type get: {'matrix', 'array', 'tensor', 'tn'}, optional :param route: How to compute the plaquette environment, see :meth:`compute_partial_traces`. :type route: {None, 'boundary', 'envs', 'cluster_boundary'}, optional :param kwargs: Supplied to :meth:`compute_partial_traces`. :rtype: array or Tensor or TensorNetwork or (array, float) or (Tensor, float) .. py:method:: compute_local_expectation_via_envs(terms, max_bond, *, cutoff=None, method=None, normalized=True, return_all=False, progbar=False, **kwargs) Compute many local expectations at once, as ``tr(rho G)`` with each reduced density matrix ``rho`` from :meth:`compute_partial_traces_via_envs`, for open or periodic boundaries. :param terms: The local terms to compute values for. Sites can cross either periodic boundary. :type terms: dict[coordinate or tuple[coordinate], array_like] :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cutoff: Compression cutoff. By default use the default of the compression function. :type cutoff: float, optional :param method: The compression method, see :meth:`compute_partial_traces_via_envs`. :type method: str or callable, optional :param normalized: 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. :type normalized: bool or "return", optional :param return_all: Whether to return each expectation in ``terms`` separately or sum them all together (the default). :type return_all: bool, optional :param progbar: Whether to show a progress bar, with one step per reduced density matrix. :type progbar: bool, optional :param kwargs: Supplied to :meth:`compute_partial_traces_via_envs`. :rtype: scalar or dict .. py:method:: 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) Compute local expectations as ``tr(rho G)``. Form each reduced density matrix ``rho`` from a separate rectangular cluster. See :meth:`partial_trace_cluster_boundary`. :param terms: 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. :type terms: dict[coordinate or tuple[coordinate], array_like] :param max_bond: Maximum boundary bond dimension, often called 'chi'. Use ``None`` to truncate using only ``cutoff``. :type max_bond: int or None :param max_distance: Number of sites to add on each side. Must be non-negative. :type max_distance: int, optional :param gauges: Simple update bond gauges keyed by index. :type gauges: dict[str, array_like], optional :param cutoff: Singular value cutoff for boundary compression. Defaults to ``1e-10``. :type cutoff: float, optional :param method: Boundary compression method. Defaults to ``'mps'``. :type method: str or callable, optional :param normalized: Normalize each reduced density matrix to unit trace. If ``"return"`` and ``return_all=True``, return ``(expec, trace)`` for each term without dividing by the trace. If ``"return"`` and ``return_all=False``, divide each value by its trace before summing. :type normalized: bool or "return", optional :param return_all: Whether to return each expectation. By default, return their sum. :type return_all: bool, optional :param progbar: Whether to show one progress step per reduced density matrix. :type progbar: bool, optional :param kwargs: Additional options for :meth:`compute_partial_traces_cluster_boundary`. :rtype: scalar or dict .. py:method:: compute_local_expectation(terms, max_bond, *, cutoff=None, method=None, normalized=True, return_all=False, route=None, progbar=False, **kwargs) Compute local expectations as ``tr(rho G)``, using reduced density matrices from :meth:`compute_partial_traces`. Return their sum by default. By default normalize each expectation by its local trace, :math:`\langle O_i \rangle = Tr[\rho_p O_i] / Tr[\rho_p]`. This avoids a separate norm contraction and usually improves accuracy. :param terms: 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. :type terms: dict[coordinate or tuple[coordinate], array_like] :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cutoff: The cutoff used when compressing the environments. By default use the default of the compression function, or ``1e-10`` for ``route='boundary'`` and ``route='cluster_boundary'``. :type cutoff: float, optional :param method: Compression method for the selected route. By default, use that route's default. :type method: str or callable, optional :param normalized: 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. :type normalized: bool or "return", optional :param return_all: Whether to return each expectation in ``terms`` separately or sum them all together (the default). :type return_all: bool, optional :param route: How to compute each reduced density matrix, see :meth:`compute_partial_traces`. By default use ``'envs'`` if either direction is periodic and ``'boundary'`` otherwise. :type route: {None, 'boundary', 'envs', 'cluster_boundary'}, optional :param progbar: Whether to show a progress bar, with one step per reduced density matrix. :type progbar: bool, optional :param kwargs: Additional options for the selected route. :rtype: scalar or dict .. py:method:: local_expectation(G, where, max_bond, *, cutoff=None, method=None, normalized=True, route=None, **kwargs) Compute the local expectation ``tr(rho G)`` of operator ``G`` at sites ``where``, with ``rho`` from :meth:`partial_trace`. See :meth:`compute_local_expectation` for many terms at once. :param G: The local operator, as a matrix or with one axis per ket site then one axis per bra site. :type G: array_like :param where: The site or sites to compute the expectation at. :type where: coordinate or sequence of coordinates :param max_bond: Maximum environment bond dimension, often called 'chi'. Supply ``None`` to truncate using only ``cutoff``. This is not recommended in 2D. :type max_bond: int or None :param cutoff: The cutoff used when compressing the environments. By default use the default of the compression function, or ``1e-10`` for ``route='boundary'`` and ``route='cluster_boundary'``. :type cutoff: float, optional :param method: Compression method for the selected route. By default, use that route's default. :type method: str or callable, optional :param normalized: Normalize the reduced density matrix to unit trace. If "return", give ``(expec, trace)`` without dividing by the trace. :type normalized: bool or "return", optional :param route: How to compute the reduced density matrix, see :meth:`compute_partial_traces`. :type route: {None, 'boundary', 'envs', 'cluster_boundary'}, optional :param kwargs: Supplied to :meth:`compute_partial_traces`. :rtype: scalar or (scalar, scalar) .. py:method:: 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) Normalize this PEPS. :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param canonize: Whether to sweep one way with canonization before compressing. :type canonize: bool, optional :param method: How to perform the compression on the boundary. :type method: {'mps', 'full-bond', ...}, optional :param layer_tags: Tags for the ket and bra layers, which are then contracted one by one in this order. Use ``True`` or ``1`` for ``("KET", "BRA")``, or ``False``, ``0`` or ``None`` to contract both layers together. :type layer_tags: None, bool, int or tuple[str, str], optional :param balance_bonds: Whether to balance the bonds after normalization, a form of conditioning. :type balance_bonds: bool, optional :param equalize_norms: Whether to set all the tensor norms to the same value after normalization, another form of conditioning. :type equalize_norms: bool, optional :param inplace: Whether to perform the normalization inplace or not. :type inplace: bool, optional :param contract_boundary_opts: Supplied to :meth:`~quimb.tensor.tn2d.core.TensorNetwork2D.contract_boundary`, by default, two layer contraction will be used. .. py:attribute:: normalize_ .. py:class:: TensorNetwork2DOperator(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`TensorNetwork2D`, :py:obj:`quimb.tensor.tnag.core.TensorNetworkGenOperator` Mixin class for a 2D square lattice TN operator, i.e. one with both 'upper' and 'lower' site (physical) indices. .. py:attribute:: _EXTRA_PROPS :value: ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_upper_ind_id', '_lower_ind_id') .. py:method:: reindex_lower_sites(new_id, where=None, inplace=False) Update the lower site index labels to a new string specifier. :param new_id: A string with a format placeholder to accept an int, e.g. ``"ket{},{}"``. :type new_id: str :param where: Which sites to update the index labels on. If ``None`` (default) all sites. :type where: None or slice :param inplace: Whether to reindex in place. :type inplace: bool .. py:attribute:: reindex_lower_sites_ .. py:method:: reindex_upper_sites(new_id, where=None, inplace=False) Update the upper site index labels to a new string specifier. :param new_id: A string with a format placeholder to accept an int, e.g. ``"ket{},{}"``. :type new_id: str :param where: Which sites to update the index labels on. If ``None`` (default) all sites. :type where: None or slice :param inplace: Whether to reindex in place. :type inplace: bool .. py:attribute:: reindex_upper_sites_ .. py:method:: lower_ind(i, j=None) Get the lower index for a given site. .. py:method:: upper_ind(i, j=None) Get the upper index for a given site. .. py:method:: phys_dim(i=0, j=0, which='upper') Get a physical index size of this 2D operator. .. py:class:: TensorNetwork2DFlat(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`TensorNetwork2D` Mixin class for a 2D square lattice tensor network with a single tensor per site, for example, both PEPS and PEPOs. .. py:attribute:: _EXTRA_PROPS :value: ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly') .. py:method:: expand_bond_dimension(new_bond_dim, inplace=True, bra=None, rand_strength=0.0) Increase the bond dimension of this flat, 2D, tensor network, padding the tensor data with either zeros or random entries. :param new_bond_dim: The new dimension. If smaller or equal to the current bond dimension nothing will happend. :type new_bond_dim: int :param inplace: Whether to expand in place (the default), or return a new TN. :type inplace: bool, optional :param bra: Expand this TN with the same data also, assuming it to be the conjugate, bra, TN. :type bra: TensorNetwork2DFlat, optional :param rand_strength: If greater than zero, pad the data arrays with gaussian noise of this strength. :type rand_strength: float, optional :returns: **tn** :rtype: TensorNetwork2DFlat .. py:method:: compress(max_bond=None, cutoff=1e-10, equalize_norms=False, row_sweep='right', col_sweep='up', **compress_opts) Compress all bonds in this flat 2D tensor network. :param max_bond: The maximum boundary dimension, AKA 'chi'. The default of ``None`` means truncation is left purely to ``cutoff`` and is not recommended in 2D. :type max_bond: int, optional :param cutoff: Cut-off value to used to truncate singular values in the boundary contraction. :type cutoff: float, optional :param compress_opts: Supplied to :meth:`compress_between`. :type compress_opts: None or dict, optional .. py:class:: PEPS(arrays, *, shape='urdlp', tags=None, site_ind_id='k{},{}', site_tag_id='I{},{}', x_tag_id='X{}', y_tag_id='Y{}', **tn_opts) Bases: :py:obj:`TensorNetwork2DVector`, :py:obj:`TensorNetwork2DFlat` Projected Entangled Pair States object (2D):: ... │ │ │ │ │ │ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │ │ │ │ │ │ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │ │ │ │ │ │ ... ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │ │ │ │ │ │ ●────●────●────●────●────●── ╱ ╱ ╱ ╱ ╱ ╱ :param arrays: The core tensor data arrays. :type arrays: sequence of sequence of array_like :param shape: 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'. :type shape: str, optional :param tags: Extra global tags to add to the tensor network. :type tags: set[str], optional :param site_ind_id: String specifier for naming convention of site indices. :type site_ind_id: str, optional :param site_tag_id: String specifier for naming convention of site tags. :type site_tag_id: str, optional :param x_tag_id: String specifier for naming convention of row ('x') tags. :type x_tag_id: str, optional :param y_tag_id: String specifier for naming convention of column ('y') tags. :type y_tag_id: str, optional .. py:attribute:: _EXTRA_PROPS :value: ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_site_ind_id') .. py:attribute:: _site_ind_id :value: 'k{},{}' .. py:attribute:: _site_tag_id :value: 'I{},{}' .. py:attribute:: _x_tag_id :value: 'X{}' .. py:attribute:: _y_tag_id :value: 'Y{}' .. py:attribute:: _Lx .. py:attribute:: _Ly .. py:method:: from_fill_fn(fill_fn, Lx, Ly, bond_dim, phys_dim=2, cyclic=False, shape='urdlp', **peps_opts) :classmethod: Create a 2D PEPS from a filling function with signature ``fill_fn(shape)``. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param phys_dim: The physical index dimension. :type phys_dim: int, optional :param cyclic: Whether the lattice is cyclic in the x and y directions. :type cyclic: bool or tuple[bool, bool], optional :param shape: 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. :type shape: str, optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS`. :returns: **psi** :rtype: PEPS .. py:method:: empty(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts) :classmethod: Create an empty 2D PEPS. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param physical: The physical index dimension. :type physical: int, optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS`. :returns: **psi** :rtype: PEPS .. seealso:: :py:obj:`PEPS.from_fill_fn` .. py:method:: ones(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts) :classmethod: Create a 2D PEPS whose tensors are filled with ones. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param physical: The physical index dimension. :type physical: int, optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS`. :returns: **psi** :rtype: PEPS .. seealso:: :py:obj:`PEPS.from_fill_fn` .. py:method:: zeros(Lx, Ly, bond_dim, phys_dim=2, like='numpy', **peps_opts) :classmethod: Create a 2D PEPS whose tensors are filled with zeros. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param physical: The physical index dimension. :type physical: int, optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS`. :returns: **psi** :rtype: PEPS .. seealso:: :py:obj:`PEPS.from_fill_fn` .. py:method:: rand(Lx, Ly, bond_dim, phys_dim=2, dist='normal', loc=0.0, scale=1.0, dtype='float64', seed=None, **peps_opts) :classmethod: Create a random (un-normalized) PEPS. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param physical: The physical index dimension. :type physical: int, optional :param dist: Type of random number to generate, defaults to 'normal'. :type dist: {'normal', 'uniform', 'rademacher', 'exp'}, optional :param loc: An additive offset to add to the random numbers. :type loc: float, optional :param dtype: The dtype to create the arrays with, default is real double. :type dtype: dtype, optional :param seed: A random seed. :type seed: int, optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS`. :returns: **psi** :rtype: PEPS .. seealso:: :py:obj:`PEPS.from_fill_fn` .. py:method:: product_state(site_map, cyclic=False, **peps_opts) :classmethod: Create a PEPS representing a product state, with explicit bonds of dimension 1 between sites. :param site_map: A mapping of site coordinates to physical vectors, or a 2D array of physical vectors. Each vector being a single site state. :type site_map: dict[tuple[int, int], array] or Sequence[Sequence[array]] :param cyclic: Whether the lattice is cyclic in the x and y directions. :type cyclic: bool or tuple[bool, bool], optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS`. :rtype: PEPS .. py:method:: vacuum(Lx, Ly, phys_dim=2, **peps_opts) :classmethod: Create the 'vaccum' state PEPS, i.e. |00...0>. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param phys_dim: The physical index dimension. :type phys_dim: int, optional :param peps_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPS.product_state`. .. py:method:: add_PEPS(other, inplace=False) .. py:attribute:: add_PEPS_ .. py:method:: show() Print a unicode schematic of this PEPS and its bond dimensions. .. py:class:: 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) Bases: :py:obj:`TensorNetwork2DOperator`, :py:obj:`TensorNetwork2DFlat` Projected Entangled Pair Operator object:: ... │╱ │╱ │╱ │╱ │╱ │╱ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │╱ │╱ │╱ │╱ │╱ │╱ ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │╱ │╱ │╱ │╱ │╱ │╱ ... ●────●────●────●────●────●── ╱│ ╱│ ╱│ ╱│ ╱│ ╱│ │╱ │╱ │╱ │╱ │╱ │╱ ●────●────●────●────●────●── ╱ ╱ ╱ ╱ ╱ ╱ :param arrays: The core tensor data arrays. :type arrays: sequence of sequence of array :param shape: 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. :type shape: str, optional :param tags: Extra global tags to add to the tensor network. :type tags: set[str], optional :param upper_ind_id: String specifier for naming convention of upper site indices. :type upper_ind_id: str, optional :param lower_ind_id: String specifier for naming convention of lower site indices. :type lower_ind_id: str, optional :param site_tag_id: String specifier for naming convention of site tags. :type site_tag_id: str, optional :param x_tag_id: String specifier for naming convention of row ('x') tags. :type x_tag_id: str, optional :param y_tag_id: String specifier for naming convention of column ('y') tags. :type y_tag_id: str, optional :param cyclic: 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 explicit ``bool`` or ``(cyclic_x, cyclic_y)`` to override inference; this is needed when bond dimensions are 1 (shape inference then cannot detect cyclic boundaries). :type cyclic: None, bool, or tuple[bool, bool], optional .. py:attribute:: _EXTRA_PROPS :value: ('_site_tag_id', '_x_tag_id', '_y_tag_id', '_Lx', '_Ly', '_upper_ind_id', '_lower_ind_id') .. py:attribute:: _upper_ind_id :value: 'k{},{}' .. py:attribute:: _lower_ind_id :value: 'b{},{}' .. py:attribute:: _site_tag_id :value: 'I{},{}' .. py:attribute:: _x_tag_id :value: 'X{}' .. py:attribute:: _y_tag_id :value: 'Y{}' .. py:attribute:: _Lx .. py:attribute:: _Ly .. py:method:: from_fill_fn(fill_fn, Lx, Ly, bond_dim, phys_dim=2, cyclic=False, shape='urdlbk', **pepo_opts) :classmethod: Create a PEPO and fill the tensor entries with a supplied function matching signature ``fill_fn(shape) -> array``. :param fill_fn: A function that takes a shape tuple and returns a data array. :type fill_fn: callable :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param phys_dim: The physical indices dimension. :type phys_dim: int, optional :param cyclic: Whether the lattice is cyclic in the x and y directions. :type cyclic: bool or tuple[bool, bool], optional :param shape: How to layout the indices of the tensors, the default is ``(up, right, down, left bra, ket) == 'urdlbk'``. :type shape: str, optional :param pepo_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPO`. .. py:method:: rand(Lx, Ly, bond_dim, phys_dim=2, herm=False, dist='normal', loc=0.0, scale=1.0, dtype='float64', seed=None, **pepo_opts) :classmethod: Create a random PEPO. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param physical: The physical index dimension. :type physical: int, optional :param herm: Whether to symmetrize the tensors across the physical bonds to make the overall operator hermitian. :type herm: bool, optional :param dtype: The dtype to create the arrays with, default is real double. :type dtype: dtype, optional :param seed: A random seed. :type seed: int, optional :param pepo_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPO`. :returns: **X** :rtype: PEPO .. py:attribute:: rand_herm .. py:method:: zeros(Lx, Ly, bond_dim, phys_dim=2, dtype='float64', backend='numpy', **pepo_opts) :classmethod: Create a PEPO with all zero entries. :param Lx: The number of rows. :type Lx: int :param Ly: The number of columns. :type Ly: int :param bond_dim: The bond dimension. :type bond_dim: int :param physical: The physical index dimension. :type physical: int, optional :param dtype: The dtype to create the arrays with, default is real double. :type dtype: dtype, optional :param backend: Which backend to use, default is ``'numpy'``. :type backend: str, optional :param pepo_opts: Supplied to :class:`~quimb.tensor.tn2d.core.PEPO`. .. py:method:: add_PEPO(other, inplace=False) .. py:attribute:: add_PEPO_ .. py:method:: show() Print a unicode schematic of this PEPO and its bond dimensions. .. py:function:: show_2d(tn_2d, show_lower=False, show_upper=False) Base function for printing a unicode schematic of flat 2D TNs. .. py:function:: calc_plaquette_sizes(coo_groups, autogroup=True) Find a sequence of plaquette blocksizes that will cover all the terms (coordinate pairs) in ``pairs``. :param coo_groups: The sequence of 2D coordinates pairs describing terms. Each should either be a single 2D coordinate or a sequence of 2D coordinates. :type coo_groups: sequence of tuple[tuple[int]] or tuple[int] :param autogroup: Whether to return the minimal sequence of blocksizes that will cover all terms or merge them into a single ``((x_bsz, y_bsz),)``. :type autogroup: bool, optional :returns: **bszs** -- Pairs of blocksizes. :rtype: tuple[tuple[int]] .. rubric:: 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),) .. py:function:: plaquette_to_sites(p) Turn a plaquette ``((i0, j0), (di, dj))`` into the sites it contains. .. rubric:: Examples >>> plaquette_to_sites([(3, 4), (2, 2)]) ((3, 4), (3, 5), (4, 4), (4, 5)) .. py:function:: calc_plaquette_map(plaquettes) Generate a dictionary of all the coordinate pairs in ``plaquettes`` mapped to the 'best' (smallest) rectangular plaquette that contains them. .. rubric:: 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. .. py:function:: tensor_network_2d_distance(a, b, xAA=None, xAB=None, xBB=None, normalized=False, **kwargs)