Matrix Market#
Matrix Market 交换格式是 NIST 描述的一种基于文本的文件格式。Matrix Market 支持用于稀疏矩阵的 坐标格式 和用于密集矩阵的 数组格式。scipy.io
模块提供了 scipy.io.mmread
和 scipy.io.mmwrite
函数,分别用于读写 Matrix Market 格式的数据。这些函数适用于 numpy.ndarray
或 scipy.sparse.coo_matrix
对象,具体取决于数据是 数组 格式还是 坐标 格式。这些函数可以与 NetworkX 的 convert_matrix
模块中的函数结合使用,以 Matrix Market 格式读写图。
示例#
使用 Matrix Market 的数组格式(array format)读写稠密矩阵对应的图
>>> import scipy as sp
>>> 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 的坐标格式(coordinate format)读写稀疏矩阵对应的图
>>> import scipy as sp
>>> 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_array(sp.io.mmread(fh))
>>> H.edges() == G.edges()
True