
    wgf.                     4   d Z ddlmZmZmZ ddlZddlmZm	Z	m
Z
 g dZ e
d       ej                  d      ddd	d
              ZddZ e
d       ej                  d      dd              Z e	d      ej                  d               Zd Zd Zd Zd Zy)z3
Label propagation community detection algorithms.
    )CounterdefaultdictdequeN)groupsnot_implemented_forpy_random_state)label_propagation_communitiesasyn_lpa_communities"fast_label_propagation_communitiesseedweight)
edge_attrs)r   r   c             #     K   t        |       }|j                  |       t        |       }t        |       D ci c]  \  }}||
 }}}|r|j	                         }|j                  |       | j                  |      dkD  rt        | |||      }t        |j                               }	|j                  |D 
cg c]  }
||
   |	k(  s|
 c}
      }
||   |
k7  rP|
||<   t        j                  | |      D ]2  }||   |
k7  s||vs|j                  |       |j                  |       4 |rt        |      j                         E d{    yc c}}w c c}
w 7 w)u  Returns communities in `G` as detected by fast label propagation.

    The fast label propagation algorithm is described in [1]_. The algorithm is
    probabilistic and the found communities may vary in different executions.

    The algorithm operates as follows. First, the community label of each node is
    set to a unique label. The algorithm then repeatedly updates the labels of
    the nodes to the most frequent label in their neighborhood. In case of ties,
    a random label is chosen from the most frequent labels.

    The algorithm maintains a queue of nodes that still need to be processed.
    Initially, all nodes are added to the queue in a random order. Then the nodes
    are removed from the queue one by one and processed. If a node updates its label,
    all its neighbors that have a different label are added to the queue (if not
    already in the queue). The algorithm stops when the queue is empty.

    Parameters
    ----------
    G : Graph, DiGraph, MultiGraph, or MultiDiGraph
        Any NetworkX graph.

    weight : string, or None (default)
        The edge attribute representing a non-negative weight of an edge. If None,
        each edge is assumed to have weight one. The weight of an edge is used in
        determining the frequency with which a label appears among the neighbors of
        a node (edge with weight `w` is equivalent to `w` unweighted edges).

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

    Returns
    -------
    communities : iterable
        Iterable of communities given as sets of nodes.

    Notes
    -----
    Edge directions are ignored for directed graphs.
    Edge weights must be non-negative numbers.

    References
    ----------
    .. [1] Vincent A. Traag & Lovro Šubelj. "Large network community detection by
       fast label propagation." Scientific Reports 13 (2023): 2701.
       https://doi.org/10.1038/s41598-023-29610-z
    r   N)r   shuffleset	enumeratepopleftremovedegree_fast_label_countmaxvalueschoicenxall_neighborsappendaddr   )Gr   r   nodes_queue	nodes_setinodecommslabel_freqsmax_freqcommnbrs               t/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/community/label_propagation.pyr   r      sW    f (KLL AI %.aL1DT1W1E1
""$ 88D>A+AudFCK;--/0H ;;"-O$T1Bh1NOD T{d""d ++At4 +CSzT)c.B#**3/!c*+) 2 e}##%%%7 2 P &sA   6EEA0E5EE5E=E&E)EEEc           	         || j                         s5t        t        |j                  t	        j
                  | |                  }|S t        t              }| |   D ]!  }|||   xx   t        | |   |         z  cc<   # | j                         r=| j                  |   D ]+  }|||   xx   t        | j                  |   |         z  cc<   - |S t        t              }| j                  ||d      D ]  \  }}}|||   xx   |z  cc<    | j                         r-| j                  ||d      D ]  \  }}}|||   xx   |z  cc<    |S )zComputes the frequency of labels in the neighborhood of a node.

    Returns a dictionary keyed by label to the frequency of that label.
       datadefault)is_multigraphr   mapgetr   r   r   intlenis_directedpredfloatedgesin_edges)r   r#   r"   r   r$   r'   _ws           r(   r   r   i   s^    ~ !#eii1A1A!T1J"KLK. ' &c*Kw =E#J'3qws|+<<'= }}66$< FCc
+s166$<3D/EE+F  "%(FA> 	)IAsAc
#q(#	) ==?ZZ61ZE -	QE#J'1,'-        c              #     K   t        |       D ci c]  \  }}||
 }}}d}|rd}t        |       }|j                  |       |D ]  }| |   s	|#t        t	        |j
                  | |               }	n<t        t              }	| j                  ||d      D ]  \  }
}}|	||   xx   |z  cc<    t        |	j                               }|	j                         D cg c]  \  }}||k(  s| }}}||   |vs|j                  |      ||<   d} |rt        |      j                         E d{    yc c}}w c c}}w 7 w)u  Returns communities in `G` as detected by asynchronous label
    propagation.

    The asynchronous label propagation algorithm is described in
    [1]_. The algorithm is probabilistic and the found communities may
    vary on different executions.

    The algorithm proceeds as follows. After initializing each node with
    a unique label, the algorithm repeatedly sets the label of a node to
    be the label that appears most frequently among that nodes
    neighbors. The algorithm halts when each node has the label that
    appears most frequently among its neighbors. The algorithm is
    asynchronous because each node is updated without waiting for
    updates on the remaining nodes.

    This generalized version of the algorithm in [1]_ accepts edge
    weights.

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

    weight : string
        The edge attribute representing the weight of an edge.
        If None, each edge is assumed to have weight one. In this
        algorithm, the weight of an edge is used in determining the
        frequency with which a label appears among the neighbors of a
        node: a higher weight means the label appears more often.

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

    Returns
    -------
    communities : iterable
        Iterable of communities given as sets of nodes.

    Notes
    -----
    Edge weight attributes must be numerical.

    References
    ----------
    .. [1] Raghavan, Usha Nandini, Réka Albert, and Soundar Kumara. "Near
           linear time algorithm to detect community structures in large-scale
           networks." Physical Review E 76.3 (2007): 036106.
    TFNr*   r+   )r   listr   r   r/   r0   r   r5   r6   r   r   itemsr   r   )r   r   r   r!   nlabelscontnodesr"   
label_freqr8   vwtr%   labelfreqbest_labelss                    r(   r
   r
      s_    h  )|,tq!ad,F,D
QU 	DT7 ~ %SQtW%=>
 )/
 !61 E 0HAq"vay)R/)0 :,,./H)3)9)9);%%tx?OK  d|;.#{{;7t?	 L f~$$&&&S -: 's:   ED5B=ED;)D;-
E8EE/E0Edirectedc                    t        |       }t        |       D ci c]  \  }}||
 }}}t        ||       s9|j                         D ]  \  }}|D ]  }t	        |||          t        ||       s9t        t              }|j                         D ]  \  }	}
||
   j                  |	        |j                         S c c}}w )ab  Generates community sets determined by label propagation

    Finds communities in `G` using a semi-synchronous label propagation
    method [1]_. This method combines the advantages of both the synchronous
    and asynchronous models. Not implemented for directed graphs.

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

    Returns
    -------
    communities : iterable
        A dict_values object that contains a set of nodes for each community.

    Raises
    ------
    NetworkXNotImplemented
       If the graph is directed

    References
    ----------
    .. [1] Cordasco, G., & Gargano, L. (2010, December). Community detection
       via semi-synchronous label propagation algorithms. In Business
       Applications of Social Network Analysis (BASNA), 2010 IEEE International
       Workshop on (pp. 1-8). IEEE.
    )	_color_networkr   _labeling_completer>   _update_labelr   r   r   r   )r   coloringkrD   labelingcolorrB   r?   clustersr"   rF   s              r(   r	   r	      s    > a H!*1.A1.H. 1-$NN, 	.LE5 .a1-.	. !1- 3H~~' "eD!"?? /s   B:c                     i }t         j                  j                  |       }|j                         D ]$  \  }}||v r||   j	                  |       |h||<   & |S )zColors the network so that neighboring nodes all have distinct colors.

    Returns a dict keyed by color to a set of nodes with that color.
    )r   rN   greedy_colorr>   r   )r   rN   colorsr"   rQ   s        r(   rK   rK     sb    
 H[[%%a(F||~ %eHUO%#fHUO	%
 Or:   c                 0     t         fdD              S )zDetermines whether or not LPA is done.

    Label propagation is complete when all nodes have a label that is
    in the set of highest frequency labels amongst its neighbors.

    Nodes with no neighbors are considered complete.
    c              3   f   K   | ](  }t        |         d kD  s|   t        |      v  * yw)r   N)r2   _most_frequent_labels).0rD   r   rP   s     r(   	<genexpr>z%_labeling_complete.<locals>.<genexpr>1  s9      AB3qQRt9WX=,Q!<<s   11)all)rP   r   s   ``r(   rL   rL   )  s      FG  r:   c                     ||    s|    hS t        fd||    D              }t        |j                               }|j                         D ch c]  \  }}||k(  s| c}}S c c}}w )zReturns a set of all labels with maximum frequency in `labeling`.

    Input `labeling` should be a dict keyed by node to labels.
    c              3   (   K   | ]	  }|     y wN )rY   qrP   s     r(   rZ   z(_most_frequent_labels.<locals>.<genexpr>A  s     1AHQK1s   )r   r   r   r>   )r"   rP   r   freqsr%   rF   rG   s    `     r(   rX   rX   6  sf    
 T7  1411E5<<>"H%*[[]GkeTdh6FEGGGs   A&A&c                     t        | ||      }t        |      dk(  r|j                         || <   yt        |      dkD  r||    |vrt        |      || <   yyy)zUpdates the label of a node using the Prec-Max tie breaking algorithm

    The algorithm is explained in: 'Community Detection via Semi-Synchronous
    Label Propagation Algorithms' Cordasco and Gargano, 2011
    r*   N)rX   r2   popr   )r"   rP   r   high_labelss       r(   rM   rM   F  s`     (h:K
;1$*	[	A	D>, -HTN - 
r:   r^   )NN)__doc__collectionsr   r   r   networkxr   networkx.utilsr   r   r   __all___dispatchabler   r   r
   r	   rK   rL   rX   rM   r_   r:   r(   <module>rk      s    4 3  G G X&48t S& ' S&l F X&[' ' ['| Z )  !)X
H .r:   