在无向图中,对于给定的源节点(以下代码/图片中的sa')和目标节点列表(tlist = [' ta',&#39> ; tb',' tc',' td',' te' tf'])我试图找到子集直接连接的目标节点,即如果它们通过另一个目标节点连接,它们不会进入子集。
因此对于无向图G:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_path(['te','og','oe','sa','oa','ta','tb'])
#G = nx.Graph()
G.add_path(['tf','oe'])
G.add_path(['sa','of','td','od'])
G.add_path(['sa','ob','tc','oc','td'])
val_map = {'sa': 1.0,
'ta': 0.5714285714285714,
'tb': 0.5714285714285714,
'tc': 0.5714285714285714,
'td': 0.5714285714285714,
'te': 0.5714285714285714,
'tf': 0.5714285714285714
}
values = [val_map.get(node, 0.25) for node in G.nodes()]
nx.draw(G, cmap=plt.get_cmap('jet'), node_color=values,with_labels=True)
plt.show()
目标节点的结果子集应该是[' ta'' tc'''''''''' 39; TF']
提前致谢!
答案 0 :(得分:0)
对不起我糟糕的编程风格,但这只是一个草稿。无论如何它似乎工作,请测试其他无向图并在必要时进行改进:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_path(['te','og','oe','sa','oa','ta','tb'])
G.add_path(['tf','oe'])
G.add_path(['sa','of','td','od'])
G.add_path(['sa','ob','tc','oc','td'])
tlist=['ta','tb','tc','td','te','tf']
def deduplicate_list(seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or seen_add(x))]
def nearest_connected_neighbors(graph,sourcenode,targetnodes):
templist=[]
endendlist=[]
searchlist=[]
tlist=targetnodes
G=graph
nlist=G.neighbors(sourcenode)
donelist=[sourcenode]
while len(nlist)>0:
for n in nlist:
donelist.append(n)
if n in tlist:
endendlist.append(n)
endendlist=deduplicate_list(endendlist)
searchlist = list(set(nlist) - set(endendlist))
for n in searchlist:
templist.extend(G.neighbors(n))
templist=deduplicate_list(templist)
nlist=[]
nlist=list(set(templist) - set(donelist))
return endendlist
print nearest_connected_neighbors(G,'sa',tlist)