當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。