在图中查找相邻节点

Find neighboring nodes in graph

我有以下图表:

import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
g.add_edge(131,673,weight=673)
g.add_edge(131,201,weight=201)
g.add_edge(131,303,weight=20)
g.add_edge(673,96,weight=96)
g.add_edge(673,205,weight=44)
g.add_edge(673,110,weight=7)
g.add_edge(201,96,weight=96)
g.add_edge(201,232,weight=10)
nx.draw(g,with_labels=True)
plt.show()
g.nodes(data=True)
g.edges(data=True)

我需要创建一个函数 myfunction(g, node_list) returns 一个节点权重 < 50 的子图。

例如,如果我运行 myfunction(g, [131, 201]),输出应该是:

EdgeDataView([(131, 303, {'weight': 20}), (201, 232, {'weight': 10})])

一种方法是遍历列表中的所有节点,并使用来自 networkx 的 nx.neighbors 函数找到它们的邻居。然后,您可以设置一个 if 条件来检查感兴趣的节点与其邻居之间的边的权重。如果条件满足您的约束,您可以将邻居、边缘和权重添加到您的子图中。

查看下面的代码:

import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
g.add_edge(131,673,weight=673)
g.add_edge(131,201,weight=201)
g.add_edge(131,303,weight=20)
g.add_edge(673,96,weight=96)
g.add_edge(673,205,weight=44)
g.add_edge(673,110,weight=7)
g.add_edge(201,96,weight=96)
g.add_edge(201,232,weight=10)

fig=plt.figure(figsize=(10,10))

#Plot full graph
plt.subplot(211)
plt.title('Full graph')
labels_g = nx.get_edge_attributes(g,'weight')
pos_g=nx.circular_layout(g)
nx.draw_networkx_edge_labels(g,pos_g,edge_labels=labels_g)
nx.draw(g,pos=pos_g,with_labels=True)

def check_neighbor_weights(g,nodes):
  subg=nx.Graph() #Create subgraph

  for n in nodes:
    subg.add_node(n)
    neighbors=g.neighbors(n) #Find all neighbors of node n
    for neighs in neighbors:
      if g[n][neighs]['weight']<50: #Check if the weigh t is below 50
        subg.add_edge(n,neighs,weight=g[n][neighs]['weight'])
  return subg

subg=check_neighbor_weights(g,[131,201]) #Returns subgraph of interest

plt.subplot(212)
plt.title('subgraph')
labels_subg = nx.get_edge_attributes(subg,'weight')
pos_subg=nx.circular_layout(subg)
nx.draw_networkx_edge_labels(subg,pos=pos_subg,edge_labels=labels_subg)
nx.draw(subg,pos=pos_subg,with_labels=True)

plt.show()

并且输出给出: