
    wg                         d Z ddlmZ ddlZddlmZ ddlmZm	Z	m
Z
 dgZd Z e	d       e
d	       ej                  d
      dd                     Zy)uB   Functions for computing the Kernighan–Lin bipartition algorithm.    )countN)is_partition)
BinaryHeapnot_implemented_forpy_random_statekernighan_lin_bisectionc              #      K   t               t               fx\  }}t        t                      D ]4  \  }}}t        fd|D              }|   j	                  ||r|n|        6  fd}d}	d}
|rX|rU|j                         \  }} |||       |j                         \  }} |||       |
||z   z  }
|	dz  }	|
|	||ff |r|rSyyyyw)z
    This is a modified form of Kernighan-Lin, which moves single nodes at a
    time, alternating between sides to keep the bisection balanced.  We keep
    two min-heaps of swap costs to make optimal-next-move selection fast.
    c              3   8   K   | ]  \  }}|   r|n|   y w)N ).0vwsides      p/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/community/kernighan_lin.py	<genexpr>z'_kernighan_lin_sweep.<locals>.<genexpr>   s"     >da$q'Qr)>s   c                     |   D ]C  \  }}|      }|j                  |      }|"|d| |u r| n|z  z  }|j                  ||d       E y )N   T)getinsert)	costs_xxyr   costs_ycost_ycostsedgesr   s	         r   _update_costsz+_kernighan_lin_sweep.<locals>._update_costs   sd    !H 	0DAqDGnG[[^F!!W%7rQ??q&$/	0    r      N)r   zipr   sumr   pop)r   r   costs0costs1uside_uedges_ucost_ur   itotcostr   cost_vr   s   ``           @r   _kernighan_lin_sweepr,      s      (\:<77NFFU!%'47 ?67>g>>fQ&vg>?0 	
AG
VJJL	6fa JJL	6fa 6F?"	Qq1a&   V&V&s   CCCdirected   weight)
edge_attrsc                    t        |       }t        |       }|j                  |       t        |      D ci c]  \  }}||
 }	}}|dg|dz  z  dg|dz   dz  z  z   }
n>	 |\  }}t        | ||f      st        j                  d      dg|z  }
|D ]
  }d|
|	|   <    | j                         r]|D cg c]M  }| |   j                         D cg c],  \  }}|	|   t        fd|j                         D              f. c}}O }}}}nL|D cg c]=  }| |   j                         D cg c]  \  }}|	|   |j                  d      f c}}? }}}}t        |      D ]H  }t        t        ||
            }t!        |      \  }}}|dk\  r n|d| D ]  \  }}\  }}d|
|<   d|
|<    J t#        ||
      D ch c]  \  }}|dk(  s| }}}t#        ||
      D ch c]  \  }}|dk(  s| }}}||fS c c}}w # t        t
        f$ r}t        j                  d      |d}~ww xY wc c}}w c c}}}w c c}}w c c}}}w c c}}w c c}}w )u  Partition a graph into two blocks using the Kernighan–Lin
    algorithm.

    This algorithm partitions a network into two sets by iteratively
    swapping pairs of nodes to reduce the edge cut between the two sets.  The
    pairs are chosen according to a modified form of Kernighan-Lin [1]_, which
    moves node individually, alternating between sides to keep the bisection
    balanced.

    Parameters
    ----------
    G : NetworkX graph
        Graph must be undirected.

    partition : tuple
        Pair of iterables containing an initial partition. If not
        specified, a random balanced partition is used.

    max_iter : int
        Maximum number of times to attempt swaps to find an
        improvement before giving up.

    weight : key
        Edge data key to use as weight. If None, the weights are all
        set to one.

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

    Returns
    -------
    partition : tuple
        A pair of sets of nodes representing the bipartition.

    Raises
    ------
    NetworkXError
        If partition is not a valid partition of the nodes of the graph.

    References
    ----------
    .. [1] Kernighan, B. W.; Lin, Shen (1970).
       "An efficient heuristic procedure for partitioning graphs."
       *Bell Systems Technical Journal* 49: 291--307.
       Oxford University Press 2011.

    Nr   r   r   zpartition must be two setszpartition invalidc              3   B   K   | ]  }|j                  d         yw)r   N)r   )r   er/   s     r   r   z*kernighan_lin_bisection.<locals>.<genexpr>u   s     DAquuVQ/Ds   )lenlistshuffle	enumerate	TypeError
ValueErrornxNetworkXErrorr   is_multigraphitemsr!   valuesr   ranger,   minr    )G	partitionmax_iterr/   seednlabelsr)   r   indexr   ABerrar%   dr   r3   r   min_costmin_i_ss      `                    r   r   r   +   s   j 	AA!WFLL'/0daQT0E0sa1f~A!| 44	JDAq A1v&""#677sQw 	ADqN	 	 
 

  aDJJLAq q3DDDE
 
 NT
 
HIadjjlCdaeAhfa()C
 
 8_ )%67 Z%q=!&5M 	LAq&1aDGDG	 64(3tq!AF3A364(3tq!AF3A3a4KQ 1 :& 	J""#?@cI	J
 D
 	43se   G9!G? 4H21H, H2H?,!H9H?<I
I I.I?H)H$$H),H29H?)N
   r/   N)__doc__	itertoolsr   networkxr:   -networkx.algorithms.community.community_utilsr   networkx.utilsr   r   r   __all__r,   _dispatchabler   r   r   r   <module>rY      sa    H   F K K$
%!> Z X&] '  !]r   