a
    1b4                     @   sp   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
 g dZdd	d
Ze
de
ddddZeZdS )z8Functions for detecting communities based on modularity.    )defaultdictN)
modularity)MappedQueue)not_implemented_for)greedy_modularity_communities#naive_greedy_modularity_communities$_naive_greedy_modularity_communities   c                     sB  |   }|  }|dk s ||kr4td| d| | |}d| |rfdd| j|dD }fdd| j|dD }nfdd| j|dD  }}td	d
  | j|ddD ]<\}	}
}|	|
krq |	 |
  |7  <  |
 |	  |7  < q 	 D ]P\}	}|	 D ]>\}
}| |||	 ||
  ||	 ||
      |	 |
< qq fdd| D t
fdd| D }dd | D }t||kr0z| \}}	}
W n ty   Y q0Y n0 | }|	   t|	 dkr||	 jd  |
 jd |
|	fkrZ||
|	f |
 |
|	f t|
 dkrl||
 jd  n|
 |
|	f |dkrzq0t||	 ||
 B ||
< ||	= t |	 }t |
 }||B |	|
h }||@ }|D ]d}||v r |
 |  |	 |  }nl||v r2 |
 | |||	 ||  || ||	     }n0 |	 | |||
 ||  || ||
     }|
|f||
ffD ]\}}| }| | |< t|dkr|jd }nd}||f}| }||v r|j|||d n|j||d |du r|j||d n.|jd }||ks |j|jkrr||| qrq̈ |	 D ]} | |	 } | |	= ||
kr<||	f|	|ffD ]h\}}| }||f}|jd |kr|| || t|dkr||jd  n
|| qpq< |	= t
 |	< ||
  ||	 7  < d||	< |r||
  ||	 7  < d||	< qt| tddS )a	  Find communities in G using greedy modularity maximization.

    This function uses Clauset-Newman-Moore greedy modularity maximization [2]_.

    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 or until number of communities `n_communities` is reached.

    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.

    n_communities: int
        Desired number of communities: the community merging process is
        terminated once this number of communities is reached, or until
        modularity can not be further increased. Must be between 1 and the
        total number of nodes in `G`. Default is ``1``, meaning the community
        merging process continues until all nodes are in the same community
        or until the best community structure is found.

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

    Examples
    --------
    >>> from networkx.algorithms.community import greedy_modularity_communities
    >>> G = nx.karate_club_graph()
    >>> c = 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$n_communities must be between 1 and z. Got c                    s   i | ]\}}||  qS  r
   ).0nodeZdeg_outq0r
   Klib/python3.9/site-packages/networkx/algorithms/community/modularity_max.py
<dictcomp>`       z1greedy_modularity_communities.<locals>.<dictcomp>)weightc                    s   i | ]\}}||  qS r
   r
   )r   r   Zdeg_inr   r
   r   r   a   r   c                    s   i | ]\}}||  d  qS )g      ?r
   )r   r   Zdegr   r
   r   r   c   r   c                   S   s   t tS N)r   floatr
   r
   r
   r   <lambda>g   r   z/greedy_modularity_communities.<locals>.<lambda>)datadefaultc                    s,   i | ]$  t  fd d   D qS )c                    s   i | ]\}} |f| qS r
   r
   )r   vdqur
   r   r   u   r   z<greedy_modularity_communities.<locals>.<dictcomp>.<dictcomp>)r   items)r   )dq_dictr   r   r   u   r   c                    s*   g | ]"}t  | d kr | jd  qS )r   )lenheapr   n)dq_heapr
   r   
<listcomp>w   r   z1greedy_modularity_communities.<locals>.<listcomp>c                 S   s   i | ]}|t |gqS r
   	frozensetr    r
   r
   r   r   z   r   r   N)priorityTkeyreverse)Zis_directedZnumber_of_nodes
ValueErrorsizeZ
out_degreeZ	in_degreeZdegreer   Zedgesr   r   r   pop
IndexErrorpushr   remover%   setupdater&   sortedvalues) Gr   
resolutionZn_communitiesdirectedNmabr   r   ZwtZnbrdictHcommunitiesZnegdqr   Zu_nbrsZv_nbrsZall_nbrsZ	both_nbrswZdq_vwrowcolZdq_heap_rowZd_oldmaxdZd_negdqZrow_maxZdq_oldZd_oldr
   )r   r"   r   r   r      s    @
:



20







r   r6   Z
multigraphc                 C   s  t dd |  D }g }d}t| |||d}|du s@||krr|}t |}d}t|D ]\}	}
t|D ]\}}||	ksht|
dksht|dkrqh|
|B ||< tg ||	< t| |||d}||kr||kr|}|	||| f}n6|rt|	|t|d |d k r|}|	||| f}|
||	< |||< qhqX|dur.|| |\}	}}||	 ||  }
}|
|B ||< tg ||	< q.tdd |D tdd	S )
a8  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

    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
    --------
    >>> from networkx.algorithms.community import \
    ... naive_greedy_modularity_communities
    >>> G = nx.karate_club_graph()
    >>> c = 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
    c                 s   s   | ]}t |gV  qd S r   r$   )r   r   r
   r
   r   	<genexpr>"  r   z6naive_greedy_modularity_communities.<locals>.<genexpr>N)r5   r   r   r	   c                 s   s   | ]}t |d kr|V  qdS )r   N)r   )r   cr
   r
   r   rA   N  r   Tr'   )	listZnodesr   	enumerater   r%   minappendr2   )r4   r5   r   r<   ZmergesZold_modularityZnew_modularityZtrial_communitiesZto_mergeir   jr   Ztrial_modularityr   r
   r
   r   r      sB    2 
$

r   )Nr	   r	   )r	   N)__doc__collectionsr   ZnetworkxZnxZ%networkx.algorithms.community.qualityr   Znetworkx.utils.mapped_queuer   Znetworkx.utilsr   __all__r   r   r   r
   r
   r
   r   <module>   s   
 ``