矩阵市场#

这个 Matrix Market 交换格式是NIST描述的一种基于文本的文件格式。矩阵市场同时支持 坐标格式 对于稀疏矩阵和 数组格式 对于稠密矩阵。这个 scipy.io 模块提供了 scipy.io.mmreadscipy.io.mmwrite 分别以矩阵市场格式读取和写入数据的函数。这些函数可与以下任一项一起使用 numpy.ndarrayscipy.sparse.coo_matrix 对象,具体取决于数据是否在 阵列坐标 格式化。这些功能可以与NetworkX的功能相结合 convert_matrix 读写矩阵市场格式的图形的模块。

实例#

使用Matrix Market的图形读写功能 数组格式 对于密集矩阵:

>>> import scipy as sp
>>> import scipy.io  # for mmread() and mmwrite()
>>> import io  # Use BytesIO as a stand-in for a Python file object
>>> fh = io.BytesIO()

>>> G = nx.complete_graph(5)
>>> a = nx.to_numpy_array(G)
>>> print(a)
[[0. 1. 1. 1. 1.]
 [1. 0. 1. 1. 1.]
 [1. 1. 0. 1. 1.]
 [1. 1. 1. 0. 1.]
 [1. 1. 1. 1. 0.]]

>>> # Write to file in Matrix Market array format
>>> sp.io.mmwrite(fh, a)
>>> print(fh.getvalue().decode('utf-8'))  # file contents
%%MatrixMarket matrix array real symmetric
%
5 5
0.0000000000000000e+00
1.0000000000000000e+00
1.0000000000000000e+00
1.0000000000000000e+00
1.0000000000000000e+00
0.0000000000000000e+00
1.0000000000000000e+00
1.0000000000000000e+00
1.0000000000000000e+00
0.0000000000000000e+00
1.0000000000000000e+00
1.0000000000000000e+00
0.0000000000000000e+00
1.0000000000000000e+00
0.0000000000000000e+00

>>> # Read from file
>>> fh.seek(0)
>>> H = nx.from_numpy_array(sp.io.mmread(fh))
>>> H.edges() == G.edges()
True

使用Matrix Market的图形读写功能 坐标格式 对于稀疏矩阵:

>>> import scipy as sp
>>> import scipy.io  # for mmread() and mmwrite()
>>> import io  # Use BytesIO as a stand-in for a Python file object
>>> fh = io.BytesIO()

>>> G = nx.path_graph(5)
>>> m = nx.to_scipy_sparse_array(G)
>>> print(m)
  (0, 1)        1
  (1, 0)        1
  (1, 2)        1
  (2, 1)        1
  (2, 3)        1
  (3, 2)        1
  (3, 4)        1
  (4, 3)        1

>>> sp.io.mmwrite(fh, m)
>>> print(fh.getvalue().decode('utf-8'))  # file contents
%%MatrixMarket matrix coordinate integer symmetric
%
5 5 4
2 1 1
3 2 1
4 3 1
5 4 1

>>> # Read from file
>>> fh.seek(0)
>>> H = nx.from_scipy_sparse_matrix(sp.io.mmread(fh))
>>> H.edges() == G.edges()
True