import networkx as nx
import numpy as np
# make dummy adjacency matrix
a = np.random.rand(100,100)
a = np.tril(a)
a = a>0.95
# make graph from adjaceny matrix
G = nx.from_numpy_matrix(a)
def neigh(G, node, depth):
""" given starting node, recursively find neighbours
until desired depth is reached
"""
node_list = []
if depth==0:
node_list.append(node)
else:
for neighbor in G.neighbors(node):
node_list.append(node)
node_list += neigh(G, neighbor, depth-1)
return list(set(node_list)) # intermediate conversion to set to lose duplicates.
# a bit more compressed:
def neigh_short(G, node, depth):
""" given starting node, recursively find neighbours
until desired depth is reached
"""
node_list = [node]
if depth>0:
for neighbor in G.neighbors(node)
node_list += neigh_short(G, neighbor, depth-1)
return list(set(node_list)) # intermediate conversion to set to lose duplicates.
# example:
# find all neighbours with distance 2 from node 5:
n = neigh(G, node=5, depth=2)
# extract the respective subgraph from G and store in H
H = G.subgraph(n)
下面是一个使用
networkx
的实现:相关问题 更多 >
编程相关推荐