networkx库建模
这里按照边建立了图
networkx库优先考虑节点,以 (i,j)来表示边,所以它的很多函数返回的都是与节点相关的值,举例如下:
-
nx.all_shortest_paths(G, start, destination)返回一个generator,转化为列表后是[ [0, 4, 3], [0, 2, 3]]这种形式,每一行表示路径,每一列表示节点,可以由此构建路径-节点邻接矩阵
-
nx.adjacency_matrix(G)返回的是节点-节点邻接矩阵,但其打印形式更接近dict,调用时也是node_node[i,j] 而非 node_node[i][j]
(0, 1) 1 (0, 2) 1 (0, 3) 1 (1, 0) 1
-
nx.incidence_matrix(G)返回节点-路段邻接矩阵,每一行表示节点,每一列表示路段。但我个人不推荐这种用法,因为构建边的时候,是使用(i,j)表示边,但从下述打印结果来看,函数为每条边又赋予了一个编号,但我们在定义时是不知道的。
(0, 0) 1.0 (1, 0) 1.0 (0, 1) 1.0 (2, 1) 1.0 (0, 2) 1.0
-
可以根据路径-节点邻接矩阵和节点-节点邻接矩阵构建路径-路段邻接字典 {r, (i,j): 1 or 0}, 1 表示路段(i,j)包含于路径r中,0表示不包含。
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from itertools import combinations
# create a graph
G = nx.Graph()
# edges
elist=[(0,1),(0,4),(0,2),(1,2),(1,4),(2,3),(3,4)]
# create graph
G.add_edges_from(elist)
# create OD pair
OD_node_set=[0,2,3,4]
OD_set = list(combinations(OD_node_set, 2)) # [(1,3),(1,4),(1,5),(3,4),(3,5),(4,5)]
# find shortest paths of given OD pairs
path = []
for i in range(len(OD_set)):
routes = nx.all_shortest_paths(G, OD_set[i][0], OD_set[i][1])
for route in routes:
path.append(route)
num_path = len(path)
# [[0, 2], [0, 4, 3], [0, 2, 3], [0, 4], [2, 3], [2, 0, 4], [2, 1, 4], [2, 3, 4], [3, 4]]
# path-node incidence matrix: [[]]
num_node = G.number_of_nodes()
path_node = np.zeros((num_path, num_node))
for r in range(num_path):
for i in path[r]:
path_node[r][i] = 1
# print(path_node)
# node-node adjacent dict: {(i,j):0 or 1}
node_node = nx.adjacency_matrix(G)
# print(node_node)
# path-link incidence dict: {r,(i,j): 0 or 1}
path_link = {}
for r in range(num_path):
for i, j in elist:
path_link[r, (i, j)] = path_node[r][i] * path_node[r][j] * node_node[i, j]
# for key in path_link.keys():
# print(key,path_link[key])
# paint graph
aX = plt.plot()
nx.draw(G,with_labels=True)
plt.show()