quimb.tensor.belief_propagation.d2bp ==================================== .. py:module:: quimb.tensor.belief_propagation.d2bp Classes ------- .. autoapisummary:: quimb.tensor.belief_propagation.d2bp.D2BP Functions --------- .. autoapisummary:: quimb.tensor.belief_propagation.d2bp._parse_global_gloops quimb.tensor.belief_propagation.d2bp.contract_d2bp quimb.tensor.belief_propagation.d2bp.compress_d2bp quimb.tensor.belief_propagation.d2bp.sample_d2bp Module Contents --------------- .. py:function:: _parse_global_gloops(tn, gloops=None) .. py:class:: D2BP(tn, *, messages=None, output_inds=None, optimize='auto-hq', damping=0.0, update='sequential', normalize=None, distance=None, local_convergence=True, contract_every=None, inplace=False, **contract_opts) Bases: :py:obj:`quimb.tensor.belief_propagation.bp_common.BeliefPropagationCommon` Dense (as in one tensor per site) 2-norm (as in for wavefunctions and operators) belief propagation. Allows messages reuse. This version assumes no hyper indices (i.e. a standard PEPS like tensor network). Potential use cases for D2BP and a PEPS like tensor network are: - globally compressing it from bond dimension ``D`` to ``D'`` - eagerly applying gates and locally compressing back to ``D`` - sampling configurations - estimating the norm of the tensor network :param tn: The tensor network to form the 2-norm of and run BP on. :type tn: TensorNetwork :param messages: The initial messages to use, effectively defaults to all ones if not specified. :type messages: dict[(str, int), array_like], optional :param output_inds: The indices to consider as output (dangling) indices of the tn. Computed automatically if not specified. :type output_inds: set[str], optional :param optimize: The path optimizer to use when contracting the messages. :type optimize: str or PathOptimizer, optional :param damping: The damping factor to apply to messages. This simply mixes some part of the old message into the new one, with the final message being ``damping * old + (1 - damping) * new``. This makes convergence more reliable but slower. :type damping: float or callable, optional :param update: Whether to update messages sequentially (newly computed messages are immediately used for other updates in the same iteration round) or in parallel (all messages are comptued using messages from the previous round only). Sequential generally helps convergence but parallel can possibly converge to differnt solutions. :type update: {'sequential', 'parallel'}, optional :param normalize: How to normalize messages after each update. If None choose automatically. If a callable, it should take a message and return the normalized message. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phase of the message, by default used for complex dtypes. :type normalize: {'L1', 'L2', 'L2phased', 'Linf', callable}, optional :param distance: How to compute the distance between messages to check for convergence. If None choose automatically. If a callable, it should take two messages and return the distance. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf', or 'cosine' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phases of the messages, by default used for complex dtypes if phased normalization is not already being used. :type distance: {'L1', 'L2', 'L2phased', 'Linf', 'cosine', callable}, optional :param local_convergence: Whether to allow messages to locally converge - i.e. if all their input messages have converged then stop updating them. :type local_convergence: bool, optional :param contract_every: If not None, 'contract' (via BP) the tensor network every ``contract_every`` iterations. The resulting values are stored in ``zvals`` at corresponding points ``zval_its``. :type contract_every: int, optional :param inplace: Whether to perform any operations inplace on the input tensor network. :type inplace: bool, optional :param contract_opts: Other options supplied to ``cotengra.array_contract``. .. py:attribute:: contract_opts .. py:attribute:: local_convergence :value: True .. py:attribute:: touch_map .. py:attribute:: touched .. py:attribute:: exprs .. py:method:: build_expr(ix) .. py:method:: update_touched_from_tids(*tids) Specify that the messages for the given ``tids`` have changed. .. py:method:: update_touched_from_tags(tags, which='any') Specify that the messages for the messages touching ``tags`` have changed. .. py:method:: update_touched_from_inds(inds, which='any') Specify that the messages for the messages touching ``inds`` have changed. .. py:method:: iterate(tol=5e-06) Perform a single iteration of dense 2-norm belief propagation. .. py:method:: compute_marginal(ind) Compute the marginal for the index ``ind``. .. py:method:: normalize_message_pairs() Normalize a pair of messages such that ` = 1` and ` = ` (but in general != 1). .. py:method:: local_tensor_contract(tid) Contract the local region of the tensor at ``tid``. .. py:method:: normalize_tensors(strip_exponent=True) Normalize the tensors in the tensor network such that their 2-norm is 1. If ``strip_exponent`` is ``True`` then accrue the phase and exponent (log10) into the ``sign`` and ``exponent`` attributes of the D2BP object (the default), contract methods can then reinsert these factors when returning the final result. .. py:method:: contract(strip_exponent=False, check_zero=True) Estimate the total contraction, i.e. the 2-norm. :param strip_exponent: Whether to strip the exponent from the final result. If ``True`` then the returned result is ``(mantissa, exponent)``. :type strip_exponent: bool, optional :rtype: scalar or (scalar, float) .. py:method:: get_cluster_excited(tids=None, partial_trace_map=(), exclude=()) Get the local norm tensor network for ``tids`` with BP messages inserted on the boundary and excitation projectors inserted on the inner bonds. See arxiv.org/abs/2409.03108 for more details. :param tids: The tensor ids to include in the cluster. :type tids: iterable of hashable :param partial_trace_map: A remapping of ket indices to bra indices to perform an effective partial trace. :type partial_trace_map: dict[str, str], optional :param exclude: A set of bond indices to exclude from inserting excitation projectors on, e.g. when forming a reduced density matrix. :type exclude: iterable of str, optional :rtype: TensorNetwork .. py:method:: contract_loop_series_expansion(gloops=None, multi_excitation_correct=True, tol_correction=1e-12, maxiter_correction=100, strip_exponent=False, optimize='auto-hq', **contract_opts) Contract the norm of the tensor network using the same procedure as in https://arxiv.org/abs/2409.03108 - "Loop Series Expansions for Tensor Networks". :param gloops: The gloop sizes to use. If an integer, then generate all gloop sizes up to this size. If a tuple, then use these gloops. :type gloops: int or iterable of tuples, optional :param multi_excitation_correct: Whether to use the multi-excitation correction. If ``True``, then the free energy is refined iteratively until self consistent. :type multi_excitation_correct: bool, optional :param tol_correction: The tolerance for the multi-excitation correction. :type tol_correction: float, optional :param maxiter_correction: The maximum number of iterations for the multi-excitation correction. :type maxiter_correction: int, optional :param strip_exponent: Whether to strip the exponent from the final result. If ``True`` then the returned result is ``(mantissa, exponent)``. :type strip_exponent: bool, optional :param optimize: The path optimizer to use when contracting the messages. :type optimize: str or PathOptimizer, optional :param contract_opts: Other options supplied to ``TensorNetwork.contract``. .. py:method:: partial_trace_loop_series_expansion(where, gloops=None, normalized=True, grow_from='alldangle', strict_size=True, multi_excitation_correct=True, optimize='auto-hq', **contract_opts) Compute the reduced density matrix for the sites specified by ``where`` using the loop series expansion method from https://arxiv.org/abs/2409.03108 - "Loop Series Expansions for Tensor Networks". :param where: The sites to from the reduced density matrix of. :type where: sequence[hashable] :param gloops: The generalized loops to use, or an integer to automatically generate all up to a certain size. If none use the smallest non- trivial size. :type gloops: int or iterable of tuples, optional :param normalized: Whether to normalize the final density matrix. :type normalized: bool, optional :param grow_from: How to grow the generalized loops from the specified ``where``: - 'alldangle': clusters up to max size, where target sites are allowed to dangle. - 'all': clusters where loop, up to max size, has to include *all* target sites. - 'any': clusters where loop, up to max size, can include *any* of the target sites. Remaining target sites are added as extras. By default 'alldangle'. :type grow_from: {'alldangle', 'all', 'any'}, optional :param strict_size: Whether to enforce the maximum size of the generalized loops, only relevant for `grow_from="any"`. :type strict_size: bool, optional :param multi_excitation_correct: Whether to use the multi-excitation correction. If ``True``, then the free energy is refined iteratively until self consistent. :type multi_excitation_correct: bool, optional :param optimize: The path optimizer to use when contracting the messages. :type optimize: str or PathOptimizer, optional :param contract_opts: Other options supplied to ``TensorNetwork.contract``. .. py:method:: contract_gloop_expand(gloops=None, autocomplete=True, optimize='auto-hq', strip_exponent=False, check_zero=True, info=None, progbar=False, **contract_opts) .. py:method:: compress(max_bond, cutoff=0.0, cutoff_mode=4, renorm=0, inplace=False) Compress the initial tensor network using the current messages. .. py:method:: gauge_insert(tn, smudge=1e-12) Insert the sqrt of messages on the boundary of a part of the main BP TN. :param tn: The tensor network to insert the messages into. :type tn: TensorNetwork :param smudge: Smudge factor to avoid numerical issues, the eigenvalues of the messages are clipped to be at least the largest eigenvalue times this factor. :type smudge: float, optional :returns: The sequence of tensors, indices and inverse gauges to apply to reverse the gauges applied. :rtype: list[tuple[Tensor, str, array_like]] .. py:method:: gauge_temp(tn, ungauge_outer=True) Context manager to temporarily gauge a tensor network, presumably a subnetwork of the main BP network, using the current messages, and then un-gauge it afterwards. :param tn: The tensor network to gauge. :type tn: TensorNetwork :param ungauge_outer: Whether to un-gauge the outer indices of the tensor network. :type ungauge_outer: bool, optional .. py:method:: gate_(G, where, max_bond=None, cutoff=0.0, cutoff_mode='rsum2', renorm=0, tn=None, **gate_opts) Apply a gate to the tensor network at the specified sites, using the current messages to gauge the tensors. .. py:method:: get_cluster_norm(tids, partial_trace_map=()) Get the local norm tensor network for ``tids`` with BP messages inserted on the boundary. Optionally open some physical indices up to perform an effective partial trace. :param tids: The tensor ids to include in the cluster. :type tids: iterable of hashable :param partial_trace_map: A remapping of ket indices to bra indices to perform an effective partial trace. :type partial_trace_map: dict[str, str], optional :rtype: TensorNetwork .. py:method:: partial_trace(where, normalized=True, tids_region=None, get='matrix', bra_ind_id=None, optimize='auto-hq', **contract_opts) Get the reduced density matrix for the sites specified by ``where``, with the remaining network approximated by messages on the boundary. :param where: The sites to from the reduced density matrix of. :type where: sequence[hashable] :param get: The type of object to return. If 'tn', return the uncontracted tensor network object. If 'tensor', return the labelled density operator as a `Tensor`. If 'array', return the unfused raw array with 2 * len(where) dimensions. If 'matrix', fuse the ket and bra indices and return this 2D matrix. :type get: {'tn', 'tensor', 'array', 'matrix'}, optional :param bra_ind_id: If ``get="tn"``, how to label the bra indices. If None, use the default based on the current site_ind_id. :type bra_ind_id: str, optional :param optimize: The path optimizer to use when contracting the tensor network. :type optimize: str or PathOptimizer, optional :param contract_opts: Other options supplied to ``TensorNetwork.contract``. :rtype: TensorNetwork or Tensor or array .. py:method:: partial_trace_gloop_expand(where, gloops=None, combine='sum', normalized=True, grow_from='alldangle', strict_size=True, optimize='auto-hq', **contract_opts) Compute a reduced density matrix for the sites specified by ``where`` using the generalized loop cluster expansion. :param where: The sites to from the reduced density matrix of. :type where: sequence[hashable] :param gloops: The generalized loops to use, or an integer to automatically generate all up to a certain size. If none use the smallest non- trivial size. :type gloops: int or iterable of tuples, optional :param combine: How to combine the contributions from each generalized loop. If 'sum', use coefficient weighted addition. If 'prod', use power weighted multiplication. :type combine: {'sum', 'prod'}, optional :param normalized: Whether to normalize the density matrix. If True or "local", normalize each cluster density matrix by its trace. If "separate", normalize the final density matrix by its trace (usually less accurate). If False, do not normalize. :type normalized: bool or {"local", "separate"}, optional :param grow_from: How to grow the generalized loops from the specified ``where``: - 'alldangle': clusters up to max size, where target sites are allowed to dangle. - 'all': clusters where loop, up to max size, has to include *all* target sites. - 'any': clusters where loop, up to max size, can include *any* of the target sites. Remaining target sites are added as extras. By default 'alldangle'. :type grow_from: {'alldangle', 'all', 'any'}, optional :param strict_size: Whether to enforce the maximum size of the generalized loops, only relevant for `grow_from="any"`. :type strict_size: bool, optional :param optimize: The path optimizer to use when contracting the tensor network. :type optimize: str or PathOptimizer, optional :param contract_opts: Other options supplied to ``TensorNetwork.contract``. .. py:function:: contract_d2bp(tn, *, messages=None, output_inds=None, max_iterations=1000, tol=5e-06, damping=0.0, diis=False, update='sequential', normalize=None, distance=None, tol_abs=None, tol_rolling_diff=None, local_convergence=True, optimize='auto-hq', strip_exponent=False, check_zero=True, info=None, progbar=False, **contract_opts) Estimate the norm squared of ``tn`` using dense 2-norm belief propagation (no hyper indices). :param tn: The tensor network to form the 2-norm of and run BP on. :type tn: TensorNetwork :param messages: The initial messages to use, effectively defaults to all ones if not specified. :type messages: dict[(str, int), array_like], optional :param output_inds: The indices to consider as output (dangling) indices of the tn. Computed automatically if not specified. :type output_inds: set[str], optional :param max_iterations: The maximum number of iterations to perform. :type max_iterations: int, optional :param tol: The convergence tolerance for messages. :type tol: float, optional :param damping: The damping parameter to use, defaults to no damping. :type damping: float, optional :param diis: Whether to use direct inversion in the iterative subspace to help converge the messages by extrapolating to low error guesses. If a dict, should contain options for the DIIS algorithm. The relevant options are {`max_history`, `beta`, `rcond`}. :type diis: bool or dict, optional :param update: Whether to update messages sequentially or in parallel. :type update: {'sequential', 'parallel'}, optional :param normalize: How to normalize messages after each update. If None choose automatically. If a callable, it should take a message and return the normalized message. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phase of the message, by default used for complex dtypes. :type normalize: {'L1', 'L2', 'L2phased', 'Linf', callable}, optional :param distance: How to compute the distance between messages to check for convergence. If None choose automatically. If a callable, it should take two messages and return the distance. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf', or 'cosine' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phases of the messages, by default used for complex dtypes if phased normalization is not already being used. :type distance: {'L1', 'L2', 'L2phased', 'Linf', 'cosine', callable}, optional :param tol_abs: The absolute convergence tolerance for maximum message update distance, if not given then taken as ``tol``. :type tol_abs: float, optional :param tol_rolling_diff: The rolling mean convergence tolerance for maximum message update distance, if not given then taken as ``tol``. This is used to stop running when the messages are just bouncing around the same level, without any overall upward or downward trends, roughly speaking. :type tol_rolling_diff: float, optional :param local_convergence: Whether to allow messages to locally converge - i.e. if all their input messages have converged then stop updating them. :type local_convergence: bool, optional :param optimize: The path optimizer to use when contracting the messages. :type optimize: str or PathOptimizer, optional :param strip_exponent: Whether to return the mantissa and exponent separately. :type strip_exponent: bool, optional :param check_zero: Whether to check for zero values and return zero early. :type check_zero: bool, optional :param info: If supplied, the following information will be added to it: ``converged`` (bool), ``iterations`` (int), ``max_mdiff`` (float), ``rolling_abs_mean_diff`` (float). :type info: dict, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Other options supplied to ``cotengra.array_contract``. :rtype: scalar or (scalar, float) .. py:function:: compress_d2bp(tn, max_bond, cutoff=0.0, cutoff_mode='rsum2', renorm=0, messages=None, output_inds=None, max_iterations=1000, tol=5e-06, damping=0.0, diis=False, update='sequential', normalize=None, distance=None, tol_abs=None, tol_rolling_diff=None, local_convergence=True, optimize='auto-hq', inplace=False, info=None, progbar=False, **contract_opts) Compress the tensor network ``tn`` using dense 2-norm belief propagation. :param tn: The tensor network to form the 2-norm of, run BP on and then compress. :type tn: TensorNetwork :param max_bond: The maximum bond dimension to compress to. :type max_bond: int :param cutoff: The cutoff to use when compressing. :type cutoff: float, optional :param cutoff_mode: The cutoff mode to use when compressing. :type cutoff_mode: int, optional :param renorm: Whether to renormalize the singular values when compressing. :type renorm: float, optional :param messages: The initial messages to use, effectively defaults to all ones if not specified. :type messages: dict[(str, int), array_like], optional :param output_inds: The indices to consider as output (dangling) indices of the tn. Computed automatically if not specified. :type output_inds: set[str], optional :param max_iterations: The maximum number of iterations to perform. :type max_iterations: int, optional :param tol: The convergence tolerance for messages. :type tol: float, optional :param damping: The damping parameter to use, defaults to no damping. :type damping: float, optional :param diis: Whether to use direct inversion in the iterative subspace to help converge the messages by extrapolating to low error guesses. If a dict, should contain options for the DIIS algorithm. The relevant options are {`max_history`, `beta`, `rcond`}. :type diis: bool or dict, optional :param update: Whether to update messages sequentially or in parallel. :type update: {'sequential', 'parallel'}, optional :param normalize: How to normalize messages after each update. If None choose automatically. If a callable, it should take a message and return the normalized message. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phase of the message, by default used for complex dtypes. :type normalize: {'L1', 'L2', 'L2phased', 'Linf', callable}, optional :param distance: How to compute the distance between messages to check for convergence. If None choose automatically. If a callable, it should take two messages and return the distance. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf', or 'cosine' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phases of the messages, by default used for complex dtypes if phased normalization is not already being used. :type distance: {'L1', 'L2', 'L2phased', 'Linf', 'cosine', callable}, optional :param tol_abs: The absolute convergence tolerance for maximum message update distance, if not given then taken as ``tol``. :type tol_abs: float, optional :param tol_rolling_diff: The rolling mean convergence tolerance for maximum message update distance, if not given then taken as ``tol``. This is used to stop running when the messages are just bouncing around the same level, without any overall upward or downward trends, roughly speaking. :type tol_rolling_diff: float, optional :param local_convergence: Whether to allow messages to locally converge - i.e. if all their input messages have converged then stop updating them. :type local_convergence: bool, optional :param optimize: The path optimizer to use when contracting the messages. :type optimize: str or PathOptimizer, optional :param inplace: Whether to perform the compression inplace. :type inplace: bool, optional :param info: If specified, update this dictionary with information about the belief propagation run. :type info: dict, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Other options supplied to ``cotengra.array_contract``. :rtype: TensorNetwork .. py:function:: sample_d2bp(tn, output_inds=None, messages=None, max_iterations=100, tol=0.01, bias=None, seed=None, optimize='auto-hq', damping=0.0, diis=False, update='sequential', normalize=None, distance=None, tol_abs=None, tol_rolling_diff=None, local_convergence=True, progbar=False, **contract_opts) Sample a configuration from ``tn`` using dense 2-norm belief propagation. :param tn: The tensor network to sample from. :type tn: TensorNetwork :param output_inds: Which indices to sample. :type output_inds: set[str], optional :param messages: The initial messages to use, effectively defaults to all ones if not specified. :type messages: dict[(str, int), array_like], optional :param max_iterations: The maximum number of iterations to perform, per marginal. :type max_iterations: int, optional :param tol: The convergence tolerance for messages. :type tol: float, optional :param bias: Bias the sampling towards more locally likely bit-strings. This is done by raising the probability of each bit-string to this power. :type bias: float, optional :param seed: A random seed for reproducibility. :type seed: int, optional :param optimize: The path optimizer to use when contracting the messages. :type optimize: str or PathOptimizer, optional :param damping: The damping parameter to use, defaults to no damping. :type damping: float, optional :param diis: Whether to use direct inversion in the iterative subspace to help converge the messages by extrapolating to low error guesses. If a dict, should contain options for the DIIS algorithm. The relevant options are {`max_history`, `beta`, `rcond`}. :type diis: bool or dict, optional :param update: Whether to update messages sequentially or in parallel. :type update: {'sequential', 'parallel'}, optional :param normalize: How to normalize messages after each update. If None choose automatically. If a callable, it should take a message and return the normalized message. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phase of the message, by default used for complex dtypes. :type normalize: {'L1', 'L2', 'L2phased', 'Linf', callable}, optional :param distance: How to compute the distance between messages to check for convergence. If None choose automatically. If a callable, it should take two messages and return the distance. If a string, it should be one of 'L1', 'L2', 'L2phased', 'Linf', or 'cosine' for the corresponding norms. 'L2phased' is like 'L2' but also normalizes the phases of the messages, by default used for complex dtypes if phased normalization is not already being used. :type distance: {'L1', 'L2', 'L2phased', 'Linf', 'cosine', callable}, optional :param tol_abs: The absolute convergence tolerance for maximum message update distance, if not given then taken as ``tol``. :type tol_abs: float, optional :param tol_rolling_diff: The rolling mean convergence tolerance for maximum message update distance, if not given then taken as ``tol``. This is used to stop running when the messages are just bouncing around the same level, without any overall upward or downward trends, roughly speaking. :type tol_rolling_diff: float, optional :param local_convergence: Whether to allow messages to locally converge - i.e. if all their input messages have converged then stop updating them. :type local_convergence: bool, optional :param progbar: Whether to show a progress bar. :type progbar: bool, optional :param contract_opts: Other options supplied to ``cotengra.array_contract``. :returns: * **config** (*dict[str, int]*) -- The sampled configuration, a mapping of output indices to values. * **tn_config** (*TensorNetwork*) -- The tensor network with the sampled configuration applied. * **omega** (*float*) -- The BP probability of the sampled configuration.