gpt4 book ai didi

python - networkx中的约束短路径算法?

转载 作者:行者123 更新时间:2023-12-04 11:03:34 24 4
gpt4 key购买 nike

我正在使用 networkx 来解决最短路径问题。我主要使用 shortest_path .我想知道,使用当前版本的 networkx,是否可以限制最短路径计算?
下面的示例生成了 A 和 G 之间的这两条最短路径:
shortest route
左边的图片显示了最小化“长度”属性时的最佳路线,右边的图片显示了最小化“高度”属性时的最佳路线。
如果我们计算这些路线的统计数据,我们会得到:

Best route by length: ['A', 'B', 'E', 'F', 'D', 'G']
Best route by height: ['A', 'C', 'E', '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}), ("A", "C", {"length": 9.7}), ("D", "C", {"length": 0.3}),
("B", "E", {"length": 4.8}), ("D", "E", {"length": 0.05}), ("C", "E", {"length": 0.1}),
("E", "C", {"length": 0.7}), ("E", "F", {"length": 0.4}), ("E", "G", {"length": 15.}),
("F", "C", {"length": 0.9}), ("F", "D", {"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, "A", "G",weight="length")
print(f"Best route by length: {best_route_by_length}")

best_route_by_height = nx.shortest_path(MG, "A", "G",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,
best_route_by_length,
'height'))}
stats_best_route['by_height']={'length': sum(get_route_edge_attributes(MG,
best_route_by_height,
'length')),
'height': 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)

最佳答案

近似解:

  • 按长度运行最短
  • 如果高度在限制内
    然后完成
  • 删除路径中最大高度的链接
  • 重复直到完成。

  • 障碍:
  • 如果具有最大高度的路径链接很重要,则删除它会使目的地无法到达。如果发生这种情况,则必须返回,更换最高链接并删除第二高链接......
  • 不能保证找到最佳路径。
  • 关于python - networkx中的约束短路径算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67674893/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com