请给出输出所有边被最短路径使用次数的完整代码
时间: 2024-02-28 09:55:39 浏览: 60
完整代码如下:
```
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx")
edges = []
for i in range(len(df)):
edge = {
"id": df.loc[i, "边的编号"],
"tail": df.loc[i, "边的尾节点"],
"head": df.loc[i, "边的头节点"],
"length": df.loc[i, "长度"],
"capacity": df.loc[i, "容量"]
}
edges.append(edge)
plt.figure(figsize=(15,15))
G = nx.DiGraph()
for edge in edges:
G.add_edge(edge["tail"], edge["head"], weight=edge["length"])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.5)
plt.show()
all_pairs = dict(nx.all_pairs_dijkstra_path_length(G))
rows = []
for start_node, dist_dict in all_pairs.items():
for end_node, dist in dist_dict.items():
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist})
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
# 计算每个节点到其他节点的平均最短距离
avg_dists = []
for node in G.nodes():
dist_sum = 0
for dist in all_pairs[node].values():
dist_sum += dist
avg_dist = dist_sum / len(G.nodes())
avg_dists.append(avg_dist)
# 画柱状图
plt.figure(figsize=(15,15))
plt.bar(G.nodes(), avg_dists)
plt.title("每个节点到其他节点的平均最短距离")
plt.xlabel("节点")
plt.ylabel("平均最短距离")
plt.show()
# 计算每条边被最短路径使用的次数
all_paths = dict(nx.all_pairs_dijkstra_path(G))
edge_counts = {edge["id"]: 0 for edge in edges}
for start_node in all_paths:
for end_node in all_paths[start_node]:
path = all_paths[start_node][end_node]
for i in range(len(path) - 1):
edge_id = G[path[i]][path[i+1]]["id"]
edge_counts[edge_id] += 1
# 输出每条边被最短路径使用的次数
for edge in edges:
print("边{}被使用了{}次".format(edge["id"], edge_counts[edge["id"]]))
```
这段代码在计算完所有节点对之间的最短路径后,遍历所有路径上的边,统计每条边被使用的次数,并输出每条边被使用的次数。
阅读全文