K iWdZddlmZddlmZmZddlZddlm Z gdZ e dejddZ e d dd Z e d dd Ze d dd Ze d ddZejd ddZejd ddZejdZejddZe dejddZy)z>Algorithms to characterize the number of triangles in a graph.)Counter)chain combinationsN)not_implemented_for) trianglesaverage_clustering clustering transitivitysquare_clusteringgeneralized_degreedirectedc .|H||vrtt||ddzSt||Dcic] \}}}}||dzc}}}}Si}|jD]#\}}|D chc]} | |vs| |k7s| c} ||<%ttj |d} |j D]J\} }|D]@} ||| z} t| }| | xx|z cc<| | xx|z cc<| j| BLt | Scc}}}}wcc} w)aCompute 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 adjacencyrdictfromkeysitemslenupdate)Gnodesvdt_ later_nbrsnode neighborsntriangle_countsnode1node2 third_nodesms a/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/algorithms/cluster.pyrrsGL  A:21e<=a@AE E-Gq%,PQQjaAq16 QQ J;;=Wi'0V!AZ4GAQUIAV 4W dmmAq12O&,,.0y 0E#j&77KK A E "a ' " E "a ' "  " "; /  00   /RWsD ' D1D7D multigraphc#<K|jj}nfdj|D}|D]Z\}}t||hz t fdD}t d|jD}|t ||f\yw)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. Nc3,K|] }||f ywN.0r!rs r' z-_triangles_and_degree_iter..f>Aq!A$i>c3ZK|]"}tt||hz z$ywr+)rset)r.wrvss r'r/z-_triangles_and_degree_iter..js)EQSs1Q4yA3!78Es(+c3,K|] \}}||zywr+r,)r.kvals r'r/z-_triangles_and_degree_iter..ksBVQSBs)adjr nbunch_iterr3rsumr)rr nodes_nbrsrv_nbrs gen_degree ntrianglesr5s` @r'rrZs }UU[[] >u)=> 3 6 [A3 E"EE Bz/?/?/ABB #b':z22 3sBBweightc #Kddl}jdk(rdn$tfdjdD|jj }nfdj |D}fd}|D]\}}t||hz }d} t} |D]t} | j| t| | z } ||| } | |j|| zDcgc]}| || |z|||zc}jz } v|t|d t| zfycc}ww) aReturn 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. rNc3JK|]\}}}|jdywrBNgetr.urrr@s r'r/z6_weighted_triangles_and_degree_iter..~"LgaAvq)L #Tdatac3,K|] }||f ywr+r,r-s r'r/z6_weighted_triangles_and_degree_iter..r0r1c:||jdz SNrBrErHrr max_weightr@s r'wtz/_weighted_triangles_and_degree_iter..wt!tAw{{61% 22r) numpynumber_of_edgesmaxedgesr9rr:r3addcbrtr;rfloat)rrr@npr<rRinbrsinbrsweighted_trianglesseenjjnbrswijr7rQs` ` @r'#_weighted_triangles_and_degree_iterreos? ~**,1 Ld9KLL  }UU[[] >u)=> 3=4D QCu A HHQK!I$EQ(C "''6;emD#1a.2a8+D#ce   #e*a%(:";;<<=EsC%E*D?=Ec #Kfdj|D}|D]\}}}t||hz }t||hz }d}t||D]g} tj| | hz } tj| | hz } |t dt|| z|| z|| z|| zDz }it |t |z} t ||z} || | |fyw)aReturn 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. c3\K|]#}|j|j|f%ywr+_pred_succr-s r'r/z6_directed_triangles_and_degree_iter..(L!1aggaj!''!*-L),rc3 K|]}dywrDr,)r.r7s r'r/z6_directed_triangles_and_degree_iter..s&&s N)r:r3rrirjr;r)rrr<r]predssuccsipredsisuccsdirected_trianglesrbjpredsjsuccsdtotaldbidirectionals` r'#_directed_triangles_and_degree_iterrwsMq}}U7KLJ%>5%Uqc!Uqc!vv& A_s*F_s*F #&f_f_f_f_ &#   Vs6{*Vf_-&.*<=='>sC*C-c #Kddl}jdk(rdn$tfdjdDfdj |D}fd}|D]O\}}}t ||hz } t ||hz } d} | D]s} t j | | hz } t j| | hz }| |j| | zDcgc]}|| ||||z||| z!c}jz } | |j| |zDcgc]}|| ||||z|| |z!c}jz } | |j| | zDcgc]}|| ||||z||| z!c}jz } | |j| |zDcgc]}|| ||||z|| |z!c}jz } v| D]s} t j | | hz } t j| | hz }| |j| | zDcgc]}||| |||z||| z!c}jz } | |j| |zDcgc]}||| |||z|| |z!c}jz } | |j| | zDcgc]}||| |||z||| z!c}jz } | |j| |zDcgc]}||| |||z|| |z!c}jz } vt| t| z}t| | z}|||t| fRycc}wcc}wcc}wcc}wcc}wcc}wcc}wcc}ww) aReturn 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. rNrBc3JK|]\}}}|jdywrDrErGs r'r/z?_directed_weighted_triangles_and_degree_iter..rIrJTrKc3\K|]#}|j|j|f%ywr+rhr-s r'r/z?_directed_weighted_triangles_and_degree_iter..rkrlc:||jdz SrOrErPs r'rRz8_directed_weighted_triangles_and_degree_iter..wtrSrT) rUrVrWrXr:r3rirjrZr;rr[)rrr@r\r<rRr]rnrorprqrrrbrsrtr7rurvrQs` ` @r',_directed_weighted_triangles_and_degree_iterr|s ~**,1 Ld9KLL Lq}}U7KLJ3&'E5%Uqc!Uqc! A_s*F_s*F "'';AF?Ka"Q(R1X%1a0K#ce   "'';AF?Ka"Q(R1X%1a0K#ce   "'';AF?Ka"Q(R1X%1a0K#ce   "'';AF?Ka"Q(R1X%1a0K#ce     A_s*F_s*F "'';AF?Ka"Q(R1X%1a0K#ce   "'';AF?Ka"Q(R1X%1a0K#ce   "'';AF?Ka"Q(R1X%1a0K#ce   "'';AF?Ka"Q(R1X%1a0K#ce    Vs6{*Vf_-&.%0B*CDDO'ELLLLLLLLshCO%"$N=*O%0$O*O%>$O"*O% $O 0A+O%$O?*O%)$O *O%7$O*O%$O )A>> 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 valuesabsr;r)rrr@ count_zeroscrs r'rrsSl 1eF+224A  (1SVaZQ ( ( q6CF? )s AAc ^|jr|Bt|||}|Dcic]#\}}}}||dk(rdn|||dz zd|zz dzz %}}}}}nt||}|Dcic]#\}}}}||dk(rdn|||dz zd|zz dzz %}}}}}no|6t|||}|D cic]\}} }||dk(rdn || | dz zz }} }}n7t ||}|D  cic]\}} }} ||dk(rdn || | dz zz }}} }} ||vr||S|Scc}}}}wcc}}}}wcc}} }wcc} }} }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). rrBr) is_directedr|rwrer) rrr@td_iterrdtdbrclustercrrs r'r r 6sp }}  B1eVTG%, Ar2qQ1A"Q-!b&*@A)E$FFH :!UCG%, Ar2qQ1A"Q-!b&*@A)E$FFH  9!UFKGMTUU'!QQ1Aa!e,==UHU0E:GPWXX*!Q1Q1Aa!e,==XHX z O+ VYs(D ((D +D !D' c t|Dcgc]\}}}}|||dz zf}}}}}t|dk(ryttt |\}}|dk(rdS||z Scc}}}}w)aCompute 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 rBr)rrmapr;zip)rrrrrtriangles_contrircontris r'r r sD,Fa+H'Q1aAQK !C&6!78IvQ16I$66sA cj||}n|j|}i}|jGfddt}||D]}|}t|dz }|dkrd||<!d}t||z} d} d} |D]6} | } |t| |zz }t| |z}| |z } | ||dz zz } 8t j fd|D}||z}|j ||D]}t||z}| ||dz zz } | dz} || z | z | z }|dkDr | |z ||<d||<||vr||S|S)uCompute 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 ----- Self loops are ignored. 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 ceZdZdZfdZy)square_clustering..GAdjz>Calculate (and cache) node neighbor sets excluding self-loops.cPt|x}||<|j||Sr+)r3discard)selfr v_neighbors_G_adjs r' __missing__z+square_clustering..GAdj.__missing__s-$'q N 2K$q'    " rTN)__name__ __module__ __qualname____doc__r)rsr'GAdjrs L rTrrBrc3(K|] }| ywr+r,)r.rHG_adjs r'r/z$square_clustering..@s'FQa'Fsr)r:_adjrrr3unionr)rr node_iterr rrr v_degrees_m1 uw_degreesuw_countrsquaresrH u_neighborsp2two_hop_neighborsx potentialrrs @@r'r r sr } MM%( J VVFt FE .Ah ;'!+ 1 JqM   {#l2  %A(K #k*\9 9J[;./B OI rR!V} $G % II'F+'FG[(!!!$" %A[58+,B rR!V} $G % A )I5? q=#i/JqMJqM].^ z%  rTc ||vrtt||dSt||Dcic] \}}}}|| c}}}}Scc}}}}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 )rr)rrrrrgds r'r r SsNz z.q%89!<<%?5%I J JkaArArE JJ JsA r+)Nr@)NNT)NN)r collectionsr itertoolsrrnetworkxnxnetworkx.utilsr__all__ _dispatchablerrrerwr|rr r r r r,rTr'rsUD). Z B!!B!J\"3#3(\"%=#%=P\">#>B\"<E#<E~X&8'8vX&o'od'7'7T{{|Z =K!=KrT