MCPcopy
hub / github.com/dmlc/dgl / khop_graph

Function khop_graph

python/dgl/transforms/functional.py:1178–1263  ·  view source on GitHub ↗

Return the graph whose edges connect the :attr:`k`-hop neighbors of the original graph. More specifically, an edge from node ``u`` and node ``v`` exists in the new graph if and only if a path with length :attr:`k` exists from node ``u`` to node ``v`` in the original graph. The adja

(g, k, copy_ndata=True)

Source from the content-addressed store, hash-verified

1176
1177
1178def khop_graph(g, k, copy_ndata=True):
1179 """Return the graph whose edges connect the :attr:`k`-hop neighbors of the original graph.
1180
1181 More specifically, an edge from node ``u`` and node ``v`` exists in the new graph if
1182 and only if a path with length :attr:`k` exists from node ``u`` to node ``v`` in the
1183 original graph.
1184
1185 The adjacency matrix of the returned graph is :math:`A^k`
1186 (where :math:`A` is the adjacency matrix of :math:`g`).
1187
1188 Parameters
1189 ----------
1190 g : DGLGraph
1191 The input graph.
1192 k : int
1193 The :math:`k` in `k`-hop graph.
1194 copy_ndata: bool, optional
1195 If True, the node features of the new graph are copied from the
1196 original graph.
1197
1198 If False, the new graph will not have any node features.
1199
1200 (Default: True)
1201
1202 Returns
1203 -------
1204 DGLGraph
1205 The returned graph.
1206
1207 Notes
1208 -----
1209 If :attr:`copy_ndata` is True, the resulting graph will share the node feature
1210 tensors with the input graph. Hence, users should try to avoid in-place operations
1211 which will be visible to both graphs.
1212
1213 This function discards the batch information. Please use
1214 :func:`dgl.DGLGraph.set_batch_num_nodes`
1215 and :func:`dgl.DGLGraph.set_batch_num_edges` on the transformed graph
1216 to maintain the information.
1217
1218 Examples
1219 --------
1220
1221 Below gives an easy example:
1222
1223 >>> import dgl
1224 >>> g = dgl.graph(([0, 1], [1, 2]))
1225 >>> g_2 = dgl.transforms.khop_graph(g, 2)
1226 >>> print(g_2.edges())
1227 (tensor([0]), tensor([2]))
1228
1229 A more complicated example:
1230
1231 >>> import dgl
1232 >>> g = dgl.graph(([0,1,2,3,4,0,1,2,3,4], [0,1,2,3,4,1,2,3,4,0]))
1233 >>> dgl.khop_graph(g, 1)
1234 DGLGraph(num_nodes=5, num_edges=10,
1235 ndata_schemes={}

Callers

nothing calls this directly

Calls 4

adj_externalMethod · 0.80
num_nodesMethod · 0.45
formatsMethod · 0.45
graphMethod · 0.45

Tested by

no test coverage detected