如何计算邻接矩阵csv [python]的短路测地距离?

时间:2016-07-25 09:38:33

标签: python csv matrix shortest-path adjacency-matrix

我有一个图的邻接矩阵

graph

  

n 1 2 3 4 5 6 7 8 9

     

1 0 1 1 1 0 0 0 0 0

     

2 1 0 1 0 0 0 0 0 0

     

3 1 1 0 1 0 0 0 0 0

     

4 1 0 1 0 1 1 0 0 0

     

5 0 0 0 1 0 1 1 1 0

     

6 0 0 0 1 1 0 1 1 0

     

7 0 0 0 0 1 1 0 1 1

     

8 0 0 0 0 1 1 1 0 0

     

9 0 0 0 0 0 0 1 0 0

如何使用python将其转换为geodesic discance矩阵?

我的目标是让它像这样:

  

n 1 2 3 4 5 6 7 8 9

     

1 0 1 1 1 2 2 3 3 4

     

2 1 0 1 2 3 3 4 4 5

     

3 1 1 0 1 2 2 3 3 4

     

4 1 2 1 0 1 1 2 2 3

     

5 2 3 2 1 0 1 1 1 2

     

6 2 3 2 1 1 0 1 1 2

     

7 3 4 3 2 1 1 0 1 1

     

8 3 4 3 2 1 1 1 0 2

     

9 4 5 4 3 2 2 1 2 0

我在networkx中尝试了一些代码,但它只能在(n)的一个源和一个目的地计算而不是整个矩阵。我真的需要你的帮助。 谢谢

1 个答案:

答案 0 :(得分:0)

networkx可以计算整个矩阵。只需要为nx.shortest_path函数提供源或目标(参见https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html - 最后一个示例)。这是我的解决方案:

import pprint
import networkx as nx
import pandas as pd
import numpy as np
mat = pd.read_csv('adjacency.csv', index_col=0, delim_whitespace=True).values
G = nx.from_numpy_matrix(mat)
p = nx.shortest_path(G)
shortest_path_mat = np.zeros(mat.shape)
for i in range(mat.shape[0]):
    shortest_path_mat[i, :] = np.array([len(x) for x in p[i].values()])
pprint.pprint(shortest_path_mat-1)

adjacency.csv

n 1 2 3 4 5 6 7 8 9

1 0 1 1 1 0 0 0 0 0

2 1 0 1 0 0 0 0 0 0

3 1 1 0 1 0 0 0 0 0

4 1 0 1 0 1 1 0 0 0

5 0 0 0 1 0 1 1 1 0

6 0 0 0 1 1 0 1 1 0

7 0 0 0 0 1 1 0 1 1

8 0 0 0 0 1 1 1 0 0

9 0 0 0 0 0 0 1 0 0
相关问题