当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python SciPy io.mmwrite用法及代码示例


本文简要介绍 python 语言中 scipy.io.mmwrite 的用法。

用法:

scipy.io.mmwrite(target, a, comment=None, field=None, precision=None, symmetry='AUTO')#

将稀疏或密集数组 a 写入 Matrix Market file-like 目标。

参数

target str 或 file-like

Matrix Market 文件名(扩展名 .mtx)或打开 file-like 对象。

a 类似数组

稀疏或密集的二维数组。

comment str,可选

要添加到 Matrix Market 文件之前的注释。

field 无或 str,可选

‘real’, ‘complex’, ‘pattern’或‘integer’。

precision 无或整数,可选

显示实值或复值的位数。

symmetry 无或 str,可选

‘AUTO’、‘general’, ‘symmetric’、‘skew-symmetric’或‘hermitian’。如果对称性为 None,则 ‘a’ 的对称类型由其值确定。如果对称性为“AUTO”,则 ‘a’ 的对称类型由 mmwrite 决定确定或设置为 ‘general’。

返回

None

注意

例子

>>> from io import BytesIO
>>> import numpy as np
>>> from scipy.sparse import coo_matrix
>>> from scipy.io import mmwrite

将一个小 NumPy 数组写入矩阵市场文件。该文件将以'array' 格式写入。

>>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
>>> target = BytesIO()
>>> mmwrite(target, a)
>>> print(target.getvalue().decode('latin1'))
%%MatrixMarket matrix array real general
%
2 4
1
0
0
2.5
0
0
0
6.25

向输出文件添加注释,并将精度设置为 3。

>>> target = BytesIO()
>>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
>>> print(target.getvalue().decode('latin1'))
%%MatrixMarket matrix array real general
%
% Some test data.
%
2 4
1.00e+00
0.00e+00
0.00e+00
2.50e+00
0.00e+00
0.00e+00
0.00e+00
6.25e+00

在调用 mmwrite 之前转换为稀疏矩阵。这将导致输出格式为 'coordinate' 而不是 'array'

>>> target = BytesIO()
>>> mmwrite(target, coo_matrix(a), precision=3)
>>> print(target.getvalue().decode('latin1'))
%%MatrixMarket matrix coordinate real general
%
2 4 3
1 1 1.00e+00
2 2 2.50e+00
2 4 6.25e+00

将复杂的 Hermitian 数组写入矩阵市场文件。请注意,实际上只有六个值写入文件;其他值由对称性暗示。

>>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
>>> z
array([[ 3. +0.j,  1. +2.j,  4. -3.j],
       [ 1. -2.j,  1. +0.j, -0. -5.j],
       [ 4. +3.j,  0. +5.j,  2.5+0.j]])
>>> target = BytesIO()
>>> mmwrite(target, z, precision=2)
>>> print(target.getvalue().decode('latin1'))
%%MatrixMarket matrix array complex hermitian
%
3 3
3.0e+00 0.0e+00
1.0e+00 -2.0e+00
4.0e+00 3.0e+00
1.0e+00 0.0e+00
0.0e+00 5.0e+00
2.5e+00 0.0e+00

该方法是线程化的。默认线程数等于系统中CPU的数量。使用threadpoolctl覆盖:

>>> import threadpoolctl
>>>
>>> target = BytesIO()
>>> with threadpoolctl.threadpool_limits(limits=2):
...     mmwrite(target, a)

相关用法


注:本文由纯净天空筛选整理自scipy.org大神的英文原创作品 scipy.io.mmwrite。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。