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
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