2016-07-25 23 views
0

ich habe eine Adjazenzmatrix des GraphenWie berechnet man den kurzen Weg geodätischen Abstand der Adjazenzmatrix csv [Python]?

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

, wie es konvertieren discance Matrix mit Python geodätischen?

mein Ziel ist es, so zu machen:

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

habe ich versucht, einige Code in NetworkX aber es kann in einer Hand und ein Ziel von (n) nicht die gesamte Matrix nur berechnen. Ich brauche wirklich deine Hilfe. Danke

Antwort

0

networkx kann die gesamte Matrix berechnen. Man braucht der Quelle nx.shortest_path nur die Quelle oder das Ziel nicht zu geben (siehe https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html - letztes Beispiel). Hier ist meine Lösung:

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

Ich habe NetworkX installiert, pandas, numpy aber immer noch Fehler – kikiegoguma

+0

'Datei„C: \ Benutzer \ kikiegoguma \ Anaconda \ Lib \ site-packages \ networkx \ convert_matrix.py ", Zeile 487, aus from_numpy_matrix " nx, ny =% s "% (A.form,)) networkx.exception.NetworkXError: ('Adjazenzmatrix ist nicht quadratisch.', 'nx, ny = (9, 0) ') ' – kikiegoguma

+0

Vielleicht stimmt etwas in deiner' csv' Datei nicht. Bitte setzen Sie eine Leerzeile zwischen jede Wertezeile. Sie können es nicht von hier kopieren. –