如何解决networkx中的约束短路径算法?
我正在使用 networkx 来解决最短路径问题。我主要使用 shortest_path。我想知道,在当前版本的 networkx 中,是否可以限制最短路径计算?
左边的图片显示了最小化“长度”属性时的最佳路线,右边的图片显示了最小化“高度”属性时的最佳路线。
如果我们计算这些路线的统计数据,我们会得到:
Best route by length: ['A','B','E','F','D','G']
Best route by height: ['A','C','G']
Stats best routes: {
'by_length': {'length': 13.7,'height': 373.0},'by_height': {'length': 24.8,'height': 115.0}
}
有没有办法在计算最短路径时添加约束? (例如,通过最小化长度属性但同时保持 height<300
计算图网络的代码:
import matplotlib.pyplot as plt
from itertools import combinations,groupby
import os
import numpy as np
import networkx as nx
import random
# 1. Define test network
MG = nx.MultiDiGraph()
MG.add_edges_from([("B","A",{"length": 0.8}),("A","B",{"length": 1.}),("D","G",{"length": 3.5}),("B","D",{"length": 20.8}),"C",{"length": 9.7}),{"length": 0.3}),"E",{"length": 4.8}),{"length": 0.05}),("C",{"length": 0.1}),("E",{"length": 0.7}),"F",{"length": 0.4}),{"length": 15.}),("F",{"length": 0.9}),{"length": 4.}),])
attrs = {'B': {"x": -20.,"y": 60.},'A': {"x": 28.,"y":55.},'C': {"x": -12.,"y": 40.},'D': {"x": 40.,"y":45.},'E': {"x": 8.,"y": 35.},'F': {"x": -8.,"y":15.},'G': {"x": 21.,"y":5.},}
for num,(k,v) in enumerate(attrs.items()):
attrs[k]={**v,}
nx.set_node_attributes(MG,attrs)
rng = np.random.default_rng(seed=42)
random_height = list(rng.uniform(low=0,high=100,size=len(MG.edges)).round(0))
attrs={}
for num,edge in enumerate(MG.edges):
attrs[edge]={'height': random_height[num]}
nx.set_edge_attributes(MG,attrs)
# 2. Calculate shortest route
best_route_by_length = nx.shortest_path(MG,weight="length")
print(f"Best route by length: {best_route_by_length}")
best_route_by_height = nx.shortest_path(MG,weight="height")
print(f"Best route by height: {best_route_by_height}")
# 3. Get stats for each route
def get_route_edge_attributes(
G,route,attribute=None,minimize_key="length",retrieve_default=None
):
"""
"""
attribute_values = []
for u,v in zip(route[:-1],route[1:]):
# if there are parallel edges between two nodes,select the one with the
# lowest value of minimize_key
data = min(G.get_edge_data(u,v).values(),key=lambda x: x[minimize_key])
if attribute is None:
attribute_value = data
elif retrieve_default is not None:
attribute_value = data.get(attribute,retrieve_default(u,v))
else:
attribute_value = data[attribute]
attribute_values.append(attribute_value)
return attribute_values
stats_best_route={}
stats_best_route['by_length']={'length': sum(get_route_edge_attributes(MG,best_route_by_length,'length')),'height': sum(get_route_edge_attributes(MG,'height'))}
stats_best_route['by_height']={'length': sum(get_route_edge_attributes(MG,best_route_by_height,'height'))}
print(f"Stats best routes: {stats_best_route}")
编辑 07/06/21
我的问题可能太大,无法使用蛮力解决方案。
我还在networkx discussion page中开了一个帖子,似乎可以实现一个特殊的类,它在single_source_dijkstra
中作用于数字。
然而,这个解决方案并不完美:如果有两条可接受的短路径(在高度上),算法将找到较短的一条,而不管其高度如何。当存在可接受的路径时,这会使看起来不可能到达目标节点......(更多详细信息:https://github.com/networkx/networkx/discussions/4832#discussioncomment-778358)
解决方法
近似解决方案:
- 跑得最短
- 如果高度在限制范围内 然后完成
- 删除路径中具有最大高度的链接
- 重复直到完成。
障碍:
-
如果具有最大高度的路径链接很重要,删除它会使目的地无法到达。如果发生这种情况,则需要返回,替换最高链接并删除第二高链接......
-
不能保证找到最佳路径。
您真正的问题是否小到可以对 all_simple_paths()
使用蛮力?
from networkx.algorithms.simple_paths import all_simple_paths
shortest_paths_constrained = []
for path in all_simple_paths(MG,"A","G"):
if sum(get_route_edge_attributes(MG,path,'height')) < 300:
path_length = sum(get_route_edge_attributes(MG,'length'))
result = (path,path_length)
if not shortest_paths_constrained:
shortest_paths_constrained.append(result)
elif path_length == shortest_paths_constrained[0][1]:
shortest_paths_constrained.append(result)
elif path_length < shortest_paths_constrained[0][1]:
shortest_paths_constrained = [result]
它给 shortest_paths_constrained
作为
[(['A','C','E','F','D','G'],17.7)]
效率低下——但是,如果可行,它肯定会给出正确的解决方案。请注意,如果这对您的问题很重要,它还应该返回 length
约束内最短 height
的所有关系。如果需要,由您决定如何打破可能的联系。
好消息是 all_simple_paths()
返回一个生成器,而不是尝试一次找到所有路径,因此在内存中拟合所有路径不是问题。然而,完成计算需要多长时间是一个更大的谜......
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。