identified_nodes#
- identified_nodes(G, u, v, self_loops=True, copy=True)#
Returns the graph that results from contracting
u
andv
.Node contraction identifies the two nodes as a single node incident to any edge that was incident to the original two nodes.
- Parameters
- GNetworkX graph
The graph whose nodes will be contracted.
- u, vnodes
Must be nodes in
G
.- self_loopsBoolean
If this is True, any edges joining
u
andv
inG
become self-loops on the new node in the returned graph.- copyBoolean
If this is True (default True), make a copy of
G
and return that instead of directly changingG
.
- Returns
- Networkx graph
If Copy is True, A new graph object of the same type as
G
(leavingG
unmodified) withu
andv
identified in a single node. The right nodev
will be merged into the nodeu
, so onlyu
will appear in the returned graph. If copy is False, ModifiesG
withu
andv
identified in a single node. The right nodev
will be merged into the nodeu
, so onlyu
will appear in the returned graph.
See also
Notes
For multigraphs, the edge keys for the realigned edges may not be the same as the edge keys for the old edges. This is natural because edge keys are unique only within each pair of nodes.
For non-multigraphs where
u
andv
are adjacent to a third nodew
, the edge (v
,w
) will be contracted into the edge (u
,w
) with its attributes stored into a “contraction” attribute.This function is also available as
identified_nodes
.Examples
Contracting two nonadjacent nodes of the cycle graph on four nodes
C_4
yields the path graph (ignoring parallel edges):>>> G = nx.cycle_graph(4) >>> M = nx.contracted_nodes(G, 1, 3) >>> P3 = nx.path_graph(3) >>> nx.is_isomorphic(M, P3) True
>>> G = nx.MultiGraph(P3) >>> M = nx.contracted_nodes(G, 0, 2) >>> M.edges MultiEdgeView([(0, 1, 0), (0, 1, 1)])
>>> G = nx.Graph([(1, 2), (2, 2)]) >>> H = nx.contracted_nodes(G, 1, 2, self_loops=False) >>> list(H.nodes()) [1] >>> list(H.edges()) [(1, 1)]