how to calculate short path geodesic distance of adjacency matrix csv [python]?

ぐ巨炮叔叔 提交于 2019-12-23 04:17:34

问题


i have an adjacency matrix of graph

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

how to convert it to geodesic discance matrix using python?

my goal is to make it like this :

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

i've tried some code in networkx but it only can calculate at one source and one destination of (n) not the whole matrix. I really need your help. Thank you


回答1:


networkx can calculate the whole matrix. One just need not to give source or destination to the nx.shortest_path function (see https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html - last example). Here's my solution:

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


来源:https://stackoverflow.com/questions/38564308/how-to-calculate-short-path-geodesic-distance-of-adjacency-matrix-csv-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!