该环节需要基于python的networkx库进行。实验中所用到的excel文件内容如图8所示。Python中的部分操作内容可以参考如下链接:
[4] https://zhuanlan.zhihu.com/p/164470586
图8
通过以下代码可以构建复杂网络,节点为道路端点,连边为道路。
#节点经纬度字典
dict_loc=dict(zip(df_node['节点ID'],list(zip(df_node['经度'],df_node['纬度']))))
# 创建空的交通网络
G = nx.Graph()
# 添加节点到交通网络
for index, row in df_node.iterrows():
node_id = row['节点ID']
longitude = row['经度']
latitude = row['纬度']
G.add_node(node_id, pos=(longitude, latitude))
# 添加边到交通网络
for index, row in df_edge.iterrows():
road_id = row['道路ID']
start_node = row['节点1']
end_node = row['节点2']
road_length = row['长度']
G.add_edge(start_node, end_node, road_id=road_id, length=road_length)
4**、最短路径计算**
以下代码以节点“19814”与节点“30073”为例展示了最短路径的计算方式,批量计算可以通过For循环实现。另外,由于实际计算中所需的POI(如配送中心)并不一定是道路的端点,此时可以通过一些判断准则,选取合适的道路端点代表POI(如选取距离POI最近的端点)。
# 计算最短路径
start_node = 19814
end_node = 30073
shortest_path = nx.shortest_path(G, source=start_node, target=end_node, weight='length')
shortest_distance = nx.shortest_path_length(G, source=start_node, target=end_node, weight='length')
# 打印最短路径和最短距离
print(f"最短路径: {shortest_path}")
print(f"最短距离: {shortest_distance}")