繁体   English   中英

使用 networkx 的最短路径的边缘属性

[英]Edge attributes of shortest path using networkx

我正在尝试使用 networkx 来计算两个节点之间的最短路径。 例如:

paths = nx.shortest_path(G, ‘A’, ‘C’, weight=‘cost’)

paths将返回类似于:['A', 'B', 'C']

nx.shortest_path_length()返回该路径的成本,这也很有帮助。 但是,我还想返回为此路径遍历的边列表。 在这些边缘内是我存储的其他属性,我想返回。

这可能吗?

这是一个可以满足您所有需要的代码(希望是:p):

import numpy as np
# import matplotlib.pyplot as plt
import networkx as nx

# Create a random graph with 8 nodes, with degree=3
G = nx.random_regular_graph(3, 8, seed=None)

# Add 'cost' attributes to the edges
for (start, end) in G.edges:
    G.edges[start, end]['cost'] = np.random.randint(1,10)

# Find the shortest path from 0 to 7, use 'cost' as weight
sp = nx.shortest_path(G, source=0, target=7, weight='cost')
print("Shortest path: ", sp)

# Create a graph from 'sp'
pathGraph = nx.path_graph(sp)  # does not pass edges attributes

# Read attributes from each edge
for ea in pathGraph.edges():
    #print from_node, to_node, edge's attributes
    print(ea, G.edges[ea[0], ea[1]])

输出将类似于以下内容:

Shortest path:  [0, 5, 7]
(0, 5) {'cost': 2}
(5, 7) {'cost': 3}

该脚本允许您获取访问边缘的属性列表

import networkx as nx
import matplotlib.pyplot as plt

Nodes = [('A', 'B'),('A', 'C'), ('C', 'D'), ('D', 'B'), ('C', 'B')]

G = nx.Graph()
num = 1 #name edge
for node in Nodes:
    G.add_edge(*node, num = num, weight = 1)
    num += 1

pos = nx.spring_layout(G)
edge_labels = nx.get_edge_attributes(G, 'num')
nx.draw(G,  with_labels=True, node_color='skyblue', pos=pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_color='red')
plt.show()

path = nx.shortest_path(G)
st = 'A' #start node
end = 'D' #end node
path_edges = [edge_labels.get(x, edge_labels.get((x[1],x[0]))) for x in zip(path[st][end], path[st][end][1:])]
print('Path by nodes: ', path[st][end])
print('Path by edges: ', path_edges)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM