从文件读取矩阵,制作边缘列表,并将edgelist写入文件

时间:2013-03-07 23:20:34

标签: python networkx

这应该很简单,但我无法弄清楚。我只需要

  • 从文件中读取矩阵到Python(该矩阵没有标题/行名称)
  • 将其转换为edgelist
  • 将edgelist写入文件

我可以单独执行这些操作,但我不知道如何从导入的矩阵转到networkx模块中的图形对象。如果我能够转换为networkx图,那么我可以创建一个edgelist并写入文件。

要读入的矩阵示例(保存在.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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:1)

import numpy as np

#read matrix without head.
a = np.loadtxt('admatrix.txt', delimiter=',', dtype=int)  #set the delimiter as you need
print "a:"
print a
print 'shape:',a.shape[0] ,"*", a.shape[1]

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

num_edge = 0
edgeSet = set()

for row in range(a.shape[0]):
    for column in range(a.shape[1]):
        if a.item(row,column) == 1 and (column,row) not in edgeSet: #get rid of repeat edge
            num_edge += 1
            edgeSet.add((row,column))

print '\nnum_edge:', num_edge
print 'edge Set:', edgeSet
print ''
for edge in edgeSet:
    print edge[0] , edge[1]

此代码将读取以逗号分隔的邻接矩阵文件,并输出带有打印的边列表。

例如,adj-matrix.txt是:

0, 1, 0, 1
1, 0, 1, 0
0, 1, 0, 0
1, 0, 0, 0

edgelist的输出将是:

0 1
0 3
1 2

答案 3 :(得分:0)

  1. 对于阅读文件,您需要python的fp = open('\path\to\filename.txt')

    docs.python.org great information如何做到这一点,并且在您第一次学习时通常是搜索答案的好地方。

  2. 您可以查看边缘列表的networkx包。他们有examples如何做到这一点。如果您已安装setuptools,则可以使用easy_install networkx

  3. 进行安装