
    hF                         S r SSKJr  SSKrSSKJr  SSKJr  SSK	J
r
  SS/rSS	 jr\R                  " S
S9    SS j5       r\" S5      \" S5      \R                  " S
S9SS j5       5       5       rg)z8Functions for detecting communities based on modularity.    )defaultdictN)
modularity)not_implemented_for)MappedQueuegreedy_modularity_communities#naive_greedy_modularity_communitiesc              #     #    U R                  5       nU R                  5       nU R                  U5      nSU-  nU(       aM  U R                  US9 VVs0 s H
  u  pxXxU-  _M     n	nnU R	                  US9 VV
s0 s H
  u  pzXzU-  _M     nnn
O+U R                  US9 VVs0 s H  u  p|X|U-  S-  _M     snn=p[        S 5      nU R                  USS9 H+  u  pnX:X  a  M  X   U==   U-  ss'   X   U==   U-  ss'   M-     UR                  5        HA  u  nnUR                  5        H'  u  nnUU-  X)U   X   -  X   X   -  -   -  -
  X   U'   M)     MC     U  VVVs0 s H7  o[        X   R                  5        VVs0 s H  u  nnX4U* _M     snn5      _M9     nnnn[        U  Vs/ s H)  n[        UU   5      S:  d  M  UU   R                  S   PM+     sn5      nU  Vs0 s H  nU[        U/5      _M     nnUR                  5       v   [        U5      S:  Gak   UR                  5       u  npU* nUv   UU   R                  5         [        UU   5      S:  a!  UR!                  UU   R                  S   5        UU   R                  S   X4:X  a[  UR#                  X45        UU   R#                  X45        [        UU   5      S:  a!  UR!                  UU   R                  S   5        OUU   R#                  X45        [        UU   UU   -  5      UU'   UU	 [%        X   5      n[%        X   5      nUU-  X1-
  nUU-  nU GH(  nUU;   a  X   U   X   U   -   nOGUU;   a!  X   U   X)U   UU   -  U	U   X   -  -   -  -
  nO X   U   X)U   UU   -  U	U   X   -  -   -  -
  nUU4UU44 H  u  nnUU   n UUU   U'   [        U 5      S:  a  U R                  S   n!OSn!UU4n"U* n#UU;   a  U R'                  U"U"U#S9  OU R!                  U"U#S9  U!c  UR!                  U"U#S9  Mx  U R                  S   n$U!U$:w  d  U!R(                  U$R(                  :w  d  M  UR'                  U!U$5        M     GM+     X    H  nUU   U   n%UU   U	 UU:w  d  M  UU4UU44 H  u  nnUU   n UU4n&U R                  S   U&:X  aS  U R#                  U&5        UR#                  U&5        [        U 5      S:  a   UR!                  U R                  S   5        Ms  Mu  U R#                  U&5        M     M     X	 [        5       UU'   X==   X   -  ss'   SX'   U(       a  X==   X   -  ss'   SX'   UR                  5       v   [        U5      S:  a  GMj  ggs  snnf s  sn
nf s  snnf s  snnf s  snnnf s  snf s  snf ! [         a     gf = f7f)	a4  Yield community partitions of G and the modularity change at each step.

This function performs Clauset-Newman-Moore greedy modularity maximization [2]_
At each step of the process it yields the change in modularity that will occur in
the next step followed by yielding the new community partition after that step.

Greedy modularity maximization begins with each node in its own community
and repeatedly joins the pair of communities that lead to the largest
modularity until one community contains all nodes (the partition has one set).

This function maximizes the generalized modularity, where `resolution`
is the resolution parameter, often expressed as $\gamma$.
See :func:`~networkx.algorithms.community.quality.modularity`.

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

weight : string or None, optional (default=None)
    The name of an edge attribute that holds the numerical value used
    as a weight.  If None, then each edge has weight 1.
    The degree is the sum of the edge weights adjacent to the node.

resolution : float (default=1)
    If resolution is less than 1, modularity favors larger communities.
    Greater than 1 favors smaller communities.

Yields
------
Alternating yield statements produce the following two objects:

communities: dict_values
    A dict_values of frozensets of nodes, one for each community.
    This represents a partition of the nodes of the graph into communities.
    The first yield is the partition with each node in its own community.

dq: float
    The change in modularity when merging the next two communities
    that leads to the largest modularity.

See Also
--------
modularity

References
----------
.. [1] Newman, M. E. J. "Networks: An Introduction", page 224
   Oxford University Press 2011.
.. [2] Clauset, A., Newman, M. E., & Moore, C.
   "Finding community structure in very large networks."
   Physical Review E 70(6), 2004.
.. [3] Reichardt and Bornholdt "Statistical Mechanics of Community
   Detection" Phys. Rev. E74, 2006.
.. [4] Newman, M. E. J."Analysis of weighted networks"
   Physical Review E 70(5 Pt 2):056131, 2004.
   )weightg      ?c                       [        [        5      $ )N)r   float     ^/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/community/modularity_max.py<lambda>:_greedy_modularity_communities_generator.<locals>.<lambda>[   s	    +e"4r   )datadefaultr   N)priority)is_directednumber_of_nodessize
out_degree	in_degreedegreer   edgesitemsr   lenheap	frozensetvaluespop
IndexErrorpushremovesetupdater   )'Gr   
resolutiondirectedNmq0nodedeg_outadeg_inbdegdq_dictuvwtnbrdictdqdq_heapnHcommunitiesnegdqu_nbrsv_nbrsall_nbrs	both_nbrswdq_vwrowcoldq_heap_rowd_oldmaxdd_negdqrow_maxdq_oldd_olds'                                          r   (_greedy_modularity_communities_generatorrN      s    r }}H	A 	
vA	
QB
 56\\\5PQ5PMDTR<5PQ34;;f;3MN3M<4TB;3MN78xxvx7NO7N)$Rx#~%7NOO 45GGGG3b6
1
1	 4 mmo
7]]_EArGjaD14K!$+4M&NNGJqM % & WXXVWQR+
8H8H8JK8Juq"vs{8JKLLVWGXJAc'!*o6I'WQZ__Q'JKA /00a1in$aK0



 a&1*	%%'KE1 V
wqz?QFF71:??1%& 1:??1!'HHaVAJqf%71:"wqzq)* AJqf% #;q>KN#BCAN WZWZVOv-VO	AI~
1
15f
1
dQqTkAaD14K6O(PP
1
dQqTkAaD14K6O(PPVaV,S%cl$)S!{#a'*//2H#H#J &;&&q!g&>  $$Q$9#FF1wF/ *..q1G7*h.?.?7CSCS.S737 - N AQZ]F
1Av"#Q!Q 0HC")#,K #JE"''*e3#**51{+a/FF;#3#3A#67 0 $**51 !1 , J ]
	DADLDAD  ""[ a&1**= RNO$ LXJ 1  		s   AWV#W8V	WV3B+W V#>VV#W)V*V*W$V/;$W V4 3H&W4WC1W	WV##W4
W>W WWr   )
edge_attrsc                 <   U R                  5       (       d  U  Vs/ s H  oU1PM     sn$ US:  d  X0R                  5       :  a  [        S[        U 5       SU S35      eUb]  US:  d  X@R                  5       :  a  [        S[        U 5       SU S35      eXC:  a  [        SU SU 35      eUS:X  a  [	        U 5      /$ OU R                  5       n[        XUS9n[        U5      n[        U5      U:  a>   [        U5      nUS:  a  [        U5      U::  a  O[        U5      n[        U5      U:  a  M>  [        U[        S	S
9$ s  snf ! [         aN    [        U[        S	S
9n[        U5      U:  a+  UtpnX-  /nUR                  U5        [        U5      U:  a  M+  Us $ f = f)a,  Find communities in G using greedy modularity maximization.

This function uses Clauset-Newman-Moore greedy modularity maximization [2]_
to find the community partition with the largest modularity.

Greedy modularity maximization begins with each node in its own community
and repeatedly joins the pair of communities that lead to the largest
modularity until no further increase in modularity is possible (a maximum).
Two keyword arguments adjust the stopping condition. `cutoff` is a lower
limit on the number of communities so you can stop the process before
reaching a maximum (used to save computation time). `best_n` is an upper
limit on the number of communities so you can make the process continue
until at most n communities remain even if the maximum modularity occurs
for more. To obtain exactly n communities, set both `cutoff` and `best_n` to n.

This function maximizes the generalized modularity, where `resolution`
is the resolution parameter, often expressed as $\gamma$.
See :func:`~networkx.algorithms.community.quality.modularity`.

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

weight : string or None, optional (default=None)
    The name of an edge attribute that holds the numerical value used
    as a weight.  If None, then each edge has weight 1.
    The degree is the sum of the edge weights adjacent to the node.

resolution : float, optional (default=1)
    If resolution is less than 1, modularity favors larger communities.
    Greater than 1 favors smaller communities.

cutoff : int, optional (default=1)
    A minimum number of communities below which the merging process stops.
    The process stops at this number of communities even if modularity
    is not maximized. The goal is to let the user stop the process early.
    The process stops before the cutoff if it finds a maximum of modularity.

best_n : int or None, optional (default=None)
    A maximum number of communities above which the merging process will
    not stop. This forces community merging to continue after modularity
    starts to decrease until `best_n` communities remain.
    If ``None``, don't force it to continue beyond a maximum.

Raises
------
ValueError : If the `cutoff` or `best_n`  value is not in the range
    ``[1, G.number_of_nodes()]``, or if `best_n` < `cutoff`.

Returns
-------
communities: list
    A list of frozensets of nodes, one for each community.
    Sorted by length with largest communities first.

Examples
--------
>>> G = nx.karate_club_graph()
>>> c = nx.community.greedy_modularity_communities(G)
>>> sorted(c[0])
[8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]

See Also
--------
modularity

References
----------
.. [1] Newman, M. E. J. "Networks: An Introduction", page 224
   Oxford University Press 2011.
.. [2] Clauset, A., Newman, M. E., & Moore, C.
   "Finding community structure in very large networks."
   Physical Review E 70(6), 2004.
.. [3] Reichardt and Bornholdt "Statistical Mechanics of Community
   Detection" Phys. Rev. E74, 2006.
.. [4] Newman, M. E. J."Analysis of weighted networks"
   Physical Review E 70(5 Pt 2):056131, 2004.
r
   zcutoff must be between 1 and z. Got .zbest_n must be between 1 and z Must have best_n >= cutoff. Got z < )r   r)   Tkeyreverser   )
r   r   
ValueErrorr   r&   rN   nextStopIterationsortedextend)r(   r   r)   cutoffbest_nr;   community_genr=   r9   comm1comm2rests               r   r   r      s   l 6688QQ
!2!2!448QvhaPQQQJF%6%6%88<SVHF6(RSTUU??xs6(STTQ;F8O  ""$ =	ZM
 }%K k
V
#
	m$B 6c+&&0=)! k
V
#$ +355S  6  	 #tDKk"V+&1#t$}o""4( k"V+ 	s   D>2E AFFFr*   
multigraphc           	         U R                  5        Vs/ s H  n[        U/5      PM     nn/ nSn[        XXS9nUb  Xv:  Ga  Un[        U5      nSn	[	        U5       H  u  p[	        U5       H  u  pX::  d  [        U5      S:X  d  [        U5      S:X  a  M*  X<-  X'   [        / 5      X'   [        XXS9nX:  a<  X:  a	  UnXXv-
  4n	O.U	(       a'  [        X5      [        U	S   U	S   5      :  a  UnXXv-
  4n	X8U
'   XU'   M     M     U	b0  UR                  U	5        U	u  pnXJ   XK   pX<-  XK'   [        / 5      XJ'   Uc  M  Xv:  a  GM  [        S U 5       [
        SS9$ s  snf )a  Find communities in G using greedy modularity maximization.

This implementation is O(n^4), much slower than alternatives, but it is
provided as an easy-to-understand reference implementation.

Greedy modularity maximization begins with each node in its own community
and joins the pair of communities that most increases modularity until no
such pair exists.

This function maximizes the generalized modularity, where `resolution`
is the resolution parameter, often expressed as $\gamma$.
See :func:`~networkx.algorithms.community.quality.modularity`.

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

resolution : float (default=1)
    If resolution is less than 1, modularity favors larger communities.
    Greater than 1 favors smaller communities.

weight : string or None, optional (default=None)
    The name of an edge attribute that holds the numerical value used
    as a weight.  If None, then each edge has weight 1.
    The degree is the sum of the edge weights adjacent to the node.

Returns
-------
list
    A list of sets of nodes, one for each community.
    Sorted by length with largest communities first.

Examples
--------
>>> G = nx.karate_club_graph()
>>> c = nx.community.naive_greedy_modularity_communities(G)
>>> sorted(c[0])
[8, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]

See Also
--------
greedy_modularity_communities
modularity
N)r)   r   r   r
   c              3   H   #    U  H  n[        U5      S :  d  M  Uv   M     g7f)r   N)r   ).0cs     r   	<genexpr>6naive_greedy_modularity_communities.<locals>.<genexpr>  s     8kSVaZ11ks   "	"TrR   )	nodesr    r   list	enumerater   minappendrX   )r(   r)   r   r5   r=   mergesold_modularitynew_modularitytrial_communitiesto_mergeijr6   trial_modularityr9   s                  r   r   r   e  s   d ,-77959a9aS>9K5FN:UN

 N$C' -k*DA!+.6SVq[CFaK'(u!$'0}!$#-Z$  $5'8)9$%.*I#J!c!i#hqk8A;2O&O)9$%.*I#J'(!$'(!$- / +0 MM(#HA">;>qUKN&r]KNI 
 N$CL 8k8c4PPY 6s   E)Nr
   )Nr
   r
   N)r
   N)__doc__collectionsr   networkxnx%networkx.algorithms.community.qualityr   networkx.utilsr   networkx.utils.mapped_queuer   __all__rN   _dispatchabler   r   r   r   r   <module>r}      s    > #  < . 3 $)O#d X& 6 '6D Z \"X&[Q ' # ![Qr   