Python networkx加权图在最短路径计算中未考虑节点的权重?
我正在使用Python3和Networkx1.11 我制作了一个加权图,边和一些节点上都有权重,但是当我计算最短路径的权重时,节点的权重没有被考虑在内(下面的代码) 有人知道如何确保考虑节点权重吗 谢谢! 萨姆 在中,我们有Python networkx加权图在最短路径计算中未考虑节点的权重?,python,python-3.x,networkx,shortest-path,weighted-graph,Python,Python 3.x,Networkx,Shortest Path,Weighted Graph,我正在使用Python3和Networkx1.11 我制作了一个加权图,边和一些节点上都有权重,但是当我计算最短路径的权重时,节点的权重没有被考虑在内(下面的代码) 有人知道如何确保考虑节点权重吗 谢谢! 萨姆 在中,我们有dijkstra_路径(G,source,target,weight='weight'),其中weight可以是两个节点和边的函数。以下是提供的示例: 权重函数可用于包含节点权重 在本例中,我们取边的开始和结束节点权重的平均值,并将其添加到边的权重中 这将包括每个中间节点的完
dijkstra_路径(G,source,target,weight='weight')
,其中weight
可以是两个节点和边的函数。以下是提供的示例:
权重函数可用于包含节点权重
在本例中,我们取边的开始和结束节点权重的平均值,并将其添加到边的权重中
这将包括每个中间节点的完整值和两个端点节点的一半
您可以将函数修改为node\u\u wt+edge\u wt
。然后,路径将包括每条边的权重以及作为路径中遇到的边的基础的每个节点的权重。(因此,它将包括起始节点和每个中间节点的全部重量,但不包括最终节点)
另一种解决方法是创建一个有向图
H
,其中边u
到v
的边权重是u
的权重和边在G
中的权重之和
或者,您可以将边的权重设置为
v
的权重和边的权重之和,只要您对是否包含基准或目标保持一致。因此,无论路径是在进入或离开节点时添加的,路径都会受到惩罚。对于路径的最终权重是否包含基本节点或目标节点,您可能需要小心一点。我希望ALGO考虑所有的权重,所以在这个例子中,每个边的+2和节点B'NETWorkX的5都有一个考虑权重的方法。你的答案应该是六。短路径是a->b,b->d,d->e,2+2+2=6我的理解是最短路径
用于未加权的图(我刚才也检查了,它返回了正确的路径,但权重为3=>无权重),而dijkstra_路径
考虑了边权重。我只需要一种考虑节点权重的方法。我的答案应该是11:2+2+2+5(节点b的权重是5)
import networkx as nx
from matplotlib import pyplot as plt
# Set up a station map
all_stations = ['a','b','c','d','e']
interchange_stations = ['b']
routes = {'a':{'b':2}, 'c':{'b':2}, 'b':{'d':2}, 'd':{'e':2}}
print(routes)
# Make a network graph
G = nx.Graph()
# Add all the nodes (stations)
for station in all_stations:
weight = 0
if station in interchange_stations:
weight = 5
G.add_node(station, weight=weight)
print(G.nodes(data=True))
# Iterate through each line and add the time between stations
for name1, value in routes.items():
for name2, time in value.items():
if name1 == name2:
continue
G.add_edge(name1, name2, weight=time)
print(G.edges(data=True))
# Work out the minimium distance between all stops
route_times = nx.all_pairs_dijkstra_path_length(G)
# Work out the minimum path between all stops
route = nx.all_pairs_dijkstra_path(G)
print(route['a']['e']) # Returns: ['a', 'b', 'd', 'e']
print(route_times['a']['e']) # Returns: 6 (should be 2+2+2+5)
def func(u, v, d):
node_u_wt = G.nodes[u].get('node_weight', 1)
node_v_wt = G.nodes[v].get('node_weight', 1)
edge_wt = d.get('weight', 1)
return node_u_wt/2 + node_v_wt/2 + edge_wt