U
    9vf  ã                   @   sj   d Z ddlZddlmZ ddlmZ ddgZejedd	ƒdd
d„ƒƒZdd„ Z	ejedd	ƒdd„ ƒƒZ
dS )z8Algorithms to calculate reciprocity in a directed graph.é    N)ÚNetworkXErroré   )Únot_implemented_forÚreciprocityÚoverall_reciprocityZ
undirectedZ
multigraphc                 C   sN   |dkrt | ƒS || kr@tt| |ƒƒd }|dkr<tdƒ‚n|S tt| |ƒƒS )af  Compute the reciprocity in a directed graph.

    The reciprocity of a directed graph is defined as the ratio
    of the number of edges pointing in both directions to the total
    number of edges in the graph.
    Formally, $r = |{(u,v) \in G|(v,u) \in G}| / |{(u,v) \in G}|$.

    The reciprocity of a single node u is defined similarly,
    it is the ratio of the number of edges in both directions to
    the total number of edges attached to node u.

    Parameters
    ----------
    G : graph
       A networkx directed graph
    nodes : container of nodes, optional (default=whole graph)
       Compute reciprocity for nodes in this container.

    Returns
    -------
    out : dictionary
       Reciprocity keyed by node label.

    Notes
    -----
    The reciprocity is not defined for isolated nodes.
    In such cases this function will return None.

    Né   zNot defined for isolated nodes.)r   ÚnextÚ_reciprocity_iterr   Údict)ÚGÚnodesr   © r   úC/tmp/pip-unpacked-wheel-_lngutwb/networkx/algorithms/reciprocity.pyr   
   s    !
c           	      c   sz   |   |¡}|D ]f}t|  |¡ƒ}t|  |¡ƒ}||@ }t|ƒt|ƒ }|dkrZ|dfV  qdt|ƒ | }||fV  qdS )z*Return an iterator of (node, reciprocity).r   Nr   )Znbunch_iterÚsetZpredecessorsÚ
successorsÚlen)	r   r   ÚnÚnodeÚpredÚsuccÚoverlapZn_totalr   r   r   r   r	   <   s    
r	   c                 C   s4   |   ¡ }||  ¡   ¡  d }|dkr,tdƒ‚|| S )z«Compute the reciprocity for the whole graph.

    See the doc of reciprocity for the definition.

    Parameters
    ----------
    G : graph
       A networkx graph

    r   r   zNot defined for empty graphs)Znumber_of_edgesZto_undirectedr   )r   Z
n_all_edgeZn_overlap_edger   r   r   r   N   s
    )N)Ú__doc__ZnetworkxZnxr   Úutilsr   Ú__all__Ú	_dispatchr   r	   r   r   r   r   r   Ú<module>   s   0