
    ިsgF                         d Z ddlmZ ddlZddlmZ ddlmZ ddl	m
Z
 ddgZdd	Z ej                  d
      	 	 	 	 dd       Z ed       ed       ej                  d
      dd                     Zy)z8Functions for detecting communities based on modularity.    )defaultdictN)
modularity)not_implemented_for)MappedQueuegreedy_modularity_communities#naive_greedy_modularity_communitiesc              #   x  K   | j                         }| j                         }| j                  |      }d|z  }|rQ| j                  |      D ci c]  \  }}|||z   }	}}| j	                  |      D 
ci c]  \  }}
||
|z   }}}
n.| j                  |      D ci c]  \  }}|||z  dz   c}}x}	}t        d       }| j                  |d      D ],  \  }}}||k(  r||   |xx   |z  cc<   ||   |xx   |z  cc<   . |j                         D ]C  \  }}|j                         D ]+  \  }}||z  ||	|   ||   z  ||   |	|   z  z   z  z
  ||   |<   - E | D ci c]6  }|t        ||   j                         D ci c]  \  }}||f|  c}}      8 }}}}t        | D cg c]&  }t        ||         dkD  s||   j                  d   ( c}      }| D ci c]  }|t        |g       }}|j                          t        |      dkD  rh	 |j                         \  }}}| }| ||   j                          t        ||         dkD  r!|j!                  ||   j                  d          ||   j                  d   ||fk(  r\|j#                  ||f       ||   j#                  ||f       t        ||         dkD  r8|j!                  ||   j                  d          n||   j#                  ||f       t        ||   ||   z        ||<   ||= t%        ||         }t%        ||         }||z  ||hz
  }||z  }|D ]*  }||v r||   |   ||   |   z   }nK||v r$||   |   ||	|   ||   z  |	|   ||   z  z   z  z
  }n#||   |   ||	|   ||   z  |	|   ||   z  z   z  z
  }||f||ffD ]  \  }}||   } |||   |<   t        |       dkD  r| j                  d   }!nd}!||f}"| }#||v r| j'                  |"|"|#       n| j!                  |"|#       |!|j!                  |"|#       || j                  d   }$|!|$k7  s|!j(                  |$j(                  k7  s|j'                  |!|$        - ||   D ]  }||   |   }%||   |= ||k7  s||f||ffD ]  \  }}||   } ||f}&| j                  d   |&k(  rP| j#                  |&       |j#                  |&       t        |       dkD  sR|j!                  | j                  d          q| j#                  |&         ||= t               ||<   |	|xx   |	|   z  cc<   d|	|<   |r||xx   ||   z  cc<   d||<   |j                          t        |      dkD  rgyyc c}}w c c}
}w c c}}w c c}}w c c}}}w c c}w c c}w # t        $ r Y yw xY ww)	a  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                       t        t              S )N)r   float     _/var/www/html/venv/lib/python3.12/site-packages/networkx/algorithms/community/modularity_max.py<lambda>z:_greedy_modularity_communities_generator.<locals>.<lambda>[   s    +e"4 r   )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_generatorrM      sl    r }}H	A 	
vA	
QB
 56\\\5PQMD'T7R<QQ34;;f;3MN<4T6B;NN78xxvx7NO)$sRx#~%OOA 45GGGG3 1b6
1
1	 mmo O
7]]_ 	OEArGjAaD1Q4K!A$1+4M&NNGAJqM	OO WXXXQRq+
8H8H8JKuq"1vs{KLLXGXJAc'!*o6IWQZ__Q'JKA /001in$0K0



 a&1*	%%'KE1a V
wqz?QFF71:??1%& 1:??1!Q'HHaVAJq!f%71:"wqzq)* AJq!f% #;q>KN#BCAN WQZWQZVO1v-VO	 $	4AI~
1
15f
1
adQqTkAaD1Q4K6O(PP
1
adQqTkAaD1Q4K6O(PPVaV, 4S%cl$)S!{#a'*//2H#H#J &;&&q!g&>  $$Q$9#FF1wF/ *..q1G7*h.?.?7CSCS.S7374$	4N  	2AQZ]F
1Av"#Q!Q 0 2HC")#,K #JE"''*e3#**51{+a/FF;#3#3A#67 $**512	2, AJ ]
	!!!aDAaDLDAaD  ""[ a&1*= RNO$ LXJ 1  		s   AV:V V:8VV:!V4B0V:$!VV
VV:,V!V!V:"V&6#V:V+ .H2V:!2V:AV:.BV: V:VV:+	V74V:6V77V:r   )
edge_attrsc                 *   | j                         s| D cg c]  }|h c}S |dk  s|| j                         kD  rt        dt        |        d| d      |Z|dk  s|| j                         kD  rt        dt        |        d| d      ||k  rt        d| d|       |dk(  rt	        |       gS | j                         }t        | ||      }t        |      }t        |      |kD  r:	 t        |      }|dk  rt        |      |k  rnt        |      }t        |      |kD  r:t        |t        d	
      S c c}w # t        $ rP t        |t        d	
      }t        |      |kD  r+|^}	}
}|	|
z  g}|j                  |       t        |      |kD  r+|cY S w xY w)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%   rM   nextStopIterationsortedextend)r'   r   r(   cutoffbest_nr:   community_genr<   r8   comm1comm2rests               r   r   r      s   l 668
!2!2!448QvhaPQQQJFQ%6%6%88<SVHF6(RSTUUF??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#ut$u}o""4( k"V+ 	s   
D4)D9 9AFFFr)   
multigraphc                    | j                         D cg c]  }t        |g       }}g }d}t        | |||      }|||kD  r
|}t        |      }d}	t	        |      D ]  \  }
}t	        |      D ]  \  }}||
k  st        |      dk(  st        |      dk(  r(||z  ||<   t        g       ||
<   t        | |||      }||k\  r;||kD  r|}|
|||z
  f}	n+|	r)t        |
|      t        |	d   |	d         k  r
|}|
|||z
  f}	|||
<   |||<     |	7|j                  |	       |	\  }
}}||
   ||   }}||z  ||<   t        g       ||
<   |||kD  r
t        d |D        t
        d      S c c}w )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   >   K   | ]  }t        |      d kD  s|  yw)r   N)r   ).0cs     r   	<genexpr>z6naive_greedy_modularity_communities.<locals>.<genexpr>  s     8SVaZ18s   TrQ   )	nodesr   r   list	enumerater   minappendrW   )r'   r(   r   r4   r<   mergesold_modularitynew_modularitytrial_communitiesto_mergeijr5   trial_modularityr8   s                  r   r   r   e  s   d ,-7795a9aS>5K5FN;:fUN

 N^$C' -k* 	)DAq!+. )16SVq[CFaK'(1u!!$'0}!!$#-(Z$  $~5'.8)9$%q.>*I#J!c!Qi#hqk8A;2O&O)9$%q.>*I#J'(!!$'(!!$-)	)0 MM(#HAq"q>;q>qAUKN&r]KNI 
 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__rM   _dispatchabler   r   r   r   r   <module>r{      s    > #  < . 3 $)O#d X& 6 '6D Z \"X&[Q ' # ![Qr   