
    hO                        d Z ddlmZ ddlmZmZ ddlZddlm	Z	 g dZ
 e	d      ej                  dd              Z e	d	      dd
       Z e	d	      dd       Z e	d	      dd       Z e	d	      dd       Z ej                  d      dd       Z ej                  d      dd       Zej                  d        Zej                  dd       Z e	d      ej                  dd              Zy)z>Algorithms to characterize the number of triangles in a graph.    )Counter)chaincombinationsN)not_implemented_for)	trianglesaverage_clustering
clusteringtransitivitysquare_clusteringgeneralized_degreedirectedc           
      .   |H|| v rt        t        | |            d   dz  S t        | |      D ci c]  \  }}}}||dz   c}}}}S i }| j                         D ]#  \  }}|D 	ch c]  }	|	|vs|	|k7  s|	 c}	||<   % t        t        j                  | d            }
|j                         D ]J  \  }}|D ]@  }|||   z  }t        |      }|
|xx   |z  cc<   |
|xx   |z  cc<   |
j                  |       B L t	        |
      S c c}}}}w c c}	w )a  Compute the number of triangles.

    Finds the number of triangles that include a node as one vertex.

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

    nodes : node, iterable of nodes, or None (default=None)
        If a singleton node, return the number of triangles for that node.
        If an iterable, compute the number of triangles for each of those nodes.
        If `None` (the default) compute the number of triangles for all nodes in `G`.

    Returns
    -------
    out : dict or int
       If `nodes` is a container of nodes, returns number of triangles keyed by node (dict).
       If `nodes` is a specific node, returns number of triangles for the node (int).

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.triangles(G, 0))
    6
    >>> print(nx.triangles(G))
    {0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
    >>> print(list(nx.triangles(G, [0, 1]).values()))
    [6, 6]

    Notes
    -----
    Self loops are ignored.

       r   )	next_triangles_and_degree_iter	adjacencyr   dictfromkeysitemslenupdate)Gnodesvdt_
later_nbrsnode	neighborsntriangle_countsnode1node2third_nodesms                  X/var/www/django_project/virt/lib/python3.12/site-packages/networkx/algorithms/cluster.pyr   r      sG   L A:21e<=a@AEE -Gq%,PQQjaAq16	QQ J ;;= Wi'0V!AZ4GAQUIAV
4W
 dmmAq12O&,,. 0y 	0E#j&77KK AE"a'"E"a'""";/	00   / R Ws   D

'	D1D7D
multigraphc              #   <   K   | j                   j                         }n fd j                  |      D        }|D ]Z  \  }}t        |      |hz
  t	         fdD              }t        d |j                         D              }|t              ||f \ yw)zReturn an iterator of (node, degree, triangles, generalized degree).

    This double counts triangles so you may want to divide by 2.
    See degree(), triangles() and generalized_degree() for definitions
    and details.

    Nc              3   ,   K   | ]  }||   f  y wN .0r!   r   s     r'   	<genexpr>z-_triangles_and_degree_iter.<locals>.<genexpr>f        >Aq!A$i>   c              3   Z   K   | ]"  }t        t        |         |hz
  z         $ y wr+   )r   set)r.   wr   vss     r'   r/   z-_triangles_and_degree_iter.<locals>.<genexpr>j   s)     EQSs1Q4yA3!78Es   (+c              3   ,   K   | ]  \  }}||z    y wr+   r,   )r.   kvals      r'   r/   z-_triangles_and_degree_iter.<locals>.<genexpr>k   s     BVQSBs   )adjr   nbunch_iterr3   r   sumr   )r   r   
nodes_nbrsr   v_nbrs
gen_degree
ntrianglesr5   s   `      @r'   r   r   Z   s      }UU[[]
>u)=>
 3	6[A3E"EE
Bz/?/?/ABB
#b':z22	3s   BBweightc              #      K   ddl } j                         dk(  rdn$t        fd j                  d      D              | j                  j                         }n fd j                  |      D        } fd}|D ]  \  }}t        |      |hz
  }d}	t               }
|D ]t  }|
j                  |       t         |         |
z
  } |||      }|	|j                  ||z  D cg c]  }| |||      z   |||      z   c}      j                         z  }	v |t        |      d	t        |	      z  f  yc c}w w)
a  Return an iterator of (node, degree, weighted_triangles).

    Used for weighted clustering.
    Note: this returns the geometric average weight of edges in the triangle.
    Also, each triangle is counted twice (each direction).
    So you may want to divide by 2.

    r   N   c              3   J   K   | ]  \  }}}|j                  d         ywrB   Ngetr.   ur   r   r@   s       r'   r/   z6_weighted_triangles_and_degree_iter.<locals>.<genexpr>~   "     LgaAvq)L    #Tdatac              3   ,   K   | ]  }||   f  y wr+   r,   r-   s     r'   r/   z6_weighted_triangles_and_degree_iter.<locals>.<genexpr>   r0   r1   c                 :    |    |   j                  d      z  S NrB   rE   rH   r   r   
max_weightr@   s     r'   wtz/_weighted_triangles_and_degree_iter.<locals>.wt   !    tAw{{61%
22    r   )numpynumber_of_edgesmaxedgesr9   r   r:   r3   addcbrtr;   r   float)r   r   r@   npr<   rR   inbrsinbrsweighted_trianglesseenjjnbrswijr7   rQ   s   ` `            @r'   #_weighted_triangles_and_degree_iterre   o   s?     ~**,1
Ld9KLL
}UU[[]
>u)=>
3  =4D	QCu 		AHHQK!I$E Q(C"''6;emD#1a.2a8+D#ce		 #e*a%(:";;<<= Es   C%E*D?=Ec              #      K    fd j                  |      D        }|D ]  \  }}}t        |      |hz
  }t        |      |hz
  }d}t        ||      D ]g  }	t         j                  |	         |	hz
  }
t         j                  |	         |	hz
  }|t        d t        ||
z  ||z  ||
z  ||z        D              z  }i t        |      t        |      z   }t        ||z        }||||f  yw)a  Return an iterator of
    (node, total_degree, reciprocal_degree, directed_triangles).

    Used for directed clustering.
    Note that unlike `_triangles_and_degree_iter()`, this function counts
    directed triangles so does not count triangles twice.

    c              3   \   K   | ]#  }|j                   |   j                  |   f % y wr+   _pred_succr-   s     r'   r/   z6_directed_triangles_and_degree_iter.<locals>.<genexpr>   (     L!1aggaj!''!*-L   ),r   c              3       K   | ]  }d   ywrD   r,   )r.   r7   s     r'   r/   z6_directed_triangles_and_degree_iter.<locals>.<genexpr>   s      & &s   N)r:   r3   r   ri   rj   r;   r   )r   r   r<   r]   predssuccsipredsisuccsdirected_trianglesrb   jpredsjsuccsdtotaldbidirectionals   `             r'   #_directed_triangles_and_degree_iterrw      s     Mq}}U7KLJ% >5%Uqc!Uqc!vv& 	A_s*F_s*F# &f_f_f_f_	& # 	 Vs6{*Vf_-&.*<=='>s   C*C-c              #      K   ddl } j                         dk(  rdn$t        fd j                  d      D               fd j	                  |      D        } fd}|D ]O  \  }}}t        |      |hz
  }	t        |      |hz
  }
d}|	D ]s  }t         j                  |         |hz
  }t         j                  |         |hz
  }||j                  |	|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }||j                  |	|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }||j                  |
|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }||j                  |
|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }v |
D ]s  }t         j                  |         |hz
  }t         j                  |         |hz
  }||j                  |	|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }||j                  |	|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }||j                  |
|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }||j                  |
|z  D cg c]  } |||       |||      z   |||      z  ! c}      j                         z  }v t        |	      t        |
      z   }t        |	|
z        }|||t        |      f R yc c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w w)	a  Return an iterator of
    (node, total_degree, reciprocal_degree, directed_weighted_triangles).

    Used for directed weighted clustering.
    Note that unlike `_weighted_triangles_and_degree_iter()`, this function counts
    directed triangles so does not count triangles twice.

    r   NrB   c              3   J   K   | ]  \  }}}|j                  d         ywrD   rE   rG   s       r'   r/   z?_directed_weighted_triangles_and_degree_iter.<locals>.<genexpr>   rI   rJ   TrK   c              3   \   K   | ]#  }|j                   |   j                  |   f % y wr+   rh   r-   s     r'   r/   z?_directed_weighted_triangles_and_degree_iter.<locals>.<genexpr>   rk   rl   c                 :    |    |   j                  d      z  S rO   rE   rP   s     r'   rR   z8_directed_weighted_triangles_and_degree_iter.<locals>.wt   rS   rT   )rU   rV   rW   rX   r:   r3   ri   rj   rZ   r;   r   r[   )r   r   r@   r\   r<   rR   r]   rn   ro   rp   rq   rr   rb   rs   rt   r7   ru   rv   rQ   s   ` `               @r'   ,_directed_weighted_triangles_and_degree_iterr|      s     ~**,1
Ld9KLL
Lq}}U7KLJ3 & 'E5%Uqc!Uqc! 	A_s*F_s*F"'';AF?Ka"Q(R1X%1a0K#ce "'';AF?Ka"Q(R1X%1a0K#ce "'';AF?Ka"Q(R1X%1a0K#ce "'';AF?Ka"Q(R1X%1a0K#ce	   	A_s*F_s*F"'';AF?Ka"Q(R1X%1a0K#ce "'';AF?Ka"Q(R1X%1a0K#ce "'';AF?Ka"Q(R1X%1a0K#ce "'';AF?Ka"Q(R1X%1a0K#ce	  Vs6{*Vf_-&.%0B*CDDO'E L L L L L L L Lsh   CO%"$N=*O%0$O*O%>$O"*O%$O0A+O%$O?*O%)$O*O%7$O*O%$O )A<O%)
edge_attrsc                     t        | ||      j                         }|s|D cg c]  }t        |      dkD  s| }}t        |      t	        |      z  S c c}w )u  Compute the average clustering coefficient for the graph G.

    The clustering coefficient for the graph is the average,

    .. math::

       C = \frac{1}{n}\sum_{v \in G} c_v,

    where :math:`n` is the number of nodes in `G`.

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

    nodes : container of nodes, optional (default=all nodes in G)
       Compute average clustering for nodes in this container.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    count_zeros : bool
       If False include only the nodes with nonzero clustering in the average.

    Returns
    -------
    avg : float
       Average clustering

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.average_clustering(G))
    1.0

    Notes
    -----
    This is a space saving routine; it might be faster
    to use the clustering function to get a list and then take the average.

    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
       http://jponnela.com/web_documents/a9.pdf
    .. [2] Marcus Kaiser,  Mean clustering coefficients: the role of isolated
       nodes and leafs on clustering measures for small-world networks.
       https://arxiv.org/abs/0802.2512
    )r@   r   )r	   valuesabsr;   r   )r   r   r@   count_zeroscr   s         r'   r   r      sS    l 	1eF+224A(1SVaZQ((q6CF? )s
   AAc                 ^   | j                         r|Bt        | ||      }|D ci c]#  \  }}}}||dk(  rdn|||dz
  z  d|z  z
  dz  z  % }}}}}nt        | |      }|D ci c]#  \  }}}}||dk(  rdn|||dz
  z  d|z  z
  dz  z  % }}}}}no|6t        | ||      }|D 	ci c]  \  }}	}||dk(  rdn
||	|	dz
  z  z   }}	}}n7t	        | |      }|D 	
ci c]  \  }}	}}
||dk(  rdn
||	|	dz
  z  z   }}}	}}
|| v r||   S |S c c}}}}w c c}}}}w c c}}	}w c c}
}}	}w )u]  Compute the clustering coefficient for nodes.

    For unweighted graphs, the clustering of a node :math:`u`
    is the fraction of possible triangles through that node that exist,

    .. math::

      c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},

    where :math:`T(u)` is the number of triangles through node :math:`u` and
    :math:`deg(u)` is the degree of :math:`u`.

    For weighted graphs, there are several ways to define clustering [1]_.
    the one used here is defined
    as the geometric average of the subgraph edge weights [2]_,

    .. math::

       c_u = \frac{1}{deg(u)(deg(u)-1))}
             \sum_{vw} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.

    The edge weights :math:`\hat{w}_{uv}` are normalized by the maximum weight
    in the network :math:`\hat{w}_{uv} = w_{uv}/\max(w)`.

    The value of :math:`c_u` is assigned to 0 if :math:`deg(u) < 2`.

    Additionally, this weighted definition has been generalized to support negative edge weights [3]_.

    For directed graphs, the clustering is similarly defined as the fraction
    of all possible directed triangles or geometric average of the subgraph
    edge weights for unweighted and weighted directed graph respectively [4]_.

    .. math::

       c_u = \frac{T(u)}{2(deg^{tot}(u)(deg^{tot}(u)-1) - 2deg^{\leftrightarrow}(u))},

    where :math:`T(u)` is the number of directed triangles through node
    :math:`u`, :math:`deg^{tot}(u)` is the sum of in degree and out degree of
    :math:`u` and :math:`deg^{\leftrightarrow}(u)` is the reciprocal degree of
    :math:`u`.


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

    nodes : node, iterable of nodes, or None (default=None)
        If a singleton node, return the number of triangles for that node.
        If an iterable, compute the number of triangles for each of those nodes.
        If `None` (the default) compute the number of triangles for all nodes in `G`.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    Returns
    -------
    out : float, or dictionary
       Clustering coefficient at specified nodes

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.clustering(G, 0))
    1.0
    >>> print(nx.clustering(G))
    {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}

    Notes
    -----
    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
       http://jponnela.com/web_documents/a9.pdf
    .. [2] Intensity and coherence of motifs in weighted complex
       networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski,
       Physical Review E, 71(6), 065103 (2005).
    .. [3] Generalization of Clustering Coefficients to Signed Correlation Networks
       by G. Costantini and M. Perugini, PloS one, 9(2), e88669 (2014).
    .. [4] Clustering in complex directed networks by G. Fagiolo,
       Physical Review E, 76(2), 026107 (2007).
    r   rB   r   )is_directedr|   rw   re   r   )r   r   r@   td_iterr   dtdbr   clustercr   r   s              r'   r	   r	   6  s   p 	}}B1eVTG %,  Ar2q Q1A"Q-!b&*@A)E$FFH 
 :!UCG %,  Ar2q Q1A"Q-!b&*@A)E$FFH  9!UFKGMTUU'!QQ1Aa!e,==UHU0E:GPWXX*!Q1Q1Aa!e,==XHXzO+ V Ys   (D
((D
+D !D'
c           
          t        |       D cg c]  \  }}}}|||dz
  z  f }}}}}t        |      dk(  ryt        t        t	        |       \  }}|dk(  rdS ||z  S c c}}}}w )a  Compute graph transitivity, the fraction of all possible triangles
    present in G.

    Possible triangles are identified by the number of "triads"
    (two edges with a shared vertex).

    The transitivity is

    .. math::

        T = 3\frac{\#triangles}{\#triads}.

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

    Returns
    -------
    out : float
       Transitivity

    Notes
    -----
    Self loops are ignored.

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.transitivity(G))
    1.0
    rB   r   )r   r   mapr;   zip)r   r   r   r   r   triangles_contrir   contris           r'   r
   r
     s    D ,Fa+H 'Q1aAQK  !C&6!78IvQ16I$66s   A 
c           	         || }n| j                  |      }i }|D ]  }d||<   d}t        | |   d      D ]v  \  }}t        t        | |         t        | |         z  |hz
        }||xx   |z  cc<   |dz   }	|| |   v r|	dz  }	|t        | |         |	z
  t        | |         |	z
  z   |z   z  }x |dkD  s||xx   |z  cc<    || v r||   S |S )ue  Compute the squares clustering coefficient for nodes.

    For each node return the fraction of possible squares that exist at
    the node [1]_

    .. math::
       C_4(v) = \frac{ \sum_{u=1}^{k_v}
       \sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v}
       \sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},

    where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and
    :math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u -
    (1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where
    :math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0
    otherwise. [2]_

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

    nodes : container of nodes, optional (default=all nodes in G)
       Compute clustering for nodes in this container.

    Returns
    -------
    c4 : dictionary
       A dictionary keyed by node with the square clustering coefficient value.

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.square_clustering(G, 0))
    1.0
    >>> print(nx.square_clustering(G))
    {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}

    Notes
    -----
    While :math:`C_3(v)` (triangle clustering) gives the probability that
    two neighbors of node v are connected with each other, :math:`C_4(v)` is
    the probability that two neighbors of node v share a common
    neighbor different from v. This algorithm can be applied to both
    bipartite and unipartite networks.

    References
    ----------
    .. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005
        Cycles and clustering in bipartite networks.
        Physical Review E (72) 056127.
    .. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of
        Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875.
        https://arxiv.org/abs/0710.0117v1
    r   r   rB   )r:   r   r   r3   )
r   r   	node_iterr	   r   	potentialrH   r4   squaresdegms
             r'   r   r     s   n }	MM%(	J '
1	 1q) 	KDAq3qt9s1Q4y0QC78GqMW$MQ;DAaDy	#ad)d*s1Q4y4/?@7JJI	K q=qMY&M' z%  rT   c           
          || v rt        t        | |            d   S t        | |      D ci c]
  \  }}}}|| c}}}}S c c}}}}w )u(  Compute the generalized degree for nodes.

    For each node, the generalized degree shows how many edges of given
    triangle multiplicity the node is connected to. The triangle multiplicity
    of an edge is the number of triangles an edge participates in. The
    generalized degree of node :math:`i` can be written as a vector
    :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc, k_i^{(N-2)})` where
    :math:`k_i^{(j)}` is the number of edges attached to node :math:`i` that
    participate in :math:`j` triangles.

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

    nodes : container of nodes, optional (default=all nodes in G)
       Compute the generalized degree for nodes in this container.

    Returns
    -------
    out : Counter, or dictionary of Counters
       Generalized degree of specified nodes. The Counter is keyed by edge
       triangle multiplicity.

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.generalized_degree(G, 0))
    Counter({3: 4})
    >>> print(nx.generalized_degree(G))
    {0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}), 4: Counter({3: 4})}

    To recover the number of triangles attached to a node:

    >>> k1 = nx.generalized_degree(G, 0)
    >>> sum([k * v for k, v in k1.items()]) / 2 == nx.triangles(G, 0)
    True

    Notes
    -----
    Self loops are ignored.

    In a network of N nodes, the highest triangle multiplicity an edge can have
    is N-2.

    The return value does not include a `zero` entry if no edges of a
    particular triangle multiplicity are present.

    The number of triangles node :math:`i` is attached to can be recovered from
    the generalized degree :math:`\mathbf{k}_i=(k_i^{(0)}, \dotsc,
    k_i^{(N-2)})` by :math:`(k_i^{(1)}+2k_i^{(2)}+\dotsc +(N-2)k_i^{(N-2)})/2`.

    References
    ----------
    .. [1] Networks with arbitrary edge multiplicities by V. Zlatić,
        D. Garlaschelli and G. Caldarelli, EPL (Europhysics Letters),
        Volume 97, Number 2 (2012).
        https://iopscience.iop.org/article/10.1209/0295-5075/97/28005
       )r   r   )r   r   r   r   r   gds         r'   r   r   "  sN    z z.q%89!<<%?5%IJJkaArArEJJJs   A
r+   )Nr@   )NNT)NN)__doc__collectionsr   	itertoolsr   r   networkxnxnetworkx.utilsr   __all___dispatchabler   r   re   rw   r|   r   r	   r
   r   r   r,   rT   r'   <module>r      sU   D  )  . Z B!  !B!J \"3 #3( \"%= #%=P \"> #>B \"<E #<E~ X&8 '8v X&o 'od '7 '7T J JZ Z =K  !=KrT   