Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/scipy/sparse/_matrix_io.py: 14%
42 statements
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-14 06:37 +0000
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-14 06:37 +0000
1import numpy as np
2import scipy as sp
4__all__ = ['save_npz', 'load_npz']
7# Make loading safe vs. malicious input
8PICKLE_KWARGS = dict(allow_pickle=False)
11def save_npz(file, matrix, compressed=True):
12 """ Save a sparse matrix or array to a file using ``.npz`` format.
14 Parameters
15 ----------
16 file : str or file-like object
17 Either the file name (string) or an open file (file-like object)
18 where the data will be saved. If file is a string, the ``.npz``
19 extension will be appended to the file name if it is not already
20 there.
21 matrix: spmatrix or sparray
22 The sparse matrix or array to save.
23 Supported formats: ``csc``, ``csr``, ``bsr``, ``dia`` or ``coo``.
24 compressed : bool, optional
25 Allow compressing the file. Default: True
27 See Also
28 --------
29 scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format.
30 numpy.savez: Save several arrays into a ``.npz`` archive.
31 numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive.
33 Examples
34 --------
35 Store sparse matrix to disk, and load it again:
37 >>> import numpy as np
38 >>> import scipy as sp
39 >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
40 >>> sparse_matrix
41 <2x3 sparse matrix of type '<class 'numpy.int64'>'
42 with 2 stored elements in Compressed Sparse Column format>
43 >>> sparse_matrix.toarray()
44 array([[0, 0, 3],
45 [4, 0, 0]], dtype=int64)
47 >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
48 >>> sparse_matrix = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
50 >>> sparse_matrix
51 <2x3 sparse matrix of type '<class 'numpy.int64'>'
52 with 2 stored elements in Compressed Sparse Column format>
53 >>> sparse_matrix.toarray()
54 array([[0, 0, 3],
55 [4, 0, 0]], dtype=int64)
56 """
57 arrays_dict = {}
58 if matrix.format in ('csc', 'csr', 'bsr'):
59 arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
60 elif matrix.format == 'dia':
61 arrays_dict.update(offsets=matrix.offsets)
62 elif matrix.format == 'coo':
63 arrays_dict.update(row=matrix.row, col=matrix.col)
64 else:
65 msg = f'Save is not implemented for sparse matrix of format {matrix.format}.'
66 raise NotImplementedError(msg)
67 arrays_dict.update(
68 format=matrix.format.encode('ascii'),
69 shape=matrix.shape,
70 data=matrix.data
71 )
72 if isinstance(matrix, sp.sparse.sparray):
73 arrays_dict.update(_is_array=True)
74 if compressed:
75 np.savez_compressed(file, **arrays_dict)
76 else:
77 np.savez(file, **arrays_dict)
80def load_npz(file):
81 """ Load a sparse array/matrix from a file using ``.npz`` format.
83 Parameters
84 ----------
85 file : str or file-like object
86 Either the file name (string) or an open file (file-like object)
87 where the data will be loaded.
89 Returns
90 -------
91 result : csc_array, csr_array, bsr_array, dia_array or coo_array
92 A sparse array/matrix containing the loaded data.
94 Raises
95 ------
96 OSError
97 If the input file does not exist or cannot be read.
99 See Also
100 --------
101 scipy.sparse.save_npz: Save a sparse array/matrix to a file using ``.npz`` format.
102 numpy.load: Load several arrays from a ``.npz`` archive.
104 Examples
105 --------
106 Store sparse array/matrix to disk, and load it again:
108 >>> import numpy as np
109 >>> import scipy as sp
110 >>> sparse_array = sp.sparse.csc_array([[0, 0, 3], [4, 0, 0]])
111 >>> sparse_array
112 <2x3 sparse array of type '<class 'numpy.int64'>'
113 with 2 stored elements in Compressed Sparse Column format>
114 >>> sparse_array.toarray()
115 array([[0, 0, 3],
116 [4, 0, 0]], dtype=int64)
118 >>> sp.sparse.save_npz('/tmp/sparse_array.npz', sparse_array)
119 >>> sparse_array = sp.sparse.load_npz('/tmp/sparse_array.npz')
121 >>> sparse_array
122 <2x3 sparse array of type '<class 'numpy.int64'>'
123 with 2 stored elements in Compressed Sparse Column format>
124 >>> sparse_array.toarray()
125 array([[0, 0, 3],
126 [4, 0, 0]], dtype=int64)
128 In this example we force the result to be csr_array from csr_matrix
129 >>> sparse_matrix = sp.sparse.csc_matrix([[0, 0, 3], [4, 0, 0]])
130 >>> sp.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix)
131 >>> tmp = sp.sparse.load_npz('/tmp/sparse_matrix.npz')
132 >>> sparse_array = sp.sparse.csr_array(tmp)
133 """
134 with np.load(file, **PICKLE_KWARGS) as loaded:
135 sparse_format = loaded.get('format')
136 if sparse_format is None:
137 raise ValueError(f'The file {file} does not contain '
138 f'a sparse array or matrix.')
139 sparse_format = sparse_format.item()
141 if not isinstance(sparse_format, str):
142 # Play safe with Python 2 vs 3 backward compatibility;
143 # files saved with SciPy < 1.0.0 may contain unicode or bytes.
144 sparse_format = sparse_format.decode('ascii')
146 if loaded.get('_is_array'):
147 sparse_type = sparse_format + '_array'
148 else:
149 sparse_type = sparse_format + '_matrix'
151 try:
152 cls = getattr(sp.sparse, f'{sparse_type}')
153 except AttributeError as e:
154 raise ValueError(f'Unknown format "{sparse_type}"') from e
156 if sparse_format in ('csc', 'csr', 'bsr'):
157 return cls((loaded['data'], loaded['indices'], loaded['indptr']),
158 shape=loaded['shape'])
159 elif sparse_format == 'dia':
160 return cls((loaded['data'], loaded['offsets']),
161 shape=loaded['shape'])
162 elif sparse_format == 'coo':
163 return cls((loaded['data'], (loaded['row'], loaded['col'])),
164 shape=loaded['shape'])
165 else:
166 raise NotImplementedError(f'Load is not implemented for '
167 f'sparse matrix of format {sparse_format}.')