quimb.tensor.tensor_arbgeom =========================== .. py:module:: quimb.tensor.tensor_arbgeom .. autoapi-nested-parse:: Classes and algorithms related to arbitrary geometry tensor networks. Attributes ---------- .. autoapisummary:: quimb.tensor.tensor_arbgeom._VALID_GATE_PROPAGATE quimb.tensor.tensor_arbgeom._LAZY_GATE_CONTRACT Classes ------- .. autoapisummary:: quimb.tensor.tensor_arbgeom.TensorNetworkGen quimb.tensor.tensor_arbgeom.TensorNetworkGenVector quimb.tensor.tensor_arbgeom.TensorNetworkGenOperator Functions --------- .. autoapisummary:: quimb.tensor.tensor_arbgeom.get_coordinate_formatter quimb.tensor.tensor_arbgeom.prod quimb.tensor.tensor_arbgeom.tensor_network_align quimb.tensor.tensor_arbgeom.tensor_network_apply_op_vec quimb.tensor.tensor_arbgeom.tensor_network_apply_op_op quimb.tensor.tensor_arbgeom.create_lazy_edge_map quimb.tensor.tensor_arbgeom.tensor_network_ag_sum quimb.tensor.tensor_arbgeom.tensor_network_ag_gate quimb.tensor.tensor_arbgeom.gauge_product_boundary_vector quimb.tensor.tensor_arbgeom.gloop_remove_dangling quimb.tensor.tensor_arbgeom.sloop_remove_dangling quimb.tensor.tensor_arbgeom._handle_rehearse quimb.tensor.tensor_arbgeom._compute_expecs_maybe_in_parallel quimb.tensor.tensor_arbgeom._tn_local_expectation quimb.tensor.tensor_arbgeom._tn_local_expectation_cluster quimb.tensor.tensor_arbgeom._tn_local_expectation_exact quimb.tensor.tensor_arbgeom._tn_local_expectation_sloop_expand quimb.tensor.tensor_arbgeom._tn_local_expectation_gloop_expand quimb.tensor.tensor_arbgeom._combine_expansion_expectations Module Contents --------------- .. py:function:: get_coordinate_formatter(ndims) .. py:function:: prod(xs) Product of all elements in ``xs``. .. py:function:: tensor_network_align(*tns: TensorNetworkGen, ind_ids=None, trace=False, inplace=False) Align an arbitrary number of tensor networks in a stack-like geometry:: a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a | | | | | | | | | | | | | | | | | | <- ind_ids[0] (defaults to 1st id) b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b-b | | | | | | | | | | | | | | | | | | <- ind_ids[1] ... | | | | | | | | | | | | | | | | | | <- ind_ids[-2] y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y-y | | | | | | | | | | | | | | | | | | <- ind_ids[-1] z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z-z :param tns: The TNs to align, should be structured and either effective 'vectors' (have a ``site_ind_id``) or 'operators' (have a ``up_ind_id`` and ``lower_ind_id``). :type tns: sequence of TensorNetwork :param ind_ids: String with format specifiers to id each level of sites with. Will be automatically generated like ``(tns[0].site_ind_id, "__ind_a{}__", "__ind_b{}__", ...)`` if not given. :type ind_ids: None, or sequence of str :param inplace: Whether to modify the input tensor networks inplace. :type inplace: bool :returns: **tns_aligned** :rtype: sequence of TensorNetwork .. py:function:: tensor_network_apply_op_vec(A: TensorNetworkGenOperator, x: TensorNetworkGenVector, which_A='lower', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts) Apply a general a general tensor network representing an operator (has ``upper_ind_id`` and ``lower_ind_id``) to a tensor network representing a vector (has ``site_ind_id``), by contracting each pair of tensors at each site then compressing the resulting tensor network. How the compression takes place is determined by the type of tensor network passed in. The returned tensor network has the same site indices as ``x``, and it is the ``lower_ind_id`` of ``A`` that is contracted. This is like performing ``A.to_dense() @ x.to_dense()``, or the transpose thereof, depending on the value of ``which_A``. :param A: The tensor network representing the operator. :type A: TensorNetworkGenOperator :param x: The tensor network representing the vector. :type x: TensorNetworkGenVector :param which_A: Whether to contract the lower or upper indices of ``A`` with the site indices of ``x``. :type which_A: {"lower", "upper"}, optional :param contract: Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site. :type contract: bool :param fuse_multibonds: If ``contract=True``, whether to fuse any multibonds after contracting the tensors at each site. :type fuse_multibonds: bool :param compress: Whether to compress the resulting tensor network. :type compress: bool :param inplace: Whether to modify ``x``, the input vector tensor network inplace. :type inplace: bool :param inplace_A: Whether to modify ``A``, the operator tensor network inplace. :type inplace_A: bool :param compress_opts: Options to pass to ``tn.compress``, where ``tn`` is the resulting tensor network, if ``compress=True``. :returns: The same type as ``x``. :rtype: TensorNetworkGenVector .. py:function:: tensor_network_apply_op_op(A: TensorNetworkGenOperator, B: TensorNetworkGenOperator, which_A='lower', which_B='upper', contract=False, fuse_multibonds=True, compress=False, inplace=False, inplace_A=False, **compress_opts) Apply the operator (has upper and lower site inds) represented by tensor network ``A`` to the operator represented by tensor network ``B``. The resulting tensor network has the same upper and lower indices as ``B``. Optionally contract the tensors at each site, fuse any multibonds, and compress the resulting tensor network. This is like performing ``A.to_dense() @ B.to_dense()``, or various combinations of tranposes thereof, depending on the values of ``which_A`` and ``which_B``. :param A: The tensor network representing the operator to apply. :type A: TensorNetworkGenOperator :param B: The tensor network representing the target operator. :type B: TensorNetworkGenOperator :param which_A: Whether to contract the lower or upper indices of ``A``. :type which_A: {"lower", "upper"}, optional :param which_B: Whether to contract the lower or upper indices of ``B``. :type which_B: {"lower", "upper"}, optional :param contract: Whether to contract the tensors at each site after applying the operator, yielding a single tensor at each site. :type contract: bool :param fuse_multibonds: If ``contract=True``, whether to fuse any multibonds after contracting the tensors at each site. :type fuse_multibonds: bool :param compress: Whether to compress the resulting tensor network. :type compress: bool :param inplace: Whether to modify ``B``, the target tensor network inplace. :type inplace: bool :param inplace_A: Whether to modify ``A``, the applied operator tensor network inplace. :type inplace_A: bool :param compress_opts: Options to pass to ``tn.compress``, where ``tn`` is the resulting tensor network, if ``compress=True``. :returns: The same type as ``B``. :rtype: TensorNetworkGenOperator .. py:function:: create_lazy_edge_map(tn: TensorNetworkGen, site_tags=None) Given a tensor network, where each tensor is in exactly one group or 'site', compute which sites are connected to each other, without checking each pair. :param tn: The tensor network to analyze. :type tn: TensorNetwork :param site_tags: Which tags to consider as 'sites', by default uses ``tn.site_tags``. :type site_tags: None or sequence of str, optional :returns: * **edges** (*dict[tuple[str, str], list[str]]*) -- Each key is a sorted pair of tags, which are connected, and the value is a list of the indices connecting them. * **neighbors** (*dict[str, list[str]]*) -- For each site tag, the other site tags it is connected to. .. py:function:: tensor_network_ag_sum(tna: TensorNetworkGen, tnb: TensorNetworkGen, site_tags=None, negate=False, compress=False, inplace=False, **compress_opts) Add two tensor networks with arbitrary, but matching, geometries. They should have the same site tags, with a single tensor per site and sites connected by a single index only (but the name of this index can differ in the two TNs). :param tna: The first tensor network to add. :type tna: TensorNetworkGen :param tnb: The second tensor network to add. :type tnb: TensorNetworkGen :param site_tags: Which tags to consider as 'sites', by default uses ``tna.site_tags``. :type site_tags: None or sequence of str, optional :param negate: Whether to negate the second tensor network before adding. :type negate: bool, optional :param compress: Whether to compress the resulting tensor network, by calling the ``compress`` method with the given options. :type compress: bool, optional :param inplace: Whether to modify the first tensor network inplace. :type inplace: bool, optional :returns: The resulting tensor network. :rtype: TensorNetworkGen .. py:function:: tensor_network_ag_gate(self: TensorNetworkGen, G, where, contract=False, tags=None, propagate_tags=False, which=None, info=None, inplace=False, **compress_opts) Apply a gate to this vector tensor network at sites ``where``. This is essentially a wrapper around :meth:`~quimb.tensor.tensor_core.TensorNetwork.gate_inds` apart from ``where`` can be specified as a list of sites, and tags can be optionally, intelligently propagated to the new gate tensor. .. math:: | \psi \rangle \rightarrow G_\mathrm{where} | \psi \rangle :param G: The gate array to apply, should match or be factorable into the shape ``(*phys_dims, *phys_dims)``. :type G: array_ike :param where: The sites to apply the gate to. :type where: node or sequence[node] :param contract: 'swap-split-gate', 'auto-split-gate'}, optional How to apply the gate, see :meth:`~quimb.tensor.tensor_core.TensorNetwork.gate_inds`. :type contract: {False, True, 'split', 'reduce-split', 'split-gate', :param tags: Tags to add to the new gate tensor. :type tags: str or sequence of str, optional :param propagate_tags: Whether to propagate tags to the new gate tensor:: - False: no tags are propagated - True: all tags are propagated - 'register': only site tags corresponding to ``where`` are added. - 'sites': all site tags on the current sites are propgated, resulting in a lightcone like tagging. :type propagate_tags: {False, True, 'register', 'sites'}, optional :param info: Used to store extra optional information such as the singular values if not absorbed. :type info: None or dict, optional :param inplace: Whether to perform the gate operation inplace on the tensor network or not. :type inplace: bool, optional :param compress_opts: Supplied to :func:`~quimb.tensor.tensor_core.tensor_split` for any ``contract`` methods that involve splitting. Ignored otherwise. :rtype: TensorNetworkGenVector .. seealso:: :py:obj:`TensorNetwork.gate_inds` .. py:class:: TensorNetworkGen(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`quimb.tensor.tensor_core.TensorNetwork` A tensor network which notionally has a single tensor per 'site', though these could be labelled arbitrarily could also be linked in an arbitrary geometry by bonds. .. py:attribute:: _NDIMS :value: 1 .. py:attribute:: _EXTRA_PROPS :value: ('_sites', '_site_tag_id') .. py:method:: _compatible_arbgeom(other) Check whether ``self`` and ``other`` represent the same set of sites and are tagged equivalently. .. 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:`TensorNetworkGen` instance. :param other: The other tensor network to combine with. :type other: TensorNetworkGen 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: TensorNetworkGen or TensorNetwork .. py:property:: nsites The total number of sites. .. py:method:: gen_site_coos() Generate the coordinates of all sites, same as ``self.sites``. .. py:property:: sites Tuple of the possible sites in this tensor network. .. py:method:: _get_site_set() The set of all sites. .. py:method:: gen_sites_present() Generate the sites which are currently present (e.g. if a local view of a larger tensor network), based on whether their tags are present. .. rubric:: Examples >>> tn = qtn.TN3D_rand(4, 4, 4, 2) >>> tn_sub = tn.select_local('I1,2,3', max_distance=1) >>> list(tn_sub.gen_sites_present()) [(0, 2, 3), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 3)] .. py:property:: site_tag_id The string specifier for tagging each site of this tensor network. .. py:method:: site_tag(site) The name of the tag specifiying the tensor at ``site``. .. py:method:: retag_sites(new_id, where=None, inplace=False) Modify the site tags for all or some tensors in this tensor network (without changing the ``site_tag_id``). :param new_id: A string with a format placeholder to accept a site, e.g. "S{}". :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 retag in place. :type inplace: bool .. py:property:: site_tags All of the site tags. .. py:property:: site_tags_present All of the site tags still present in this tensor network. .. py:method:: retag_all(new_id, inplace=False) Retag all sites and change the ``site_tag_id``. .. py:attribute:: retag_all_ .. py:method:: _get_site_tag_set() The oset of all site tags. .. py:method:: filter_valid_site_tags(tags) Get the valid site tags from ``tags``. .. py:method:: maybe_convert_coo(x) Check if ``x`` is a valid site and convert to the corresponding site tag if so, else return ``x``. .. py:method:: gen_tags_from_coos(coos) Generate the site tags corresponding to the given coordinates. .. py:method:: _get_tids_from_tags(tags, which='all') This is the function that lets coordinates such as ``site`` be used for many 'tag' based functions. .. py:method:: _get_tid_to_site_map() Get a mapping from low level tensor id to the site it represents, assuming there is a single tensor per site. .. py:method:: bond(coo1, coo2) Get the name of the index defining the bond between sites at ``coo1`` and ``coo2``. This will error if there is not exactly one bond between the sites. :param coo1: The first site, or site tag. :type coo1: hashable or str :param coo2: The second site, or site tag. :type coo2: hashable or str :rtype: str .. py:method:: bond_size(coo1, coo2) Return the (combined) size of the bond(s) between sites at ``coo1`` and ``coo2``. :param coo1: The first site, or site tag. :type coo1: hashable or str :param coo2: The second site, or site tag. :type coo2: hashable or str :rtype: int .. py:method:: gen_bond_coos() Generate the coordinates (pairs of sites) of all bonds. .. py:method:: get_site_neighbor_map() Get a mapping from each site to its neighbors. .. py:method:: gen_gloops_sites(max_size=None, sites=None, grow_from='all') Generate sets of sites that represent 'generalized loops' where every node is connected to at least two other loop nodes. This is a simple wrapper around ``TensorNewtork.gen_gloops`` that works with the sites rather than ``tids``. :param max_size: Set the maximum number of tensors that can appear in a loop. If ``None``, wait until any valid loop is found and set that as the maximum size. :type max_size: None or int :param tags: If supplied, only consider loops containing these tids. :type tags: None or sequence of str :Yields: *tuple[hashable]* .. py:method:: reset_cached_properties() Reset any cached properties, one should call this when changing the actual geometry of a TN inplace, for example. .. py:method:: align(*args, inplace=False, **kwargs) .. py:attribute:: align_ .. py:method:: __add__(other) .. py:method:: __sub__(other) .. py:method:: __iadd__(other) .. py:method:: __isub__(other) .. py:method:: normalize_simple(gauges, **contract_opts) Normalize this network using simple local gauges. After calling this, any tree-like sub network gauged with ``gauges`` will have 2-norm 1. Inplace operation on both the tensor network and ``gauges``. :param gauges: The gauges to normalize with. :type gauges: dict[str, array_like] .. py:method:: get_local_sloops(*, where=None, sloops=None, intersect=False, grow_from='all', strict_size=True, info=None) Parse the `sloops` argument to get the relevant simple loops for the given `where` sites. If `sloops` is an integer, auto generate loops locally, otherwise filter the given loops to only include those relevant to `where`. Simple loops are loops where each site is connected to exactly two other sites. .. py:method:: get_local_gloops(*, tids=None, where=None, gloops=None, grow_from='all', strict_size=True, info=None) Parse the `gloops` argument to get the relevant generalized loops for the given `where` sites. If `gloops` is an integer, auto generate loops locally, otherwise filter the given loops to only include those relevant to `where`. An example loop with where=("A", "B"), for `grow_from='all'`:: | | -o---o- | | -A---B- | | Setting `grow_from='any'` in would also generates loops like:: | | -o---o- | | | -o---A---B- | | | where only site A is part of the original, generating loop, but both A and B are part of the returned cluster. :param tids: The tensor ids to consider. Either this or `where` must be supplied. :type tids: sequence[int], optional :param where: The sites to consider. Either this or `tids` must be supplied. :type where: sequence[hashable], optional :param info: A dictionary to store information across different calls. :type info: dict :param gloops: The gloops to consider. If ``None``, auto generate local gloops up to the smallest non-trivial cluster size. If an integer, generate gloops locally with up to that size. If a sequence of sequences, use those gloops. :type gloops: None, int, or sequence of sequence of hashable, optional :param grow_from: Whether to generate gloops that originally contain all or just any of the target sites in `where`. The base sites are always included in all returned gloops, even if they were not part of the supplied or auto-generated cluster. :type grow_from: {"all", "any"}, optional :rtype: tuple[frozenset[hashable]] .. py:function:: gauge_product_boundary_vector(tn, tags, which='all', max_bond=1, smudge=1e-06, canonize_distance=0, select_local_distance=None, select_local_opts=None, **contract_around_opts) .. py:function:: gloop_remove_dangling(sites, neighbors, where=()) Given cluster `sites` and edges given by the `neighbors` mapping, remove all sites that are not connected to at least two other sites, reducing it in this way to a generalised loop. :param sites: The sites in the original cluster. :type sites: sequence[hashable] :param neighbors: The neighbors of each site. :type neighbors: dict[hashable, sequence[hashable]] :param where: The sites to keep, even if they are dangling. :type where: sequence[hashable], optional :rtype: frozenset[hashable] .. py:function:: sloop_remove_dangling(path, neighbor_inds, where_tids) .. py:data:: _VALID_GATE_PROPAGATE .. py:data:: _LAZY_GATE_CONTRACT .. py:class:: TensorNetworkGenVector(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`TensorNetworkGen` A tensor network which notionally has a single tensor and outer index per 'site', though these could be labelled arbitrarily and could also be linked in an arbitrary geometry by bonds. .. py:attribute:: _EXTRA_PROPS :value: ('_sites', '_site_tag_id', '_site_ind_id') .. py:property:: site_ind_id The string specifier for the physical indices. .. py:method:: site_ind(site) .. py:property:: site_inds Return a tuple of all site indices. .. py:property:: site_inds_present All of the site inds still present in this tensor network. .. py:method:: reset_cached_properties() Reset any cached properties, one should call this when changing the actual geometry of a TN inplace, for example. .. 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:: reindex_all(new_id, inplace=False) Reindex all physical sites and change the ``site_ind_id``. .. py:attribute:: reindex_all_ .. py:method:: gen_inds_from_coos(coos) Generate the site inds corresponding to the given coordinates. .. py:method:: phys_dim(site=None) Get the physical dimension of ``site``, defaulting to the first site if not specified. .. py:method:: to_dense(*inds_seq, to_qarray=False, to_ket=None, **contract_opts) Contract this tensor network 'vector' into a dense array. By default, turn into a 'ket' ``qarray``, i.e. column vector of shape ``(d, 1)``. :param inds_seq: How to group the site indices into the dense array. By default, use a single group ordered like ``sites``, but only containing those sites which are still present. :type inds_seq: sequence of sequences of str :param to_qarray: Whether to turn the dense array into a ``qarray``, if the backend would otherwise be ``'numpy'``. :type to_qarray: bool :param to_ket: Whether to reshape the dense array into a ket (shape ``(d, 1)`` array). If ``None`` (default), do this only if the ``inds_seq`` is not supplied. :type to_ket: None or str :param contract_opts: Options to pass to :meth:`~quimb.tensor.tensor_core.TensorNewtork.contract`. :rtype: array .. py:attribute:: to_qarray .. py:method:: gate_with_op_lazy(A, transpose=False, inplace=False, **kwargs) Act lazily with the operator tensor network ``A``, which should have matching structure, on this vector/state tensor network, like ``A @ x``. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted. .. math:: | x \rangle \rightarrow A | x \rangle or (if ``transpose=True``): .. math:: | x \rangle \rightarrow A^T | x \rangle :param A: The operator tensor network to gate with, or apply to this tensor network. :type A: TensorNetworkGenOperator :param transpose: Whether to contract the lower or upper indices of ``A`` with the site indices of ``x``. If ``False`` (the default), the lower indices of ``A`` will be contracted with the site indices of ``x``, if ``True`` the upper indices of ``A`` will be contracted with the site indices of ``x``, which is like applying ``A.T @ x``. :type transpose: bool, optional :param inplace: Whether to perform the gate operation inplace on this tensor network. :type inplace: bool, optional :rtype: TensorNetworkGenVector .. py:attribute:: gate_with_op_lazy_ .. py:attribute:: gate .. py:attribute:: gate_ .. py:method:: gate_simple_(G, where, gauges, renorm=True, smudge=1e-12, power=1.0, **gate_opts) Apply a gate to this vector tensor network at sites ``where``, using simple update style gauging of the tensors first, as supplied in ``gauges``. The new singular values for the bond are reinserted into ``gauges``. :param G: The gate to be applied. :type G: array_like :param where: The sites to apply the gate to. :type where: node or sequence[node] :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like] :param renorm: Whether to renormalise the singular after the gate is applied, before reinserting them into ``gauges``. :type renorm: bool, optional :param smudge: A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues. :type smudge: float, optional :param power: The power to raise the singular values to before multiplying them in and inverting them. :type power: float, optional :param gate_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.gate_inds`. .. py:method:: gate_fit_local_(G, where, max_distance=1, mode='graphdistance', fillin=False, gauges=None, connect_path=True, **fit_opts) Apply gate ``G`` to sites ``where`` by directly fitting a local patch of tensors, optionally gauging the boudary of this local patch first. :param G: The gate to be applied. :type G: array_like :param where: The sites to apply the gate to. :type where: node or sequence[node] :param max_distance: The maximum distance from ``where`` to select tensors up to. :type max_distance: int, optional :param mode: How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing ``where``, of size up to ``max_distance``, ensuring no dangling tensors. :type mode: {'graphdistance', 'loopunion'}, optional :param fillin: Whether to fill in the local patch with additional tensors, or not. `fillin` tensors are those connected by two or more bonds to the original local patch, the process is repeated int(fillin) times. :type fillin: bool or int, optional :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like], optional :param connect_path: If the sites in ``where `` are a non-adjacent pair, whether to set the initial patch as a path that connects them. :type connect_path: bool, optional :param fit_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.fit`. .. py:method:: make_reduced_density_matrix(where, allow_dangling=True, bra_ind_id='b{}', mangle_append='*', layer_tags=('KET', 'BRA')) Form the tensor network representation of the reduced density matrix, taking special care to handle potential hyper inner and outer indices. :param where: The sites to keep. :type where: node or sequence[node] :param allow_dangling: Whether to allow dangling indices in the resulting density matrix. These are non-physical indices, that usually result from having cut a region of the tensor network. :type allow_dangling: bool, optional :param bra_ind_id: The string format to use for the bra indices. :type bra_ind_id: str, optional :param mangle_append: The string to append to indices that are not traced out. :type mangle_append: str, optional :param layer_tags: The tags to apply to the ket and bra tensor network layers. :type layer_tags: tuple of str, optional .. py:method:: partial_trace_exact(where, optimize='auto-hq', normalized=True, rehearse=False, get='matrix', **contract_opts) Compute the reduced density matrix at sites ``where`` by exactly contracting the full overlap tensor network. :param where: The sites to keep. :type where: sequence[node] :param optimize: The contraction path optimizer to use, when exactly contracting the full tensor network. :type optimize: str or PathOptimizer, optional :param normalized: Whether to normalize the result. If "return", return the norm separately. :type normalized: bool or "return", optional :param rehearse: Whether to perform the computation or not, if ``True`` return a rehearsal info dict. :type rehearse: bool, optional :param get: Whether to return the result as a dense array, the data itself, or a tensor network. :type get: {'matrix', 'array', 'tensor'}, optional :rtype: array or Tensor or dict or (array, float), (Tensor, float) .. py:method:: local_expectation_exact(G, where, optimize='auto-hq', normalized=True, rehearse=False, **contract_opts) Compute the local expectation of operator ``G`` at sites ``where`` by exactly contracting the full overlap tensor network. :param G: The operator to compute the expectation of. :type G: array_like :param where: The sites to compute the expectation at. :type where: sequence[node] :param optimize: The contraction path optimizer to use, when exactly contracting the full tensor network. :type optimize: str or PathOptimizer, optional :param normalized: Whether to normalize the result. If "return", return the norm separately. :type normalized: bool or "return", optional :param rehearse: Whether to perform the computation or not, if ``True`` return a rehearsal info dict. :type rehearse: bool, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. :rtype: float or (float, float) .. py:method:: compute_local_expectation_exact(terms, optimize='auto-hq', *, normalized=True, return_all=False, rehearse=False, executor=None, progbar=False, **contract_opts) Compute the local expectations of many operators, by exactly contracting the full overlap tensor network. :param terms: The terms to compute the expectation of, with keys being the sites and values being the local operators. :type terms: dict[node or (node, node), array_like] :param optimize: The contraction path optimizer to use, when exactly contracting the full tensor network. :type optimize: str or PathOptimizer, optional :param normalized: Whether to normalize the result. :type normalized: bool, optional :param return_all: Whether to return all results, or just the summed expectation. :type return_all: bool, optional :param rehearse: Whether to perform the computations or not:: - False: perform the computation. - 'tn': return the tensor networks of each local expectation, without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree`` for each local expectation. - True: run the path optimizer and return the ``PathInfo`` for each local expectation. :type rehearse: {False, 'tn', 'tree', True}, optional :param executor: If supplied compute the terms in parallel using this executor. :type executor: Executor, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. :returns: **expecs** -- If ``return_all==False``, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term's location to the expectation value. :rtype: float or dict[node or (node, node), float] .. py:method:: get_cluster(where, gauges=None, max_distance=0, mode='graphdistance', fillin=0, grow_from='all', smudge=1e-12, power=1.0) Get the wavefunction cluster tensor network for the sites surrounding ``where``, potentially gauging the region with the simple update style bond gauges in ``gauges``. :param where: The sites around which to form the cluster. :type where: sequence[node] :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like], optional :param max_distance: The maximum graph distance to include tensors neighboring ``where`` when computing the expectation. The default 0 means only the tensors at sites ``where`` are used, 1 includes their direct neighbors, etc. :type max_distance: int, optional :param mode: How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing ``where``, of size up to ``max_distance``, ensuring no dangling tensors. :type mode: {'graphdistance', 'loopunion'}, optional :param fillin: When selecting the local tensors, whether and how many times to 'fill-in' corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See :meth:`~quimb.tensor.tensor_core.TensorNetwork.select_local`. :type fillin: bool or int, optional :param grow_from: If mode is 'loopunion', whether each loop should contain *all* of the initial tagged tensors, or just *any* of them (generating a larger region). :type grow_from: {"all", "any"}, optional :param smudge: A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues. :type smudge: float, optional :param power: The power to raise the singular values to before multiplying them in and inverting them. :type power: float, optional :rtype: TensorNetworkGenVector .. py:method:: partial_trace_cluster(where, gauges=None, optimize='auto-hq', normalized=True, max_distance=0, mode='graphdistance', fillin=0, grow_from='all', smudge=1e-12, power=1.0, get='matrix', rehearse=False, **contract_opts) Compute the approximate reduced density matrix at sites ``where`` by contracting a local cluster of tensors, potentially gauging the region with the simple update style bond gauges in ``gauges``. :param where: The sites to keep. :type where: sequence[node] :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like], optional :param optimize: The contraction path optimizer to use, when exactly contracting the local tensors. :type optimize: str or PathOptimizer, optional :param normalized: Whether to normalize the result. If "return", return the norm separately. :type normalized: bool or "return", optional :param max_distance: The maximum graph distance to include tensors neighboring ``where`` when computing the expectation. The default 0 means only the tensors at sites ``where`` are used, 1 includes there direct neighbors, etc. :type max_distance: int, optional :param mode: How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing ``where``, of size up to ``max_distance``, ensuring no dangling tensors. :type mode: {'graphdistance', 'loopunion'}, optional :param fillin: When selecting the local tensors, whether and how many times to 'fill-in' corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See :meth:`~quimb.tensor.tensor_core.TensorNetwork.select_local`. :type fillin: bool or int, optional :param grow_from: If mode is 'loopunion', whether each loop should contain *all* of the initial tagged tensors, or just *any* of them (generating a larger region). :type grow_from: {"all", "any"}, optional :param smudge: A small value to add to the gauges before multiplying them in and inverting them to avoid numerical issues. :type smudge: float, optional :param power: The power to raise the singular values to before multiplying them in and inverting them. :type power: float, optional :param get: Whether to return the result as a fused matrix (i.e. always 2D), unfused array, or still labeled Tensor. :type get: {'matrix', 'array', 'tensor'}, optional :param rehearse: Whether to perform the computation or not, if ``True`` return a rehearsal info dict. :type rehearse: bool, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. .. py:method:: local_expectation_cluster(G, where, normalized=True, max_distance=0, mode='graphdistance', fillin=False, grow_from='all', gauges=None, smudge=0.0, power=1.0, optimize='auto', max_bond=None, rehearse=False, **contract_opts) Approximately compute a single local expectation value of the gate ``G`` at sites ``where``, either treating the environment beyond ``max_distance`` as the identity, or using simple update style bond gauges as supplied in ``gauges``. This selects a local neighbourhood of tensors up to distance ``max_distance`` away from ``where``, then traces over dangling bonds after potentially inserting the bond gauges, to form an approximate version of the reduced density matrix. .. math:: \langle \psi | G | \psi \rangle \approx \frac{ \mathrm{Tr} [ G \tilde{\rho}_\mathrm{where} ] }{ \mathrm{Tr} [ \tilde{\rho}_\mathrm{where} ] } assuming ``normalized==True``. :param G: The gate to compute the expecation of. :type G: array_like :param where: The sites to compute the expectation at. :type where: node or sequence[node] :param normalized: Whether to locally normalize the result, i.e. divide by the expectation value of the identity. :type normalized: bool, optional :param max_distance: The maximum graph distance to include tensors neighboring ``where`` when computing the expectation. The default 0 means only the tensors at sites ``where`` are used, 1 includes there direct neighbors, etc. :type max_distance: int, optional :param mode: How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing ``where``, of size up to ``max_distance``, ensuring no dangling tensors. :type mode: {'graphdistance', 'loopunion'}, optional :param fillin: When selecting the local tensors, whether and how many times to 'fill-in' corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See :meth:`~quimb.tensor.tensor_core.TensorNetwork.select_local`. :type fillin: bool or int, optional :param grow_from: If mode is 'loopunion', whether each loop should contain *all* of the initial tagged tensors, or just *any* of them (generating a larger region). :type grow_from: {"all", "any"}, optional :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like], optional :param optimize: The contraction path optimizer to use, when exactly contracting the local tensors. :type optimize: str or PathOptimizer, optional :param max_bond: If specified, use compressed contraction. :type max_bond: None or int, optional :param rehearse: Whether to perform the computations or not:: - False: perform the computation. - 'tn': return the tensor networks of each local expectation, without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree`` for each local expectation. - True: run the path optimizer and return the ``PathInfo`` for each local expectation. :type rehearse: {False, 'tn', 'tree', True}, optional :returns: **expectation** :rtype: float .. py:attribute:: local_expectation_simple .. py:method:: compute_local_expectation_cluster(terms, *, max_distance=0, mode='graphdistance', fillin=False, grow_from='all', normalized=True, gauges=None, optimize='auto', max_bond=None, return_all=False, rehearse=False, executor=None, progbar=False, **contract_opts) Compute all local expectations of the given terms, either treating the environment beyond ``max_distance`` as the identity, or using simple update style bond gauges as supplied in ``gauges``. This selects a local neighbourhood of tensors up to distance ``max_distance`` away from each term's sites, then traces over dangling bonds after potentially inserting the bond gauges, to form an approximate version of the reduced density matrix. .. math:: \sum_\mathrm{i} \langle \psi | G_\mathrm{i} | \psi \rangle \approx \sum_\mathrm{i} \frac{ \mathrm{Tr} [ G_\mathrm{i} \tilde{\rho}_\mathrm{i} ] }{ \mathrm{Tr} [ \tilde{\rho}_\mathrm{i} ] } assuming ``normalized==True``. :param terms: The terms to compute the expectation of, with keys being the sites and values being the local operators. :type terms: dict[node or (node, node), array_like] :param max_distance: The maximum graph distance to include tensors neighboring ``where`` when computing the expectation. The default 0 means only the tensors at sites ``where`` are used, 1 includes there direct neighbors, etc. :type max_distance: int, optional :param mode: How to select the local tensors, either by graph distance or by selecting the union of all loopy regions containing ``where``, of size up to ``max_distance``, ensuring no dangling tensors. :type mode: {'graphdistance', 'loopunion'}, optional :param fillin: When selecting the local tensors, whether and how many times to 'fill-in' corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See :meth:`~quimb.tensor.tensor_core.TensorNetwork.select_local`. :type fillin: bool or int, optional :param grow_from: If mode is 'loopunion', whether each loop should contain *all* of the initial tagged tensors, or just *any* of them (generating a larger region). :type grow_from: {"all", "any"}, optional :param normalized: Whether to locally normalize the result, i.e. divide by the expectation value of the identity. This implies that a different normalization factor is used for each term. :type normalized: bool, optional :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like], optional :param optimize: The contraction path optimizer to use, when exactly contracting the local tensors. :type optimize: str or PathOptimizer, optional :param max_bond: If specified, use compressed contraction. :type max_bond: None or int, optional :param return_all: Whether to return all results, or just the summed expectation. :type return_all: bool, optional :param rehearse: Whether to perform the computations or not:: - False: perform the computation. - 'tn': return the tensor networks of each local expectation, without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree`` for each local expectation. - True: run the path optimizer and return the ``PathInfo`` for each local expectation. :type rehearse: {False, 'tn', 'tree', True}, optional :param executor: If supplied compute the terms in parallel using this executor. :type executor: Executor, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. :returns: **expecs** -- If ``return_all==False``, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term's location to the expectation value. :rtype: float or dict[node or (node, node), float] .. py:attribute:: compute_local_expectation_simple .. py:method:: local_expectation_sloop_expand(G, where, sloops=None, gauges=None, *, grow_from='all', strict_size=True, intersect=False, autocomplete=True, autoreduce=True, combine='prod', normalized=True, info=None, optimize='auto', progbar=False, **contract_opts) Compute the expectation of operator ``G`` at site(s) ``where`` by expanding the expectation in terms of loops of tensors. :param G: The operator to compute the expectation of. :type G: array_like :param where: The sites to compute the expectation at. :type where: node or sequence[node] :param sloops: The loops to use. If an integer, all loops up to and including that length will be used if the loop passes through all sites in ``where``. If ``None`` the maximum loop length is set as the shortest loop found. If an explicit set of loops is given, only these loops are considered, but only if they pass through all sites in ``where``, and ``intersect`` is ignored. :type sloops: None or sequence[NetworkPath], optional :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be gauged. :type gauges: dict[str, array_like], optional :param normalized: Whether to normalize the result. If "local" each loop term is normalized separately. If ``True`` each term is normalized using a loop expansion estimate of the norm. If ``False`` no normalization is performed. :type normalized: bool or "local", optional :param optimize: The contraction path optimizer to use. :type optimize: str or PathOptimizer, optional :param info: A dictionary to store intermediate results in to avoid recomputing them. This is useful when computing various expectations with different sets of loops. This should only be reused when both the tensor network and gauges remain the same. :type info: dict, optional :param intersect: If ``loops`` is not an explicit set of loops, whether to consider self intersecting loops in the search for loops passing through ``where``. :type intersect: bool, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. :returns: **expec** :rtype: scalar .. py:method:: compute_local_expectation_sloop_expand(terms, sloops=None, gauges=None, *, grow_from='all', strict_size=True, intersect=False, autocomplete=True, autoreduce=True, combine='prod', normalized=True, info=None, return_all=False, optimize='auto', executor=None, progbar=False, **contract_opts) .. py:method:: local_expectation_gloop_expand(G, where, gloops=None, gauges=None, combine='prod', normalized=True, autocomplete=True, autoreduce=True, grow_from='all', strict_size=True, optimize='auto', info=None, progbar=False, **contract_opts) Compute the expectation of operator ``G`` at site(s) ``where`` by expanding the expectation in terms of generalized loops of tensors. :param G: The operator to compute the expectation of. :type G: array_like :param where: The sites to compute the expectation at. :type where: node or sequence[node] :param gloops: The generalized loops to use. If an integer, generate loops up to and including this size. If ``None`` the maximum loop size is set as the smallest non-trivial loop found. If an explicit set of loops is given, only these loops are considered. :type gloops: None, int, or sequence[sequence[node]], optional :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be gauged. :type gauges: dict[str, array_like], optional :param combine: How to combine the local expectations of each cluster. :type combine: {"prod", "sum"}, optional :param normalized: Whether and how to normalize the result. - True: uses "prod" if combine="prod", "local" if combine="sum". - "prod": shorthand for `combine="prod"` and `normalized=True`. - "local": each cluster within a term is normalized separately. - "separate": the expectation and normalization are computed separately and then combined for each term. :type normalized: bool, "prod", "local" or "separate", "global", optional :param autocomplete: Whether to automatically complete the local region graph by adding all required intersecting regions automatically. :type autocomplete: bool, optional :param autoreduce: Whether to reduce any clusters with dangling bonds (which can still be generated as intersecting regions of loops) to generalized loops with dangling bonds removed. Should only be used at a BP fixed point. :type autoreduce: bool, optional :param grow_from: If auto generating loops, whether generate only those which contain *all* sites in the term, or just *any*. The loops generated by "any" are a superset of those generated by "all", giving a more accuracte estimate. :type grow_from: {"all", "any"}, optional :param optimize: The contraction path optimizer to use. :type optimize: str or PathOptimizer, optional :param info: A dictionary to store intermediate results in to avoid recomputing them. This is useful when computing various expectations with different sets of loops. This should only be reused when both the tensor network and gauges remain the same. :type info: dict, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. :returns: **expec** :rtype: scalar .. py:method:: norm_gloop_expand(gloops=None, autocomplete=False, autoreduce=True, gauges=None, optimize='auto', progbar=False, **contract_opts) Compute the norm of this tensor network by expanding it in terms of generalized loops of tensors. .. py:method:: compute_local_expectation_gloop_expand(terms, gloops=None, *, gauges=None, combine='prod', normalized=True, autocomplete=True, autoreduce=True, grow_from='all', strict_size=True, optimize='auto', info=None, return_all=False, executor=None, progbar=False, **contract_opts) Contract many local expectations using generalized loop expansion. :param terms: The terms to compute the expectation of, with keys being the site(s) and values being the local operators as plain arrays. :type terms: dict[node or tuple[node], array_like] :param gloops: The generalized loops to use. If an integer, generate loops up to and including this size. If ``None`` the maximum loop size is set as the smallest non-trivial loop found. If an explicit set of loops is given, only these loops are considered. :type gloops: None, int, or sequence[sequence[node]], optional :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be used. :type gauges: dict[str, array_like], optional :param combine: How to combine the local expectations of each cluster. :type combine: {"prod", "sum"}, optional :param normalized: Whether and how to normalize the result. - True: uses "prod" if combine="prod", "local" if combine="sum". - "prod": shorthand for `combine="prod"` and `normalized=True`. - "local": each cluster within a term is normalized separately. - "separate": the expectation and normalization are computed separately and then combined for each term. - "global": a single normalization factor is computed and used for all terms. :type normalized: bool, "prod", "local" or "separate", "global", optional :param autocomplete: Whether to automatically complete the local region graph by adding all required intersecting regions automatically. :type autocomplete: bool, optional :param autoreduce: Whether to reduce any clusters with dangling bonds (which can still be generated as intersecting regions of loops) to generalized loops with dangling bonds removed. Should only be used at a BP fixed point. :type autoreduce: bool, optional :param grow_from: If auto generating loops, whether generate only those which contain *all* sites in the term, or just *any*. The loops generated by "any" are a superset of those generated by "all", giving a more accuracte estimate. :type grow_from: {"all", "any"}, optional :param optimize: The contraction path optimizer to use. :type optimize: str or PathOptimizer, optional :param info: A dictionary to store intermediate results in to avoid recomputing them. This is useful when computing various expectations with different sets of loops. This should only be reused when both the tensor network and gauges remain the same. :type info: dict, optional :param return_all: Whether to return all results, or just the summed expectation. :type return_all: bool, optional :param executor: If supplied compute the terms in parallel using this executor. :type executor: Executor, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract`. :returns: **expecs** -- If ``return_all==False``, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term's location to the expectation value. :rtype: float or dict[node or tuple[node], float] .. py:method:: partial_trace(keep, max_bond, optimize, flatten=True, reduce=False, normalized=True, symmetrized='auto', rehearse=False, method='contract_compressed', **contract_compressed_opts) Partially trace this tensor network state, keeping only the sites in ``keep``, using compressed contraction. :param keep: The sites to keep. :type keep: iterable of hashable :param max_bond: The maximum bond dimensions to use while compressed contracting. :type max_bond: int :param optimize: The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction. :type optimize: str or PathOptimizer, optional :param flatten: Whether to force 'flattening' (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually improved. If ``'all'`` also flatten the tensors in ``keep``. :type flatten: {False, True, 'all'}, optional :param reduce: Whether to first 'pull' the physical indices off their respective tensors using QR reduction. Experimental. :type reduce: bool, optional :param normalized: Whether to normalize the reduced density matrix at the end. :type normalized: bool, optional :param symmetrized: Whether to symmetrize the reduced density matrix at the end. This should be unecessary if ``flatten`` is set to ``True``. :type symmetrized: {'auto', True, False}, optional :param rehearse: Whether to perform the computation or not:: - False: perform the computation. - 'tn': return the tensor network without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree``.. - True: run the path optimizer and return the ``PathInfo``. :type rehearse: {False, 'tn', 'tree', True}, optional :param contract_compressed_opts: Additional keyword arguments to pass to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract_compressed`. :type contract_compressed_opts: dict, optional :returns: **rho** -- The reduce density matrix of sites in ``keep``. :rtype: array_like .. py:method:: local_expectation(G, where, max_bond, optimize, flatten=True, normalized=True, symmetrized='auto', reduce=False, rehearse=False, **contract_compressed_opts) Compute the local expectation of operator ``G`` at site(s) ``where`` by approximately contracting the full overlap tensor network. :param G: The local operator to compute the expectation of. :type G: array_like :param where: The sites to compute the expectation for. :type where: node or sequence of nodes :param max_bond: The maximum bond dimensions to use while compressed contracting. :type max_bond: int :param optimize: The contraction path optimizer to use, should specifically generate contractions paths designed for compressed contraction. :type optimize: str or PathOptimizer, optional :param method: The method to use to compute the expectation value. :type method: {'rho', 'rho-reduced'}, optional :param flatten: Whether to force 'flattening' (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy is usually much improved. :type flatten: bool, optional :param normalized: If computing via `partial_trace`, whether to normalize the reduced density matrix at the end. :type normalized: bool, optional :param symmetrized: If computing via `partial_trace`, whether to symmetrize the reduced density matrix at the end. This should be unecessary if ``flatten`` is set to ``True``. :type symmetrized: {'auto', True, False}, optional :param rehearse: Whether to perform the computation or not:: - False: perform the computation. - 'tn': return the tensor network without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree``.. - True: run the path optimizer and return the ``PathInfo``. :type rehearse: {False, 'tn', 'tree', True}, optional :param contract_compressed_opts: Additional keyword arguments to pass to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract_compressed`. :type contract_compressed_opts: dict, optional :returns: **expec** :rtype: float .. py:method:: compute_local_expectation(terms, max_bond, optimize, *, flatten=True, normalized=True, symmetrized='auto', reduce=False, return_all=False, rehearse=False, executor=None, progbar=False, **contract_compressed_opts) Compute the local expectations of many local operators, by approximately contracting the full overlap tensor network. :param terms: The terms to compute the expectation of, with keys being the sites and values being the local operators. :type terms: dict[node or (node, node), array_like] :param max_bond: The maximum bond dimension to use during contraction. :type max_bond: int :param optimize: The compressed contraction path optimizer to use. :type optimize: str or PathOptimizer :param method: The method to use to compute the expectation value. - 'rho': compute the expectation value via the reduced density matrix. - 'rho-reduced': compute the expectation value via the reduced density matrix, having reduced the physical indices onto the bonds first. :type method: {'rho', 'rho-reduced'}, optional :param flatten: Whether to force 'flattening' (contracting all physical indices) of the tensor network before contraction, whilst this makes the TN generally more complex to contract, the accuracy can often be much improved. :type flatten: bool, optional :param normalized: Whether to locally normalize the result. :type normalized: bool, optional :param symmetrized: Whether to symmetrize the reduced density matrix at the end. This should be unecessary if ``flatten`` is set to ``True``. :type symmetrized: {'auto', True, False}, optional :param return_all: Whether to return all results, or just the summed expectation. If ``rehease is not False``, this is ignored and a dict is always returned. :type return_all: bool, optional :param rehearse: Whether to perform the computations or not:: - False: perform the computation. - 'tn': return the tensor networks of each local expectation, without running the path optimizer. - 'tree': run the path optimizer and return the ``cotengra.ContractonTree`` for each local expectation. - True: run the path optimizer and return the ``PathInfo`` for each local expectation. :type rehearse: {False, 'tn', 'tree', True}, optional :param executor: If supplied compute the terms in parallel using this executor. :type executor: Executor, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_compressed_opts: Supplied to :meth:`~quimb.tensor.tensor_core.TensorNetwork.contract_compressed`. :returns: **expecs** -- If ``return_all==False``, return the summed expectation value of the given terms. Otherwise, return a dictionary mapping each term's location to the expectation value. :rtype: float or dict[node or (node, node), float] .. py:attribute:: compute_local_expectation_rehearse .. py:attribute:: compute_local_expectation_tn .. py:method:: sample_configuration_cluster(gauges=None, max_distance=0, fillin=0, max_iterations=100, tol=5e-06, optimize='auto-hq', seed=None) Sample a configuration for this state using the simple update or cluster style environement approximation. The algorithms proceeds as a decimation: 1. Compute every remaining site's local density matrix. 2. The site with the largest bias is sampled. 3. The site is projected into this sampled local config. 4. The state is regauged given the projection. 5. Repeat until all sites are sampled. :param gauges: The store of gauge bonds, the keys being indices and the values being the vectors. Only bonds present in this dictionary will be gauged. :type gauges: dict[str, array_like], optional :param max_distance: The maximum distance to consider when computing the local density matrix for each site. Zero meaning on the site itself, 1 meaning the site and its immediate neighbors, etc. :type max_distance: int, optional :param fillin: When selecting the local tensors, whether and how many times to 'fill-in' corner tensors attached multiple times to the local region. On a lattice this fills in the corners. See :meth:`~quimb.tensor.tensor_core.TensorNetwork.select_local`. :type fillin: bool or int, optional :param max_iterations: The maximum number of iterations to perform when gauging the state. :type max_iterations: int, optional :param tol: The tolerance to converge to when gauging the state. :type tol: float, optional :param optimize: The contraction path optimizer to use. :type optimize: str or PathOptimizer, optional :param seed: A random seed or random number generator to use. :type seed: None, int or np.random.Generator, optional :returns: * **config** (*dict[Node, int]*) -- The sampled configuration. * **omega** (*float*) -- The probability of the sampled configuration in terms of the approximate distribution induced by the cluster scheme. .. py:class:: TensorNetworkGenOperator(ts=(), *, virtual=False, check_collisions=True) Bases: :py:obj:`TensorNetworkGen` A tensor network which notionally has a single tensor and two outer indices per 'site', though these could be labelled arbitrarily and could also be linked in an arbitrary geometry by bonds. By convention, if converted to a dense matrix, the 'upper' indices would be on the left and the 'lower' indices on the right. .. py:attribute:: _EXTRA_PROPS :value: ('_sites', '_site_tag_id', '_upper_ind_id', '_lower_ind_id') .. py:property:: upper_ind_id The string specifier for the upper phyiscal indices. .. py:method:: upper_ind(site) Get the upper physical index name of ``site``. .. py:method:: reindex_upper_sites(new_id, where=None, inplace=False) Modify the upper site indices for all or some tensors in this operator tensor network (without changing the ``upper_ind_id``). :param new_id: A string with a format placeholder to accept a site, e.g. "up{}". :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_upper_sites_ .. py:property:: upper_inds Return a tuple of all upper indices. .. py:property:: upper_inds_present Return a tuple of all upper indices still present in the tensor network. .. py:property:: lower_ind_id The string specifier for the lower phyiscal indices. .. py:method:: lower_ind(site) Get the lower physical index name of ``site``. .. py:method:: reindex_lower_sites(new_id, where=None, inplace=False) Modify the lower site indices for all or some tensors in this operator tensor network (without changing the ``lower_ind_id``). :param new_id: A string with a format placeholder to accept a site, e.g. "up{}". :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_lower_sites_ .. py:property:: lower_inds Return a tuple of all lower indices. .. py:property:: lower_inds_present Return a tuple of all lower indices still present in the tensor network. .. py:method:: to_dense(*inds_seq, to_qarray=False, **contract_opts) Contract this tensor network 'operator' into a dense array. :param inds_seq: How to group the site indices into the dense array. By default, use a single group ordered like ``sites``, but only containing those sites which are still present. :type inds_seq: sequence of sequences of str :param to_qarray: Whether to turn the dense array into a ``qarray``, if the backend would otherwise be ``'numpy'``. :type to_qarray: bool :param contract_opts: Options to pass to :meth:`~quimb.tensor.tensor_core.TensorNewtork.contract`. :rtype: array .. py:attribute:: to_qarray .. py:method:: phys_dim(site=None, which='upper') Get the physical dimension of ``site``. .. py:attribute:: gate_upper .. py:attribute:: gate_upper_ .. py:attribute:: gate_lower .. py:attribute:: gate_lower_ .. py:method:: gate_upper_with_op_lazy(A, transpose=False, inplace=False) Act lazily with the operator tensor network ``A``, which should have matching structure, on this operator tensor network (``B``), like ``A @ B``. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted. .. math:: B \rightarrow A B or (if ``transpose=True``): .. math:: B \rightarrow A^T B :param A: The operator tensor network to gate with, or apply to this tensor network. :type A: TensorNetworkGenOperator :param transpose: Whether to contract the lower or upper indices of ``A`` with the upper indices of ``B``. If ``False`` (the default), the lower indices of ``A`` will be contracted with the upper indices of ``B``, if ``True`` the upper indices of ``A`` will be contracted with the upper indices of ``B``, which is like applying the transpose first. :type transpose: bool, optional :param inplace: Whether to perform the gate operation inplace on this tensor network. :type inplace: bool, optional :rtype: TensorNetworkGenOperator .. py:attribute:: gate_upper_with_op_lazy_ .. py:method:: gate_lower_with_op_lazy(A, transpose=False, inplace=False) Act lazily 'from the right' with the operator tensor network ``A``, which should have matching structure, on this operator tensor network (``B``), like ``B @ A``. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted. .. math:: B \rightarrow B A or (if ``transpose=True``): .. math:: B \rightarrow B A^T :param A: The operator tensor network to gate with, or apply to this tensor network. :type A: TensorNetworkGenOperator :param transpose: Whether to contract the upper or lower indices of ``A`` with the lower indices of this TN. If ``False`` (the default), the upper indices of ``A`` will be contracted with the lower indices of ``B``, if ``True`` the lower indices of ``A`` will be contracted with the lower indices of this TN, which is like applying the transpose first. :type transpose: bool, optional :param inplace: Whether to perform the gate operation inplace on this tensor network. :type inplace: bool, optional :rtype: TensorNetworkGenOperator .. py:attribute:: gate_lower_with_op_lazy_ .. py:method:: gate_sandwich_with_op_lazy(A, inplace=False) Act lazily with the operator tensor network ``A``, which should have matching structure, on this operator tensor network (``B``), like :math:`B \rightarrow A B A^\dagger`. The returned tensor network will have the same structure as this one, but with the operator gated in lazily, i.e. uncontracted. :param A: The operator tensor network to gate with, or apply to this tensor network. :type A: TensorNetworkGenOperator :param inplace: Whether to perform the gate operation inplace on this tensor :type inplace: bool, optional :rtype: TensorNetworkGenOperator .. py:attribute:: gate_sandwich_with_op_lazy_ .. py:function:: _handle_rehearse(rehearse, tn: quimb.tensor.tensor_core.TensorNetwork, optimize, **kwargs) .. py:function:: _compute_expecs_maybe_in_parallel(fn, tn, terms, return_all=False, executor=None, progbar=False, **kwargs) Unified helper function for the various methods that compute many expectations, possibly in parallel, possibly with a progress bar. .. py:function:: _tn_local_expectation(tn: TensorNetworkGenVector, *args, **kwargs) Define as function for pickleability. .. py:function:: _tn_local_expectation_cluster(tn: TensorNetworkGenVector, *args, **kwargs) Define as function for pickleability. .. py:function:: _tn_local_expectation_exact(tn: TensorNetworkGenVector, *args, **kwargs) Define as function for pickleability. .. py:function:: _tn_local_expectation_sloop_expand(tn: TensorNetworkGenVector, *args, **kwargs) Define as function for pickleability. .. py:function:: _tn_local_expectation_gloop_expand(tn: TensorNetworkGenVector, *args, **kwargs) Define as function for pickleability. .. py:function:: _combine_expansion_expectations(expecs, counts, norms, combine='prod', normalized=True)