
    h<                     *   S r SSKJrJr  SSKJr  SSKJrJr  SSK	J
r
  SSKJr  SSKJr  SSKJr  SS	KrSS
KJrJrJr  / SQr " S S\5      r\" S5      \R2                  " SSS9 S(S j5       5       r\R2                  " S	S	S.SS9 S)S j5       r\R2                  " SSS9S*S j5       r\\\\S.r\" S5      \R2                  " SSS9 S+S j5       5       r\" S5      \R2                  " SSS9 S+S j5       5       r\R2                  " SSS9S,S j5       r \R2                  " SSS9 S-S j5       r!\R2                  " SSS9S,S j5       r"\" S5      \R2                  " SSS 9S.SS	S!.S" jj5       5       r# " S# S$5      r$\R2                  " SS%9S	S	S&.S' j5       r%g	)/z=
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                   $    \ rS rSrSrSrSrSrSrg)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____firstlineno____doc__OPENINCLUDEDEXCLUDED__static_attributes__r       N/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/tree/mst.pyr   r      s     DHHr&   r   
multigraphweightdata)
edge_attrspreserve_edge_attrsTc              #     ^ ^^^^#    [        T 5      nU UUU4S jmU4S jUR                  5        5       nU Vs/ s H	  oc  M  UPM     nnU(       av  U4S jUR                  5        5       nU Vs/ s H	  oc  M  UPM     nnU H6  u  pnXi   Xj   :w  d  M  U(       a  XU4v   OX4v   UR                  X5        M8     U(       a  Mu  ggs  snf s  snf 7f)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                 
  > T	(       a  SOSn[        S5      nSn[        R                  " TU SS9 HO  nUS   R                  T
S5      U-  n[	        U5      (       a  T(       a  M4  SU 3n[        U5      eXR:  d  MK  UnUnMQ     U$ )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_edge$boruvka_mst_edges.<locals>.best_edgeS   s     qe!!!YT:A261%,BRyy:1#> o%z ; r&   c              3   4   >#    U  H  nT" U5      v   M     g 7fNr   .0r8   rB   s     r'   	<genexpr>$boruvka_mst_edges.<locals>.<genexpr>k   s     I8H9)I&&8H   Nc              3   4   >#    U  H  nT" U5      v   M     g 7frE   r   rF   s     r'   rH   rI      s     M<Lyi	**<LrJ   )r   to_setsunion)r?   rA   r)   keysr*   r@   forest
best_edgesedgeuvdrB   s   ```  `      @r'   boruvka_mst_edgesrU   -   s     H q\F 0 J8HIJ#-B:4$:JB   NFNN<LM
'1Fztdz
F "GA!yFI%'M$JQ" "/ * C( Gs4   3CC
C

'C1C;CC/CC)r)   	partitionc              #     #    [        5       nU R                  5       (       a  U R                  SSS9nOU R                  SS9n / n	/ n
U H  nUS   nUR                  US5      n[	        U5      (       a  U(       a  M3  [        SU 35      eU4U-   nUR                  U5      [        R                  :X  a  U	R                  U5        M}  UR                  U5      [        R                  :X  a  M  U
R                  U5        M     U(       a  [        U
[        S5      S9nO[        U
[        S5      SS	9nU	R                  U5        U	nA
AA	U R                  5       (       ad  U H]  u  nnnnnUU   UU   :w  d  M  U(       a  U(       a	  UUUU4v   OUUU4v   OU(       a  UUU4v   OUU4v   UR                  UU5        M_     g
U H=  u  nnnnUU   UU   :w  d  M  U(       a  UUU4v   OUU4v   UR                  UU5        M?     g
7f)ah  
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rN   r*   r1   r/   r   r2   r   )key)rY   reverseN)r   is_multigraphedgesr6   r	   r7   r   r#   appendr$   sortedr
   extendrM   )r?   rA   r)   rN   r*   r@   rV   subtreesr\   included_edges
open_edgesr<   rT   r=   rQ   sorted_open_edgessorted_edgesrR   rS   ks                       r'   kruskal_mst_edgesrf      s    \ {HT-T" NJbEUU6199A!EFFuqy55}555!!$'UU9!7!77d#   "::a=A"::a=$O +,!L%~ 	*NB1a{hqk)Aqj(AgAgd
q!$ + (KB1a{hqk)Q'MQ$Jq!$ (s   E-H3AH,Hc              #     #    U R                  5       n[        n[        n[        U 5      n	[	        5       n
U(       a  SOSnU	(       Ga  U	R                  5       n/ nU1nU(       a  U R                  U   R                  5        Hx  u  nnUR                  5        H^  u  nnUR                  US5      U-  n[        U5      (       a  U(       a  M4  SXUU4 3n[        U5      eU" UU[        U
5      XUU45        M`     Mz     O}U R                  U   R                  5        H\  u  nnUR                  US5      U-  n[        U5      (       a  U(       a  M4  SXU4 3n[        U5      eU" UU[        U
5      XU45        M^     U	(       Ga  U(       Ga  U(       a  U" U5      u  nnpnnOU" U5      u  nnpnX;   d  X;  a  M?  U(       a  U(       a  U(       a  XWU4v   OXW4v   OU(       a  XU4v   OX4v   UR                  U5        U	R                  U5        U(       a  U R                  U   R                  5        H  u  nnUU;   a  M  UR                  5        H`  u  nnUR                  US5      U-  n[        U5      (       a  U(       a  M4  SUUUU4 3n[        U5      eU" UU[        U
5      UUUU45        Mb     M     OU R                  U   R                  5        Hf  u  nnUU;   a  M  UR                  US5      U-  n[        U5      (       a  U(       a  M<  SUUU4 3n[        U5      eU" UU[        U
5      UUU45        Mh     U	(       a
  U(       a  GM  U	(       a  GM  gg7f)aE  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/   r2   N)r[   r   r   setr   popadjitemsr6   r	   r7   nextadddiscard)r?   rA   r)   rN   r*   r@   r[   pushri   nodescr9   rR   frontiervisitedrS   keydictre   rT   r=   r>   W_wk2d2
new_weights                              r'   prim_mst_edgesr{      s    : OO%MD
CFEA1RD
IIK#eeAhnn.
7#MMODAqvq)D0BRyy%$ BA!Q<.Q(o-BQq!#<= , / a(1UU61%,99! >aykJC$S/)XDGQ156 ) #&x= 1aAq #H1aA|q~1*$'M'M$JKKNMM!"#%%(.."2JAwG| ")--/B%'VVFA%6%=
 ,,) ($F1bRT~FV"WC",S/1X
DGQ2r'JK #2 #3 UU1X^^-EArG| !#!2T!9JZ((%$ BAq":,O(o-JQAr#BC .E / %s   MM!M!M!)boruvkau   borůvkakruskalprimdirectedc           	      n     [         U   nU" U SX#XES9$ ! [         a  nU S3n[        U5      UeSnAff = f)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rA   r)   rN   r*   r@   
ALGORITHMSKeyErrorr7   	r?   	algorithmr)   rN   r*   r@   algoerrr>   s	            r'   r   r   s  sU    h')$
 	4 	  'CDo3&'   	 
4/4c           	      n     [         U   nU" U SX#XES9$ ! [         a  nU S3n[        U5      UeSnAff = f)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     sU    f')$
 	5 	  'CDo3&'r   )preserve_all_attrsreturns_graphc           	          [        XUSSUS9nU R                  5       nUR                  R                  U R                  5        UR	                  U R
                  R                  5       5        UR                  U5        U$ )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rN   r*   r@   )r   	__class__graphupdateadd_nodes_fromrp   rk   add_edges_fromr?   r)   r   r@   r\   Ts         r'   r   r   0  sf    d #	f4dzE 	
AGGNN177QWW]]_%UHr&   c           
         [        U UUSSUUS9nU R                  5       nUR                  R                  U R                  5        UR	                  U R
                  R                  5       5        UR                  U5        U$ )uV  
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)rN   r*   r@   rV   )rf   r   r   r   r   rp   rk   r   )r?   rA   r)   rV   r@   r\   r   s          r'   r   r   l  sp    ` 	E 	
AGGNN177QWW]]_%UHr&   c           	         [        XUSSUS9n[        U5      nU R                  5       nUR                  R	                  U R                  5        UR                  U R                  R                  5       5        UR                  U5        U$ )uG  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   rp   rk   r   r   s         r'   r   r     so    h #	f4dzE KE	AGGNN177QWW]]_%UHr&      )r,   r   )multiplicativeseedc                  ^ ^^^^ U4S jmU UUU4S jnU4S jnT R                  5       S:  a   [        R                  " T R                  5      $ [	        5       mSn[	        T R                  5       5      m[        T R                  5       5      nUR                  U5        U GH@  u  pUb  T U   U	   U   OSn
U" 5       u  pU" X5      nT" X5      T" X5      4nXR
                  ;   am  [        R                  " XSS9nU" X5      nT(       a	  U
U-  U-  nOBXj-   [        R                  " U5      -  U-   nU[        R                  " U5      -  U-   nUU-  nOS	nUR                  S	S
5      nUU:  a  TR                  X45        OXj-  nTR                  X45        [        T5      T R                  5       S-
  :X  d  GM  [        R                  " 5       nUR                  T5        Us  $    [!        S[        T5       S35      e)u  
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                 4   > X;  a  U$ T" X U   5      nX U'   U$ )ac  
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   'random_spanning_tree.<locals>.find_node  s,    2 #KLt*<=C!$Jr&   c            	      "  > [         R                  " TS9n [        U R                  5       5      R	                  T	5      nU R                  U5        0 nT H7  u  p4T
" X#5      nT
" X$5      nXV:X  a  M  [         R                  " XUSSS9  XRU'   M9     X 4$ )z
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)r4   
MultiGraphrh   r\   
differenceremove_edges_fromcontracted_nodes)resultedges_to_remover   rR   rS   u_repv_repr?   UVr   s          r'   prepare_graph+random_spanning_tree.<locals>.prepare_graph9  s     15 flln-88;  1 DAl.El.E~uUS"'  ##r&   c                 ^  > T(       a  [         R                  " X5      $ U R                  5       S:X  a.  U R                  US9R	                  5       R                  5       S   $ SnU R                  US9 H7  u  p4nX%[         R                  " [         R                  " XU4SS9S5      -  -  nM9     U$ )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   r1   r   r   FrQ   r   N)r4   total_spanning_tree_weightnumber_of_edgesr\   __iter____next__contracted_edge)r?   r)   totalrR   rS   rw   r   s         r'   spanning_tree_total_weight8random_spanning_tree.<locals>.spanning_tree_total_weightd  s    2 00;;   "a'wwFw+446??A!DD  wwFw3GA!!>!>**1q6eLd"  E  4 r&   r   r   r   Fr   g        g      ?zSomething went wrong! Only z edges in the spanning tree!)number_of_nodesr4   empty_graphrp   rh   r\   r   shuffler   r   uniformremoverm   lenGraphr   	Exception)r?   r)   r   r   r   r   st_cached_valueshuffled_edgesrR   rS   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1f 	Q~~agg&&AOAGGIA!'')_NLL &,&81Q476?a,8L h*Ih,BC '''--eL %?|$T!$'<<?RR	 $.11,?@BWX	 $b&C&CJ&OO)*  &3	ILLc"y=HHaV 'OEE1&Mq6Q&&(1,,HHJM((+  U V 1#a&9UV
WWr&   c                   f    \ rS rSrSr\" SS9 " S S5      5       rSS jrS rS	 r	S
 r
S rS rSrg)r   i  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                   @    \ rS rSr% Sr\\S'   \" SS9r\	\S'   S r
Srg	)
SpanningTreeIterator.Partitioni  z
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                 r    [         R                  U R                  U R                  R	                  5       5      $ rE   )r   	Partitionr   r   r   )selfs    r'   __copy__'SpanningTreeIterator.Partition.__copy__  s-    '11!4!4!9!9!; r&   r   N)r   r   r   r    r!   r3   __annotations__r   r   dictr   r%   r   r&   r'   r   r     s#    	
 $U33	r&   r   c                     UR                  5       U l        SU R                  l        X l        X0l        X@l        SU l        g)a  
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)   rA   r@   partition_key)r   r?   r)   rA   r@   s        r'   __init__SpanningTreeIterator.__init__  s:    ( $(!$ J 	r&   c                    [        5       U l        U R                  U R                  5        [	        U R                  U R
                  U R                  U R                  U R                  5      R                  U R                  S9nU R                  R                  U R                  U R
                  (       a  UOU* 0 5      5        U $ )zM
Returns
-------
SpanningTreeIterator
    The iterator object for this graph
r)   )r   partition_queue_clear_partitionr?   r   rA   r)   r   r@   sizeputr   )r   r   s     r'   r   SpanningTreeIterator.__iter__  s      -dff%,FFDLL$++t/A/A4??

$dkk$
" 	 	  NN:J;K	
 r&   c                 t   U R                   R                  5       (       a
  U ?U ? [        eU R                   R	                  5       nU R                  U5        [        U R                  U R                  U R                  U R                  U R                  5      nU R                  X5        U R                  U5        U$ )zp
Returns
-------
(multi)Graph
    The spanning tree of next greatest weight, which ties broken
    arbitrarily.
)r   emptyr?   StopIterationr6   _write_partitionr   rA   r)   r   r@   
_partitionr   )r   rV   	next_trees      r'   r   SpanningTreeIterator.__next__#  s     %%'',((,,.	i(+FFDLL$++t/A/A4??
	 		-i(r&   c                 >   U R                  SUR                  R                  5       5      nU R                  SUR                  R                  5       5      nUR                   GH8  nXQR                  ;  d  M  [        R
                  UR                  U'   [        R                  UR                  U'   U R                  U5        [        U R                  U R                  U R                  U R                  U R                  5      nUR                  U R                  S9n[        R                   " U5      (       aD  U R                  (       a  UOU* Ul        U R$                  R'                  UR)                  5       5        UR                  R                  5       Ul        GM;     g)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   r\   r   r$   r#   r   r   r?   rA   r)   r   r@   r   r4   is_connectedr   r   r   r   )r   rV   partition_treep1p2r<   p1_mstp1_mst_weights           r'   r   SpanningTreeIterator._partition9  s.    ^^Ay77<<>?^^Ay77<<>?%%A000'4'='=!!!$'4'='=!!!$%%b)0FFLLKK&&OO !'4;; ???6**59\\M~BM((,,R[[];$&$5$5$:$:$<!' &r&   c                     UR                   nU R                  nU R                  nUR                  5       (       a  UR	                  SSS9OUR	                  SS9nU H0  Gt pgUR                  [        U5      [        R                  5      Xs'   M2     g)z
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.
TrX   r1   N)	r   r   r?   r[   r\   r6   tupler   r"   )r   rV   r   r   r?   r\   r<   rT   s           r'   r   %SpanningTreeIterator._write_partition^  s     #11**FF ./__->->AGGDG)AGGQUGDV 	 EQ-11%(M<N<NOA r&   c                     U R                   nUR                  5       (       a  UR                  SSS9OUR                  SS9nU H  Gt pEX%;   d  M  XR	 M     g)z'
Removes partition data from the graph
TrX   r1   N)r   r[   r\   )r   r?   r   r\   r<   rT   s         r'   r   %SpanningTreeIterator._clear_partitiont  sX     **-.__->->AGGDG)AGGQUGDV 	 EQ!$ r&   )r?   r@   rA   r   r   r)   N)r)   TF)r   r   r   r    r!   r   r   r   r   r   r   r   r   r%   r   r&   r'   r   r     sE    & T  
<&,#=JP,
%r&   r   )r+   )rootr)   c                   SSK n[        U 5      S:X  a  [        R                  " S5      e[        R                  " U 5      (       dk  [        R
                  " U 5      (       d  g[        R                  " XS9R                  5       n[        UR                  R                  USS2SS24   5      5      $ Uc  [        R                  " S5      eX;  a  [        R                  " S5      e[        R                  " U 5      (       d  gU/U  Vs/ s H  oUU:w  d  M
  UPM     sn-   n[        R                  " XUS9nUR                  UR                  SS	95      nX-
  n[        UR                  R                  USS2SS24   5      5      $ s  snf )
u  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.)nodelistr)   )axis)numpyr   r4   NetworkXPointlessConceptis_directedr   laplacian_matrixtoarrayr3   linalgdetNetworkXErroris_weakly_connectedadjacency_matrixdiagsum)	r?   r  r)   npG_laplaciannr  ADs	            r'   r   r     sH   P 
1v{))*STT >>!q!!))!;CCERYY]];qr12v#6788 |QRR}EFF!!!$$ vA3AqdA33H
A@A
1A%K {12qr62344 4s   	FF)Tr)   FTF)r)   TTFN)r)   TTF)r}   r)   TTF)r)   r}   F)Tr)   rV   FrE   )&r!   dataclassesr   r   enumr   heapqr   r   	itertoolsr   mathr	   operatorr
   queuer   networkxr4   networkx.utilsr   r   r   __all__r   _dispatchablerU   rf   r{   r   r   r   r   r   r   r   r   r   r   r&   r'   <module>r"     s&  
 )  #      J J
D  \"X6BHM]# C #]#@ T2 TXk%k%\ X6BgD CgDV !! 	
 Z X6BNSZ C !Zz Z X6BNSY C !Yx T>8 ?8v T>HM< ?<~ T>; ?;| d$?_X4d _X @ _XDo% o%d X&(,T B5 'B5r&   