
    hO                        S r SSKJr  SSKJrJr  SSKrSSKJ	r	  / SQr
\	" S5      \R                  SS j5       5       r\	" S	5      SS
 j5       r\	" S	5      SS j5       r\	" S	5      SS j5       r\	" S	5      SS j5       r\R                  " SS9SS j5       r\R                  " SS9SS j5       r\R                  S 5       r\R                  SS j5       r\	" S5      \R                  SS j5       5       rg)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           
      :   UbG  X;   a  [        [        X5      5      S   S-  $ [        X5       VVVVs0 s H  u  p#pEX$S-  _M     snnnn$ 0 nU R                  5        H(  u  pxU V	s1 s H  oU;  d  M
  X:w  d  M  U	iM     sn	Xg'   M*     [        [        R                  U S5      5      n
UR                  5        HI  u  pU H>  nXU   -  n[        U5      nX==   U-  ss'   X==   U-  ss'   U
R                  U5        M@     MK     [	        U
5      $ s  snnnnf s  sn	f )an  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                  M/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/cluster.pyr   r      s"   L :21<=a@AEE -Gq,PQ,PjaA6	,PQQ J ;;='0Vy!Z4GAAIAyV
 )
 dmmAq12O&,,.E#&77KK A"a'""a'""";/  /   / R Ws   D
&	D3D:D
multigraphc              #   B  ^ ^#    Uc  T R                   R                  5       nOU 4S jT R                  U5       5       nU HZ  u  p4[        U5      U1-
  m[	        U U4S jT 5       5      n[        S UR                  5        5       5      nU[        T5      Xe4v   M\     g7f)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   0   >#    U  H  oTU   4v   M     g 7fN .0r!   r   s     r'   	<genexpr>-_triangles_and_degree_iter.<locals>.<genexpr>f        >)=A!A$i)=   c              3   `   >#    U  H#  n[        T[        TU   5      U1-
  -  5      v   M%     g 7fr+   )r   set)r.   wr   vss     r'   r/   r0   j   s,     E"QSs1Q4yA3!788"   +.c              3   .   #    U  H  u  pX-  v   M     g 7fr+   r,   )r.   kvals      r'   r/   r0   k   s     B/AVQ/As   )adjr   nbunch_iterr4   r   sumr   )r   r   
nodes_nbrsr   v_nbrs
gen_degree
ntrianglesr6   s   `      @r'   r   r   Z   s      }UU[[]
>u)=>
	[A3E"EE
Bz/?/?/ABB
#b':22	  s   BBweightc              #     ^ ^^#    SSK nTb  T R                  5       S:X  a  SmO"[        U4S jT R                  SS9 5       5      mUc  T R                  R                  5       nOU 4S jT R                  U5       5       nU UU4S jnU H  u  pg[        U5      U1-
  nSn	[        5       n
U Hr  nU
R                  U5        [        T U   5      U
-
  nU" Xk5      nXR                  X-   Vs/ s H  oU" X5      -  U" X5      -  PM     sn5      R                  5       -  n	Mt     U[        U5      S	[        U	5      -  4v   M     gs  snf 7f)
zReturn 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   L   >#    U  H  u  po3R                  TS 5      v   M     g7frD   Ngetr.   ur   r   rB   s       r'   r/   6_weighted_triangles_and_degree_iter.<locals>.<genexpr>~   #     L9KgaAvq))9K   !$Tdatac              3   0   >#    U  H  oTU   4v   M     g 7fr+   r,   r-   s     r'   r/   rK      r1   r2   c                 :   > TU    U   R                  TS5      T-  $ NrD   rG   rJ   r   r   
max_weightrB   s     r'   wt/_weighted_triangles_and_degree_iter.<locals>.wt   !    tAw{{61%
22    r   )numpynumber_of_edgesmaxedgesr;   r   r<   r4   addcbrtr=   r   float)r   r   rB   npr>   rU   inbrsinbrsweighted_trianglesseenjjnbrswijr9   rT   s   ` `            @r'   #_weighted_triangles_and_degree_iterri   o   s*     ~**,1
Ld9KLL
}UU[[]
>u)=>
3 D	QCuAHHQK!I$E Q(C''6;mDm1.2a8+mD#ce  #e*a%(:";;<<  Es   C$E)EAEc              #     ^ #    U 4S jT R                  U5       5       nU H  u  p4n[        U5      U1-
  n[        U5      U1-
  nSn[        Xg5       Hd  n	[        T R                  U	   5      U	1-
  n
[        T R                  U	   5      U	1-
  nU[        S [        Xj-  Xk-  Xz-  X{-  5       5       5      -  nMf     [        U5      [        U5      -   n[        Xg-  5      nX<X4v   M     g7f)zReturn 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   `   >#    U  H#  oTR                   U   TR                  U   4v   M%     g 7fr+   _pred_succr-   s     r'   r/   6_directed_triangles_and_degree_iter.<locals>.<genexpr>   (     L7K!aggaj!''!*-7Kr7   r   c              3   &   #    U  H  nS v   M	     g7frF   r,   )r.   r9   s     r'   r/   ro      s      &A s   N)r<   r4   r   rm   rn   r=   r   )r   r   r>   ra   predssuccsipredsisuccsdirected_trianglesrf   jpredsjsuccsdtotaldbidirectionals   `             r'   #_directed_triangles_and_degree_iterr{      s      Mq}}U7KLJ%%Uqc!Uqc!v&A_s*F_s*F# &____	& #  ' Vs6{*V_-.==' &s   C&C)c              #     ^ ^^#    SSK nTb  T R                  5       S:X  a  SmO"[        U4S jT R                  SS9 5       5      mU 4S jT R	                  U5       5       nU UU4S jnU GH:  u  pgn[        U5      U1-
  n	[        U5      U1-
  n
SnU	 GHh  n[        T R                  U   5      U1-
  n[        T R                  U   5      U1-
  nXR                  X-   Vs/ s H  o" X5      U" X5      -  U" X5      -  PM     sn5      R                  5       -  nXR                  X-   Vs/ s H  o" X5      U" X5      -  U" X5      -  PM     sn5      R                  5       -  nXR                  X-   Vs/ s H  o" X5      U" Xo5      -  U" X5      -  PM     sn5      R                  5       -  nXR                  X-   Vs/ s H  o" X5      U" Xo5      -  U" X5      -  PM     sn5      R                  5       -  nGMk     U
 GHh  n[        T R                  U   5      U1-
  n[        T R                  U   5      U1-
  nXR                  X-   Vs/ s H  o" Xl5      U" X5      -  U" X5      -  PM     sn5      R                  5       -  nXR                  X-   Vs/ s H  o" Xl5      U" X5      -  U" X5      -  PM     sn5      R                  5       -  nXR                  X-   Vs/ s H  o" Xl5      U" Xo5      -  U" X5      -  PM     sn5      R                  5       -  nXR                  X-   Vs/ s H  o" Xl5      U" Xo5      -  U" X5      -  PM     sn5      R                  5       -  nGMk     [        U	5      [        U
5      -   n[        X-  5      nUUU[        U5      4v   GM=     gs  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf 7f)	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   NrD   c              3   L   >#    U  H  u  po3R                  TS 5      v   M     g7frF   rG   rI   s       r'   r/   ?_directed_weighted_triangles_and_degree_iter.<locals>.<genexpr>   rL   rM   TrN   c              3   `   >#    U  H#  oTR                   U   TR                  U   4v   M%     g 7fr+   rl   r-   s     r'   r/   r~      rp   r7   c                 :   > TU    U   R                  TS5      T-  $ rR   rG   rS   s     r'   rU   8_directed_weighted_triangles_and_degree_iter.<locals>.wt   rW   rX   )rY   rZ   r[   r\   r<   r4   rm   rn   r^   r=   r   r_   )r   r   rB   r`   r>   rU   ra   rr   rs   rt   ru   rv   rf   rw   rx   r9   ry   rz   rT   s   ` `               @r'   ,_directed_weighted_triangles_and_degree_iterr      s     ~**,1
Ld9KLL
Lq}}U7KLJ3 &%Uqc!Uqc!A_s*F_s*F'';A?K?a"Q(RX%10?K#ce '';A?K?a"Q(RX%10?K#ce '';A?K?a"Q(RX%10?K#ce '';A?K?a"Q(RX%10?K#ce   A_s*F_s*F'';A?K?a"Q(RX%10?K#ce '';A?K?a"Q(RX%10?K#ce '';A?K?a"Q(RX%10?K#ce '';A?K?a"Q(RX%10?K#ce   Vs6{*V_-&.%0B*CDDO & L L L L L L L Lsh   CO!#N+(O,#N0(O7#N5(O#N:%A+O#N?3(O#O>(O&#O		(O1#OA?O)
edge_attrsc                     [        XUS9R                  5       nU(       d#  U Vs/ s H  n[        U5      S:  d  M  UPM     nn[        U5      [	        U5      -  $ s  snf )uW  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
)rB   r   )r	   valuesabsr=   r   )r   r   rB   count_zeroscr   s         r'   r   r      sR    l 	1F+224A(1SVaZQ(q6CF? )s
   AAc                 f   U R                  5       (       a  UbA  [        XU5      nU VVVVs0 s H!  u  pEpgXGS:X  a  SOXuUS-
  -  SU-  -
  S-  -  _M#     nnnnnO[        X5      nU VVVVs0 s H!  u  pEpgXGS:X  a  SOXuUS-
  -  SU-  -
  S-  -  _M#     nnnnnOoUb6  [        XU5      nU VV	Vs0 s H  u  pIotUS:X  a  SO	XyU	S-
  -  -  _M     nn	nnO6[	        X5      nU VV	VV
s0 s H  u  pIpzXGS:X  a  SO	XyU	S-
  -  -  _M     nnn	nn
X;   a  X   $ U$ s  snnnnf s  snnnnf s  snn	nf s  sn
nn	nf )ua  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   rD   r   )is_directedr   r{   ri   r   )r   r   rB   td_iterr   dtdbr   clustercr   r   s              r'   r	   r	   6  sl   p 	}}B1VTG %,$+LA2 Q1AQ-!b&*@A)E$FF$+  H
 :!CG %,$+LA2 Q1AQ-!b&*@A)E$FF$+  H 9!FKGMTUW'!Q1Aa!e,==WHUH0:GPWXPW*!Q1Aa!e,==PWHXzO+ V Ys   (D
,(D
/D$%D+
c           
          [        U 5       VVVVs/ s H  u  pp4X2US-
  -  4PM     nnnnn[        U5      S:X  a  g[        [        [	        U6 5      u  pgUS:X  a  S$ Xg-  $ s  snnnnf )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
rD   r   )r   r   mapr=   zip)r   r   r   r   r   triangles_contrir   contris           r'   r
   r
     sx    D ,Fa+H+HZQ1QK+H   !C&6!78IQ16I$66s   A 
c           	         Uc  U nOU R                  U5      n0 nU H  nSX4'   Sn[        X   S5       Hr  u  pg[        [        X   5      [        X   5      -  U1-
  5      nX4==   U-  ss'   US-   n	XpU   ;   a  U	S-  n	U[        X   5      U	-
  [        X   5      U	-
  -   U-   -  nMt     US:  d  M  X4==   U-  ss'   M     X;   a  X1   $ U$ )u  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   rD   )r<   r   r   r4   )
r   r   	node_iterr	   r   	potentialrJ   r5   squaresdegms
             r'   r   r     s    n }	MM%(	J
	 q)DA3qt9s14y0QC78GMW$MQ;DaDy	#ad)d*s14y4/?@7JJI * q=MY&M  z  rX   c           
          X;   a  [        [        X5      5      S   $ [        X5       VVVVs0 s H  u  p#pEX%_M
     snnnn$ s  snnnnf )ut  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   "  sE    z z.q89!<<%?%IJ%IkaAAE%IJJJs   A
r+   )NrB   )NNT)NN)__doc__collectionsr   	itertoolsr   r   networkxnxnetworkx.utilsr   __all___dispatchabler   r   ri   r{   r   r   r	   r
   r   r   r,   rX   r'   <module>r      sQ   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rX   