2013-03-07 75 views
1

這應該很簡單,但我無法弄清楚。我只需要從文件中讀取矩陣,創建邊界列表並將邊界列表寫入文件

  • 讀取矩陣從文件成Python(即矩陣沒有頁眉/行名稱)
  • 將其轉換爲EdgeList都
  • 寫EdgeList都提交

我可以分別做這些,但我不知道如何從導入的矩陣轉到networkx模塊中的圖形對象。如果我能夠轉換爲networkx圖形,那麼我可以創建一個邊界列表並寫入文件。

矩陣的一個例子來讀取(它保存在.txt文件)

1 0 1 0 1 
1 0 1 0 0 
1 0 1 0 1 
0 0 1 0 0 
1 1 1 1 0 
1 1 1 0 1 
1 0 1 0 0 
+1

這似乎是一些功課。但是,您可以從http://stackoverflow.com/questions/6644529/read-from-a-text-file-python – user1929959 2013-03-07 23:27:59

+0

開始不,不是功課,我只是不知道蟒蛇 – sckott 2013-03-07 23:28:27

+0

不過,這個問題似乎是與圖論有關。請參閱相關鏈接。 – user1929959 2013-03-07 23:30:02

回答

3

安裝它,您不必NetworkX轉換爲一個簡單的邊列表:

adj = """1 0 1 0 1 
1 0 1 0 0 
1 0 1 0 1 
0 0 1 0 0 
1 1 1 1 0 
1 1 1 0 1 
1 0 1 0 0""" 

for row,line in enumerate(adj.split('\n')): 
    for col,val in enumerate(line.split(' ')): 
     if val == '1': 
      print row,col 
+0

尼斯,這是一個簡單的解決方案,而這正是我需要的 – sckott 2013-03-08 18:04:29

0
  1. 要讀取的文件,你想python的fp = open('\path\to\filename.txt')

    docs.python.org已經great information如何做到這一點,當你第一次學習時,往往是尋找答案的好地方。

  2. 你可能有一個看networkx包邊列表。他們有examples如何做到這一點。如果您已經安裝了setuptools的,你可以用easy_install networkx

+0

感謝指針 – sckott 2013-03-08 01:10:16

4

這將使用numpy的讀取矩陣和轉換將鄰接數據轉換爲邊緣列表。然後它創建一個networkx圖,並繪製一張圖。

import numpy as np 
import networkx as nx 
import matplotlib.pyplot as plt 


# Load the adjacency matrix into a numpy array. 
a = np.loadtxt('matrix.txt', dtype=int) 

print "a:" 
print a 

num_nodes = a.shape[0] + a.shape[1] 

# Get the row and column coordinates where the array is 1. 
rows, cols = np.where(a == 1) 

# We label the nodes corresponding to the rows with integers from 0 to 
# a.shape[0]-1, and we label the nodes corresponding to the columns with 
# integers from a.shape[0] to a.shape[0] + a.shape[1] - 1. 
# Rearranges the list of rows and columns into a list of edge tuples. 
edges = zip(rows.tolist(), (cols + a.shape[0]).tolist()) 
print "U nodes:", np.arange(a.shape[0]) 
print "V nodes:", np.arange(a.shape[1]) + a.shape[0] 
print "edges" 
print edges 

# Create a Graph object (from the networkx library). 
b = nx.Graph() 
b.add_nodes_from(range(num_nodes)) # This line not strictly necessry. 
b.add_edges_from(edges) 

# Draw the graph. First create positions for each node. Put the U nodes 
# on the left (x=1) and the V nodes on the right (x=2). 
pos = dict([(k, (1, k - 0.5 * a.shape[0])) 
      for k in range(a.shape[0])]) 
pos.update(dict([(k + a.shape[0], (2, k - 0.5 * a.shape[1])) 
        for k in range(a.shape[1])])) 
nx.draw_networkx(b, pos=pos, node_color=(['c'] * a.shape[0]) + (['y'] * a.shape[1])) 

plt.axis('off') 
plt.show() 

輸出:

a: 
[[1 0 1 0 1] 
[1 0 1 0 0] 
[1 0 1 0 1] 
[0 0 1 0 0] 
[1 1 1 1 0] 
[1 1 1 0 1] 
[1 0 1 0 0]] 
U nodes: [0 1 2 3 4 5 6] 
V nodes: [ 7 8 9 10 11] 
edges: 
[(0, 7), (0, 9), (0, 11), (1, 7), (1, 9), (2, 7), (2, 9), (2, 11), (3, 9), (4, 7), (4, 8), (4, 9), (4, 10), (5, 7), (5, 8), (5, 9), (5, 11), (6, 7), (6, 9)] 

情節: bipartite graph

+0

尼斯,感謝這個徹底的幫助。這很好,但我接受了下面的答案,因爲它比較簡單......儘管給了你一個贊成票 – sckott 2013-03-08 18:04:00