
    h                        S r SSKrSSKrSSKJrJr  SSKrSSK	J
r
Jr  / SQr\
" S5      \
" S5      \R                  S 5       5       5       r\
" S5      \
" S5      \R                  S	 5       5       5       r\
" S5      \
" S5      \R                  SS
 j5       5       5       r\R                  S S j5       r\
" S5      \
" S5      \R                  SS j5       5       5       r\
" S5      \
" S5      \R                  S!S j5       5       5       rS rS!S jr\" SS5      rS r\R                  S 5       r\R                  S"S j5       r\R                  S 5       r\R                  S S j5       rS r\R                  " SS9S 5       r\R                  S 5       rS r\
" S5      \
" S5      \" S5      \R                  S#S j5       5       5       5       r g)$a  
Algorithms for finding k-edge-augmentations

A k-edge-augmentation is a set of edges, that once added to a graph, ensures
that the graph is k-edge-connected; i.e. the graph cannot be disconnected
unless k or more edges are removed.  Typically, the goal is to find the
augmentation with minimum weight.  In general, it is not guaranteed that a
k-edge-augmentation exists.

See Also
--------
:mod:`edge_kcomponents` : algorithms for finding k-edge-connected components
:mod:`connectivity` : algorithms for determining edge connectivity.
    N)defaultdict
namedtuple)not_implemented_forpy_random_state)k_edge_augmentationis_k_edge_connectedis_locally_k_edge_connecteddirected
multigraphc                   ^ TS:  a  [        ST 35      eU R                  5       TS-   :  a  g[        U4S jU R                  5        5       5      (       a  gTS:X  a  [        R
                  " U 5      $ TS:X  a8  [        R
                  " U 5      =(       a    [        R                  " U 5      (       + $ [        R                  " U TS9T:  $ )a  Tests to see if a graph is k-edge-connected.

Is it impossible to disconnect the graph by removing fewer than k edges?
If so, then G is k-edge-connected.

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

k : integer
    edge connectivity to test for

Returns
-------
boolean
    True if G is k-edge-connected.

See Also
--------
:func:`is_locally_k_edge_connected`

Examples
--------
>>> G = nx.barbell_graph(10, 0)
>>> nx.is_k_edge_connected(G, k=1)
True
>>> nx.is_k_edge_connected(G, k=2)
False
   k must be positive, not Fc              3   2   >#    U  H  u  pUT:  v   M     g 7fN ).0ndks      d/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/connectivity/edge_augmentation.py	<genexpr>&is_k_edge_connected.<locals>.<genexpr>A   s     *ztqQUzs      cutoff)
ValueErrornumber_of_nodesanydegreenxis_connectedhas_bridgesedge_connectivity)Gr   s    `r   r   r      s    D 	1u3A3788QU"	*qxxz*	*	* 6??1%%!V??1%?bnnQ.?*??''!499    c                     US:  a  [        SU 35      eU R                  U5      U:  d  U R                  U5      U:  a  gUS:X  a  [        R                  " XU5      $ [        R                  R                  XX#S9nXC:  $ )a  Tests to see if an edge in a graph is locally k-edge-connected.

Is it impossible to disconnect s and t by removing fewer than k edges?
If so, then s and t are locally k-edge-connected in G.

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

s : node
    Source node

t : node
    Target node

k : integer
    local edge connectivity for nodes s and t

Returns
-------
boolean
    True if s and t are locally k-edge-connected in G.

See Also
--------
:func:`is_k_edge_connected`

Examples
--------
>>> from networkx.algorithms.connectivity import is_locally_k_edge_connected
>>> G = nx.barbell_graph(10, 0)
>>> is_locally_k_edge_connected(G, 5, 15, k=1)
True
>>> is_locally_k_edge_connected(G, 5, 15, k=2)
False
>>> is_locally_k_edge_connected(G, 1, 5, k=2)
True
r   r   Fr   )r   r   r    has_pathconnectivitylocal_edge_connectivity)r$   str   localks        r   r	   r	   M   s|    V 	1u3A3788 	xx{Q!((1+/ 6;;qQ''__<<Q1<OF;r%   c              #   D  #     US::  a  [        SU 35      eU R                  5       US-   :  a"  SU SUS-    S3n[        R                  " U5      eUbC  [	        U5      S:X  a4  [        R
                  " X5      (       d  [        R                  " S5      e/ nO-US:X  a  [        XX4S	9nOUS
:X  a  [        XUS9nO[        XX#SS9n[        U5       Sh  vN   g N! [        R                   a/    U(       a&  Uc  [        U 5      nO
[        XX#S9nU Sh  vN     ge f = f7f)a  Finds set of edges to k-edge-connect G.

Adding edges from the augmentation to G make it impossible to disconnect G
unless k or more edges are removed. This function uses the most efficient
function available (depending on the value of k and if the problem is
weighted or unweighted) to search for a minimum weight subset of available
edges that k-edge-connects G. In general, finding a k-edge-augmentation is
NP-hard, so solutions are not guaranteed to be minimal. Furthermore, a
k-edge-augmentation may not exist.

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

k : integer
    Desired edge connectivity

avail : dict or a set of 2 or 3 tuples
    The available edges that can be used in the augmentation.

    If unspecified, then all edges in the complement of G are available.
    Otherwise, each item is an available edge (with an optional weight).

    In the unweighted case, each item is an edge ``(u, v)``.

    In the weighted case, each item is a 3-tuple ``(u, v, d)`` or a dict
    with items ``(u, v): d``.  The third item, ``d``, can be a dictionary
    or a real number.  If ``d`` is a dictionary ``d[weight]``
    correspondings to the weight.

weight : string
    key to use to find weights if ``avail`` is a set of 3-tuples where the
    third item in each tuple is a dictionary.

partial : boolean
    If partial is True and no feasible k-edge-augmentation exists, then all
    a partial k-edge-augmentation is generated. Adding the edges in a
    partial augmentation to G, minimizes the number of k-edge-connected
    components and maximizes the edge connectivity between those
    components. For details, see :func:`partial_k_edge_augmentation`.

Yields
------
edge : tuple
    Edges that, once added to G, would cause G to become k-edge-connected.
    If partial is False, an error is raised if this is not possible.
    Otherwise, generated edges form a partial augmentation, which
    k-edge-connects any part of G where it is possible, and maximally
    connects the remaining parts.

Raises
------
NetworkXUnfeasible
    If partial is False and no k-edge-augmentation exists.

NetworkXNotImplemented
    If the input graph is directed or a multigraph.

ValueError:
    If k is less than 1

Notes
-----
When k=1 this returns an optimal solution.

When k=2 and ``avail`` is None, this returns an optimal solution.
Otherwise when k=2, this returns a 2-approximation of the optimal solution.

For k>3, this problem is NP-hard and this uses a randomized algorithm that
    produces a feasible solution, but provides no guarantees on the
    solution weight.

Examples
--------
>>> # Unweighted cases
>>> G = nx.path_graph((1, 2, 3, 4))
>>> G.add_node(5)
>>> sorted(nx.k_edge_augmentation(G, k=1))
[(1, 5)]
>>> sorted(nx.k_edge_augmentation(G, k=2))
[(1, 5), (5, 4)]
>>> sorted(nx.k_edge_augmentation(G, k=3))
[(1, 4), (1, 5), (2, 5), (3, 5), (4, 5)]
>>> complement = list(nx.k_edge_augmentation(G, k=5, partial=True))
>>> G.add_edges_from(complement)
>>> nx.edge_connectivity(G)
4

>>> # Weighted cases
>>> G = nx.path_graph((1, 2, 3, 4))
>>> G.add_node(5)
>>> # avail can be a tuple with a dict
>>> avail = [(1, 5, {"weight": 11}), (2, 5, {"weight": 10})]
>>> sorted(nx.k_edge_augmentation(G, k=1, avail=avail, weight="weight"))
[(2, 5)]
>>> # or avail can be a 3-tuple with a real number
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
[(1, 5), (2, 5), (4, 5)]
>>> # or avail can be a dict
>>> avail = {(1, 5): 11, (2, 5): 10, (4, 3): 1, (4, 5): 51}
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail))
[(1, 5), (2, 5), (4, 5)]
>>> # If augmentation is infeasible, then a partial solution can be found
>>> avail = {(1, 5): 11}
>>> sorted(nx.k_edge_augmentation(G, k=2, avail=avail, partial=True))
[(1, 5)]
r   z"k must be a positive integer, not r   zimpossible to z! connect in graph with less than z nodesNzno available edgesavailweightpartialr   r/   r0   )r   r/   r0   seed)r   r/   r0   )r   r   r    NetworkXUnfeasiblelenr   one_edge_augmentationbridge_augmentationgreedy_k_edge_augmentationlistcomplement_edgespartial_k_edge_augmentation)r$   r   r/   r0   r1   msg	aug_edgess          r   r   r      s.    b%6A!EFF 1q5("1#%Fq1ugVTC'',,3u:?))!//++,@AAI!V-vI !V+A6JI 3eI
 	?""   },Q/	 8%	 !  sG   D CC CC D C 9DDDD DD c           	   #     #    S n[        X#U S9u  pVU R                  5       nUR                  S [        X&5       5       5        [	        [
        R                  " XqS95      nU H  n	[        U	5      S:  d  M  UR                  U	5      R                  5       n
U
R                  SS9 VVVs0 s H  u  pnSU;   d  M  US   US	   _M     nnnnU
R                  UR                  5       5        [
        R                  " XUS
9 Sh  vN   M     [        R                  " US5       HD  u  nnU" XU5       H1  u  pUR                  X5      nUR!                  SS5      nUc  M-  Uv   M3     MF     gs  snnnf  No7f)a  Finds augmentation that k-edge-connects as much of the graph as possible.

When a k-edge-augmentation is not possible, we can still try to find a
small set of edges that partially k-edge-connects as much of the graph as
possible. All possible edges are generated between remaining parts.
This minimizes the number of k-edge-connected subgraphs in the resulting
graph and maximizes the edge connectivity between those subgraphs.

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

k : integer
    Desired edge connectivity

avail : dict or a set of 2 or 3 tuples
    For more details, see :func:`k_edge_augmentation`.

weight : string
    key to use to find weights if ``avail`` is a set of 3-tuples.
    For more details, see :func:`k_edge_augmentation`.

Yields
------
edge : tuple
    Edges in the partial augmentation of G. These edges k-edge-connect any
    part of G where it is possible, and maximally connects the remaining
    parts. In other words, all edges from avail are generated except for
    those within subgraphs that have already become k-edge-connected.

Notes
-----
Construct H that augments G with all edges in avail.
Find the k-edge-subgraphs of H.
For each k-edge-subgraph, if the number of nodes is more than k, then find
the k-edge-augmentation of that graph and add it to the solution. Then add
all edges in avail between k-edge subgraphs to the solution.

See Also
--------
:func:`k_edge_augmentation`

Examples
--------
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
>>> G.add_node(8)
>>> avail = [(1, 3), (1, 4), (1, 5), (2, 4), (2, 5), (3, 5), (1, 8)]
>>> sorted(partial_k_edge_augmentation(G, k=2, avail=avail))
[(1, 5), (1, 8)]
c              3      #    U Vs0 s H  o3[        U R                  U   5      _M     nnUR                  5        H$  u  p5UR                  U5      nU H  nX74v   M
     M&     gs  snf 7f)z"finds edges between disjoint nodesN)setadjitemsintersection)Honly1only2u	only1_adjneighbs	neighbs12vs           r   _edges_between_disjoint<partial_k_edge_augmentation.<locals>._edges_between_disjointV  sa     /45u!AEE!H%u	5#//+JA,,U3If  , 6s   A)"A$A A)r0   r$   c              3   <   #    U  H  u  u  pnXX1U4S .4v   M     g7fr0   	generatorNr   )r   rG   rK   ws       r   r   .partial_k_edge_augmentation.<locals>.<genexpr>d  s)      	
0	 a!f560s   r   r   TdatarR   r0   )r   r/   Nr   )_unpack_available_edgescopyadd_edges_fromzipr9   r    k_edge_subgraphsr5   subgraphedgesremove_edges_fromkeysr   itcombinationsget_edge_dataget)r$   r   r/   r0   rL   avail_uvavail_wrD   r\   nodesCrG   rK   r   	sub_availcc1cc2edges                     r   r;   r;      si    l 0JH 	
A	
 0	
 B//78 "u:>

5!&&(A "#d!3!3IQ1!# ,+(+!3   	 01 --aIFFF "" OO$4a8S+AC8DA%A55d+D
	 9 9 Gs1   A0E362E3(E*
9E*
;E3E1AE3E3c                 2    Uc  [        U 5      $ [        XX#S9$ )a  Finds minimum weight set of edges to connect G.

Equivalent to :func:`k_edge_augmentation` when k=1. Adding the resulting
edges to G will make it 1-edge-connected. The solution is optimal for both
weighted and non-weighted variants.

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

avail : dict or a set of 2 or 3 tuples
    For more details, see :func:`k_edge_augmentation`.

weight : string
    key to use to find weights if ``avail`` is a set of 3-tuples.
    For more details, see :func:`k_edge_augmentation`.

partial : boolean
    If partial is True and no feasible k-edge-augmentation exists, then the
    augmenting edges minimize the number of connected components.

Yields
------
edge : tuple
    Edges in the one-augmentation of G

Raises
------
NetworkXUnfeasible
    If partial is False and no one-edge-augmentation exists.

Notes
-----
Uses either :func:`unconstrained_one_edge_augmentation` or
:func:`weighted_one_edge_augmentation` depending on whether ``avail`` is
specified. Both algorithms are based on finding a minimum spanning tree.
As such both algorithms find optimal solutions and run in linear time.

See Also
--------
:func:`k_edge_augmentation`
r.   )#unconstrained_one_edge_augmentationweighted_one_edge_augmentation)r$   r/   r0   r1   s       r   r6   r6     s'    ^ }2155-6
 	
r%   c                     U R                  5       S:  a  [        R                  " S5      eUc  [        U 5      $ [	        XUS9$ )a  Finds the a set of edges that bridge connects G.

Equivalent to :func:`k_edge_augmentation` when k=2, and partial=False.
Adding the resulting edges to G will make it 2-edge-connected.  If no
constraints are specified the returned set of edges is minimum an optimal,
otherwise the solution is approximated.

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

avail : dict or a set of 2 or 3 tuples
    For more details, see :func:`k_edge_augmentation`.

weight : string
    key to use to find weights if ``avail`` is a set of 3-tuples.
    For more details, see :func:`k_edge_augmentation`.

Yields
------
edge : tuple
    Edges in the bridge-augmentation of G

Raises
------
NetworkXUnfeasible
    If no bridge-augmentation exists.

Notes
-----
If there are no constraints the solution can be computed in linear time
using :func:`unconstrained_bridge_augmentation`. Otherwise, the problem
becomes NP-hard and is the solution is approximated by
:func:`weighted_bridge_augmentation`.

See Also
--------
:func:`k_edge_augmentation`
   z.impossible to bridge connect less than 3 nodes)r0   )r   r    r4   !unconstrained_bridge_augmentationweighted_bridge_augmentation)r$   r/   r0   s      r   r7   r7     sE    X 	Q##$TUU}033+AVDDr%   c                     X:  a  X4$ X4$ )zAReturns the nodes in an undirected edge in lower-triangular orderr   )rG   rK   s     r   _orderedru     s    UA6&&r%   c                 &  ^ Tc  Sm[        U [        5      (       a3  [        U R                  5       5      n[        U R	                  5       5      nOFU4S jnU  Vs/ s H  ofSS PM	     nnU  Vs/ s H  n[        U5      S:X  a  SO
U" US   5      PM!     nnUbh  U VVs/ s H  u  pxUR                  Xx5      (       + PM     n	nn[        [        R                  " X95      5      n[        [        R                  " XI5      5      nX44$ s  snf s  snf s  snnf )z=Helper to separate avail into edges and corresponding weightsr0   c                 4   >  U T   $ ! [          a    U s $ f = fr   )	TypeError)r   r0   s    r   _try_getitem-_unpack_available_edges.<locals>._try_getitem  s&    y  s    r   r   r   )	
isinstancedictr9   r`   valuesr5   has_edgera   compress)
r/   r0   r$   re   rf   ry   tuprG   rK   flagss
    `        r   rX   rX     s    ~%

%u||~&	 )..!H.LQRESCA1<B+@@ER}2:;($!QZZ%%(;H45r{{723 /R <s   D-&D"DMetaEdge)meta_uvuvrS   c              #   &  #    [        [        5      n[        X!5       H-  u  nu  pV[        X   X   5      nX7   R	                  XEU45        M/     UR                  5        H.  u  u  pn
X:w  d  M  [        U
5      u  pEn[        X4XV4U5      v   M0     g7f)aJ  Maps available edges in the original graph to edges in the metagraph.

Parameters
----------
mapping : dict
    mapping produced by :func:`collapse`, that maps each node in the
    original graph to a node in the meta graph

avail_uv : list
    list of edges

avail_w : list
    list of edge weights

Notes
-----
Each node in the metagraph is a k-edge-connected component in the original
graph.  We don't care about any edge within the same k-edge-connected
component, so we ignore self edges.  We also are only interested in the
minimum weight edge bridging each k-edge-connected component so, we group
the edges by meta-edge and take the lightest in each group.

Examples
--------
>>> # Each group represents a meta-node
>>> groups = ([1, 2, 3], [4, 5], [6])
>>> mapping = {n: meta_n for meta_n, ns in enumerate(groups) for n in ns}
>>> avail_uv = [(1, 2), (3, 6), (1, 4), (5, 2), (6, 1), (2, 6), (3, 1)]
>>> avail_w = [20, 99, 20, 15, 50, 99, 20]
>>> sorted(_lightest_meta_edges(mapping, avail_uv, avail_w))
[MetaEdge(meta_uv=(0, 1), uv=(5, 2), w=15), MetaEdge(meta_uv=(0, 2), uv=(6, 1), w=50)]
N)r   r9   r[   ru   appendrB   minr   )mappingre   rf   grouped_wuvrS   rG   rK   r   mumvchoices_wuvs              r   _lightest_meta_edgesr     s     B d#K+	6A7:wz2##Q1I.	 , "-!2!2!4+8+&GA!B8aVQ// "5s   A'B-$Bc              #     #    [        [        R                  " U 5      5      n[        X5      n[        UR	                  5       5      n[        [        X3SS 5      5      n[        [         5      nUR                  S   R                  5        H  u  pgXW   R                  U5        M     U H  u  pXX   S   XY   S   4v   M     g7f)a  Finds the smallest set of edges to connect G.

This is a variant of the unweighted MST problem.
If G is not empty, a feasible solution always exists.

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

Yields
------
edge : tuple
    Edges in the one-edge-augmentation of G

See Also
--------
:func:`one_edge_augmentation`
:func:`k_edge_augmentation`

Examples
--------
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
>>> G.add_nodes_from([6, 7, 8])
>>> sorted(unconstrained_one_edge_augmentation(G))
[(1, 4), (4, 6), (6, 7), (7, 8)]
r   Nr   r   )
r9   r    connected_componentscollapserg   r[   r   graphrB   r   )
r$   ccs1rh   
meta_nodesmeta_auginverser   rK   r   r   s
             r   rn   rn   F  s     : ''*+DAaggiJC
qrN34H$G	"((*
! +{1~w{1~.. s   B?Cc              #     #    [        XU S9u  pE[        U [        R                  " U 5      5      nUR                  S   n[        XtU5      nUR                  S U 5       5        [        R                  " U5      n	U(       d1  [        R                  " U	5      (       d  [        R                  " S5      eU	R                  SS9 H  u  pnSU;   d  M  US   nUv   M     g7f)	a=  Finds the minimum weight set of edges to connect G if one exists.

This is a variant of the weighted MST problem.

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

avail : dict or a set of 2 or 3 tuples
    For more details, see :func:`k_edge_augmentation`.

weight : string
    key to use to find weights if ``avail`` is a set of 3-tuples.
    For more details, see :func:`k_edge_augmentation`.

partial : boolean
    If partial is True and no feasible k-edge-augmentation exists, then the
    augmenting edges minimize the number of connected components.

Yields
------
edge : tuple
    Edges in the subset of avail chosen to connect G.

See Also
--------
:func:`one_edge_augmentation`
:func:`k_edge_augmentation`

Examples
--------
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
>>> G.add_nodes_from([6, 7, 8])
>>> # any edge not in avail has an implicit weight of infinity
>>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 1)]
>>> # find another solution by giving large weights to edges in the
>>> # previous solution (note some of the old edges must be used)
>>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 2)]
rN   r   c              3   8   #    U  H  u  u  pp4XXCS .4v   M     g7frP   r   )r   r   r   r   rS   s        r   r   1weighted_one_edge_augmentation.<locals>.<genexpr>  s%      0OHRb 
A/00s   z.Not possible to connect G with available edgesTrV   rR   N)rX   r   r    r   r   r   rZ   minimum_spanning_treer!   r4   r^   )r$   r/   r0   r1   re   rf   rh   r   candidate_mappingmeta_mstr   r   r   rl   s                 r   ro   ro   q  s     \ 0JH 	B++A./Aggi G,WH 0 
 ''*H2??844##$TUU^^^.	![>DJ /s   CCCc           
   #   <  ^ #    [        [        R                  R                  T 5      5      n[	        T U5      n[        R
                  " U5       Vs/ s H6  n[        U5      S:X  a  [        U5      S-  O[        X2R                  S9SS PM8     nn[        U5      S:  aA  U Vs/ s H  oUS   PM	     nnU Vs/ s H  oUS   PM	     nn[        [        USS U5      5      nO/ nUR                  5       n	U	R                  U5        U	R                  5        V
Vs/ s H  u  pUS:X  d  M  U
PM     nn
n[        U5      S:X  a  / n[        U5      S:X  a  [        U5      /nO [        S U	R                  5        5       5      n[        R                  " X5       V
s/ s H  oR                  U
5      S:X  d  M  U
PM     nn
[         R"                  " [        U5      S-  5      n[        [        USU UU* S 5      5      nX-   n[%        [         5      nUR&                  S   R)                  5        H  u  nnUU   R+                  U5        M     UR)                  5        VVs0 s H  u  nnU[        UU 4S jS9_M     nnnT R                  5       nU H_  u  nn[,        R.                  " UU   UU   5       H8  u  nnUR1                  UU5      (       a  M  UR3                  UU5        UU4v     M]     Ma     gs  snf s  snf s  snf s  snn
f ! [         a     gf = fs  sn
f s  snnf 7f)	a	  Finds an optimal 2-edge-augmentation of G using the fewest edges.

This is an implementation of the algorithm detailed in [1]_.
The basic idea is to construct a meta-graph of bridge-ccs, connect leaf
nodes of the trees to connect the entire graph, and finally connect the
leafs of the tree in dfs-preorder to bridge connect the entire graph.

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

Yields
------
edge : tuple
    Edges in the bridge augmentation of G

Notes
-----
Input: a graph G.
First find the bridge components of G and collapse each bridge-cc into a
node of a metagraph graph C, which is guaranteed to be a forest of trees.

C contains p "leafs" --- nodes with exactly one incident edge.
C contains q "isolated nodes" --- nodes with no incident edges.

Theorem: If p + q > 1, then at least :math:`ceil(p / 2) + q` edges are
    needed to bridge connect C. This algorithm achieves this min number.

The method first adds enough edges to make G into a tree and then pairs
leafs in a simple fashion.

Let n be the number of trees in C. Let v(i) be an isolated vertex in the
i-th tree if one exists, otherwise it is a pair of distinct leafs nodes
in the i-th tree. Alternating edges from these sets (i.e.  adding edges
A1 = [(v(i)[0], v(i + 1)[1]), v(i + 1)[0], v(i + 2)[1])...]) connects C
into a tree T. This tree has p' = p + 2q - 2(n -1) leafs and no isolated
vertices. A1 has n - 1 edges. The next step finds ceil(p' / 2) edges to
biconnect any tree with p' leafs.

Convert T into an arborescence T' by picking an arbitrary root node with
degree >= 2 and directing all edges away from the root. Note the
implementation implicitly constructs T'.

The leafs of T are the nodes with no existing edges in T'.
Order the leafs of T' by DFS preorder. Then break this list in half
and add the zipped pairs to A2.

The set A = A1 + A2 is the minimum augmentation in the metagraph.

To convert this to edges in the original graph

References
----------
.. [1] Eswaran, Kapali P., and R. Endre Tarjan. (1975) Augmentation problems.
    http://epubs.siam.org/doi/abs/10.1137/0205044

See Also
--------
:func:`bridge_augmentation`
:func:`k_edge_augmentation`

Examples
--------
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
>>> sorted(unconstrained_bridge_augmentation(G))
[(1, 7)]
>>> G = nx.path_graph((1, 2, 3, 2, 4, 5, 6, 7))
>>> sorted(unconstrained_bridge_augmentation(G))
[(1, 3), (3, 7)]
>>> G = nx.Graph([(0, 1), (0, 2), (1, 2)])
>>> G.add_node(4)
>>> sorted(unconstrained_bridge_augmentation(G))
[(1, 4), (4, 0)]
r   r   )keyr   Nc              3   :   #    U  H  u  pUS :  d  M  Uv   M     g7fr   Nr   r   r   r   s      r   r   4unconstrained_bridge_augmentation.<locals>.<genexpr>/  s     :jdaAEj   	r   c                 *   > TR                  U 5      U 4$ r   )r   )rG   r$   s    r   <lambda>3unconstrained_bridge_augmentation.<locals>.<lambda>B  s    !((1+q)9r%   )r9   r    r(   bridge_componentsr   r   r5   tuplesortedr   r[   rY   rZ   nextStopIterationdfs_preorder_nodesmathceilr   r   rB   r   ra   productr   add_edge)r$   
bridge_ccsrh   ccvset1vsnodes1nodes2A1Tr   r   leafsA2rootv2halfaug_tree_edgesr   r   rK   r   mappedG2r   rG   s   `                         r   rr   rr     s    r boo77:;JJA ))!,	 -B r7a< 	b	ABHH%a*	+ -	 
  5zA~"'(%BQ%%("'(%BQ%%(#fQRj&)*	AR 88:0:41aQ:E0
5zQ
5zQEl^	:ahhj::D ..q7L7A88A;!;Ka7L yyR1%#b$iTEF,- WN $G	"((*1
! +
 "--/)JB 	F69::)   
B BJJwr{GBK8DAq;;q!$$Aq!d
	 9 !g )( 1  		 Ms   AL=K,L"K10L6K6ALK;%K;+0L L <LL0L6B!LL3AL
7L
LLLLc           
   #     #    Uc  Sn[         R                  " U 5      (       d?  U R                  5       n[        [	        X1US95      nUR                  U5        U Sh  vN   O/ nU n[        U5      S:X  a1  [         R                  " U5      (       a  [         R                  " S5      e[        XUS9u  pV[         R                  R                  U5      n[        X75      nUR                  S   n	[        XU5       V
VVVs0 s H  u  u  ppX4X4_M     nnnn
n [        S UR!                  5        5       5      n[         R$                  " X5      n[         R&                  " U5      R                  5       n[         R(                  " USSS	9  [         R*                  " UXR-                  5       S
9nU Hd  u  u  pnXU4   u  pUU
:X  a  UR/                  UXUS9  M)  UU:X  a  UR/                  UXUS9  MB  UR/                  UXUS9  UR/                  UXUS9  Mf      [1        UU5      n[5        5       nUR7                  5        H4  u  pUR9                  X5      nSU;   d  M  US   nUR;                  U5        M6     U Sh  vN   g GN!s  snnnn
f ! ["         a     gf = f! [         R2                   a  n[         R                  " S5      UeSnAff = f NS7f)a  Finds an approximate min-weight 2-edge-augmentation of G.

This is an implementation of the approximation algorithm detailed in [1]_.
It chooses a set of edges from avail to add to G that renders it
2-edge-connected if such a subset exists.  This is done by finding a
minimum spanning arborescence of a specially constructed metagraph.

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

avail : set of 2 or 3 tuples.
    candidate edges (with optional weights) to choose from

weight : string
    key to use to find weights if avail is a set of 3-tuples where the
    third item in each tuple is a dictionary.

Yields
------
edge : tuple
    Edges in the subset of avail chosen to bridge augment G.

Notes
-----
Finding a weighted 2-edge-augmentation is NP-hard.
Any edge not in ``avail`` is considered to have a weight of infinity.
The approximation factor is 2 if ``G`` is connected and 3 if it is not.
Runs in :math:`O(m + n log(n))` time

References
----------
.. [1] Khuller, Samir, and Ramakrishna Thurimella. (1993) Approximation
    algorithms for graph augmentation.
    http://www.sciencedirect.com/science/article/pii/S0196677483710102

See Also
--------
:func:`bridge_augmentation`
:func:`k_edge_augmentation`

Examples
--------
>>> G = nx.path_graph((1, 2, 3, 4))
>>> # When the weights are equal, (1, 4) is the best
>>> avail = [(1, 4, 1), (1, 3, 1), (2, 4, 1)]
>>> sorted(weighted_bridge_augmentation(G, avail))
[(1, 4)]
>>> # Giving (1, 4) a high weight makes the two edge solution the best.
>>> avail = [(1, 4, 1000), (1, 3, 1), (2, 4, 1)]
>>> sorted(weighted_bridge_augmentation(G, avail))
[(1, 3), (2, 4)]
>>> # ------
>>> G = nx.path_graph((1, 2, 3, 4))
>>> G.add_node(5)
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 1)]
>>> sorted(weighted_bridge_augmentation(G, avail=avail))
[(1, 5), (4, 5)]
>>> avail = [(1, 5, 11), (2, 5, 10), (4, 3, 1), (4, 5, 51)]
>>> sorted(weighted_bridge_augmentation(G, avail=avail))
[(1, 5), (2, 5), (4, 5)]
Nr0   r2   r   zno augmentation possiblerN   r   c              3   :   #    U  H  u  pUS :X  d  M  Uv   M     g7fr   r   r   s      r   r   /weighted_bridge_augmentation.<locals>.<genexpr>  s     7*$!QAA*r   namer~   )r   pairsrQ   zno 2-edge-augmentation possiblerR   )r    r!   rY   r9   r6   rZ   r5   r"   r4   rX   r(   r   r   r   r   r   r   r   dfs_treereverseset_edge_attributes%tree_all_pairs_lowest_common_ancestorr`   r   _minimum_rooted_branchingNetworkXExceptionr@   r^   rc   add)r$   r/   r0   rD   
connectorsre   rf   r   rh   r   r   r   r   rS   meta_to_wuvr   TRDlca_genlcaAerrbridge_connectorsrW   rl   s                            r   rs   rs   Q  s    D ~ ??1FFH/vNO
	$

5zQ>>!''(BCC/JH 2215JA ggi G  4GwOOOHRb 
1'O  $7!((*77
 
Q	B 	

2A18A6 66
--/G !#H%"9JJsBBJ7BYJJsBBJ7
 JJsBBJ7JJsBBJ7 ! P &a. '')r&$$D!!$'  !  { 	$(  L  P##$EFCOP" !s   AKI=BK<J 
K J 6CKJ  4KK7K8K K
JKJKK,KKKc                     U R                  5       nUR                  U R                  U5       Vs/ s H  o3U4PM     sn5        [        R                  " U5      nU$ s  snf )a:  Helper function to compute a minimum rooted branching (aka rooted
arborescence)

Before the branching can be computed, the directed graph must be rooted by
removing the predecessors of root.

A branching / arborescence of rooted graph G is a subgraph that contains a
directed path from the root to every other vertex. It is the directed
analog of the minimum spanning tree problem.

References
----------
[1] Khuller, Samir (2002) Advanced Algorithms Lecture 24 Notes.
https://web.archive.org/web/20121030033722/https://www.cs.umd.edu/class/spring2011/cmsc651/lec07.pdf
)rY   r_   predecessorsr    minimum_spanning_arborescence)r   r   rootedrG   r   s        r   r   r     sT      VVXF
1EF1EA$i1EFG
((0AH Gs   AT)returns_graphc                   ^^	 0 m	0 nU R                  5       nSm[        U R                  5       5      n[        U5       H^  u  mn[        U5      nUR	                  U5      (       d   S5       eUR                  U5        XRT'   T	R                  U4S jU 5       5        M`     [        UTS-   S9 H(  u  mnU1nXRT'   T	R                  U4S jU 5       5        M*     TS-   nUR                  [        U5      5        UR                  U	4S jU R                  5        5       5        [        R                  " USUS	9  T	UR                  S
'   U$ )a  Collapses each group of nodes into a single node.

This is similar to condensation, but works on undirected graphs.

Parameters
----------
G : NetworkX Graph

grouped_nodes:  list or generator
   Grouping of nodes to collapse. The grouping must be disjoint.
   If grouped_nodes are strongly_connected_components then this is
   equivalent to :func:`condensation`.

Returns
-------
C : NetworkX Graph
   The collapsed graph C of G with respect to the node grouping.  The node
   labels are integers corresponding to the index of the component in the
   list of grouped_nodes.  C has a graph attribute named 'mapping' with a
   dictionary mapping the original nodes to the nodes in C to which they
   belong.  Each node in C also has a node attribute 'members' with the set
   of original nodes in G that form the group that the node in C
   represents.

Examples
--------
>>> # Collapses a graph using disjoint groups, but not necessarily connected
>>> G = nx.Graph([(1, 0), (2, 3), (3, 1), (3, 4), (4, 5), (5, 6), (5, 7)])
>>> G.add_node("A")
>>> grouped_nodes = [{0, 1, 2, 3}, {5, 6, 7}]
>>> C = collapse(G, grouped_nodes)
>>> members = nx.get_node_attributes(C, "members")
>>> sorted(members.keys())
[0, 1, 2, 3]
>>> member_values = set(map(frozenset, members.values()))
>>> assert {0, 1, 2, 3} in member_values
>>> assert {4} in member_values
>>> assert {5, 6, 7} in member_values
>>> assert {"A"} in member_values
r   z-grouped nodes must exist in G and be disjointc              3   *   >#    U  H  oT4v   M
     g 7fr   r   r   r   is     r   r   collapse.<locals>.<genexpr>J       -u!1vu   r   )startc              3   *   >#    U  H  oT4v   M
     g 7fr   r   r   s     r   r   r   O  r   r   c              3   X   >#    U  H  u  pTU   TU   :w  d  M  TU   TU   4v   M!     g 7fr   r   )r   rG   rK   r   s      r   r   r   R  s6      -6TQ'!*PQ
:R WQZ Ys   **membersr   r   )	__class__r@   rg   	enumerate
issupersetdifference_updateupdateadd_nodes_fromrangerZ   r^   r    set_node_attributesr   )
r$   grouped_nodesr   rh   	remaininggroupnodenumber_of_groupsr   r   s
           @@r   r   r     s?   T GG	A	AAGGIIm,5E
##
 
 	;:	; 
 	##E*
-u-- - Ya!e44
-u-- 5 1uU+,- -.WWY  19W= AGGIHr%   c              #   ^  #    U R                   nU R                  5       (       aK  [        R                  " U R	                  5       S5       H!  u  p#X1U   ;  a  X#4v   X!U   ;  d  M  X24v   M#     g[        R                  " U R	                  5       S5       H  u  p#X1U   ;  d  M  X#4v   M     g7f)a  Returns only the edges in the complement of G

Parameters
----------
G : NetworkX Graph

Yields
------
edge : tuple
    Edges in the complement of G

Examples
--------
>>> G = nx.path_graph((1, 2, 3, 4))
>>> sorted(complement_edges(G))
[(1, 3), (1, 4), (2, 4)]
>>> G = nx.path_graph((1, 2, 3, 4), nx.DiGraph())
>>> sorted(complement_edges(G))
[(1, 3), (1, 4), (2, 1), (2, 4), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3)]
>>> G = nx.complete_graph(1000)
>>> sorted(complement_edges(G))
[]
r   N)_adjis_directedra   rb   rg   )r$   G_adjrG   rK   s       r   r:   r:   \  s     2 FFE}}OOAGGIq1DAa fa f	 2 OOAGGIq1DAa f 2s   AB-%:B-#
B-c                 &    U R                  U5        g)z=wrapper around rng.shuffle for python 2 compatibility reasonsN)shuffle)rnginputs     r   _compat_shuffler     s    KKr%      c           	   #   ,  #    / n[        X5      nU(       a  gUc$  [        [        U 5      5      nS/[        U5      -  nO[	        X#U S9u  pxU V	s/ s H"  n	[        [        U R                  U	5      5      PM$     n
n	[        [        XU5      5      nU VVV	s/ s H  u  poPM	     nnnn	U R                  5       nU H{  u  nnSn[        XUUS9(       dZ  UR                  UU45        UR                  UU5        UR                  U5      U:  a   UR                  U5      U:  a  [        X5      nU(       d  M{    O   U(       d  [        R                  " S5      e[!        XE5        [        U5       H  u  nnUR                  U5      U::  d  UR                  U5      U::  a  M2  UR#                  UU5        UR%                  UU45        [        XS9(       a  Mg  UR                  UU5        UR                  UU45        M     U Sh  vN   gs  sn	f s  sn	nnf  N7f)a  Greedy algorithm for finding a k-edge-augmentation

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

k : integer
    Desired edge connectivity

avail : dict or a set of 2 or 3 tuples
    For more details, see :func:`k_edge_augmentation`.

weight : string
    key to use to find weights if ``avail`` is a set of 3-tuples.
    For more details, see :func:`k_edge_augmentation`.

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

Yields
------
edge : tuple
    Edges in the greedy augmentation of G

Notes
-----
The algorithm is simple. Edges are incrementally added between parts of the
graph that are not yet locally k-edge-connected. Then edges are from the
augmenting set are pruned as long as local-edge-connectivity is not broken.

This algorithm is greedy and does not provide optimality guarantees. It
exists only to provide :func:`k_edge_augmentation` with the ability to
generate a feasible solution for arbitrary k.

See Also
--------
:func:`k_edge_augmentation`

Examples
--------
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
>>> sorted(greedy_k_edge_augmentation(G, k=2))
[(1, 7)]
>>> sorted(greedy_k_edge_augmentation(G, k=1, avail=[]))
[]
>>> G = nx.path_graph((1, 2, 3, 4, 5, 6, 7))
>>> avail = {(u, v): 1 for (u, v) in complement_edges(G)}
>>> # randomized pruning process can produce different solutions
>>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=2))
[(1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 6), (3, 7), (5, 7)]
>>> sorted(greedy_k_edge_augmentation(G, k=4, avail=avail, seed=3))
[(1, 3), (1, 5), (1, 6), (2, 4), (2, 6), (3, 7), (4, 7), (5, 7)]
Nr   rN   FrU   z/not able to k-edge-connect with available edges)r   r9   r:   r5   rX   summapr   r   r[   rY   r	   r   r   r    r4   r   remove_edgeremove)r$   r   r/   r0   r3   r=   donere   rf   r   
tiebreaker
avail_wduvrS   r   rD   rG   rK   s                    r   r8   r8     s    z Iq$D}(+,#H% 4EAN 4<<8R#c!((B'(8J<G:;J#-.:xqR:H. 	
A1*1a8aV$JJq!xx{aAHHQK1$4*104  ##$UVV D$Y188A;!qxx{a/	a!Q "1**JJq!aV$   I =.D s8   AH)H8HH#BH4BH.H HH)NNFr   )NN)NF)NNN)!__doc__	itertoolsra   r   collectionsr   r   networkxr    networkx.utilsr   r   __all___dispatchabler   r	   r   r;   r6   r7   ru   rX   r   r   rn   ro   rr   rs   r   r   r:   r   r8   r   r%   r   <module>r     se     /  ?
W Z \"-:  # !-:` Z \"4  # !4n Z \"S  # !Sl a aH \"Z 1
  ! #1
h \"Z .E  ! #.Eh'
4 j"89.0b '/ '/T A AH W Wt g! g!T0 %D &DN " "J
 \"Z k   ! #kr%   