
    ܛ7i/                        d Z ddlZddlmZ ddlmZ ddlZg dZd Z	ej                  j                  d      ej                  j                  d       ej                  d	
      dd                     Zej                  j                  d      ej                  j                  d      d               Zej                  j                  d      dddd       Zy)zOFunctions for splitting a network into two communities (finding a bipartition).    N)deepcopy)count)kernighan_lin_bisectionspectral_modularity_bipartitiongreedy_node_swap_bipartitionc              #   $   K   t         j                  j                         t         j                  j                         fx\  }} j                         D ]R  \  }}t	        fd|j                         D              }|   r|j                  ||       @|j                  ||        T  fd}d}d}	|rV|rS|j                         \  }} ||       |j                         \  }
} ||
       |	||z   z  }	|dz  }|	|||
ff |r|rQy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wtsides      g/home/rose/Desktop/poly/venv/lib/python3.12/site-packages/networkx/algorithms/community/bipartitions.py	<genexpr>z'_kernighan_lin_sweep.<locals>.<genexpr>   s#     F247R+s   c                     	|    }|    j                         D ]G  \  }}	|   }||k(  r| }|   }||v s|j                  |      d|z  z   }|j                  ||d       I y )N   T)allow_increase)itemsgetinsert)
node	side_nodenbrr   side_nbrheap_nbrcost_nbr
cost_heaps	edge_infor   s
          r   _update_heap_valuesz1_kernighan_lin_sweep.<locals>._update_heap_values   sy    J	 ,,.GCCyH9$S!(+Hh#<<,q2v5XdC /    r      N)nxutils
BinaryHeapr   sumr   pop)r   r   heap0heap1unbrscost_ur    itotcostr   cost_vr   s   ``          @r   _kernighan_lin_sweepr0      s      !# 3 3 5rxx7J7J7L LLLE5:??$4FFF7LLF#LLVG$ %
D 	
AG
EIIK	6AIIK	6A6F?"	Qq1a&   E%E%s   DDDdirected   weight)
edge_attrs
   c                    t        |       }|*|j                  |       t        |      dz  }|d| ||d }}n=	 |\  }}t
        j                  j                  | ||g      st        j                  d      |D 
ci c]  }
|
|
|v 	 }}
t              r}n| j                         rfd}nfd}| j                  j                         D ci c]7  \  }}||j                         D ci c]  \  }} ||||      x}|| c}}9 }}}}}t        |      D ]H  }t        t        ||            }t        |      \  }}}|dk\  r n|d| D ]  \  }}\  }}d||<   d||<    J |j                         D ch c]  \  }}|dk(  s| }}}|j                         D ch c]  \  }}|dk(  s| }}}||fS # 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 )	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 nodes individually, alternating between sides to keep the bisection
    balanced.

    Kernighan-Lin is an approximate algorithm for maximal modularity bisection.
    In [2]_ they suggest that fine-tuned improvements can be made using
    greedy node swapping, (see `greedy_node_swap_bipartition`).
    The improvements are typically only a few percent of the modularity value.
    But they claim that can make a difference between a good and excellent method.
    This function does not perform any improvements. But you can do that yourself.

    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 : string or function (default: "weight")
        If this is a string, then edge weights will be accessed via the
        edge attribute with this key (that is, the weight of the edge
        joining `u` to `v` will be ``G.edges[u, v][weight]``). If no
        such edge attribute exists, the weight of the edge is assumed to
        be one.

        If this is a function, the weight of an edge is the value
        returned by the function. The function must accept exactly three
        positional arguments: the two endpoints of an edge and the
        dictionary of edge attributes for that edge. The function must
        return a number or None to indicate a hidden edge.

    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.
    .. [2] M. E. J. Newman,
       "Modularity and community structure in networks",
       PNAS, 103 (23), p. 8577-8582,
       https://doi.org/10.1073/pnas.0601602103

    Nr   zpartition must be two setszpartition invalidc                 H    t        fd|j                         D              S )Nc              3   B   K   | ]  }|j                  d         yw)r"   Nr   )r   ddr3   s     r   r   z<kernighan_lin_bisection.<locals>.<lambda>.<locals>.<genexpr>   s     (PZr):Zs   )r&   valuesr*   r   dr3   s      r   <lambda>z)kernighan_lin_bisection.<locals>.<lambda>   s    S(PQXXZ(P%Pr!   c                 (    |j                  d      S )Nr"   r9   r<   s      r   r>   z)kernighan_lin_bisection.<locals>.<lambda>   s    QUU61%5r!   r   r"   )listshufflelen	TypeError
ValueErrorr#   NetworkXError	communityis_partitioncallableis_multigraph_adjr   ranger0   min)G	partitionmax_iterr3   seednodesmidABerrr   r   
sum_weightr*   r+   r   r=   r   r   r-   costsmin_costmin_i_spart1part2s      `                       r   r   r   7   s$   P GEU%jAoTc{E#$K1	JDAq ||((QF3""#677*/0%$D419%D0 
	
	P
5
 vv||~%GAt 	
djjlVldaZ1a5H/Hr.UArElVV%  
 8_))T:; Z%q=!&5MLAq&1aDGDG *   ::<2<41a16Q<E2::<2<41a16Q<E2%<E :& 	J""#?@cI	J
 1 W  32sS   F; :G(G3
,G-G-G3
:G;G;"H0H;G%
G  G%-G3

multigraphc                    ddl }t        j                  j                  |       }|j                  j	                  |      \  }}|j                  |      d   }t        |j                  |dd|f         |       }t               t               }}|D ]-  \  }	}
|	dk  r|j                  |
       |j                  |
       / ||fS )a  Return a bipartition of the nodes based on the spectrum of the
    modularity matrix of the graph.

    This method calculates the eigenvector associated with the second
    largest eigenvalue of the modularity matrix, where the modularity
    matrix *B* is defined by

    ..math::

        B_{i j} = A_{i j} - \frac{k_i k_j}{2 m},

    where *A* is the adjacency matrix, `k_i` is the degree of node *i*,
    and *m* is the number of edges in the graph. Nodes whose
    corresponding values in the eigenvector are negative are placed in
    one block, nodes whose values are nonnegative are placed in another
    block.

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

    Returns
    -------
    C : tuple
        Pair of communities as two sets of nodes of ``G``, partitioned
        according to second largest eigenvalue of the modularity matrix.

    Examples
    --------
    >>> G = nx.karate_club_graph()
    >>> MrHi, Officer = nx.community.spectral_modularity_bipartition(G)
    >>> MrHi, Officer = sorted([sorted(MrHi), sorted(Officer)])
    >>> MrHi
    [0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21]
    >>> Officer
    [8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]

    References
    ----------
    .. [1] M. E. J. Newman *Networks: An Introduction*, pages 373--378
       Oxford University Press 2011.
    .. [2] M. E. J. Newman,
       "Modularity and community structure in networks",
       PNAS, 103 (23), p. 8577-8582,
       https://doi.org/10.1073/pnas.0601602103

    r   N)
numpyr#   linalgmodularity_matrixeigargsortziprealsetadd)rM   nprT   eigenvalueseigenvectorsindexv2leftrightr*   ns              r   r   r      s    d 
		##A&A "		a 0KJJ{#B'E	RWW\!U(+,a	0B%%D1q5HHQKIIaL	 
 ;r!   )
init_splitrO   c                  " |]t        |       dz  }t        |       |z
  }t        t        j                  t	        |       |            }| D ch c]	  }||vs| }}||f}nct
        j                  j                  | |      st        j                  d      t        |      dk(  st        j                  d      t        |      }t
        j                  j                  | |      }	||	}}
d}| j                         }t        | j                        "||	k\  rG||k  rA|
}|}	t        |
      }|}t        |       }|rd}d}d}|\  }}t        "fd|D              }t        "fd|D              }|D ]  }||v r	||}}||}}n||}}||}}t        | |   j                         |z         |z  }t        | |   j                         |z        |z  }"|   }|d|dz  z  z  ||z
  |z
  z  }||z   |z   } | |kD  s| }|}|}|}! |j!                  |       !j#                  |       ||z  }||kD  rt        |      |}}
|j!                  |       |r|d	z  }||	k\  r||k  rA|S c c}w )
aa  Split the nodes into two communities based on greedy
    modularity maximization.

    The algorithm works by selecting a node to change communities which
    will maximize the modularity. The swap is made and the community
    structure with the highest modularity is kept.

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

    init_split : 2-tuple of sets of nodes
        Pair of sets of nodes in ``G`` providing an initial bipartition
        for the algorithm. If not specified, a random balanced partition
        is used. If this pair of sets is not a partition of the nodes of `G`,
        :exc:`NetworkXException` is raised.

    max_iter : int
      Maximum number of iterations of attempting swaps to find an improvement.

    Returns
    -------
    max_split : 2-tuple of sets of nodes
        Pair of sets of nodes of ``G``, partitioned according to a
        node swap greedy modularity maximization algorithm.

    Raises
    ------
    NetworkXError
      if init_split is not a valid partition of the
      graph into two communities or if G is a MultiGraph

    Examples
    --------
    >>> G = nx.barbell_graph(3, 0)
    >>> left, right = nx.community.greedy_node_swap_bipartition(G)
    >>> # Sort the communities so the nodes appear in increasing order.
    >>> left, right = sorted([sorted(left), sorted(right)])
    >>> sorted(left)
    [0, 1, 2]
    >>> sorted(right)
    [3, 4, 5]

    Notes
    -----
    This function is not implemented for multigraphs.

    References
    ----------
    .. [1] M. E. J. Newman "Networks: An Introduction", pages 373--375.
       Oxford University Press 2011.

    Nr   z"init_split is not a partition of Gz init_split must be a bipartitionr   r`   c              3   (   K   | ]	  }|     y wr
   r   r   rq   G_degrees     r   r   z/greedy_node_swap_bipartition.<locals>.<genexpr>D  s     2TT   c              3   (   K   | ]	  }|     y wr
   r   ru   s     r   r   z/greedy_node_swap_bipartition.<locals>.<genexpr>E  s     4e!erw   r"   )rB   rh   randomsampler@   r#   rF   rG   rE   r   
modularitynumber_of_edgesdictdegreer&   keysremoveri   )#rM   rr   rO   m1m2
some_nodesrq   other_nodesbest_split_so_farbest_mod	max_splitmax_moditsm
next_splitnext_modrQ   max_swapmax_nodemax_node_commro   rp   leftdrightdin_commout_commin_degout_degd_eiid_ejjdegd_sum_aiswap_changenon_max_node_commrv   s#                                     @r   r   r      s   n Vq[Vb[tAw34
"#;!Qq
':q!;'5||((J7""#GHH:!#""#EFF$Z0||&&q*;<H*HwI
C	AAHH~H
X
#.%i(
AHH M$KD%2T22E4e44F9(,eXG&+VGF(-tXG&,eGFQqTYY[7233a7AaDIIK(23a7qk1q!t8,'1AC1GH#emh6)*H H$+M(0%% (   *!!(+ H'!%-j%987	LL"C D 	qQ X
#.R s <s   	II)Nr5   r3   N)__doc__ry   copyr   	itertoolsr   networkxr#   __all__r0   r$   not_implemented_forpy_random_state_dispatchabler   r   r   r   r!   r   <module>r      s    U    $!N j)!X&p '  *pf j)l+< , *<~ l+26 s ,sr!   