triangles#
- triangles(G, nodes=None)[source]#
Compute the number of triangles.
Finds the number of triangles that include a node as one vertex.
- Parameters:
- Ggraph
A networkx graph
- nodesnode, 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 inG
.
- Returns:
- outdict or int
If
nodes
is a container of nodes, returns number of triangles keyed by node (dict). Ifnodes
is a specific node, returns number of triangles for the node (int).
Notes
Self loops are ignored.
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]
The total number of unique triangles in
G
can be determined by summing the number of triangles for each node and dividing by 3 (because a given triangle gets counted three times, once for each of its nodes).>>> sum(nx.triangles(G).values()) // 3 10 ----
Additional backends implement this function
cugraph : GPU-accelerated backend.
graphblas : OpenMP-enabled sparse linear algebra backend.
- parallelA networkx backend that uses joblib to run graph algorithms in parallel. Find the nx-parallel’s configuration guide here
The nodes are chunked into
node_chunks
and for allnode_chunks
the number of triangles that include a node as one vertex is computed in parallel overn_jobs
number of CPU cores.- Additional parameters:
- get_chunksstr, function (default = “chunks”)
A function that takes in a list of all the nodes (or nbunch) as input and returns an iterable
node_chunks
. The default chunking is done by slicing thenodes
inton_jobs
number of chunks.
[Source]