
    wg                        d Z ddlZddlZddlmZmZ ddlZddl	m
Z
mZ g dZ e
d       e
d      ej                  d                      Z e
d       e
d      ej                  d	                      Z e
d       e
d      ej                  dd
                     Zej                  d d       Z e
d       e
d      ej                  dd                     Z e
d       e
d      ej                  d!d                     Zd Zd!dZ edd      Zd Zej                  d        Zej                  d"d       Zej                  d        Zej                  d d       Zd Z ej                  d      d        Zej                  d        Zd Z e
d       e
d       ed      ej                  d#d                            Z y)$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                 j   dk  rt        d       | j                         dz   k  ryt        fd| j                         D              rydk(  rt	        j
                  |       S dk(  r-t	        j
                  |       xr t	        j                  |        S t	        j                  |       k\  S )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   .   K   | ]  \  }}|k    y wN ).0ndks      w/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/connectivity/edge_augmentation.py	<genexpr>z&is_k_edge_connected.<locals>.<genexpr>A   s     *tq!QU*s      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                    |dk  rt        d|       | j                  |      |k  s| j                  |      |k  ry|dk(  rt        j                  | ||      S t        j                  j                  | |||      }||k\  S )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;;q!Q''__<<Q1Q<OFQ;r$   c              #   B  K   	 |dk  rt        d|       | j                         |dz   k  r!d| d|dz    d}t        j                  |      |<t	        |      dk(  r.t        j
                  | |      st        j                  d      g }n9|dk(  rt        | |||	      }n$|d
k(  rt        | ||      }nt        | |||d      }t        |      E d{    y7 # t        j                  $ r. |r*|t        |       }nt        | |||      }|E d{  7   Y y w xY ww)aW  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.   r/   )r   r.   r/   seed)r   r.   r/   )r   r   r   NetworkXUnfeasiblelenr   one_edge_augmentationbridge_augmentationgreedy_k_edge_augmentationlistcomplement_edgespartial_k_edge_augmentation)r#   r   r.   r/   r0   msg	aug_edgess          r   r   r      s<    b%6A!EFF 1q5("1#%Fq1ugVTC'',,3u:?))!Q/++,@AAI!V-vwI !V+AU6JI 3QeFI
 	?""   },Q/	 8%	 !  sG   DCC CC DC 7DDDDDDc           	   #     K   d }t        |||       \  }}| j                         }|j                  d t        ||      D               t	        t        j                  ||            }|D ]  }	t        |	      dkD  s|j                  |	      j                         }
|
j                  d      D ci c]  \  }}}d|v r	|d   |d	    }}}}|
j                  |j                                t        j                  |
||
      E d{     t        j                  |d      D ]B  \  }} ||||      D ]0  \  }}|j                  ||      }|j!                  dd      }|-| 2 D yc c}}}w 7 iw)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      K   |D ci c]  }|t        | j                  |          }}|j                         D ]#  \  }}|j                  |      }|D ]  }||f 
 % yc c}w w)z"finds edges between disjoint nodesN)setadjitemsintersection)Honly1only2u	only1_adjneighbs	neighbs12vs           r   _edges_between_disjointz<partial_k_edge_augmentation.<locals>._edges_between_disjointV  sq     /45!QAEE!H%5	5#//+ 	JAw,,U3I !f	 6s   A% A >A%r/   r#   c              3   <   K   | ]  \  \  }}}|||||fd f  ywr/   	generatorNr   )r   rF   rJ   ws       r   r   z.partial_k_edge_augmentation.<locals>.<genexpr>d  s0      	
A aq!f56	
s   r   r   TdatarP   r/   )r   r.   Nr   )_unpack_available_edgescopyadd_edges_fromzipr8   r   k_edge_subgraphsr4   subgraphedgesremove_edges_fromkeysr   itcombinationsget_edge_dataget)r#   r   r.   r/   rK   avail_uvavail_wrC   rY   nodesCrF   rJ   r   	sub_availcc1cc2edges                     r   r:   r:      s    l 0fJHg 	
A	
 0	
 B//Q78 " Gu:>

5!&&(A "#d!3 Q1!# +(+I  	 01 --a1IFFFG" OO$4a8 S+AsC8 	DAq1%A55d+D
		 Gs+   A:E4=5E42E+

>E4E2	AE4"E4c                 :    |t        |       S t        | |||      S )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.   r/   r0   s       r   r5   r5     s+    ^ }2155-U67
 	
r$   c                     | j                         dk  rt        j                  d      |t        |       S t	        | ||      S )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)r/   )r   r   r3   !unconstrained_bridge_augmentationweighted_bridge_augmentation)r#   r.   r/   s      r   r6   r6     sG    X 	Q##$TUU}033+AuVDDr$   c                     | |k  r| |fS || fS )zAReturns the nodes in an undirected edge in lower-triangular orderr   )rF   rJ   s     r   _orderedrr     s    UAq6&A&r$   c                    dt        | t              r3t        | j                               }t        | j	                               }n?fd}| D cg c]  }|dd 	 }}| D cg c]  }t        |      dk(  rdn
 ||d          }}|c|D cg c]  \  }}|j                  ||        }	}}t        t        j                  ||	            }t        t        j                  ||	            }||fS c c}w c c}w c c}}w )z=Helper to separate avail into edges and corresponding weightsr/   c                 2    	 |    S # t         $ r | cY S w xY wr   )	TypeError)r   r/   s    r   _try_getitemz-_unpack_available_edges.<locals>._try_getitem  s&    y  s    r   r   r   )	
isinstancedictr8   r]   valuesr4   has_edger^   compress)
r.   r/   r#   rb   rc   rv   tuprF   rJ   flagss
    `        r   rU   rU     s    ~%

%u||~&	 )..C!H..LQRSCA1<B+@@RR}2:;$!QQZZ1%%;;He45r{{7E23W /R <s   C1$"C6C;MetaEdge)meta_uvuvrQ   c              #   0  K   t        t              }t        ||      D ]1  \  }\  }}t        | |   | |         }||   j	                  |||f       3 |j                         D ]0  \  \  }}	}
||	k7  st        |
      \  }}}t        ||	f||f|       2 yw)a  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   r8   rX   rr   appendrA   minr   )mappingrb   rc   grouped_wuvrQ   rF   rJ   r   mumvchoices_wuvs              r   _lightest_meta_edgesr     s     B d#K(+ /	6Aq71:wqz2G##Q1I.	/ "-!2!2!4 0R+8+&GAq!B8aVQ//0s   A.B1%Bc              #     K   t        t        j                  |             }t        | |      }t        |j	                               }t        t        ||dd             }t        t               }|j                  d   j                         D ]  \  }}||   j                  |        |D ]  \  }}	||   d   ||	   d   f  yw)as  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   )
r8   r   connected_componentscollapserd   rX   r   graphrA   r   )
r#   ccs1re   
meta_nodesmeta_auginverser   rJ   r   r   s
             r   rk   rk   F  s     : ''*+DDAaggiJC
JqrN34H$G	"((* 1
! /Br{1~wr{1~../s   CCc              #     K   t        |||       \  }}t        | t        j                  |             }|j                  d   }t        |||      }|j                  d |D               t        j                  |      }	|s*t        j                  |	      st        j                  d      |	j                  d      D ]  \  }
}}d|v s|d   }|  yw)	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)]
    rL   r   c              3   :   K   | ]  \  \  }}}}||||d f  ywrN   r   )r   r   r   r   rQ   s        r   r   z1weighted_one_edge_augmentation.<locals>.<genexpr>  s.      HRb! 
RAB/0s   z.Not possible to connect G with available edgesTrS   rP   N)rU   r   r   r   r   r   rW   minimum_spanning_treer    r3   r[   )r#   r.   r/   r0   rb   rc   re   r   candidate_mappingmeta_mstr   r   r   ri   s                 r   rl   rl   q  s     \ 0fJHg 	B++A./Aggi G,WhH 0 
 ''*H2??84##$TUU^^^. 	B![>DJs   CCCc           
   #      K   t        t        j                  j                               }t	         |      }t        j
                  |      D cg c]8  }t        |      dk(  rt        |      dz  nt        ||j                        dd : }}t        |      dkD  r=|D cg c]  }|d   	 }}|D cg c]  }|d   	 }}t        t        |dd |            }ng }|j                         }	|	j                  |       |	j                         D 
cg c]  \  }
}|dk(  s|
 }}
}t        |      dk(  rg }t        |      dk(  rt        |      g}n	 t        d |	j                         D              }t        j                  |	|      D 
cg c]  }
|	j                  |
      dk(  s|
 }}
t!        j"                  t        |      dz        }t        t        |d| || d             }||z   }t%        t               }|j&                  d   j)                         D ]  \  }}||   j+                  |        |j)                         D ci c]  \  }}|t        | fd       }}} j                         }|D ]U  \  }}t-        j.                  ||   ||         D ]1  \  }}|j1                  ||      r|j3                  ||       ||f  U W yc c}w c c}w c c}w c c}}
w # t        $ r Y yw xY wc c}
w c c}}w w)	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   2   K   | ]  \  }}|d kD  s|  ywr   Nr   r   r   r   s      r   r   z4unconstrained_bridge_augmentation.<locals>.<genexpr>/  s     :daAE:   r   c                 *    j                  |       | fS r   )r   )rF   r#   s    r   <lambda>z3unconstrained_bridge_augmentation.<locals>.<lambda>B  s    !((1+q)9 r$   )r8   r   r'   bridge_componentsr   r   r4   tuplesortedr   rX   rV   rW   nextStopIterationdfs_preorder_nodesmathceilr   r   rA   r   r^   productr{   add_edge)r#   
bridge_ccsre   ccvset1vsnodes1nodes2A1Tr   r   leafsA2rootv2halfaug_tree_edgesr   r   rJ   r   mappedG2r   rF   s   `                         r   ro   ro     s    r boo77:;JJA ))!,	  r7a< 	b	ABAHH%a*	+E  5zA~"'(B"Q%(("'(B"Q%((#fQRj&)*	AR 88:041aaQ0E0
5zQ
5zQEl^	:ahhj::D ..q$7LA188A;!;KaLL yyR1%#b$iTEF,- "WN $G	"((* 1
!
 "--/B 	F69::G  
B  BJJwr{GBK8 	DAq;;q!$Aq!d
		g )( 1  		 Ms   AK==KK= K,K=2K>AK=KK!.K= K# 0K=K2"K2&BK=K7 AK=03K=#	K/,K=.K//K=c           
   #     K   |d}t        j                  |       sC| j                         }t        t	        |||            }|j                  |       |E d{    ng }| }t        |      dk(  r*t        j                  |      rt        j                  d      t        |||      \  }}t         j                  j                  |      }t        ||      }|j                  d   }	t        |	||      D 
ci c]  \  \  }
}}}|
|f||f }}}}
}	 t        d |j!                         D              }t        j$                  ||      }t        j&                  |      j                         }t        j(                  |dd	       t        j*                  |||j-                         
      }|D ]r  \  \  }
}}||
|f   \  }}||
k(  r|j/                  ||||       .||k(  r|j/                  ||
||       I|j/                  ||
||       |j/                  ||||       t 	 t1        ||      }t5               }|j7                         D ]2  \  }
}|j9                  |
|      }d|v s|d   }|j;                  |       4 |E d{    y7 /c c}}}}
w # t"        $ r Y yw xY w# t         j2                  $ r}t        j                  d      |d}~ww xY w7 Pw)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)]
    Nr/   r1   r   zno augmentation possiblerL   r   c              3   2   K   | ]  \  }}|d k(  s|  ywr   r   r   s      r   r   z/weighted_bridge_augmentation.<locals>.<genexpr>  s     7$!QQA7r   namerz   )r   pairsrO   zno 2-edge-augmentation possiblerP   )r   r    rV   r8   r5   rW   r4   r!   r3   rU   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[   r`   add)r#   r.   r/   rC   
connectorsrb   rc   r   re   r   r   r   r   rQ   meta_to_wuvr   TRDlca_genlcaAerrbridge_connectorsrT   ri   s                            r   rp   rp   Q  s    D ~ ??1FFH/vNO
	$

5zQ>>!''(BCC/fJHg 2215JJA ggi G  4GXwO HRb! 
R1b'K $7!((*77
 
Q	B 	

2A18A6 66
[--/G ! 8R#RH%2"9JJsBqBJ7BYJJsBqBJ7
 JJsBqBJ7JJsBqBJ78 P &a. '') (Br2&$$D!!$'( !  { 	$(  L  P##$EFCOP" !s   AKJBK8J
K J 3C.K"J" .6K%KKKK	JKJK"K5KKKc                     | j                         }|j                  | j                  |      D cg c]  }||f c}       t        j                  |      }|S c c}w )af  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
    )rV   r\   predecessorsr   minimum_spanning_arborescence)r   r   rootedrF   r   s        r   r   r     sP      VVXF
1EFAq$iFG
((0AH Gs   AT)returns_graphc                   	 i 	i }| j                         }dt        | j                               }t        |      D ]X  \  }t        |      }|j	                  |      sJ d       |j                  |       ||<   	j                  fd|D               Z t        |dz         D ]'  \  }|h}||<   	j                  fd|D               ) dz   }|j                  t        |             |j                  	fd| j                         D               t        j                  |d|	       	|j                  d
<   |S )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   &   K   | ]  }|f 
 y wr   r   r   r   is     r   r   zcollapse.<locals>.<genexpr>J       -!1v-   r   )startc              3   &   K   | ]  }|f 
 y wr   r   r   s     r   r   zcollapse.<locals>.<genexpr>O  r   r   c              3   P   K   | ]  \  }}|   |   k7  s|   |   f  y wr   r   )r   rF   rJ   r   s      r   r   zcollapse.<locals>.<genexpr>R  s7      %)Q'!*PQ
:RWQZ s   &&membersr   r   )	__class__r?   rd   	enumerate
issupersetdifference_updateupdateadd_nodes_fromrangerW   r[   r   set_node_attributesr   )
r#   grouped_nodesr   re   	remaininggroupnodenumber_of_groupsr   r   s
           @@r   r   r     sH   T GG	A	AAGGIIm, .5E
##
 	;:	; 
 	##E*
-u--. Ya!e4 .4
-u--. 1uU+,- -.WWY  19W= AGGIHr$   c              #   H  K   | j                   }| j                         rHt        j                  | j	                         d      D ]   \  }}|||   vr||f |||   vs||f " yt        j                  | j	                         d      D ]  \  }}|||   vs||f  yw)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_directedr^   r_   rd   )r#   G_adjrF   rJ   s       r   r9   r9   \  s     2 FFE}}OOAGGIq1 	DAqa !fa !f		 OOAGGIq1 	DAqa !f	s   AB":B"	B"c                 &    | j                  |       y)z=wrapper around rng.shuffle for python 2 compatibility reasonsN)shuffle)rnginputs     r   _compat_shuffler     s    KKr$      c           	   #     K   g }t        | |      }|ry|$t        t        |             }dgt        |      z  }nt	        |||       \  }}|D 	cg c]!  }	t        t        | j                  |	            # }
}	t        t        ||
|            }|D 	cg c]  \  }}}	|	
 }}}}	| j                         }|D ]s  \  }}d}t        ||||      sY|j                  ||f       |j                  ||       |j                  |      |k\  r |j                  |      |k\  rt        ||      }|ss n |st        j                  d      t!        ||       t        |      D ]  \  }}|j                  |      |k  s|j                  |      |k  r/|j#                  ||       |j%                  ||f       t        ||      rb|j                  ||       |j                  ||f        |E d{    yc c}	w c c}	}}w 7 w)aQ  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   rL   FrR   z/not able to k-edge-connect with available edges)r   r8   r9   r4   rU   summapr   r   rX   rV   r	   r   r   r   r3   r   remove_edgeremove)r#   r   r.   r/   r2   r<   donerb   rc   r   
tiebreaker
avail_wduvrQ   r   rC   rF   rJ   s                    r   r7   r7     s    z Iq!$D}(+,#H% 4E&AN' 4<<R#c!((B'(<J<GZ:;J#-..xq!R.H. 	
A 
1*1aa8aV$JJq!xx{aAHHQK1$4*1a0
 ##$UVV D)$Y 	%188A;!qxx{a/	a!Q "1*JJq!aV$	% I =.D s8   AG<&G.5G<G3 BG<)BG<<,G<(G:)G<)NNFr   )NN)NF)NNN)!__doc__	itertoolsr^   r   collectionsr   r   networkxr   networkx.utilsr   r   __all___dispatchabler   r	   r   r:   r5   r6   rr   rU   r   r   rk   rl   ro   rp   r   r   r9   r   r7   r   r$   r   <module>r     sg     /  ?
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$   