Python networkx加权图在最短路径计算中不考虑节点的权重?

标签 python python-3.x networkx shortest-path weighted-graph

我正在使用 Python 3 和 Networkx 1.11。

我制作了一个加权图,权重位于边和一些节点上,但是当我计算最短路径的权重时,没有考虑节点的权重(代码如下)。

有人知道如何确保考虑节点权重吗?

谢谢! 山姆

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)

最佳答案

documentation for dijkstra_path ,我们有 dijkstra_path(G, source, target,weight='weight') 其中 weight 可以是两个节点和边的函数。下面是提供的示例:

The weight function can be used to include node weights.

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

In this example we take the average of start and end node weights of an edge and add it to the weight of the edge.

这将包括每个中间节点的全部值和两个端节点的一半。

您可以将函数修改为node_u_wt + edge_wt。然后,路径将包括每条边的权重以及作为路径中遇到的边的基础的每个节点的权重。 (因此它将包括起始节点和每个中间节点的全部权重,但不包括最终节点)。

<小时/>

另一个解决方法是创建一个有向图 H,其中边 uv 的边权重指定为u 的权重和 G 中边的权重

或者,您可以将边的权重设置为 v 的权重与边的权重之和,只要您对于包含基数还是目标数保持一致即可。因此,无论它是在进入还是离开节点时添加,路径都会受到该惩罚。您可能需要稍微注意路径的最终权重是否包括基本节点或目标节点。

关于Python networkx加权图在最短路径计算中不考虑节点的权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49136427/

相关文章:

python - 以 y 轴为百分比绘制直方图(使用 FuncFormatter?)

python - 无法让我的抓取工具完成循环以用完所有关键字

python - 从字典创建图形工具图形

python - Networkx 永远不会完成 200 万个节点的介数中心性计算

python - 如何使用 NetworkX 在加权图中获得最短路径?

Python - PayPal 定期付款 - 未显示协议(protocol)详细信息

python - 使用 Python 解析北欧格式日期(首先是 DMY,然后是 YMD)的最佳方法

python - 尝试使用 FFT 在 Python 中分析音频信号

python - Wxpython 如何更改Windows中Gauge Progress bar的颜色

python-3.x - Pandas:将 periodIndex 转换为多索引(年、月)