Is there any API about getting Khop neighbor graph of a given node or node list?

Is there any API about getting Khop neighbor graph of a given node or node list?
Thanks

1 Like

I think currently we only allow you to compute k-hop graph for the whole graph. I’m not sure if this is enough for your case.

I have noticed this API,but it is not very clear.
Can you give an example about the return value of the function?
Thank you! mufei

Does this example below make sense to you?

import dgl

g = dgl.DGLGraph()
g.add_nodes(3)
g.add_edges([0, 1], [1, 2]) # 0->1, 1->2
g_2 = dgl.transform.khop_graph(g, 2)
print(g_2.edges()) # 0->2

Also note that I just found a bug for this API and fixed it in PR #1433. You will need to install from source to get the latest version.

why only one edge in g_2?

It’s equivalent to raise the adjacency matrix to the power of 2, where a nonzero entry indicates that we can go from node i to node j with two steps.

1 Like

:+1:
thank you mufei

How could I get the subgraph construbuted by khop neighbors of one specific node and itself?
Is there an API like sub_graph(graph, nid, k)?
Now I try to get the 1-hop subgraph of one certain node is

sub_graph = graph.subgraph(graph.in_edges(nid)[0])
1 Like

You can find the subgraph by iteratively finding the 1st, 2nd, 3rd hop neighbors:

nids = [nid]
for _ in range(k):
    nid = graph.in_edges(nid)[0].unique()
    nids.append(new_nid)
nids = torch.cat(nids).unique()
subgraph = g.subgraph(nids)