
    \MhG                        d Z ddlmZmZ ddlmZ ddlmZmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ dd	lZdd
lmZmZmZ g dZ G d de          Z ed           ej        dd          	 d+d                        Z ej        d	d	dd          	 d,d            Z ej        dd          d-d            ZeeeedZ ed           ej        dd          	 d.d                        Z ed           ej        dd          	 d.d                        Z ej        dd          d/d            Z  ej        dd          	 d0d             Z! ej        dd          d/d!            Z" ed"           ej        dd#          d1dd	d$d%                        Z# G d& d'          Z$ ej        d(          d	d	d)d*            Z%d	S )2z=
Algorithms for calculating min/max spanning trees/forests.

    )	dataclassfield)Enum)heappopheappush)count)isnan)
itemgetter)PriorityQueueN)	UnionFindnot_implemented_forpy_random_state)	minimum_spanning_edgesmaximum_spanning_edgesminimum_spanning_treemaximum_spanning_treenumber_of_spanning_treesrandom_spanning_treepartition_spanning_treeEdgePartitionSpanningTreeIteratorc                       e Zd ZdZdZdZdZdS )r   z
    An enum to store the state of an edge partition. The enum is written to the
    edges of a graph before being pasted to `kruskal_mst_edges`. Options are:

    - EdgePartition.OPEN
    - EdgePartition.INCLUDED
    - EdgePartition.EXCLUDED
    r         N)__name__
__module____qualname____doc__OPENINCLUDEDEXCLUDED     \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/networkx/algorithms/tree/mst.pyr   r      s)          DHHHHr#   r   
multigraphweightdata)
edge_attrspreserve_edge_attrsTFc              #      K   t                     } fdfd|                                D             }d |D             }|rqfd|                                D             }d |D             }|D ]>\  }}	}
||         ||	         k    r&|r||	|
fV  n||	fV  |                    ||	           ?|odS dS )u  Iterate over edges of a Borůvka's algorithm min/max spanning tree.

    Parameters
    ----------
    G : NetworkX Graph
        The edges of `G` must have distinct weights,
        otherwise the edges may not form a tree.

    minimum : bool (default: True)
        Find the minimum (True) or maximum (False) spanning tree.

    weight : string (default: 'weight')
        The name of the edge attribute holding the edge weights.

    keys : bool (default: True)
        This argument is ignored since this function is not
        implemented for multigraphs; it exists only for consistency
        with the other minimum spanning tree functions.

    data : bool (default: True)
        Flag for whether to yield edge attribute dicts.
        If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
        If False, yield edges `(u, v)`.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.

    c                    	rdnd}t          d          }d}t          j        | d          D ]Q}|d                             
d          |z  }t	          |          rr3d| }t          |          ||k     r|}|}R|S )zReturns the optimum (minimum or maximum) edge on the edge
        boundary of the given set of nodes.

        A return value of ``None`` indicates an empty boundary.

        r   infNTr'   "NaN found as an edge weight. Edge )floatnxedge_boundarygetr	   
ValueError)	componentsignminwtboundaryewtmsgG
ignore_nanminimumr&   s          r$   	best_edgez$boruvka_mst_edges.<locals>.best_edgeS   s     #qqe!!YT::: 		 		A261%%,BRyy & >1>> oo%Ezzr#   c              3   .   K   | ]} |          V  d S Nr"   .0r5   r?   s     r$   	<genexpr>z$boruvka_mst_edges.<locals>.<genexpr>k   s-      II9))I&&IIIIIIr#   c                     g | ]}||S rA   r"   rC   edges     r$   
<listcomp>z%boruvka_mst_edges.<locals>.<listcomp>l   s    BBB41A$1A1A1Ar#   c              3   .   K   | ]} |          V  d S rA   r"   rB   s     r$   rD   z$boruvka_mst_edges.<locals>.<genexpr>   s-      MMyii	**MMMMMMr#   c                     g | ]}||S rA   r"   rF   s     r$   rH   z%boruvka_mst_edges.<locals>.<listcomp>   s    FFFtT5Ed5E5E5Er#   N)r   to_setsunion)r<   r>   r&   keysr'   r=   forest
best_edgesuvdr?   s   ```  `     @r$   boruvka_mst_edgesrS   -   s@     H q\\F       0 JIII8H8HIIIJBB:BBBJ  #  NMMMFNN<L<LMMM
FFzFFF
 " 	# 	#GAq!ayF1I%% Q'MMMMQ$JJJQ""";  # # # # #r#   )r&   	partitionc              #   F  K   t                      }|                                 r|                     dd          }n|                     d          }	 g }	g }
|D ]}|d         }|                    |d          }t	          |          r|r2t          d|           |f|z   }|                    |          t          j        k    r|	                    |           |                    |          t          j	        k    r|
                    |           |rt          |
t          d                    }nt          |
t          d          d	          }|	                    |           |	}~
~~	|                                 rZ|D ]U\  }}}}}||         ||         k    r;|r|r	||||fV  n|||fV  n|r|||fV  n||fV  |                    ||           Vd
S |D ]?\  }}}}||         ||         k    r&|r|||fV  n||fV  |                    ||           @d
S )a  
    Iterate over edge of a Kruskal's algorithm min/max spanning tree.

    Parameters
    ----------
    G : NetworkX Graph
        The graph holding the tree of interest.

    minimum : bool (default: True)
        Find the minimum (True) or maximum (False) spanning tree.

    weight : string (default: 'weight')
        The name of the edge attribute holding the edge weights.

    keys : bool (default: True)
        If `G` is a multigraph, `keys` controls whether edge keys ar yielded.
        Otherwise `keys` is ignored.

    data : bool (default: True)
        Flag for whether to yield edge attribute dicts.
        If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
        If False, yield edges `(u, v)`.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.

    partition : string (default: None)
        The name of the edge attribute holding the partition data, if it exists.
        Partition data is written to the edges using the `EdgePartition` enum.
        If a partition exists, all included edges and none of the excluded edges
        will appear in the final tree. Open edges may or may not be used.

    Yields
    ------
    edge tuple
        The edges as discovered by Kruskal's method. Each edge can
        take the following forms: `(u, v)`, `(u, v, d)` or `(u, v, k, d)`
        depending on the `key` and `data` parameters
    TrM   r'   r.   r,   r   r/   r   )key)rW   reverseN)r   is_multigraphedgesr3   r	   r4   r   r    appendr!   sortedr
   extendrL   )r<   r>   r&   rM   r'   r=   rT   subtreesrZ   included_edges
open_edgesr9   rR   r:   rG   sorted_open_edgessorted_edgesrP   rQ   ks                       r$   kruskal_mst_edgesrd      s     \ {{H #T--T"" NJ $ $bEUU6199 	G E!EEFFFuqy55}555!!$''''UU9!777d#### P"::a==AAA"::a==$OOO +,,,!L%~ 	 %* 	% 	%NB1a{hqk)) 	# &Aqj((((Ag #Agd


q!$$$	% 	% ( 	% 	%KB1a{hqk)) Q'MMMMQ$JJJq!$$$	% 	%r#   c              #     K   |                                  }t          |           }t                      }|rdnd}	|r|                                }
g }|
h}|r| j        |
                                         D ]\  }}|                                D ]k\  }}|                    |d          |	z  }t          |          r|r0d|
|||f }t          |          t          ||t          |          |
|||f           ln| j        |
                                         D ]i\  }}|                    |d          |	z  }t          |          r|r0d|
||f }t          |          t          ||t          |          |
||f           j|r|r|rt          |          \  }}}
}}}nt          |          \  }}}
}}||v s||vr=|r|r|r	|
|||fV  n|
||fV  n|r|
||fV  n|
|fV  |                    |           |                    |           |r| j        |                                         D ]\  }}||v r
|                                D ]k\  }}|                    |d          |	z  }t          |          r|r0d||||f }t          |          t          ||t          |          ||||f           ln| j        |                                         D ]n\  }}||v r
|                    |d          |	z  }t          |          r|r5d|||f }t          |          t          ||t          |          |||f           o|r||dS dS )a  Iterate over edges of Prim's algorithm min/max spanning tree.

    Parameters
    ----------
    G : NetworkX Graph
        The graph holding the tree of interest.

    minimum : bool (default: True)
        Find the minimum (True) or maximum (False) spanning tree.

    weight : string (default: 'weight')
        The name of the edge attribute holding the edge weights.

    keys : bool (default: True)
        If `G` is a multigraph, `keys` controls whether edge keys ar yielded.
        Otherwise `keys` is ignored.

    data : bool (default: True)
        Flag for whether to yield edge attribute dicts.
        If True, yield edges `(u, v, d)`, where `d` is the attribute dict.
        If False, yield edges `(u, v)`.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.

    r   r,   r/   N)rY   setr   popadjitemsr3   r	   r4   r   nextr   adddiscard)r<   r>   r&   rM   r'   r=   rY   nodescr6   rP   frontiervisitedrQ   keydictrc   rR   r:   r;   W_wk2d2
new_weights                            r$   prim_mst_edgesrx      sl     : OO%%MFFEA11RD
 BHIIKK# 	;eAhnn.. B B
7#MMOO B BDAqvq))D0BRyy .% %$QAq!Q<QQ(oo-XDGGQ1a'@AAAABB a(( ; ;1UU61%%,99 *! ! J1ayJJC$S//)BQAq#9:::: +	H +	H 2#*8#4#4 1aAqq ' 1 11aAG||q~~ 	 	 "Q1*$$$$Q'MMMM Q'MMMMQ$JJJKKNNNMM! H"#%(.."2"2 
P 
PJAwG|| ")--// P PB%'VVFA%6%6%=
 ,, 2) ) ("W1bRT~"W"WC",S//1 JQAr2+NOOOOP
P U1X^^-- 	H 	HEArG|| !#!2!2T!9JZ(( .% %$OAq":OO(oo-X
DGGQ2'FGGGGW  +	H +	H/  BH BH BH BH BHr#   )boruvkau   borůvkakruskalprimdirectedrz   c                     	 t           |         }n'# t          $ r}| d}t          |          |d}~ww xY w || d||||          S )u
  Generate edges in a minimum spanning forest of an undirected
    weighted graph.

    A minimum spanning tree is a subgraph of the graph (a tree)
    with the minimum sum of edge weights.  A spanning forest is a
    union of the spanning trees for each connected component of the graph.

    Parameters
    ----------
    G : undirected Graph
       An undirected graph. If `G` is connected, then the algorithm finds a
       spanning tree. Otherwise, a spanning forest is found.

    algorithm : string
       The algorithm to use when finding a minimum spanning tree. Valid
       choices are 'kruskal', 'prim', or 'boruvka'. The default is 'kruskal'.

    weight : string
       Edge data key to use for weight (default 'weight').

    keys : bool
       Whether to yield edge key in multigraphs in addition to the edge.
       If `G` is not a multigraph, this is ignored.

    data : bool, optional
       If True yield the edge data along with the edge.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.

    Returns
    -------
    edges : iterator
       An iterator over edges in a maximum spanning tree of `G`.
       Edges connecting nodes `u` and `v` are represented as tuples:
       `(u, v, k, d)` or `(u, v, k)` or `(u, v, d)` or `(u, v)`

       If `G` is a multigraph, `keys` indicates whether the edge key `k` will
       be reported in the third position in the edge tuple. `data` indicates
       whether the edge datadict `d` will appear at the end of the edge tuple.

       If `G` is not a multigraph, the tuples are `(u, v, d)` if `data` is True
       or `(u, v)` if `data` is False.

    Examples
    --------
    >>> from networkx.algorithms import tree

    Find minimum spanning edges by Kruskal's algorithm

    >>> G = nx.cycle_graph(4)
    >>> G.add_edge(0, 3, weight=2)
    >>> mst = tree.minimum_spanning_edges(G, algorithm="kruskal", data=False)
    >>> edgelist = list(mst)
    >>> sorted(sorted(e) for e in edgelist)
    [[0, 1], [1, 2], [2, 3]]

    Find minimum spanning edges by Prim's algorithm

    >>> G = nx.cycle_graph(4)
    >>> G.add_edge(0, 3, weight=2)
    >>> mst = tree.minimum_spanning_edges(G, algorithm="prim", data=False)
    >>> edgelist = list(mst)
    >>> sorted(sorted(e) for e in edgelist)
    [[0, 1], [1, 2], [2, 3]]

    Notes
    -----
    For Borůvka's algorithm, each edge must have a weight attribute, and
    each edge weight must be distinct.

    For the other algorithms, if the graph edges do not have a weight
    attribute a default weight of 1 will be used.

    Modified code from David Eppstein, April 2006
    http://www.ics.uci.edu/~eppstein/PADS/

    ( is not a valid choice for an algorithm.NTr>   r&   rM   r'   r=   
ALGORITHMSKeyErrorr4   	r<   	algorithmr&   rM   r'   r=   algoerrr;   s	            r$   r   r   q  sw    h')$ ' ' 'DDDoo3&' 4	4T       
4/4c                     	 t           |         }n'# t          $ r}| d}t          |          |d}~ww xY w || d||||          S )u
  Generate edges in a maximum spanning forest of an undirected
    weighted graph.

    A maximum spanning tree is a subgraph of the graph (a tree)
    with the maximum possible sum of edge weights.  A spanning forest is a
    union of the spanning trees for each connected component of the graph.

    Parameters
    ----------
    G : undirected Graph
       An undirected graph. If `G` is connected, then the algorithm finds a
       spanning tree. Otherwise, a spanning forest is found.

    algorithm : string
       The algorithm to use when finding a maximum spanning tree. Valid
       choices are 'kruskal', 'prim', or 'boruvka'. The default is 'kruskal'.

    weight : string
       Edge data key to use for weight (default 'weight').

    keys : bool
       Whether to yield edge key in multigraphs in addition to the edge.
       If `G` is not a multigraph, this is ignored.

    data : bool, optional
       If True yield the edge data along with the edge.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.

    Returns
    -------
    edges : iterator
       An iterator over edges in a maximum spanning tree of `G`.
       Edges connecting nodes `u` and `v` are represented as tuples:
       `(u, v, k, d)` or `(u, v, k)` or `(u, v, d)` or `(u, v)`

       If `G` is a multigraph, `keys` indicates whether the edge key `k` will
       be reported in the third position in the edge tuple. `data` indicates
       whether the edge datadict `d` will appear at the end of the edge tuple.

       If `G` is not a multigraph, the tuples are `(u, v, d)` if `data` is True
       or `(u, v)` if `data` is False.

    Examples
    --------
    >>> from networkx.algorithms import tree

    Find maximum spanning edges by Kruskal's algorithm

    >>> G = nx.cycle_graph(4)
    >>> G.add_edge(0, 3, weight=2)
    >>> mst = tree.maximum_spanning_edges(G, algorithm="kruskal", data=False)
    >>> edgelist = list(mst)
    >>> sorted(sorted(e) for e in edgelist)
    [[0, 1], [0, 3], [1, 2]]

    Find maximum spanning edges by Prim's algorithm

    >>> G = nx.cycle_graph(4)
    >>> G.add_edge(0, 3, weight=2)  # assign weight 2 to edge 0-3
    >>> mst = tree.maximum_spanning_edges(G, algorithm="prim", data=False)
    >>> edgelist = list(mst)
    >>> sorted(sorted(e) for e in edgelist)
    [[0, 1], [0, 3], [2, 3]]

    Notes
    -----
    For Borůvka's algorithm, each edge must have a weight attribute, and
    each edge weight must be distinct.

    For the other algorithms, if the graph edges do not have a weight
    attribute a default weight of 1 will be used.

    Modified code from David Eppstein, April 2006
    http://www.ics.uci.edu/~eppstein/PADS/
    r~   NFr   r   r   s	            r$   r   r     sw    f')$ ' ' 'DDDoo3&' 4	5d*   r   )preserve_all_attrsreturns_graphc                    t          | ||dd|          }|                                 }|j                            | j                   |                    | j                                                   |                    |           |S )u  Returns a minimum spanning tree or forest on an undirected graph `G`.

    Parameters
    ----------
    G : undirected graph
        An undirected graph. If `G` is connected, then the algorithm finds a
        spanning tree. Otherwise, a spanning forest is found.

    weight : str
       Data key to use for edge weights.

    algorithm : string
       The algorithm to use when finding a minimum spanning tree. Valid
       choices are 'kruskal', 'prim', or 'boruvka'. The default is
       'kruskal'.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.

    Returns
    -------
    G : NetworkX Graph
       A minimum spanning tree or forest.

    Examples
    --------
    >>> G = nx.cycle_graph(4)
    >>> G.add_edge(0, 3, weight=2)
    >>> T = nx.minimum_spanning_tree(G)
    >>> sorted(T.edges(data=True))
    [(0, 1, {}), (1, 2, {}), (2, 3, {})]


    Notes
    -----
    For Borůvka's algorithm, each edge must have a weight attribute, and
    each edge weight must be distinct.

    For the other algorithms, if the graph edges do not have a weight
    attribute a default weight of 1 will be used.

    There may be more than one tree with the same minimum or maximum weight.
    See :mod:`networkx.tree.recognition` for more detailed definitions.

    Isolated nodes with self-loops are in the tree as edgeless isolated nodes.

    TrM   r'   r=   )r   	__class__graphupdateadd_nodes_fromrm   ri   add_edges_fromr<   r&   r   r=   rZ   Ts         r$   r   r   .  s    d #	9f4dz  E 	
AGNN17QW]]__%%%UHr#   rT   c           	         t          | ||dd||          }|                                 }|j                            | j                   |                    | j                                                   |                    |           |S )u  
    Find a spanning tree while respecting a partition of edges.

    Edges can be flagged as either `INCLUDED` which are required to be in the
    returned tree, `EXCLUDED`, which cannot be in the returned tree and `OPEN`.

    This is used in the SpanningTreeIterator to create new partitions following
    the algorithm of Sörensen and Janssens [1]_.

    Parameters
    ----------
    G : undirected graph
        An undirected graph.

    minimum : bool (default: True)
        Determines whether the returned tree is the minimum spanning tree of
        the partition of the maximum one.

    weight : str
        Data key to use for edge weights.

    partition : str
        The key for the edge attribute containing the partition
        data on the graph. Edges can be included, excluded or open using the
        `EdgePartition` enum.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.


    Returns
    -------
    G : NetworkX Graph
        A minimum spanning tree using all of the included edges in the graph and
        none of the excluded edges.

    References
    ----------
    .. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning
           trees in order of increasing cost, Pesquisa Operacional, 2005-08,
           Vol. 25 (2), p. 219-229,
           https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en
    T)rM   r'   r=   rT   )rd   r   r   r   r   rm   ri   r   )r<   r>   r&   rT   r=   rZ   r   s          r$   r   r   j  s    ` 	  E 	
AGNN17QW]]__%%%UHr#   c                 6   t          | ||dd|          }t          |          }|                                 }|j                            | j                   |                    | j                                                   |                    |           |S )u  Returns a maximum spanning tree or forest on an undirected graph `G`.

    Parameters
    ----------
    G : undirected graph
        An undirected graph. If `G` is connected, then the algorithm finds a
        spanning tree. Otherwise, a spanning forest is found.

    weight : str
       Data key to use for edge weights.

    algorithm : string
       The algorithm to use when finding a maximum spanning tree. Valid
       choices are 'kruskal', 'prim', or 'boruvka'. The default is
       'kruskal'.

    ignore_nan : bool (default: False)
        If a NaN is found as an edge weight normally an exception is raised.
        If `ignore_nan is True` then that edge is ignored instead.


    Returns
    -------
    G : NetworkX Graph
       A maximum spanning tree or forest.


    Examples
    --------
    >>> G = nx.cycle_graph(4)
    >>> G.add_edge(0, 3, weight=2)
    >>> T = nx.maximum_spanning_tree(G)
    >>> sorted(T.edges(data=True))
    [(0, 1, {}), (0, 3, {'weight': 2}), (1, 2, {})]


    Notes
    -----
    For Borůvka's algorithm, each edge must have a weight attribute, and
    each edge weight must be distinct.

    For the other algorithms, if the graph edges do not have a weight
    attribute a default weight of 1 will be used.

    There may be more than one tree with the same minimum or maximum weight.
    See :mod:`networkx.tree.recognition` for more detailed definitions.

    Isolated nodes with self-loops are in the tree as edgeless isolated nodes.

    Tr   )	r   listr   r   r   r   rm   ri   r   r   s         r$   r   r     s    h #	9f4dz  E KKE	AGNN17QW]]__%%%UHr#      )r)   r   )multiplicativeseedc                z    fd fd}fd}                                  dk     rt          j         j                  S t	                      d}t	                                                     t                                                     }|                    |           |D ]i\  }}	| |         |	         |         nd}
 |            \  }} |||          } ||           ||	          f}||j        v rkt          j        ||d	          } |||          }r	|
|z  |z  }n?||
z   t          j	        |          z  |z   }|t          j	        |          z  |z   }||z  }nd
}|
                    d
d          }||k    r                    ||	f           n||
z  }                    ||	f           t                                                      dz
  k    r,t          j                    }|                               |c S kt!          dt                     d          )uc  
    Sample a random spanning tree using the edges weights of `G`.

    This function supports two different methods for determining the
    probability of the graph. If ``multiplicative=True``, the probability
    is based on the product of edge weights, and if ``multiplicative=False``
    it is based on the sum of the edge weight. However, since it is
    easier to determine the total weight of all spanning trees for the
    multiplicative version, that is significantly faster and should be used if
    possible. Additionally, setting `weight` to `None` will cause a spanning tree
    to be selected with uniform probability.

    The function uses algorithm A8 in [1]_ .

    Parameters
    ----------
    G : nx.Graph
        An undirected version of the original graph.

    weight : string
        The edge key for the edge attribute holding edge weight.

    multiplicative : bool, default=True
        If `True`, the probability of each tree is the product of its edge weight
        over the sum of the product of all the spanning trees in the graph. If
        `False`, the probability is the sum of its edge weight over the sum of
        the sum of weights for all spanning trees in the graph.

    seed : integer, random_state, or None (default)
        Indicator of random number generation state.
        See :ref:`Randomness<randomness>`.

    Returns
    -------
    nx.Graph
        A spanning tree using the distribution defined by the weight of the tree.

    References
    ----------
    .. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
       Algorithms, 11 (1990), pp. 185–207
    c                 B    || vr|S  | | |                   }|| |<   |S )a  
        We can think of clusters of contracted nodes as having one
        representative in the graph. Each node which is not in merged_nodes
        is still its own representative. Since a representative can be later
        contracted, we need to recursively search though the dict to find
        the final representative, but once we know it we can use path
        compression to speed up the access of the representative for next time.

        This cannot be replaced by the standard NetworkX union_find since that
        data structure will merge nodes with less representing nodes into the
        one with more representing nodes but this function requires we merge
        them using the order that contract_edges contracts using.

        Parameters
        ----------
        merged_nodes : dict
            The dict storing the mapping from node to representative
        node
            The node whose representative we seek

        Returns
        -------
        The representative of the `node`
        r"   )merged_nodesnoderep	find_nodes      r$   r   z'random_spanning_tree.<locals>.find_node  s:    2 |##K)L,t*<==C!$LJr#   c                  V   t          j                  } t          |                                                               	          }|                     |           i }D ]B\  }} 
||          } 
||          }||k    r$t          j        | ||dd           |||<   C|| fS )a  
        For the graph `G`, remove all edges not in the set `V` and then
        contract all edges in the set `U`.

        Returns
        -------
        A copy of `G` which has had all edges not in `V` removed and all edges
        in `U` contracted.
        )incoming_graph_dataF)
self_loopscopy)r1   
MultiGraphrf   rZ   
differenceremove_edges_fromcontracted_nodes)resultedges_to_remover   rP   rQ   u_repv_repr<   UVr   s          r$   prepare_graphz+random_spanning_tree.<locals>.prepare_graph7  s     1555 fllnn--88;;  111  	( 	(DAqIlA..EIlA..E~~uUSSSS"'LV##r#   c           
         rt          | |          S |                                 dk    r@|                     |                                                                          d         S d}|                     |          D ]9\  }}}||t          j         t          j        | ||fd          d          z  z  }:|S )	a^  
        Find the sum of weights of the spanning trees of `G` using the
        appropriate `method`.

        This is easy if the chosen method is 'multiplicative', since we can
        use Kirchhoff's Tree Matrix Theorem directly. However, with the
        'additive' method, this process is slightly more complex and less
        computationally efficient as we have to find the number of spanning
        trees which contain each possible edge in the graph.

        Parameters
        ----------
        G : NetworkX Graph
            The graph to find the total weight of all spanning trees on.

        weight : string
            The key for the weight edge attribute of the graph.

        Returns
        -------
        float
            The sum of either the multiplicative or additive weight for all
            spanning trees in the graph.
        r&   r   r.   r   r   FrG   r   N)r   number_of_edgesrZ   __iter____next__r1   contracted_edge)r<   r&   totalrP   rQ   rt   r   s         r$   spanning_tree_total_weightz8random_spanning_tree.<locals>.spanning_tree_total_weightb  s    2  	+Af====   ""a''wwFw++4466??AA!DD  wwFw33  GAq!Q!<*1Aq6eLLL#" " "  EE r#   r   r   Nr   Fr   g        g      ?zSomething went wrong! Only z edges in the spanning tree!)number_of_nodesr1   empty_graphrm   rf   rZ   r   shuffler   r   uniformremoverk   lenGraphr   	Exception)r<   r&   r   r   r   r   st_cached_valueshuffled_edgesrP   rQ   e_weightnode_map
prepared_GG_total_tree_weightrep_edgeprepared_G_eG_e_total_tree_weight	threshold	numeratordenominatorzspanning_treer   r   r   s   ` `                   @@@r$   r   r     s   \    @)$ )$ )$ )$ )$ )$ )$ )$V2 2 2 2 2h 	Q~ag&&&AOAGGIIA!''))__NLL    *! *!1&,&81Q476??a,}*88VLL Ih**IIh,B,BC z'''-e  L %?$>|V$T$T! 
4$'<<?RR		,x72;V < < )*	 $b&A*&M&MM)*  &3		ILLc""y==HHaV x'OEE1a&MMMq66Q&&((1,,,HJJM((+++     - V#a&&VVV
W
WWr#   c                   v    e Zd ZdZ ed           G d d                      ZddZd	 Zd
 Zd Z	d Z
d ZdS )r   u  
    Iterate over all spanning trees of a graph in either increasing or
    decreasing cost.

    Notes
    -----
    This iterator uses the partition scheme from [1]_ (included edges,
    excluded edges and open edges) as well as a modified Kruskal's Algorithm
    to generate minimum spanning trees which respect the partition of edges.
    For spanning trees with the same weight, ties are broken arbitrarily.

    References
    ----------
    .. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning
           trees in order of increasing cost, Pesquisa Operacional, 2005-08,
           Vol. 25 (2), p. 219-229,
           https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en
    T)orderc                   F    e Zd ZU dZeed<    ed          Zeed<   d Z	dS )SpanningTreeIterator.Partitionz
        This dataclass represents a partition and stores a dict with the edge
        data and the weight of the minimum spanning tree of the partition dict.
        
mst_weightF)comparepartition_dictc                 p    t                               | j        | j                                                  S rA   )r   	Partitionr   r   r   )selfs    r$   __copy__z'SpanningTreeIterator.Partition.__copy__  s0    '11!4!9!9!;!;  r#   N)
r   r   r   r   r0   __annotations__r   r   dictr   r"   r#   r$   r   r     sZ         	 	
 $uU333333	 	 	 	 	r#   r   r&   Fc                     |                                 | _        d| j        _        || _        || _        || _        d| _        dS )ao  
        Initialize the iterator

        Parameters
        ----------
        G : nx.Graph
            The directed graph which we need to iterate trees over

        weight : String, default = "weight"
            The edge attribute used to store the weight of the edge

        minimum : bool, default = True
            Return the trees in increasing order while true and decreasing order
            while false.

        ignore_nan : bool, default = False
            If a NaN is found as an edge weight normally an exception is raised.
            If `ignore_nan is True` then that edge is ignored instead.
        Nz;SpanningTreeIterators super secret partition attribute name)r   r<   __networkx_cache__r&   r>   r=   partition_key)r   r<   r&   r>   r=   s        r$   __init__zSpanningTreeIterator.__init__  sF    ( $(!$ J 	r#   c                 Z   t                      | _        |                     | j                   t	          | j        | j        | j        | j        | j                  	                    | j                  }| j        
                    |                     | j        r|n| i                      | S )zu
        Returns
        -------
        SpanningTreeIterator
            The iterator object for this graph
        r   )r   partition_queue_clear_partitionr<   r   r>   r&   r   r=   sizeputr   )r   r   s     r$   r   zSpanningTreeIterator.__iter__  s      -df%%%,FDL$+t/A4?
 

$dk$
"
" 	 	  NNF::J;KK	
 	
 	
 r#   c                 X   | j                                         r| `| ` t          | j                                         }|                     |           t          | j        | j        | j        | j	        | j
                  }|                     ||           |                     |           |S )z
        Returns
        -------
        (multi)Graph
            The spanning tree of next greatest weight, which ties broken
            arbitrarily.
        )r   emptyr<   StopIterationr3   _write_partitionr   r>   r&   r   r=   
_partitionr   )r   rT   	next_trees      r$   r   zSpanningTreeIterator.__next__"  s     %%'' 	 ,(,,..	i(((+FDL$+t/A4?
 
	 		9---i(((r#   c                    |                      d|j                                                  }|                      d|j                                                  }|j        D ]}||j        vrt          j        |j        |<   t          j        |j        |<   |                     |           t          | j	        | j
        | j        | j        | j                  }|                    | j                  }t          j        |          r=| j
        r|n| |_        | j                            |                                           |j                                        |_        dS )a|  
        Create new partitions based of the minimum spanning tree of the
        current minimum partition.

        Parameters
        ----------
        partition : Partition
            The Partition instance used to generate the current minimum spanning
            tree.
        partition_tree : nx.Graph
            The minimum spanning tree of the input partition.
        r   r   N)r   r   r   rZ   r   r!   r    r   r   r<   r>   r&   r   r=   r   r1   is_connectedr   r   r   r   )r   rT   partition_treep1p2r9   p1_mstp1_mst_weights           r$   r   zSpanningTreeIterator._partition8  sC    ^^Ay7<<>>??^^Ay7<<>>??% 	= 	=A	000'4'=!!$'4'=!!$%%b)))0FLK&O  !'4; ? ??6** <59\$UMM~BM(,,R[[]];;;$&$5$:$:$<$<!'	= 	=r#   c                 "   |j         }| j        }| j        }|                                r|                    dd          n|                    d          }|D ]5^ }}|                    t          |          t          j                  ||<   6dS )a  
        Writes the desired partition into the graph to calculate the minimum
        spanning tree.

        Parameters
        ----------
        partition : Partition
            A Partition dataclass describing a partition on the edges of the
            graph.
        TrV   r.   N)	r   r   r<   rY   rZ   r3   tupler   r   )r   rT   r   r   r<   rZ   r9   rR   s           r$   r   z%SpanningTreeIterator._write_partition]  s     #1*F ./__->->VAGGDG)))AGGQUGDVDV 	  	P 	PEQ-11%((M<NOOAm	P 	Pr#   c                     | j         }|                                r|                    dd          n|                    d          }|D ]^ }}||v r||= dS )z7
        Removes partition data from the graph
        TrV   r.   N)r   rY   rZ   )r   r<   r   rZ   r9   rR   s         r$   r   z%SpanningTreeIterator._clear_partitions  sz     *-.__->->VAGGDG)))AGGQUGDVDV 	  	% 	%EQ!!m$	% 	%r#   N)r&   TF)r   r   r   r   r   r   r   r   r   r   r   r   r"   r#   r$   r   r     s         & YT       
 
 
 
<  &  ,#= #= #=JP P P,
% 
% 
% 
% 
%r#   r   )r(   )rootr&   c                    ddl }t          |           dk    rt          j        d          t          j        |           sqt          j        |           sdS t          j        | |                                          }t          |j	        
                    |ddddf                             S t          j        d          | vrt          j        d          t          j        |           sdS gfd| D             z   }t          j        | ||	          }|                    |                    d
                    }||z
  }t          |j	        
                    |ddddf                             S )ug  Returns the number of spanning trees in `G`.

    A spanning tree for an undirected graph is a tree that connects
    all nodes in the graph. For a directed graph, the analog of a
    spanning tree is called a (spanning) arborescence. The arborescence
    includes a unique directed path from the `root` node to each other node.
    The graph must be weakly connected, and the root must be a node
    that includes all nodes as successors [3]_. Note that to avoid
    discussing sink-roots and reverse-arborescences, we have reversed
    the edge orientation from [3]_ and use the in-degree laplacian.

    This function (when `weight` is `None`) returns the number of
    spanning trees for an undirected graph and the number of
    arborescences from a single root node for a directed graph.
    When `weight` is the name of an edge attribute which holds the
    weight value of each edge, the function returns the sum over
    all trees of the multiplicative weight of each tree. That is,
    the weight of the tree is the product of its edge weights.

    Kirchoff's Tree Matrix Theorem states that any cofactor of the
    Laplacian matrix of a graph is the number of spanning trees in the
    graph. (Here we use cofactors for a diagonal entry so that the
    cofactor becomes the determinant of the matrix with one row
    and its matching column removed.) For a weighted Laplacian matrix,
    the cofactor is the sum across all spanning trees of the
    multiplicative weight of each tree. That is, the weight of each
    tree is the product of its edge weights. The theorem is also
    known as Kirchhoff's theorem [1]_ and the Matrix-Tree theorem [2]_.

    For directed graphs, a similar theorem (Tutte's Theorem) holds with
    the cofactor chosen to be the one with row and column removed that
    correspond to the root. The cofactor is the number of arborescences
    with the specified node as root. And the weighted version gives the
    sum of the arborescence weights with root `root`. The arborescence
    weight is the product of its edge weights.

    Parameters
    ----------
    G : NetworkX graph

    root : node
       A node in the directed graph `G` that has all nodes as descendants.
       (This is ignored for undirected graphs.)

    weight : string or None, optional (default=None)
        The name of the edge attribute holding the edge weight.
        If `None`, then each edge is assumed to have a weight of 1.

    Returns
    -------
    Number
        Undirected graphs:
            The number of spanning trees of the graph `G`.
            Or the sum of all spanning tree weights of the graph `G`
            where the weight of a tree is the product of its edge weights.
        Directed graphs:
            The number of arborescences of `G` rooted at node `root`.
            Or the sum of all arborescence weights of the graph `G` with
            specified root where the weight of an arborescence is the product
            of its edge weights.

    Raises
    ------
    NetworkXPointlessConcept
        If `G` does not contain any nodes.

    NetworkXError
        If the graph `G` is directed and the root node
        is not specified or is not in G.

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> round(nx.number_of_spanning_trees(G))
    125

    >>> G = nx.Graph()
    >>> G.add_edge(1, 2, weight=2)
    >>> G.add_edge(1, 3, weight=1)
    >>> G.add_edge(2, 3, weight=1)
    >>> round(nx.number_of_spanning_trees(G, weight="weight"))
    5

    Notes
    -----
    Self-loops are excluded. Multi-edges are contracted in one edge
    equal to the sum of the weights.

    References
    ----------
    .. [1] Wikipedia
       "Kirchhoff's theorem."
       https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem
    .. [2] Kirchhoff, G. R.
        Über die Auflösung der Gleichungen, auf welche man
        bei der Untersuchung der linearen Vertheilung
        Galvanischer Ströme geführt wird
        Annalen der Physik und Chemie, vol. 72, pp. 497-508, 1847.
    .. [3] Margoliash, J.
        "Matrix-Tree Theorem for Directed Graphs"
        https://www.math.uchicago.edu/~may/VIGRE/VIGRE2010/REUPapers/Margoliash.pdf
    r   Nz'Graph G must contain at least one node.r   r   z0Input `root` must be provided when G is directedz$The node root is not in the graph G.c                      g | ]
}|k    |S r"   r"   )rC   nr   s     r$   rH   z,number_of_spanning_trees.<locals>.<listcomp>  s    333qdr#   )nodelistr&   )axis)numpyr   r1   NetworkXPointlessConceptis_directedr   laplacian_matrixtoarrayr0   linalgdetNetworkXErroris_weakly_connectedadjacency_matrixdiagsum)r<   r   r&   npG_laplacianr   ADs    `      r$   r   r     s   P 
1vv{{)*STTT >! 9q!! 	1)!F;;;CCEERY]];qrr122v#677888 |QRRR1}}EFFF!!$$ q v3333A3333H
A@@@A
1Aa%K {122qrr6233444r#   )Tr&   FTF)r&   TTFN)r&   TTF)rz   r&   TTF)r&   rz   F)Tr&   rT   FrA   )&r   dataclassesr   r   enumr   heapqr   r   	itertoolsr   mathr	   operatorr
   queuer   networkxr1   networkx.utilsr   r   r   __all__r   _dispatchablerS   rd   rx   r   r   r   r   r   r   r   r   r   r"   r#   r$   <module>r     s   
 ) ( ( ( ( ( ( (       # # # # # # # #                             J J J J J J J J J J
 
 
    D    \""X6BBBHM]# ]# ]# CB #"]#@ T22   TXk% k% k% k%\ X6BBBeH eH eH CBeHR !! 	 
 Z  X6BBBNSZ Z Z CB ! Zz Z  X6BBBNSY Y Y CB ! Yx T>>>8 8 8 ?>8v T>>>HM< < < ?><~ T>>>; ; ; ?>;| d$???`X4d `X `X `X `X @? `XFo% o% o% o% o% o% o% o%d X&&&(,T B5 B5 B5 B5 '&B5 B5 B5r#   