Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/scipy/io/_fast_matrix_market/__init__.py +594 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/_fast_matrix_market/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__init__.py +63 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_byteordercodes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio4.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio5.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio5_params.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_miobase.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/byteordercodes.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio4.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio5.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio5_params.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio5_utils.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio_utils.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/miobase.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/streams.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_byteordercodes.py +75 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio.py +359 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio4.py +624 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio5.py +892 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio5_params.py +281 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio5_utils.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio_utils.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_miobase.py +429 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_streams.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio.py +20 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio4.py +24 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio5.py +28 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio5_utils.py +19 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio_utils.py +17 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/miobase.py +22 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/big_endian.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/parabola.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/some_functions.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat +0 -0
- env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat +0 -0
env-llmeval/lib/python3.10/site-packages/scipy/io/_fast_matrix_market/__init__.py
ADDED
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
1 |
+
# Copyright (C) 2022-2023 Adam Lugowski. All rights reserved.
|
2 |
+
# Use of this source code is governed by the BSD 2-clause license found in
|
3 |
+
# the LICENSE.txt file.
|
4 |
+
# SPDX-License-Identifier: BSD-2-Clause
|
5 |
+
"""
|
6 |
+
Matrix Market I/O with a C++ backend.
|
7 |
+
See http://math.nist.gov/MatrixMarket/formats.html
|
8 |
+
for information about the Matrix Market format.
|
9 |
+
|
10 |
+
.. versionadded:: 1.12.0
|
11 |
+
"""
|
12 |
+
import io
|
13 |
+
import os
|
14 |
+
|
15 |
+
import numpy as np
|
16 |
+
import scipy.sparse
|
17 |
+
from scipy.io import _mmio
|
18 |
+
|
19 |
+
__all__ = ['mminfo', 'mmread', 'mmwrite']
|
20 |
+
|
21 |
+
PARALLELISM = 0
|
22 |
+
"""
|
23 |
+
Number of threads that `mmread()` and `mmwrite()` use.
|
24 |
+
0 means number of CPUs in the system.
|
25 |
+
Use `threadpoolctl` to set this value.
|
26 |
+
"""
|
27 |
+
|
28 |
+
ALWAYS_FIND_SYMMETRY = False
|
29 |
+
"""
|
30 |
+
Whether mmwrite() with symmetry='AUTO' will always search for symmetry
|
31 |
+
inside the matrix. This is scipy.io._mmio.mmwrite()'s default behavior,
|
32 |
+
but has a significant performance cost on large matrices.
|
33 |
+
"""
|
34 |
+
|
35 |
+
_field_to_dtype = {
|
36 |
+
"integer": "int64",
|
37 |
+
"unsigned-integer": "uint64",
|
38 |
+
"real": "float64",
|
39 |
+
"complex": "complex",
|
40 |
+
"pattern": "float64",
|
41 |
+
}
|
42 |
+
|
43 |
+
|
44 |
+
def _fmm_version():
|
45 |
+
from . import _fmm_core
|
46 |
+
return _fmm_core.__version__
|
47 |
+
|
48 |
+
|
49 |
+
# Register with threadpoolctl, if available
|
50 |
+
try:
|
51 |
+
import threadpoolctl
|
52 |
+
|
53 |
+
class _FMMThreadPoolCtlController(threadpoolctl.LibController):
|
54 |
+
user_api = "scipy"
|
55 |
+
internal_api = "scipy_mmio"
|
56 |
+
|
57 |
+
filename_prefixes = ("_fmm_core",)
|
58 |
+
|
59 |
+
def get_num_threads(self):
|
60 |
+
global PARALLELISM
|
61 |
+
return PARALLELISM
|
62 |
+
|
63 |
+
def set_num_threads(self, num_threads):
|
64 |
+
global PARALLELISM
|
65 |
+
PARALLELISM = num_threads
|
66 |
+
|
67 |
+
def get_version(self):
|
68 |
+
return _fmm_version
|
69 |
+
|
70 |
+
def set_additional_attributes(self):
|
71 |
+
pass
|
72 |
+
|
73 |
+
threadpoolctl.register(_FMMThreadPoolCtlController)
|
74 |
+
except (ImportError, AttributeError):
|
75 |
+
# threadpoolctl not installed or version too old
|
76 |
+
pass
|
77 |
+
|
78 |
+
|
79 |
+
class _TextToBytesWrapper(io.BufferedReader):
|
80 |
+
"""
|
81 |
+
Convert a TextIOBase string stream to a byte stream.
|
82 |
+
"""
|
83 |
+
|
84 |
+
def __init__(self, text_io_buffer, encoding=None, errors=None, **kwargs):
|
85 |
+
super().__init__(text_io_buffer, **kwargs)
|
86 |
+
self.encoding = encoding or text_io_buffer.encoding or 'utf-8'
|
87 |
+
self.errors = errors or text_io_buffer.errors or 'strict'
|
88 |
+
|
89 |
+
def __del__(self):
|
90 |
+
# do not close the wrapped stream
|
91 |
+
self.detach()
|
92 |
+
|
93 |
+
def _encoding_call(self, method_name, *args, **kwargs):
|
94 |
+
raw_method = getattr(self.raw, method_name)
|
95 |
+
val = raw_method(*args, **kwargs)
|
96 |
+
return val.encode(self.encoding, errors=self.errors)
|
97 |
+
|
98 |
+
def read(self, size=-1):
|
99 |
+
return self._encoding_call('read', size)
|
100 |
+
|
101 |
+
def read1(self, size=-1):
|
102 |
+
return self._encoding_call('read1', size)
|
103 |
+
|
104 |
+
def peek(self, size=-1):
|
105 |
+
return self._encoding_call('peek', size)
|
106 |
+
|
107 |
+
def seek(self, offset, whence=0):
|
108 |
+
# Random seeks are not allowed because of non-trivial conversion
|
109 |
+
# between byte and character offsets,
|
110 |
+
# with the possibility of a byte offset landing within a character.
|
111 |
+
if offset == 0 and whence == 0 or \
|
112 |
+
offset == 0 and whence == 2:
|
113 |
+
# seek to start or end is ok
|
114 |
+
super().seek(offset, whence)
|
115 |
+
else:
|
116 |
+
# Drop any other seek
|
117 |
+
# In this application this may happen when pystreambuf seeks during sync(),
|
118 |
+
# which can happen when closing a partially-read stream.
|
119 |
+
# Ex. when mminfo() only reads the header then exits.
|
120 |
+
pass
|
121 |
+
|
122 |
+
|
123 |
+
def _read_body_array(cursor):
|
124 |
+
"""
|
125 |
+
Read MatrixMarket array body
|
126 |
+
"""
|
127 |
+
from . import _fmm_core
|
128 |
+
|
129 |
+
vals = np.zeros(cursor.header.shape, dtype=_field_to_dtype.get(cursor.header.field))
|
130 |
+
_fmm_core.read_body_array(cursor, vals)
|
131 |
+
return vals
|
132 |
+
|
133 |
+
|
134 |
+
def _read_body_coo(cursor, generalize_symmetry=True):
|
135 |
+
"""
|
136 |
+
Read MatrixMarket coordinate body
|
137 |
+
"""
|
138 |
+
from . import _fmm_core
|
139 |
+
|
140 |
+
index_dtype = "int32"
|
141 |
+
if cursor.header.nrows >= 2**31 or cursor.header.ncols >= 2**31:
|
142 |
+
# Dimensions are too large to fit in int32
|
143 |
+
index_dtype = "int64"
|
144 |
+
|
145 |
+
i = np.zeros(cursor.header.nnz, dtype=index_dtype)
|
146 |
+
j = np.zeros(cursor.header.nnz, dtype=index_dtype)
|
147 |
+
data = np.zeros(cursor.header.nnz, dtype=_field_to_dtype.get(cursor.header.field))
|
148 |
+
|
149 |
+
_fmm_core.read_body_coo(cursor, i, j, data)
|
150 |
+
|
151 |
+
if generalize_symmetry and cursor.header.symmetry != "general":
|
152 |
+
off_diagonal_mask = (i != j)
|
153 |
+
off_diagonal_rows = i[off_diagonal_mask]
|
154 |
+
off_diagonal_cols = j[off_diagonal_mask]
|
155 |
+
off_diagonal_data = data[off_diagonal_mask]
|
156 |
+
|
157 |
+
if cursor.header.symmetry == "skew-symmetric":
|
158 |
+
off_diagonal_data *= -1
|
159 |
+
elif cursor.header.symmetry == "hermitian":
|
160 |
+
off_diagonal_data = off_diagonal_data.conjugate()
|
161 |
+
|
162 |
+
i = np.concatenate((i, off_diagonal_cols))
|
163 |
+
j = np.concatenate((j, off_diagonal_rows))
|
164 |
+
data = np.concatenate((data, off_diagonal_data))
|
165 |
+
|
166 |
+
return (data, (i, j)), cursor.header.shape
|
167 |
+
|
168 |
+
|
169 |
+
def _get_read_cursor(source, parallelism=None):
|
170 |
+
"""
|
171 |
+
Open file for reading.
|
172 |
+
"""
|
173 |
+
from . import _fmm_core
|
174 |
+
|
175 |
+
ret_stream_to_close = None
|
176 |
+
if parallelism is None:
|
177 |
+
parallelism = PARALLELISM
|
178 |
+
|
179 |
+
try:
|
180 |
+
source = os.fspath(source)
|
181 |
+
# It's a file path
|
182 |
+
is_path = True
|
183 |
+
except TypeError:
|
184 |
+
is_path = False
|
185 |
+
|
186 |
+
if is_path:
|
187 |
+
path = str(source)
|
188 |
+
if path.endswith('.gz'):
|
189 |
+
import gzip
|
190 |
+
source = gzip.GzipFile(path, 'r')
|
191 |
+
ret_stream_to_close = source
|
192 |
+
elif path.endswith('.bz2'):
|
193 |
+
import bz2
|
194 |
+
source = bz2.BZ2File(path, 'rb')
|
195 |
+
ret_stream_to_close = source
|
196 |
+
else:
|
197 |
+
return _fmm_core.open_read_file(path, parallelism), ret_stream_to_close
|
198 |
+
|
199 |
+
# Stream object.
|
200 |
+
if hasattr(source, "read"):
|
201 |
+
if isinstance(source, io.TextIOBase):
|
202 |
+
source = _TextToBytesWrapper(source)
|
203 |
+
return _fmm_core.open_read_stream(source, parallelism), ret_stream_to_close
|
204 |
+
else:
|
205 |
+
raise TypeError("Unknown source type")
|
206 |
+
|
207 |
+
|
208 |
+
def _get_write_cursor(target, h=None, comment=None, parallelism=None,
|
209 |
+
symmetry="general", precision=None):
|
210 |
+
"""
|
211 |
+
Open file for writing.
|
212 |
+
"""
|
213 |
+
from . import _fmm_core
|
214 |
+
|
215 |
+
if parallelism is None:
|
216 |
+
parallelism = PARALLELISM
|
217 |
+
if comment is None:
|
218 |
+
comment = ''
|
219 |
+
if symmetry is None:
|
220 |
+
symmetry = "general"
|
221 |
+
if precision is None:
|
222 |
+
precision = -1
|
223 |
+
|
224 |
+
if not h:
|
225 |
+
h = _fmm_core.header(comment=comment, symmetry=symmetry)
|
226 |
+
|
227 |
+
try:
|
228 |
+
target = os.fspath(target)
|
229 |
+
# It's a file path
|
230 |
+
return _fmm_core.open_write_file(str(target), h, parallelism, precision)
|
231 |
+
except TypeError:
|
232 |
+
pass
|
233 |
+
|
234 |
+
if hasattr(target, "write"):
|
235 |
+
# Stream object.
|
236 |
+
if isinstance(target, io.TextIOBase):
|
237 |
+
raise TypeError("target stream must be open in binary mode.")
|
238 |
+
return _fmm_core.open_write_stream(target, h, parallelism, precision)
|
239 |
+
else:
|
240 |
+
raise TypeError("Unknown source object")
|
241 |
+
|
242 |
+
|
243 |
+
def _apply_field(data, field, no_pattern=False):
|
244 |
+
"""
|
245 |
+
Ensure that ``data.dtype`` is compatible with the specified MatrixMarket field type.
|
246 |
+
|
247 |
+
Parameters
|
248 |
+
----------
|
249 |
+
data : ndarray
|
250 |
+
Input array.
|
251 |
+
|
252 |
+
field : str
|
253 |
+
Matrix Market field, such as 'real', 'complex', 'integer', 'pattern'.
|
254 |
+
|
255 |
+
no_pattern : bool, optional
|
256 |
+
Whether an empty array may be returned for a 'pattern' field.
|
257 |
+
|
258 |
+
Returns
|
259 |
+
-------
|
260 |
+
data : ndarray
|
261 |
+
Input data if no conversion necessary, or a converted version
|
262 |
+
"""
|
263 |
+
|
264 |
+
if field is None:
|
265 |
+
return data
|
266 |
+
if field == "pattern":
|
267 |
+
if no_pattern:
|
268 |
+
return data
|
269 |
+
else:
|
270 |
+
return np.zeros(0)
|
271 |
+
|
272 |
+
dtype = _field_to_dtype.get(field, None)
|
273 |
+
if dtype is None:
|
274 |
+
raise ValueError("Invalid field.")
|
275 |
+
|
276 |
+
return np.asarray(data, dtype=dtype)
|
277 |
+
|
278 |
+
|
279 |
+
def _validate_symmetry(symmetry):
|
280 |
+
"""
|
281 |
+
Check that the symmetry parameter is one that MatrixMarket allows..
|
282 |
+
"""
|
283 |
+
if symmetry is None:
|
284 |
+
return "general"
|
285 |
+
|
286 |
+
symmetry = str(symmetry).lower()
|
287 |
+
symmetries = ["general", "symmetric", "skew-symmetric", "hermitian"]
|
288 |
+
if symmetry not in symmetries:
|
289 |
+
raise ValueError("Invalid symmetry. Must be one of: " + ", ".join(symmetries))
|
290 |
+
|
291 |
+
return symmetry
|
292 |
+
|
293 |
+
|
294 |
+
def mmread(source):
|
295 |
+
"""
|
296 |
+
Reads the contents of a Matrix Market file-like 'source' into a matrix.
|
297 |
+
|
298 |
+
Parameters
|
299 |
+
----------
|
300 |
+
source : str or file-like
|
301 |
+
Matrix Market filename (extensions .mtx, .mtz.gz)
|
302 |
+
or open file-like object.
|
303 |
+
|
304 |
+
Returns
|
305 |
+
-------
|
306 |
+
a : ndarray or coo_matrix
|
307 |
+
Dense or sparse matrix depending on the matrix format in the
|
308 |
+
Matrix Market file.
|
309 |
+
|
310 |
+
Notes
|
311 |
+
-----
|
312 |
+
.. versionchanged:: 1.12.0
|
313 |
+
C++ implementation.
|
314 |
+
|
315 |
+
Examples
|
316 |
+
--------
|
317 |
+
>>> from io import StringIO
|
318 |
+
>>> from scipy.io import mmread
|
319 |
+
|
320 |
+
>>> text = '''%%MatrixMarket matrix coordinate real general
|
321 |
+
... 5 5 7
|
322 |
+
... 2 3 1.0
|
323 |
+
... 3 4 2.0
|
324 |
+
... 3 5 3.0
|
325 |
+
... 4 1 4.0
|
326 |
+
... 4 2 5.0
|
327 |
+
... 4 3 6.0
|
328 |
+
... 4 4 7.0
|
329 |
+
... '''
|
330 |
+
|
331 |
+
``mmread(source)`` returns the data as sparse matrix in COO format.
|
332 |
+
|
333 |
+
>>> m = mmread(StringIO(text))
|
334 |
+
>>> m
|
335 |
+
<5x5 sparse matrix of type '<class 'numpy.float64'>'
|
336 |
+
with 7 stored elements in COOrdinate format>
|
337 |
+
>>> m.A
|
338 |
+
array([[0., 0., 0., 0., 0.],
|
339 |
+
[0., 0., 1., 0., 0.],
|
340 |
+
[0., 0., 0., 2., 3.],
|
341 |
+
[4., 5., 6., 7., 0.],
|
342 |
+
[0., 0., 0., 0., 0.]])
|
343 |
+
|
344 |
+
This method is threaded.
|
345 |
+
The default number of threads is equal to the number of CPUs in the system.
|
346 |
+
Use `threadpoolctl <https://github.com/joblib/threadpoolctl>`_ to override:
|
347 |
+
|
348 |
+
>>> import threadpoolctl
|
349 |
+
>>>
|
350 |
+
>>> with threadpoolctl.threadpool_limits(limits=2):
|
351 |
+
... m = mmread(StringIO(text))
|
352 |
+
|
353 |
+
"""
|
354 |
+
cursor, stream_to_close = _get_read_cursor(source)
|
355 |
+
|
356 |
+
if cursor.header.format == "array":
|
357 |
+
mat = _read_body_array(cursor)
|
358 |
+
if stream_to_close:
|
359 |
+
stream_to_close.close()
|
360 |
+
return mat
|
361 |
+
else:
|
362 |
+
from scipy.sparse import coo_matrix
|
363 |
+
triplet, shape = _read_body_coo(cursor, generalize_symmetry=True)
|
364 |
+
if stream_to_close:
|
365 |
+
stream_to_close.close()
|
366 |
+
return coo_matrix(triplet, shape=shape)
|
367 |
+
|
368 |
+
|
369 |
+
def mmwrite(target, a, comment=None, field=None, precision=None, symmetry="AUTO"):
|
370 |
+
r"""
|
371 |
+
Writes the sparse or dense array `a` to Matrix Market file-like `target`.
|
372 |
+
|
373 |
+
Parameters
|
374 |
+
----------
|
375 |
+
target : str or file-like
|
376 |
+
Matrix Market filename (extension .mtx) or open file-like object.
|
377 |
+
a : array like
|
378 |
+
Sparse or dense 2-D array.
|
379 |
+
comment : str, optional
|
380 |
+
Comments to be prepended to the Matrix Market file.
|
381 |
+
field : None or str, optional
|
382 |
+
Either 'real', 'complex', 'pattern', or 'integer'.
|
383 |
+
precision : None or int, optional
|
384 |
+
Number of digits to display for real or complex values.
|
385 |
+
symmetry : None or str, optional
|
386 |
+
Either 'AUTO', 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
|
387 |
+
If symmetry is None the symmetry type of 'a' is determined by its
|
388 |
+
values. If symmetry is 'AUTO' the symmetry type of 'a' is either
|
389 |
+
determined or set to 'general', at mmwrite's discretion.
|
390 |
+
|
391 |
+
Returns
|
392 |
+
-------
|
393 |
+
None
|
394 |
+
|
395 |
+
Notes
|
396 |
+
-----
|
397 |
+
.. versionchanged:: 1.12.0
|
398 |
+
C++ implementation.
|
399 |
+
|
400 |
+
Examples
|
401 |
+
--------
|
402 |
+
>>> from io import BytesIO
|
403 |
+
>>> import numpy as np
|
404 |
+
>>> from scipy.sparse import coo_matrix
|
405 |
+
>>> from scipy.io import mmwrite
|
406 |
+
|
407 |
+
Write a small NumPy array to a matrix market file. The file will be
|
408 |
+
written in the ``'array'`` format.
|
409 |
+
|
410 |
+
>>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
|
411 |
+
>>> target = BytesIO()
|
412 |
+
>>> mmwrite(target, a)
|
413 |
+
>>> print(target.getvalue().decode('latin1'))
|
414 |
+
%%MatrixMarket matrix array real general
|
415 |
+
%
|
416 |
+
2 4
|
417 |
+
1
|
418 |
+
0
|
419 |
+
0
|
420 |
+
2.5
|
421 |
+
0
|
422 |
+
0
|
423 |
+
0
|
424 |
+
6.25
|
425 |
+
|
426 |
+
Add a comment to the output file, and set the precision to 3.
|
427 |
+
|
428 |
+
>>> target = BytesIO()
|
429 |
+
>>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
|
430 |
+
>>> print(target.getvalue().decode('latin1'))
|
431 |
+
%%MatrixMarket matrix array real general
|
432 |
+
%
|
433 |
+
% Some test data.
|
434 |
+
%
|
435 |
+
2 4
|
436 |
+
1.00e+00
|
437 |
+
0.00e+00
|
438 |
+
0.00e+00
|
439 |
+
2.50e+00
|
440 |
+
0.00e+00
|
441 |
+
0.00e+00
|
442 |
+
0.00e+00
|
443 |
+
6.25e+00
|
444 |
+
|
445 |
+
Convert to a sparse matrix before calling ``mmwrite``. This will
|
446 |
+
result in the output format being ``'coordinate'`` rather than
|
447 |
+
``'array'``.
|
448 |
+
|
449 |
+
>>> target = BytesIO()
|
450 |
+
>>> mmwrite(target, coo_matrix(a), precision=3)
|
451 |
+
>>> print(target.getvalue().decode('latin1'))
|
452 |
+
%%MatrixMarket matrix coordinate real general
|
453 |
+
%
|
454 |
+
2 4 3
|
455 |
+
1 1 1.00e+00
|
456 |
+
2 2 2.50e+00
|
457 |
+
2 4 6.25e+00
|
458 |
+
|
459 |
+
Write a complex Hermitian array to a matrix market file. Note that
|
460 |
+
only six values are actually written to the file; the other values
|
461 |
+
are implied by the symmetry.
|
462 |
+
|
463 |
+
>>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
|
464 |
+
>>> z
|
465 |
+
array([[ 3. +0.j, 1. +2.j, 4. -3.j],
|
466 |
+
[ 1. -2.j, 1. +0.j, -0. -5.j],
|
467 |
+
[ 4. +3.j, 0. +5.j, 2.5+0.j]])
|
468 |
+
|
469 |
+
>>> target = BytesIO()
|
470 |
+
>>> mmwrite(target, z, precision=2)
|
471 |
+
>>> print(target.getvalue().decode('latin1'))
|
472 |
+
%%MatrixMarket matrix array complex hermitian
|
473 |
+
%
|
474 |
+
3 3
|
475 |
+
3.0e+00 0.0e+00
|
476 |
+
1.0e+00 -2.0e+00
|
477 |
+
4.0e+00 3.0e+00
|
478 |
+
1.0e+00 0.0e+00
|
479 |
+
0.0e+00 5.0e+00
|
480 |
+
2.5e+00 0.0e+00
|
481 |
+
|
482 |
+
This method is threaded.
|
483 |
+
The default number of threads is equal to the number of CPUs in the system.
|
484 |
+
Use `threadpoolctl <https://github.com/joblib/threadpoolctl>`_ to override:
|
485 |
+
|
486 |
+
>>> import threadpoolctl
|
487 |
+
>>>
|
488 |
+
>>> target = BytesIO()
|
489 |
+
>>> with threadpoolctl.threadpool_limits(limits=2):
|
490 |
+
... mmwrite(target, a)
|
491 |
+
|
492 |
+
"""
|
493 |
+
from . import _fmm_core
|
494 |
+
|
495 |
+
if isinstance(a, list) or isinstance(a, tuple) or hasattr(a, "__array__"):
|
496 |
+
a = np.asarray(a)
|
497 |
+
|
498 |
+
if symmetry == "AUTO":
|
499 |
+
if ALWAYS_FIND_SYMMETRY or (hasattr(a, "shape") and max(a.shape) < 100):
|
500 |
+
symmetry = None
|
501 |
+
else:
|
502 |
+
symmetry = "general"
|
503 |
+
|
504 |
+
if symmetry is None:
|
505 |
+
symmetry = _mmio.MMFile()._get_symmetry(a)
|
506 |
+
|
507 |
+
symmetry = _validate_symmetry(symmetry)
|
508 |
+
cursor = _get_write_cursor(target, comment=comment,
|
509 |
+
precision=precision, symmetry=symmetry)
|
510 |
+
|
511 |
+
if isinstance(a, np.ndarray):
|
512 |
+
# Write dense numpy arrays
|
513 |
+
a = _apply_field(a, field, no_pattern=True)
|
514 |
+
_fmm_core.write_body_array(cursor, a)
|
515 |
+
|
516 |
+
elif scipy.sparse.issparse(a):
|
517 |
+
# Write sparse scipy matrices
|
518 |
+
a = a.tocoo()
|
519 |
+
|
520 |
+
if symmetry is not None and symmetry != "general":
|
521 |
+
# A symmetric matrix only specifies the elements below the diagonal.
|
522 |
+
# Ensure that the matrix satisfies this requirement.
|
523 |
+
from scipy.sparse import coo_array
|
524 |
+
lower_triangle_mask = a.row >= a.col
|
525 |
+
a = coo_array((a.data[lower_triangle_mask],
|
526 |
+
(a.row[lower_triangle_mask],
|
527 |
+
a.col[lower_triangle_mask])), shape=a.shape)
|
528 |
+
|
529 |
+
data = _apply_field(a.data, field)
|
530 |
+
_fmm_core.write_body_coo(cursor, a.shape, a.row, a.col, data)
|
531 |
+
|
532 |
+
else:
|
533 |
+
raise ValueError("unknown matrix type: %s" % type(a))
|
534 |
+
|
535 |
+
|
536 |
+
def mminfo(source):
|
537 |
+
"""
|
538 |
+
Return size and storage parameters from Matrix Market file-like 'source'.
|
539 |
+
|
540 |
+
Parameters
|
541 |
+
----------
|
542 |
+
source : str or file-like
|
543 |
+
Matrix Market filename (extension .mtx) or open file-like object
|
544 |
+
|
545 |
+
Returns
|
546 |
+
-------
|
547 |
+
rows : int
|
548 |
+
Number of matrix rows.
|
549 |
+
cols : int
|
550 |
+
Number of matrix columns.
|
551 |
+
entries : int
|
552 |
+
Number of non-zero entries of a sparse matrix
|
553 |
+
or rows*cols for a dense matrix.
|
554 |
+
format : str
|
555 |
+
Either 'coordinate' or 'array'.
|
556 |
+
field : str
|
557 |
+
Either 'real', 'complex', 'pattern', or 'integer'.
|
558 |
+
symmetry : str
|
559 |
+
Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
|
560 |
+
|
561 |
+
Notes
|
562 |
+
-----
|
563 |
+
.. versionchanged:: 1.12.0
|
564 |
+
C++ implementation.
|
565 |
+
|
566 |
+
Examples
|
567 |
+
--------
|
568 |
+
>>> from io import StringIO
|
569 |
+
>>> from scipy.io import mminfo
|
570 |
+
|
571 |
+
>>> text = '''%%MatrixMarket matrix coordinate real general
|
572 |
+
... 5 5 7
|
573 |
+
... 2 3 1.0
|
574 |
+
... 3 4 2.0
|
575 |
+
... 3 5 3.0
|
576 |
+
... 4 1 4.0
|
577 |
+
... 4 2 5.0
|
578 |
+
... 4 3 6.0
|
579 |
+
... 4 4 7.0
|
580 |
+
... '''
|
581 |
+
|
582 |
+
|
583 |
+
``mminfo(source)`` returns the number of rows, number of columns,
|
584 |
+
format, field type and symmetry attribute of the source file.
|
585 |
+
|
586 |
+
>>> mminfo(StringIO(text))
|
587 |
+
(5, 5, 7, 'coordinate', 'real', 'general')
|
588 |
+
"""
|
589 |
+
cursor, stream_to_close = _get_read_cursor(source, 1)
|
590 |
+
h = cursor.header
|
591 |
+
cursor.close()
|
592 |
+
if stream_to_close:
|
593 |
+
stream_to_close.close()
|
594 |
+
return h.nrows, h.ncols, h.nnz, h.format, h.field, h.symmetry
|
env-llmeval/lib/python3.10/site-packages/scipy/io/_fast_matrix_market/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (14.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__init__.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
MATLAB® file utilities (:mod:`scipy.io.matlab`)
|
3 |
+
===============================================
|
4 |
+
|
5 |
+
.. currentmodule:: scipy.io.matlab
|
6 |
+
|
7 |
+
This submodule is meant to provide lower-level file utilities related to reading
|
8 |
+
and writing MATLAB files.
|
9 |
+
|
10 |
+
.. autosummary::
|
11 |
+
:toctree: generated/
|
12 |
+
|
13 |
+
matfile_version - Get the MATLAB file version
|
14 |
+
MatReadError - Exception indicating a read issue
|
15 |
+
MatReadWarning - Warning class for read issues
|
16 |
+
MatWriteError - Exception indicating a write issue
|
17 |
+
mat_struct - Class used when ``struct_as_record=False``
|
18 |
+
|
19 |
+
.. autosummary::
|
20 |
+
:toctree: generated/
|
21 |
+
:template: autosummary/ndarray_subclass.rst
|
22 |
+
:nosignatures:
|
23 |
+
|
24 |
+
MatlabObject - Class for a MATLAB object
|
25 |
+
MatlabOpaque - Class for a MATLAB opaque matrix
|
26 |
+
MatlabFunction - Class for a MATLAB function object
|
27 |
+
|
28 |
+
The following utilities that live in the :mod:`scipy.io`
|
29 |
+
namespace also exist in this namespace:
|
30 |
+
|
31 |
+
.. autosummary::
|
32 |
+
:toctree: generated/
|
33 |
+
|
34 |
+
loadmat - Read a MATLAB style mat file (version 4 through 7.1)
|
35 |
+
savemat - Write a MATLAB style mat file (version 4 through 7.1)
|
36 |
+
whosmat - List contents of a MATLAB style mat file (version 4 through 7.1)
|
37 |
+
|
38 |
+
Notes
|
39 |
+
-----
|
40 |
+
MATLAB(R) is a registered trademark of The MathWorks, Inc., 3 Apple Hill
|
41 |
+
Drive, Natick, MA 01760-2098, USA.
|
42 |
+
|
43 |
+
"""
|
44 |
+
# Matlab file read and write utilities
|
45 |
+
from ._mio import loadmat, savemat, whosmat
|
46 |
+
from ._mio5 import MatlabFunction
|
47 |
+
from ._mio5_params import MatlabObject, MatlabOpaque, mat_struct
|
48 |
+
from ._miobase import (matfile_version, MatReadError, MatReadWarning,
|
49 |
+
MatWriteError)
|
50 |
+
|
51 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
52 |
+
from .import (mio, mio5, mio5_params, mio4, byteordercodes,
|
53 |
+
miobase, mio_utils, streams, mio5_utils)
|
54 |
+
|
55 |
+
__all__ = [
|
56 |
+
'loadmat', 'savemat', 'whosmat', 'MatlabObject',
|
57 |
+
'matfile_version', 'MatReadError', 'MatReadWarning',
|
58 |
+
'MatWriteError', 'mat_struct', 'MatlabOpaque', 'MatlabFunction'
|
59 |
+
]
|
60 |
+
|
61 |
+
from scipy._lib._testutils import PytestTester
|
62 |
+
test = PytestTester(__name__)
|
63 |
+
del PytestTester
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.16 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_byteordercodes.cpython-310.pyc
ADDED
Binary file (1.97 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio.cpython-310.pyc
ADDED
Binary file (12.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio4.cpython-310.pyc
ADDED
Binary file (18.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio5.cpython-310.pyc
ADDED
Binary file (25.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_mio5_params.cpython-310.pyc
ADDED
Binary file (5.91 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/_miobase.cpython-310.pyc
ADDED
Binary file (11.5 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/byteordercodes.cpython-310.pyc
ADDED
Binary file (681 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio.cpython-310.pyc
ADDED
Binary file (724 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio4.cpython-310.pyc
ADDED
Binary file (976 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio5.cpython-310.pyc
ADDED
Binary file (1.17 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio5_params.cpython-310.pyc
ADDED
Binary file (1.24 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio5_utils.cpython-310.pyc
ADDED
Binary file (720 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/mio_utils.cpython-310.pyc
ADDED
Binary file (637 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/miobase.cpython-310.pyc
ADDED
Binary file (796 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/__pycache__/streams.cpython-310.pyc
ADDED
Binary file (655 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_byteordercodes.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
''' Byteorder utilities for system - numpy byteorder encoding
|
2 |
+
|
3 |
+
Converts a variety of string codes for little endian, big endian,
|
4 |
+
native byte order and swapped byte order to explicit NumPy endian
|
5 |
+
codes - one of '<' (little endian) or '>' (big endian)
|
6 |
+
|
7 |
+
'''
|
8 |
+
import sys
|
9 |
+
|
10 |
+
__all__ = [
|
11 |
+
'aliases', 'native_code', 'swapped_code',
|
12 |
+
'sys_is_le', 'to_numpy_code'
|
13 |
+
]
|
14 |
+
|
15 |
+
sys_is_le = sys.byteorder == 'little'
|
16 |
+
native_code = sys_is_le and '<' or '>'
|
17 |
+
swapped_code = sys_is_le and '>' or '<'
|
18 |
+
|
19 |
+
aliases = {'little': ('little', '<', 'l', 'le'),
|
20 |
+
'big': ('big', '>', 'b', 'be'),
|
21 |
+
'native': ('native', '='),
|
22 |
+
'swapped': ('swapped', 'S')}
|
23 |
+
|
24 |
+
|
25 |
+
def to_numpy_code(code):
|
26 |
+
"""
|
27 |
+
Convert various order codings to NumPy format.
|
28 |
+
|
29 |
+
Parameters
|
30 |
+
----------
|
31 |
+
code : str
|
32 |
+
The code to convert. It is converted to lower case before parsing.
|
33 |
+
Legal values are:
|
34 |
+
'little', 'big', 'l', 'b', 'le', 'be', '<', '>', 'native', '=',
|
35 |
+
'swapped', 's'.
|
36 |
+
|
37 |
+
Returns
|
38 |
+
-------
|
39 |
+
out_code : {'<', '>'}
|
40 |
+
Here '<' is the numpy dtype code for little endian,
|
41 |
+
and '>' is the code for big endian.
|
42 |
+
|
43 |
+
Examples
|
44 |
+
--------
|
45 |
+
>>> import sys
|
46 |
+
>>> from scipy.io.matlab._byteordercodes import to_numpy_code
|
47 |
+
>>> sys_is_le = (sys.byteorder == 'little')
|
48 |
+
>>> sys_is_le
|
49 |
+
True
|
50 |
+
>>> to_numpy_code('big')
|
51 |
+
'>'
|
52 |
+
>>> to_numpy_code('little')
|
53 |
+
'<'
|
54 |
+
>>> nc = to_numpy_code('native')
|
55 |
+
>>> nc == '<' if sys_is_le else nc == '>'
|
56 |
+
True
|
57 |
+
>>> sc = to_numpy_code('swapped')
|
58 |
+
>>> sc == '>' if sys_is_le else sc == '<'
|
59 |
+
True
|
60 |
+
|
61 |
+
"""
|
62 |
+
code = code.lower()
|
63 |
+
if code is None:
|
64 |
+
return native_code
|
65 |
+
if code in aliases['little']:
|
66 |
+
return '<'
|
67 |
+
elif code in aliases['big']:
|
68 |
+
return '>'
|
69 |
+
elif code in aliases['native']:
|
70 |
+
return native_code
|
71 |
+
elif code in aliases['swapped']:
|
72 |
+
return swapped_code
|
73 |
+
else:
|
74 |
+
raise ValueError(
|
75 |
+
'We cannot handle byte order %s' % code)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio.py
ADDED
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Module for reading and writing matlab (TM) .mat files
|
3 |
+
"""
|
4 |
+
# Authors: Travis Oliphant, Matthew Brett
|
5 |
+
|
6 |
+
from contextlib import contextmanager
|
7 |
+
|
8 |
+
from ._miobase import _get_matfile_version, docfiller
|
9 |
+
from ._mio4 import MatFile4Reader, MatFile4Writer
|
10 |
+
from ._mio5 import MatFile5Reader, MatFile5Writer
|
11 |
+
|
12 |
+
__all__ = ['mat_reader_factory', 'loadmat', 'savemat', 'whosmat']
|
13 |
+
|
14 |
+
|
15 |
+
@contextmanager
|
16 |
+
def _open_file_context(file_like, appendmat, mode='rb'):
|
17 |
+
f, opened = _open_file(file_like, appendmat, mode)
|
18 |
+
try:
|
19 |
+
yield f
|
20 |
+
finally:
|
21 |
+
if opened:
|
22 |
+
f.close()
|
23 |
+
|
24 |
+
|
25 |
+
def _open_file(file_like, appendmat, mode='rb'):
|
26 |
+
"""
|
27 |
+
Open `file_like` and return as file-like object. First, check if object is
|
28 |
+
already file-like; if so, return it as-is. Otherwise, try to pass it
|
29 |
+
to open(). If that fails, and `file_like` is a string, and `appendmat` is true,
|
30 |
+
append '.mat' and try again.
|
31 |
+
"""
|
32 |
+
reqs = {'read'} if set(mode) & set('r+') else set()
|
33 |
+
if set(mode) & set('wax+'):
|
34 |
+
reqs.add('write')
|
35 |
+
if reqs.issubset(dir(file_like)):
|
36 |
+
return file_like, False
|
37 |
+
|
38 |
+
try:
|
39 |
+
return open(file_like, mode), True
|
40 |
+
except OSError as e:
|
41 |
+
# Probably "not found"
|
42 |
+
if isinstance(file_like, str):
|
43 |
+
if appendmat and not file_like.endswith('.mat'):
|
44 |
+
file_like += '.mat'
|
45 |
+
return open(file_like, mode), True
|
46 |
+
else:
|
47 |
+
raise OSError(
|
48 |
+
'Reader needs file name or open file-like object'
|
49 |
+
) from e
|
50 |
+
|
51 |
+
|
52 |
+
@docfiller
|
53 |
+
def mat_reader_factory(file_name, appendmat=True, **kwargs):
|
54 |
+
"""
|
55 |
+
Create reader for matlab .mat format files.
|
56 |
+
|
57 |
+
Parameters
|
58 |
+
----------
|
59 |
+
%(file_arg)s
|
60 |
+
%(append_arg)s
|
61 |
+
%(load_args)s
|
62 |
+
%(struct_arg)s
|
63 |
+
|
64 |
+
Returns
|
65 |
+
-------
|
66 |
+
matreader : MatFileReader object
|
67 |
+
Initialized instance of MatFileReader class matching the mat file
|
68 |
+
type detected in `filename`.
|
69 |
+
file_opened : bool
|
70 |
+
Whether the file was opened by this routine.
|
71 |
+
|
72 |
+
"""
|
73 |
+
byte_stream, file_opened = _open_file(file_name, appendmat)
|
74 |
+
mjv, mnv = _get_matfile_version(byte_stream)
|
75 |
+
if mjv == 0:
|
76 |
+
return MatFile4Reader(byte_stream, **kwargs), file_opened
|
77 |
+
elif mjv == 1:
|
78 |
+
return MatFile5Reader(byte_stream, **kwargs), file_opened
|
79 |
+
elif mjv == 2:
|
80 |
+
raise NotImplementedError('Please use HDF reader for matlab v7.3 '
|
81 |
+
'files, e.g. h5py')
|
82 |
+
else:
|
83 |
+
raise TypeError('Did not recognize version %s' % mjv)
|
84 |
+
|
85 |
+
|
86 |
+
@docfiller
|
87 |
+
def loadmat(file_name, mdict=None, appendmat=True, **kwargs):
|
88 |
+
"""
|
89 |
+
Load MATLAB file.
|
90 |
+
|
91 |
+
Parameters
|
92 |
+
----------
|
93 |
+
file_name : str
|
94 |
+
Name of the mat file (do not need .mat extension if
|
95 |
+
appendmat==True). Can also pass open file-like object.
|
96 |
+
mdict : dict, optional
|
97 |
+
Dictionary in which to insert matfile variables.
|
98 |
+
appendmat : bool, optional
|
99 |
+
True to append the .mat extension to the end of the given
|
100 |
+
filename, if not already present. Default is True.
|
101 |
+
byte_order : str or None, optional
|
102 |
+
None by default, implying byte order guessed from mat
|
103 |
+
file. Otherwise can be one of ('native', '=', 'little', '<',
|
104 |
+
'BIG', '>').
|
105 |
+
mat_dtype : bool, optional
|
106 |
+
If True, return arrays in same dtype as would be loaded into
|
107 |
+
MATLAB (instead of the dtype with which they are saved).
|
108 |
+
squeeze_me : bool, optional
|
109 |
+
Whether to squeeze unit matrix dimensions or not.
|
110 |
+
chars_as_strings : bool, optional
|
111 |
+
Whether to convert char arrays to string arrays.
|
112 |
+
matlab_compatible : bool, optional
|
113 |
+
Returns matrices as would be loaded by MATLAB (implies
|
114 |
+
squeeze_me=False, chars_as_strings=False, mat_dtype=True,
|
115 |
+
struct_as_record=True).
|
116 |
+
struct_as_record : bool, optional
|
117 |
+
Whether to load MATLAB structs as NumPy record arrays, or as
|
118 |
+
old-style NumPy arrays with dtype=object. Setting this flag to
|
119 |
+
False replicates the behavior of scipy version 0.7.x (returning
|
120 |
+
NumPy object arrays). The default setting is True, because it
|
121 |
+
allows easier round-trip load and save of MATLAB files.
|
122 |
+
verify_compressed_data_integrity : bool, optional
|
123 |
+
Whether the length of compressed sequences in the MATLAB file
|
124 |
+
should be checked, to ensure that they are not longer than we expect.
|
125 |
+
It is advisable to enable this (the default) because overlong
|
126 |
+
compressed sequences in MATLAB files generally indicate that the
|
127 |
+
files have experienced some sort of corruption.
|
128 |
+
variable_names : None or sequence
|
129 |
+
If None (the default) - read all variables in file. Otherwise,
|
130 |
+
`variable_names` should be a sequence of strings, giving names of the
|
131 |
+
MATLAB variables to read from the file. The reader will skip any
|
132 |
+
variable with a name not in this sequence, possibly saving some read
|
133 |
+
processing.
|
134 |
+
simplify_cells : False, optional
|
135 |
+
If True, return a simplified dict structure (which is useful if the mat
|
136 |
+
file contains cell arrays). Note that this only affects the structure
|
137 |
+
of the result and not its contents (which is identical for both output
|
138 |
+
structures). If True, this automatically sets `struct_as_record` to
|
139 |
+
False and `squeeze_me` to True, which is required to simplify cells.
|
140 |
+
|
141 |
+
Returns
|
142 |
+
-------
|
143 |
+
mat_dict : dict
|
144 |
+
dictionary with variable names as keys, and loaded matrices as
|
145 |
+
values.
|
146 |
+
|
147 |
+
Notes
|
148 |
+
-----
|
149 |
+
v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.
|
150 |
+
|
151 |
+
You will need an HDF5 Python library to read MATLAB 7.3 format mat
|
152 |
+
files. Because SciPy does not supply one, we do not implement the
|
153 |
+
HDF5 / 7.3 interface here.
|
154 |
+
|
155 |
+
Examples
|
156 |
+
--------
|
157 |
+
>>> from os.path import dirname, join as pjoin
|
158 |
+
>>> import scipy.io as sio
|
159 |
+
|
160 |
+
Get the filename for an example .mat file from the tests/data directory.
|
161 |
+
|
162 |
+
>>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
|
163 |
+
>>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')
|
164 |
+
|
165 |
+
Load the .mat file contents.
|
166 |
+
|
167 |
+
>>> mat_contents = sio.loadmat(mat_fname)
|
168 |
+
|
169 |
+
The result is a dictionary, one key/value pair for each variable:
|
170 |
+
|
171 |
+
>>> sorted(mat_contents.keys())
|
172 |
+
['__globals__', '__header__', '__version__', 'testdouble']
|
173 |
+
>>> mat_contents['testdouble']
|
174 |
+
array([[0. , 0.78539816, 1.57079633, 2.35619449, 3.14159265,
|
175 |
+
3.92699082, 4.71238898, 5.49778714, 6.28318531]])
|
176 |
+
|
177 |
+
By default SciPy reads MATLAB structs as structured NumPy arrays where the
|
178 |
+
dtype fields are of type `object` and the names correspond to the MATLAB
|
179 |
+
struct field names. This can be disabled by setting the optional argument
|
180 |
+
`struct_as_record=False`.
|
181 |
+
|
182 |
+
Get the filename for an example .mat file that contains a MATLAB struct
|
183 |
+
called `teststruct` and load the contents.
|
184 |
+
|
185 |
+
>>> matstruct_fname = pjoin(data_dir, 'teststruct_7.4_GLNX86.mat')
|
186 |
+
>>> matstruct_contents = sio.loadmat(matstruct_fname)
|
187 |
+
>>> teststruct = matstruct_contents['teststruct']
|
188 |
+
>>> teststruct.dtype
|
189 |
+
dtype([('stringfield', 'O'), ('doublefield', 'O'), ('complexfield', 'O')])
|
190 |
+
|
191 |
+
The size of the structured array is the size of the MATLAB struct, not the
|
192 |
+
number of elements in any particular field. The shape defaults to 2-D
|
193 |
+
unless the optional argument `squeeze_me=True`, in which case all length 1
|
194 |
+
dimensions are removed.
|
195 |
+
|
196 |
+
>>> teststruct.size
|
197 |
+
1
|
198 |
+
>>> teststruct.shape
|
199 |
+
(1, 1)
|
200 |
+
|
201 |
+
Get the 'stringfield' of the first element in the MATLAB struct.
|
202 |
+
|
203 |
+
>>> teststruct[0, 0]['stringfield']
|
204 |
+
array(['Rats live on no evil star.'],
|
205 |
+
dtype='<U26')
|
206 |
+
|
207 |
+
Get the first element of the 'doublefield'.
|
208 |
+
|
209 |
+
>>> teststruct['doublefield'][0, 0]
|
210 |
+
array([[ 1.41421356, 2.71828183, 3.14159265]])
|
211 |
+
|
212 |
+
Load the MATLAB struct, squeezing out length 1 dimensions, and get the item
|
213 |
+
from the 'complexfield'.
|
214 |
+
|
215 |
+
>>> matstruct_squeezed = sio.loadmat(matstruct_fname, squeeze_me=True)
|
216 |
+
>>> matstruct_squeezed['teststruct'].shape
|
217 |
+
()
|
218 |
+
>>> matstruct_squeezed['teststruct']['complexfield'].shape
|
219 |
+
()
|
220 |
+
>>> matstruct_squeezed['teststruct']['complexfield'].item()
|
221 |
+
array([ 1.41421356+1.41421356j, 2.71828183+2.71828183j,
|
222 |
+
3.14159265+3.14159265j])
|
223 |
+
"""
|
224 |
+
variable_names = kwargs.pop('variable_names', None)
|
225 |
+
with _open_file_context(file_name, appendmat) as f:
|
226 |
+
MR, _ = mat_reader_factory(f, **kwargs)
|
227 |
+
matfile_dict = MR.get_variables(variable_names)
|
228 |
+
|
229 |
+
if mdict is not None:
|
230 |
+
mdict.update(matfile_dict)
|
231 |
+
else:
|
232 |
+
mdict = matfile_dict
|
233 |
+
|
234 |
+
return mdict
|
235 |
+
|
236 |
+
|
237 |
+
@docfiller
|
238 |
+
def savemat(file_name, mdict,
|
239 |
+
appendmat=True,
|
240 |
+
format='5',
|
241 |
+
long_field_names=False,
|
242 |
+
do_compression=False,
|
243 |
+
oned_as='row'):
|
244 |
+
"""
|
245 |
+
Save a dictionary of names and arrays into a MATLAB-style .mat file.
|
246 |
+
|
247 |
+
This saves the array objects in the given dictionary to a MATLAB-
|
248 |
+
style .mat file.
|
249 |
+
|
250 |
+
Parameters
|
251 |
+
----------
|
252 |
+
file_name : str or file-like object
|
253 |
+
Name of the .mat file (.mat extension not needed if ``appendmat ==
|
254 |
+
True``).
|
255 |
+
Can also pass open file_like object.
|
256 |
+
mdict : dict
|
257 |
+
Dictionary from which to save matfile variables.
|
258 |
+
appendmat : bool, optional
|
259 |
+
True (the default) to append the .mat extension to the end of the
|
260 |
+
given filename, if not already present.
|
261 |
+
format : {'5', '4'}, string, optional
|
262 |
+
'5' (the default) for MATLAB 5 and up (to 7.2),
|
263 |
+
'4' for MATLAB 4 .mat files.
|
264 |
+
long_field_names : bool, optional
|
265 |
+
False (the default) - maximum field name length in a structure is
|
266 |
+
31 characters which is the documented maximum length.
|
267 |
+
True - maximum field name length in a structure is 63 characters
|
268 |
+
which works for MATLAB 7.6+.
|
269 |
+
do_compression : bool, optional
|
270 |
+
Whether or not to compress matrices on write. Default is False.
|
271 |
+
oned_as : {'row', 'column'}, optional
|
272 |
+
If 'column', write 1-D NumPy arrays as column vectors.
|
273 |
+
If 'row', write 1-D NumPy arrays as row vectors.
|
274 |
+
|
275 |
+
Examples
|
276 |
+
--------
|
277 |
+
>>> from scipy.io import savemat
|
278 |
+
>>> import numpy as np
|
279 |
+
>>> a = np.arange(20)
|
280 |
+
>>> mdic = {"a": a, "label": "experiment"}
|
281 |
+
>>> mdic
|
282 |
+
{'a': array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
|
283 |
+
17, 18, 19]),
|
284 |
+
'label': 'experiment'}
|
285 |
+
>>> savemat("matlab_matrix.mat", mdic)
|
286 |
+
"""
|
287 |
+
with _open_file_context(file_name, appendmat, 'wb') as file_stream:
|
288 |
+
if format == '4':
|
289 |
+
if long_field_names:
|
290 |
+
message = "Long field names are not available for version 4 files"
|
291 |
+
raise ValueError(message)
|
292 |
+
MW = MatFile4Writer(file_stream, oned_as)
|
293 |
+
elif format == '5':
|
294 |
+
MW = MatFile5Writer(file_stream,
|
295 |
+
do_compression=do_compression,
|
296 |
+
unicode_strings=True,
|
297 |
+
long_field_names=long_field_names,
|
298 |
+
oned_as=oned_as)
|
299 |
+
else:
|
300 |
+
raise ValueError("Format should be '4' or '5'")
|
301 |
+
MW.put_variables(mdict)
|
302 |
+
|
303 |
+
|
304 |
+
@docfiller
|
305 |
+
def whosmat(file_name, appendmat=True, **kwargs):
|
306 |
+
"""
|
307 |
+
List variables inside a MATLAB file.
|
308 |
+
|
309 |
+
Parameters
|
310 |
+
----------
|
311 |
+
%(file_arg)s
|
312 |
+
%(append_arg)s
|
313 |
+
%(load_args)s
|
314 |
+
%(struct_arg)s
|
315 |
+
|
316 |
+
Returns
|
317 |
+
-------
|
318 |
+
variables : list of tuples
|
319 |
+
A list of tuples, where each tuple holds the matrix name (a string),
|
320 |
+
its shape (tuple of ints), and its data class (a string).
|
321 |
+
Possible data classes are: int8, uint8, int16, uint16, int32, uint32,
|
322 |
+
int64, uint64, single, double, cell, struct, object, char, sparse,
|
323 |
+
function, opaque, logical, unknown.
|
324 |
+
|
325 |
+
Notes
|
326 |
+
-----
|
327 |
+
v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.
|
328 |
+
|
329 |
+
You will need an HDF5 python library to read matlab 7.3 format mat
|
330 |
+
files (e.g. h5py). Because SciPy does not supply one, we do not implement the
|
331 |
+
HDF5 / 7.3 interface here.
|
332 |
+
|
333 |
+
.. versionadded:: 0.12.0
|
334 |
+
|
335 |
+
Examples
|
336 |
+
--------
|
337 |
+
>>> from io import BytesIO
|
338 |
+
>>> import numpy as np
|
339 |
+
>>> from scipy.io import savemat, whosmat
|
340 |
+
|
341 |
+
Create some arrays, and use `savemat` to write them to a ``BytesIO``
|
342 |
+
instance.
|
343 |
+
|
344 |
+
>>> a = np.array([[10, 20, 30], [11, 21, 31]], dtype=np.int32)
|
345 |
+
>>> b = np.geomspace(1, 10, 5)
|
346 |
+
>>> f = BytesIO()
|
347 |
+
>>> savemat(f, {'a': a, 'b': b})
|
348 |
+
|
349 |
+
Use `whosmat` to inspect ``f``. Each tuple in the output list gives
|
350 |
+
the name, shape and data type of the array in ``f``.
|
351 |
+
|
352 |
+
>>> whosmat(f)
|
353 |
+
[('a', (2, 3), 'int32'), ('b', (1, 5), 'double')]
|
354 |
+
|
355 |
+
"""
|
356 |
+
with _open_file_context(file_name, appendmat) as f:
|
357 |
+
ML, file_opened = mat_reader_factory(f, **kwargs)
|
358 |
+
variables = ML.list_variables()
|
359 |
+
return variables
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio4.py
ADDED
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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atFileReader, docfiller, matdims, read_dtype,
|
11 |
+
convert_dtypes, arr_to_chars, arr_dtype_number)
|
12 |
+
|
13 |
+
from ._mio_utils import squeeze_element, chars_to_strings
|
14 |
+
from functools import reduce
|
15 |
+
|
16 |
+
|
17 |
+
__all__ = [
|
18 |
+
'MatFile4Reader', 'MatFile4Writer', 'SYS_LITTLE_ENDIAN',
|
19 |
+
'VarHeader4', 'VarReader4', 'VarWriter4', 'arr_to_2d', 'mclass_info',
|
20 |
+
'mdtypes_template', 'miDOUBLE', 'miINT16', 'miINT32', 'miSINGLE',
|
21 |
+
'miUINT16', 'miUINT8', 'mxCHAR_CLASS', 'mxFULL_CLASS', 'mxSPARSE_CLASS',
|
22 |
+
'np_to_mtypes', 'order_codes'
|
23 |
+
]
|
24 |
+
|
25 |
+
|
26 |
+
SYS_LITTLE_ENDIAN = sys.byteorder == 'little'
|
27 |
+
|
28 |
+
miDOUBLE = 0
|
29 |
+
miSINGLE = 1
|
30 |
+
miINT32 = 2
|
31 |
+
miINT16 = 3
|
32 |
+
miUINT16 = 4
|
33 |
+
miUINT8 = 5
|
34 |
+
|
35 |
+
mdtypes_template = {
|
36 |
+
miDOUBLE: 'f8',
|
37 |
+
miSINGLE: 'f4',
|
38 |
+
miINT32: 'i4',
|
39 |
+
miINT16: 'i2',
|
40 |
+
miUINT16: 'u2',
|
41 |
+
miUINT8: 'u1',
|
42 |
+
'header': [('mopt', 'i4'),
|
43 |
+
('mrows', 'i4'),
|
44 |
+
('ncols', 'i4'),
|
45 |
+
('imagf', 'i4'),
|
46 |
+
('namlen', 'i4')],
|
47 |
+
'U1': 'U1',
|
48 |
+
}
|
49 |
+
|
50 |
+
np_to_mtypes = {
|
51 |
+
'f8': miDOUBLE,
|
52 |
+
'c32': miDOUBLE,
|
53 |
+
'c24': miDOUBLE,
|
54 |
+
'c16': miDOUBLE,
|
55 |
+
'f4': miSINGLE,
|
56 |
+
'c8': miSINGLE,
|
57 |
+
'i4': miINT32,
|
58 |
+
'i2': miINT16,
|
59 |
+
'u2': miUINT16,
|
60 |
+
'u1': miUINT8,
|
61 |
+
'S1': miUINT8,
|
62 |
+
}
|
63 |
+
|
64 |
+
# matrix classes
|
65 |
+
mxFULL_CLASS = 0
|
66 |
+
mxCHAR_CLASS = 1
|
67 |
+
mxSPARSE_CLASS = 2
|
68 |
+
|
69 |
+
order_codes = {
|
70 |
+
0: '<',
|
71 |
+
1: '>',
|
72 |
+
2: 'VAX D-float', # !
|
73 |
+
3: 'VAX G-float',
|
74 |
+
4: 'Cray', # !!
|
75 |
+
}
|
76 |
+
|
77 |
+
mclass_info = {
|
78 |
+
mxFULL_CLASS: 'double',
|
79 |
+
mxCHAR_CLASS: 'char',
|
80 |
+
mxSPARSE_CLASS: 'sparse',
|
81 |
+
}
|
82 |
+
|
83 |
+
|
84 |
+
class VarHeader4:
|
85 |
+
# Mat4 variables never logical or global
|
86 |
+
is_logical = False
|
87 |
+
is_global = False
|
88 |
+
|
89 |
+
def __init__(self,
|
90 |
+
name,
|
91 |
+
dtype,
|
92 |
+
mclass,
|
93 |
+
dims,
|
94 |
+
is_complex):
|
95 |
+
self.name = name
|
96 |
+
self.dtype = dtype
|
97 |
+
self.mclass = mclass
|
98 |
+
self.dims = dims
|
99 |
+
self.is_complex = is_complex
|
100 |
+
|
101 |
+
|
102 |
+
class VarReader4:
|
103 |
+
''' Class to read matlab 4 variables '''
|
104 |
+
|
105 |
+
def __init__(self, file_reader):
|
106 |
+
self.file_reader = file_reader
|
107 |
+
self.mat_stream = file_reader.mat_stream
|
108 |
+
self.dtypes = file_reader.dtypes
|
109 |
+
self.chars_as_strings = file_reader.chars_as_strings
|
110 |
+
self.squeeze_me = file_reader.squeeze_me
|
111 |
+
|
112 |
+
def read_header(self):
|
113 |
+
''' Read and return header for variable '''
|
114 |
+
data = read_dtype(self.mat_stream, self.dtypes['header'])
|
115 |
+
name = self.mat_stream.read(int(data['namlen'])).strip(b'\x00')
|
116 |
+
if data['mopt'] < 0 or data['mopt'] > 5000:
|
117 |
+
raise ValueError('Mat 4 mopt wrong format, byteswapping problem?')
|
118 |
+
M, rest = divmod(data['mopt'], 1000) # order code
|
119 |
+
if M not in (0, 1):
|
120 |
+
warnings.warn("We do not support byte ordering '%s'; returned "
|
121 |
+
"data may be corrupt" % order_codes[M],
|
122 |
+
UserWarning, stacklevel=3)
|
123 |
+
O, rest = divmod(rest, 100) # unused, should be 0
|
124 |
+
if O != 0:
|
125 |
+
raise ValueError('O in MOPT integer should be 0, wrong format?')
|
126 |
+
P, rest = divmod(rest, 10) # data type code e.g miDOUBLE (see above)
|
127 |
+
T = rest # matrix type code e.g., mxFULL_CLASS (see above)
|
128 |
+
dims = (data['mrows'], data['ncols'])
|
129 |
+
is_complex = data['imagf'] == 1
|
130 |
+
dtype = self.dtypes[P]
|
131 |
+
return VarHeader4(
|
132 |
+
name,
|
133 |
+
dtype,
|
134 |
+
T,
|
135 |
+
dims,
|
136 |
+
is_complex)
|
137 |
+
|
138 |
+
def array_from_header(self, hdr, process=True):
|
139 |
+
mclass = hdr.mclass
|
140 |
+
if mclass == mxFULL_CLASS:
|
141 |
+
arr = self.read_full_array(hdr)
|
142 |
+
elif mclass == mxCHAR_CLASS:
|
143 |
+
arr = self.read_char_array(hdr)
|
144 |
+
if process and self.chars_as_strings:
|
145 |
+
arr = chars_to_strings(arr)
|
146 |
+
elif mclass == mxSPARSE_CLASS:
|
147 |
+
# no current processing (below) makes sense for sparse
|
148 |
+
return self.read_sparse_array(hdr)
|
149 |
+
else:
|
150 |
+
raise TypeError('No reader for class code %s' % mclass)
|
151 |
+
if process and self.squeeze_me:
|
152 |
+
return squeeze_element(arr)
|
153 |
+
return arr
|
154 |
+
|
155 |
+
def read_sub_array(self, hdr, copy=True):
|
156 |
+
''' Mat4 read using header `hdr` dtype and dims
|
157 |
+
|
158 |
+
Parameters
|
159 |
+
----------
|
160 |
+
hdr : object
|
161 |
+
object with attributes ``dtype``, ``dims``. dtype is assumed to be
|
162 |
+
the correct endianness
|
163 |
+
copy : bool, optional
|
164 |
+
copies array before return if True (default True)
|
165 |
+
(buffer is usually read only)
|
166 |
+
|
167 |
+
Returns
|
168 |
+
-------
|
169 |
+
arr : ndarray
|
170 |
+
of dtype given by `hdr` ``dtype`` and shape given by `hdr` ``dims``
|
171 |
+
'''
|
172 |
+
dt = hdr.dtype
|
173 |
+
dims = hdr.dims
|
174 |
+
num_bytes = dt.itemsize
|
175 |
+
for d in dims:
|
176 |
+
num_bytes *= d
|
177 |
+
buffer = self.mat_stream.read(int(num_bytes))
|
178 |
+
if len(buffer) != num_bytes:
|
179 |
+
raise ValueError("Not enough bytes to read matrix '%s'; is this "
|
180 |
+
"a badly-formed file? Consider listing matrices "
|
181 |
+
"with `whosmat` and loading named matrices with "
|
182 |
+
"`variable_names` kwarg to `loadmat`" % hdr.name)
|
183 |
+
arr = np.ndarray(shape=dims,
|
184 |
+
dtype=dt,
|
185 |
+
buffer=buffer,
|
186 |
+
order='F')
|
187 |
+
if copy:
|
188 |
+
arr = arr.copy()
|
189 |
+
return arr
|
190 |
+
|
191 |
+
def read_full_array(self, hdr):
|
192 |
+
''' Full (rather than sparse) matrix getter
|
193 |
+
|
194 |
+
Read matrix (array) can be real or complex
|
195 |
+
|
196 |
+
Parameters
|
197 |
+
----------
|
198 |
+
hdr : ``VarHeader4`` instance
|
199 |
+
|
200 |
+
Returns
|
201 |
+
-------
|
202 |
+
arr : ndarray
|
203 |
+
complex array if ``hdr.is_complex`` is True, otherwise a real
|
204 |
+
numeric array
|
205 |
+
'''
|
206 |
+
if hdr.is_complex:
|
207 |
+
# avoid array copy to save memory
|
208 |
+
res = self.read_sub_array(hdr, copy=False)
|
209 |
+
res_j = self.read_sub_array(hdr, copy=False)
|
210 |
+
return res + (res_j * 1j)
|
211 |
+
return self.read_sub_array(hdr)
|
212 |
+
|
213 |
+
def read_char_array(self, hdr):
|
214 |
+
''' latin-1 text matrix (char matrix) reader
|
215 |
+
|
216 |
+
Parameters
|
217 |
+
----------
|
218 |
+
hdr : ``VarHeader4`` instance
|
219 |
+
|
220 |
+
Returns
|
221 |
+
-------
|
222 |
+
arr : ndarray
|
223 |
+
with dtype 'U1', shape given by `hdr` ``dims``
|
224 |
+
'''
|
225 |
+
arr = self.read_sub_array(hdr).astype(np.uint8)
|
226 |
+
S = arr.tobytes().decode('latin-1')
|
227 |
+
return np.ndarray(shape=hdr.dims,
|
228 |
+
dtype=np.dtype('U1'),
|
229 |
+
buffer=np.array(S)).copy()
|
230 |
+
|
231 |
+
def read_sparse_array(self, hdr):
|
232 |
+
''' Read and return sparse matrix type
|
233 |
+
|
234 |
+
Parameters
|
235 |
+
----------
|
236 |
+
hdr : ``VarHeader4`` instance
|
237 |
+
|
238 |
+
Returns
|
239 |
+
-------
|
240 |
+
arr : ``scipy.sparse.coo_matrix``
|
241 |
+
with dtype ``float`` and shape read from the sparse matrix data
|
242 |
+
|
243 |
+
Notes
|
244 |
+
-----
|
245 |
+
MATLAB 4 real sparse arrays are saved in a N+1 by 3 array format, where
|
246 |
+
N is the number of non-zero values. Column 1 values [0:N] are the
|
247 |
+
(1-based) row indices of the each non-zero value, column 2 [0:N] are the
|
248 |
+
column indices, column 3 [0:N] are the (real) values. The last values
|
249 |
+
[-1,0:2] of the rows, column indices are shape[0] and shape[1]
|
250 |
+
respectively of the output matrix. The last value for the values column
|
251 |
+
is a padding 0. mrows and ncols values from the header give the shape of
|
252 |
+
the stored matrix, here [N+1, 3]. Complex data are saved as a 4 column
|
253 |
+
matrix, where the fourth column contains the imaginary component; the
|
254 |
+
last value is again 0. Complex sparse data do *not* have the header
|
255 |
+
``imagf`` field set to True; the fact that the data are complex is only
|
256 |
+
detectable because there are 4 storage columns.
|
257 |
+
'''
|
258 |
+
res = self.read_sub_array(hdr)
|
259 |
+
tmp = res[:-1,:]
|
260 |
+
# All numbers are float64 in Matlab, but SciPy sparse expects int shape
|
261 |
+
dims = (int(res[-1,0]), int(res[-1,1]))
|
262 |
+
I = np.ascontiguousarray(tmp[:,0],dtype='intc') # fixes byte order also
|
263 |
+
J = np.ascontiguousarray(tmp[:,1],dtype='intc')
|
264 |
+
I -= 1 # for 1-based indexing
|
265 |
+
J -= 1
|
266 |
+
if res.shape[1] == 3:
|
267 |
+
V = np.ascontiguousarray(tmp[:,2],dtype='float')
|
268 |
+
else:
|
269 |
+
V = np.ascontiguousarray(tmp[:,2],dtype='complex')
|
270 |
+
V.imag = tmp[:,3]
|
271 |
+
return scipy.sparse.coo_matrix((V,(I,J)), dims)
|
272 |
+
|
273 |
+
def shape_from_header(self, hdr):
|
274 |
+
'''Read the shape of the array described by the header.
|
275 |
+
The file position after this call is unspecified.
|
276 |
+
'''
|
277 |
+
mclass = hdr.mclass
|
278 |
+
if mclass == mxFULL_CLASS:
|
279 |
+
shape = tuple(map(int, hdr.dims))
|
280 |
+
elif mclass == mxCHAR_CLASS:
|
281 |
+
shape = tuple(map(int, hdr.dims))
|
282 |
+
if self.chars_as_strings:
|
283 |
+
shape = shape[:-1]
|
284 |
+
elif mclass == mxSPARSE_CLASS:
|
285 |
+
dt = hdr.dtype
|
286 |
+
dims = hdr.dims
|
287 |
+
|
288 |
+
if not (len(dims) == 2 and dims[0] >= 1 and dims[1] >= 1):
|
289 |
+
return ()
|
290 |
+
|
291 |
+
# Read only the row and column counts
|
292 |
+
self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1)
|
293 |
+
rows = np.ndarray(shape=(), dtype=dt,
|
294 |
+
buffer=self.mat_stream.read(dt.itemsize))
|
295 |
+
self.mat_stream.seek(dt.itemsize * (dims[0] - 1), 1)
|
296 |
+
cols = np.ndarray(shape=(), dtype=dt,
|
297 |
+
buffer=self.mat_stream.read(dt.itemsize))
|
298 |
+
|
299 |
+
shape = (int(rows), int(cols))
|
300 |
+
else:
|
301 |
+
raise TypeError('No reader for class code %s' % mclass)
|
302 |
+
|
303 |
+
if self.squeeze_me:
|
304 |
+
shape = tuple([x for x in shape if x != 1])
|
305 |
+
return shape
|
306 |
+
|
307 |
+
|
308 |
+
class MatFile4Reader(MatFileReader):
|
309 |
+
''' Reader for Mat4 files '''
|
310 |
+
@docfiller
|
311 |
+
def __init__(self, mat_stream, *args, **kwargs):
|
312 |
+
''' Initialize matlab 4 file reader
|
313 |
+
|
314 |
+
%(matstream_arg)s
|
315 |
+
%(load_args)s
|
316 |
+
'''
|
317 |
+
super().__init__(mat_stream, *args, **kwargs)
|
318 |
+
self._matrix_reader = None
|
319 |
+
|
320 |
+
def guess_byte_order(self):
|
321 |
+
self.mat_stream.seek(0)
|
322 |
+
mopt = read_dtype(self.mat_stream, np.dtype('i4'))
|
323 |
+
self.mat_stream.seek(0)
|
324 |
+
if mopt == 0:
|
325 |
+
return '<'
|
326 |
+
if mopt < 0 or mopt > 5000:
|
327 |
+
# Number must have been byteswapped
|
328 |
+
return SYS_LITTLE_ENDIAN and '>' or '<'
|
329 |
+
# Not byteswapped
|
330 |
+
return SYS_LITTLE_ENDIAN and '<' or '>'
|
331 |
+
|
332 |
+
def initialize_read(self):
|
333 |
+
''' Run when beginning read of variables
|
334 |
+
|
335 |
+
Sets up readers from parameters in `self`
|
336 |
+
'''
|
337 |
+
self.dtypes = convert_dtypes(mdtypes_template, self.byte_order)
|
338 |
+
self._matrix_reader = VarReader4(self)
|
339 |
+
|
340 |
+
def read_var_header(self):
|
341 |
+
''' Read and return header, next position
|
342 |
+
|
343 |
+
Parameters
|
344 |
+
----------
|
345 |
+
None
|
346 |
+
|
347 |
+
Returns
|
348 |
+
-------
|
349 |
+
header : object
|
350 |
+
object that can be passed to self.read_var_array, and that
|
351 |
+
has attributes ``name`` and ``is_global``
|
352 |
+
next_position : int
|
353 |
+
position in stream of next variable
|
354 |
+
'''
|
355 |
+
hdr = self._matrix_reader.read_header()
|
356 |
+
n = reduce(lambda x, y: x*y, hdr.dims, 1) # fast product
|
357 |
+
remaining_bytes = hdr.dtype.itemsize * n
|
358 |
+
if hdr.is_complex and not hdr.mclass == mxSPARSE_CLASS:
|
359 |
+
remaining_bytes *= 2
|
360 |
+
next_position = self.mat_stream.tell() + remaining_bytes
|
361 |
+
return hdr, next_position
|
362 |
+
|
363 |
+
def read_var_array(self, header, process=True):
|
364 |
+
''' Read array, given `header`
|
365 |
+
|
366 |
+
Parameters
|
367 |
+
----------
|
368 |
+
header : header object
|
369 |
+
object with fields defining variable header
|
370 |
+
process : {True, False}, optional
|
371 |
+
If True, apply recursive post-processing during loading of array.
|
372 |
+
|
373 |
+
Returns
|
374 |
+
-------
|
375 |
+
arr : array
|
376 |
+
array with post-processing applied or not according to
|
377 |
+
`process`.
|
378 |
+
'''
|
379 |
+
return self._matrix_reader.array_from_header(header, process)
|
380 |
+
|
381 |
+
def get_variables(self, variable_names=None):
|
382 |
+
''' get variables from stream as dictionary
|
383 |
+
|
384 |
+
Parameters
|
385 |
+
----------
|
386 |
+
variable_names : None or str or sequence of str, optional
|
387 |
+
variable name, or sequence of variable names to get from Mat file /
|
388 |
+
file stream. If None, then get all variables in file.
|
389 |
+
'''
|
390 |
+
if isinstance(variable_names, str):
|
391 |
+
variable_names = [variable_names]
|
392 |
+
elif variable_names is not None:
|
393 |
+
variable_names = list(variable_names)
|
394 |
+
self.mat_stream.seek(0)
|
395 |
+
# set up variable reader
|
396 |
+
self.initialize_read()
|
397 |
+
mdict = {}
|
398 |
+
while not self.end_of_stream():
|
399 |
+
hdr, next_position = self.read_var_header()
|
400 |
+
name = 'None' if hdr.name is None else hdr.name.decode('latin1')
|
401 |
+
if variable_names is not None and name not in variable_names:
|
402 |
+
self.mat_stream.seek(next_position)
|
403 |
+
continue
|
404 |
+
mdict[name] = self.read_var_array(hdr)
|
405 |
+
self.mat_stream.seek(next_position)
|
406 |
+
if variable_names is not None:
|
407 |
+
variable_names.remove(name)
|
408 |
+
if len(variable_names) == 0:
|
409 |
+
break
|
410 |
+
return mdict
|
411 |
+
|
412 |
+
def list_variables(self):
|
413 |
+
''' list variables from stream '''
|
414 |
+
self.mat_stream.seek(0)
|
415 |
+
# set up variable reader
|
416 |
+
self.initialize_read()
|
417 |
+
vars = []
|
418 |
+
while not self.end_of_stream():
|
419 |
+
hdr, next_position = self.read_var_header()
|
420 |
+
name = 'None' if hdr.name is None else hdr.name.decode('latin1')
|
421 |
+
shape = self._matrix_reader.shape_from_header(hdr)
|
422 |
+
info = mclass_info.get(hdr.mclass, 'unknown')
|
423 |
+
vars.append((name, shape, info))
|
424 |
+
|
425 |
+
self.mat_stream.seek(next_position)
|
426 |
+
return vars
|
427 |
+
|
428 |
+
|
429 |
+
def arr_to_2d(arr, oned_as='row'):
|
430 |
+
''' Make ``arr`` exactly two dimensional
|
431 |
+
|
432 |
+
If `arr` has more than 2 dimensions, raise a ValueError
|
433 |
+
|
434 |
+
Parameters
|
435 |
+
----------
|
436 |
+
arr : array
|
437 |
+
oned_as : {'row', 'column'}, optional
|
438 |
+
Whether to reshape 1-D vectors as row vectors or column vectors.
|
439 |
+
See documentation for ``matdims`` for more detail
|
440 |
+
|
441 |
+
Returns
|
442 |
+
-------
|
443 |
+
arr2d : array
|
444 |
+
2-D version of the array
|
445 |
+
'''
|
446 |
+
dims = matdims(arr, oned_as)
|
447 |
+
if len(dims) > 2:
|
448 |
+
raise ValueError('Matlab 4 files cannot save arrays with more than '
|
449 |
+
'2 dimensions')
|
450 |
+
return arr.reshape(dims)
|
451 |
+
|
452 |
+
|
453 |
+
class VarWriter4:
|
454 |
+
def __init__(self, file_writer):
|
455 |
+
self.file_stream = file_writer.file_stream
|
456 |
+
self.oned_as = file_writer.oned_as
|
457 |
+
|
458 |
+
def write_bytes(self, arr):
|
459 |
+
self.file_stream.write(arr.tobytes(order='F'))
|
460 |
+
|
461 |
+
def write_string(self, s):
|
462 |
+
self.file_stream.write(s)
|
463 |
+
|
464 |
+
def write_header(self, name, shape, P=miDOUBLE, T=mxFULL_CLASS, imagf=0):
|
465 |
+
''' Write header for given data options
|
466 |
+
|
467 |
+
Parameters
|
468 |
+
----------
|
469 |
+
name : str
|
470 |
+
name of variable
|
471 |
+
shape : sequence
|
472 |
+
Shape of array as it will be read in matlab
|
473 |
+
P : int, optional
|
474 |
+
code for mat4 data type, one of ``miDOUBLE, miSINGLE, miINT32,
|
475 |
+
miINT16, miUINT16, miUINT8``
|
476 |
+
T : int, optional
|
477 |
+
code for mat4 matrix class, one of ``mxFULL_CLASS, mxCHAR_CLASS,
|
478 |
+
mxSPARSE_CLASS``
|
479 |
+
imagf : int, optional
|
480 |
+
flag indicating complex
|
481 |
+
'''
|
482 |
+
header = np.empty((), mdtypes_template['header'])
|
483 |
+
M = not SYS_LITTLE_ENDIAN
|
484 |
+
O = 0
|
485 |
+
header['mopt'] = (M * 1000 +
|
486 |
+
O * 100 +
|
487 |
+
P * 10 +
|
488 |
+
T)
|
489 |
+
header['mrows'] = shape[0]
|
490 |
+
header['ncols'] = shape[1]
|
491 |
+
header['imagf'] = imagf
|
492 |
+
header['namlen'] = len(name) + 1
|
493 |
+
self.write_bytes(header)
|
494 |
+
data = name + '\0'
|
495 |
+
self.write_string(data.encode('latin1'))
|
496 |
+
|
497 |
+
def write(self, arr, name):
|
498 |
+
''' Write matrix `arr`, with name `name`
|
499 |
+
|
500 |
+
Parameters
|
501 |
+
----------
|
502 |
+
arr : array_like
|
503 |
+
array to write
|
504 |
+
name : str
|
505 |
+
name in matlab workspace
|
506 |
+
'''
|
507 |
+
# we need to catch sparse first, because np.asarray returns an
|
508 |
+
# an object array for scipy.sparse
|
509 |
+
if scipy.sparse.issparse(arr):
|
510 |
+
self.write_sparse(arr, name)
|
511 |
+
return
|
512 |
+
arr = np.asarray(arr)
|
513 |
+
dt = arr.dtype
|
514 |
+
if not dt.isnative:
|
515 |
+
arr = arr.astype(dt.newbyteorder('='))
|
516 |
+
dtt = dt.type
|
517 |
+
if dtt is np.object_:
|
518 |
+
raise TypeError('Cannot save object arrays in Mat4')
|
519 |
+
elif dtt is np.void:
|
520 |
+
raise TypeError('Cannot save void type arrays')
|
521 |
+
elif dtt in (np.str_, np.bytes_):
|
522 |
+
self.write_char(arr, name)
|
523 |
+
return
|
524 |
+
self.write_numeric(arr, name)
|
525 |
+
|
526 |
+
def write_numeric(self, arr, name):
|
527 |
+
arr = arr_to_2d(arr, self.oned_as)
|
528 |
+
imagf = arr.dtype.kind == 'c'
|
529 |
+
try:
|
530 |
+
P = np_to_mtypes[arr.dtype.str[1:]]
|
531 |
+
except KeyError:
|
532 |
+
if imagf:
|
533 |
+
arr = arr.astype('c128')
|
534 |
+
else:
|
535 |
+
arr = arr.astype('f8')
|
536 |
+
P = miDOUBLE
|
537 |
+
self.write_header(name,
|
538 |
+
arr.shape,
|
539 |
+
P=P,
|
540 |
+
T=mxFULL_CLASS,
|
541 |
+
imagf=imagf)
|
542 |
+
if imagf:
|
543 |
+
self.write_bytes(arr.real)
|
544 |
+
self.write_bytes(arr.imag)
|
545 |
+
else:
|
546 |
+
self.write_bytes(arr)
|
547 |
+
|
548 |
+
def write_char(self, arr, name):
|
549 |
+
if arr.dtype.type == np.str_ and arr.dtype.itemsize != np.dtype('U1').itemsize:
|
550 |
+
arr = arr_to_chars(arr)
|
551 |
+
arr = arr_to_2d(arr, self.oned_as)
|
552 |
+
dims = arr.shape
|
553 |
+
self.write_header(
|
554 |
+
name,
|
555 |
+
dims,
|
556 |
+
P=miUINT8,
|
557 |
+
T=mxCHAR_CLASS)
|
558 |
+
if arr.dtype.kind == 'U':
|
559 |
+
# Recode unicode to latin1
|
560 |
+
n_chars = np.prod(dims)
|
561 |
+
st_arr = np.ndarray(shape=(),
|
562 |
+
dtype=arr_dtype_number(arr, n_chars),
|
563 |
+
buffer=arr)
|
564 |
+
st = st_arr.item().encode('latin-1')
|
565 |
+
arr = np.ndarray(shape=dims, dtype='S1', buffer=st)
|
566 |
+
self.write_bytes(arr)
|
567 |
+
|
568 |
+
def write_sparse(self, arr, name):
|
569 |
+
''' Sparse matrices are 2-D
|
570 |
+
|
571 |
+
See docstring for VarReader4.read_sparse_array
|
572 |
+
'''
|
573 |
+
A = arr.tocoo() # convert to sparse COO format (ijv)
|
574 |
+
imagf = A.dtype.kind == 'c'
|
575 |
+
ijv = np.zeros((A.nnz + 1, 3+imagf), dtype='f8')
|
576 |
+
ijv[:-1,0] = A.row
|
577 |
+
ijv[:-1,1] = A.col
|
578 |
+
ijv[:-1,0:2] += 1 # 1 based indexing
|
579 |
+
if imagf:
|
580 |
+
ijv[:-1,2] = A.data.real
|
581 |
+
ijv[:-1,3] = A.data.imag
|
582 |
+
else:
|
583 |
+
ijv[:-1,2] = A.data
|
584 |
+
ijv[-1,0:2] = A.shape
|
585 |
+
self.write_header(
|
586 |
+
name,
|
587 |
+
ijv.shape,
|
588 |
+
P=miDOUBLE,
|
589 |
+
T=mxSPARSE_CLASS)
|
590 |
+
self.write_bytes(ijv)
|
591 |
+
|
592 |
+
|
593 |
+
class MatFile4Writer:
|
594 |
+
''' Class for writing matlab 4 format files '''
|
595 |
+
def __init__(self, file_stream, oned_as=None):
|
596 |
+
self.file_stream = file_stream
|
597 |
+
if oned_as is None:
|
598 |
+
oned_as = 'row'
|
599 |
+
self.oned_as = oned_as
|
600 |
+
self._matrix_writer = None
|
601 |
+
|
602 |
+
def put_variables(self, mdict, write_header=None):
|
603 |
+
''' Write variables in `mdict` to stream
|
604 |
+
|
605 |
+
Parameters
|
606 |
+
----------
|
607 |
+
mdict : mapping
|
608 |
+
mapping with method ``items`` return name, contents pairs
|
609 |
+
where ``name`` which will appeak in the matlab workspace in
|
610 |
+
file load, and ``contents`` is something writeable to a
|
611 |
+
matlab file, such as a NumPy array.
|
612 |
+
write_header : {None, True, False}
|
613 |
+
If True, then write the matlab file header before writing the
|
614 |
+
variables. If None (the default) then write the file header
|
615 |
+
if we are at position 0 in the stream. By setting False
|
616 |
+
here, and setting the stream position to the end of the file,
|
617 |
+
you can append variables to a matlab file
|
618 |
+
'''
|
619 |
+
# there is no header for a matlab 4 mat file, so we ignore the
|
620 |
+
# ``write_header`` input argument. It's there for compatibility
|
621 |
+
# with the matlab 5 version of this method
|
622 |
+
self._matrix_writer = VarWriter4(self)
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
''' Classes for read / write of matlab (TM) 5 files
|
2 |
+
|
3 |
+
The matfile specification last found here:
|
4 |
+
|
5 |
+
https://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf
|
6 |
+
|
7 |
+
(as of December 5 2008)
|
8 |
+
|
9 |
+
=================================
|
10 |
+
Note on functions and mat files
|
11 |
+
=================================
|
12 |
+
|
13 |
+
The document above does not give any hints as to the storage of matlab
|
14 |
+
function handles, or anonymous function handles. I had, therefore, to
|
15 |
+
guess the format of matlab arrays of ``mxFUNCTION_CLASS`` and
|
16 |
+
``mxOPAQUE_CLASS`` by looking at example mat files.
|
17 |
+
|
18 |
+
``mxFUNCTION_CLASS`` stores all types of matlab functions. It seems to
|
19 |
+
contain a struct matrix with a set pattern of fields. For anonymous
|
20 |
+
functions, a sub-fields of one of these fields seems to contain the
|
21 |
+
well-named ``mxOPAQUE_CLASS``. This seems to contain:
|
22 |
+
|
23 |
+
* array flags as for any matlab matrix
|
24 |
+
* 3 int8 strings
|
25 |
+
* a matrix
|
26 |
+
|
27 |
+
It seems that whenever the mat file contains a ``mxOPAQUE_CLASS``
|
28 |
+
instance, there is also an un-named matrix (name == '') at the end of
|
29 |
+
the mat file. I'll call this the ``__function_workspace__`` matrix.
|
30 |
+
|
31 |
+
When I saved two anonymous functions in a mat file, or appended another
|
32 |
+
anonymous function to the mat file, there was still only one
|
33 |
+
``__function_workspace__`` un-named matrix at the end, but larger than
|
34 |
+
that for a mat file with a single anonymous function, suggesting that
|
35 |
+
the workspaces for the two functions had been merged.
|
36 |
+
|
37 |
+
The ``__function_workspace__`` matrix appears to be of double class
|
38 |
+
(``mxCLASS_DOUBLE``), but stored as uint8, the memory for which is in
|
39 |
+
the format of a mini .mat file, without the first 124 bytes of the file
|
40 |
+
header (the description and the subsystem_offset), but with the version
|
41 |
+
U2 bytes, and the S2 endian test bytes. There follow 4 zero bytes,
|
42 |
+
presumably for 8 byte padding, and then a series of ``miMATRIX``
|
43 |
+
entries, as in a standard mat file. The ``miMATRIX`` entries appear to
|
44 |
+
be series of un-named (name == '') matrices, and may also contain arrays
|
45 |
+
of this same mini-mat format.
|
46 |
+
|
47 |
+
I guess that:
|
48 |
+
|
49 |
+
* saving an anonymous function back to a mat file will need the
|
50 |
+
associated ``__function_workspace__`` matrix saved as well for the
|
51 |
+
anonymous function to work correctly.
|
52 |
+
* appending to a mat file that has a ``__function_workspace__`` would
|
53 |
+
involve first pulling off this workspace, appending, checking whether
|
54 |
+
there were any more anonymous functions appended, and then somehow
|
55 |
+
merging the relevant workspaces, and saving at the end of the mat
|
56 |
+
file.
|
57 |
+
|
58 |
+
The mat files I was playing with are in ``tests/data``:
|
59 |
+
|
60 |
+
* sqr.mat
|
61 |
+
* parabola.mat
|
62 |
+
* some_functions.mat
|
63 |
+
|
64 |
+
See ``tests/test_mio.py:test_mio_funcs.py`` for the debugging
|
65 |
+
script I was working with.
|
66 |
+
|
67 |
+
Small fragments of current code adapted from matfile.py by Heiko
|
68 |
+
Henkelmann; parts of the code for simplify_cells=True adapted from
|
69 |
+
http://blog.nephics.com/2019/08/28/better-loadmat-for-scipy/.
|
70 |
+
'''
|
71 |
+
|
72 |
+
import os
|
73 |
+
import time
|
74 |
+
import sys
|
75 |
+
import zlib
|
76 |
+
|
77 |
+
from io import BytesIO
|
78 |
+
|
79 |
+
import warnings
|
80 |
+
|
81 |
+
import numpy as np
|
82 |
+
|
83 |
+
import scipy.sparse
|
84 |
+
|
85 |
+
from ._byteordercodes import native_code, swapped_code
|
86 |
+
|
87 |
+
from ._miobase import (MatFileReader, docfiller, matdims, read_dtype,
|
88 |
+
arr_to_chars, arr_dtype_number, MatWriteError,
|
89 |
+
MatReadError, MatReadWarning)
|
90 |
+
|
91 |
+
# Reader object for matlab 5 format variables
|
92 |
+
from ._mio5_utils import VarReader5
|
93 |
+
|
94 |
+
# Constants and helper objects
|
95 |
+
from ._mio5_params import (MatlabObject, MatlabFunction, MDTYPES, NP_TO_MTYPES,
|
96 |
+
NP_TO_MXTYPES, miCOMPRESSED, miMATRIX, miINT8,
|
97 |
+
miUTF8, miUINT32, mxCELL_CLASS, mxSTRUCT_CLASS,
|
98 |
+
mxOBJECT_CLASS, mxCHAR_CLASS, mxSPARSE_CLASS,
|
99 |
+
mxDOUBLE_CLASS, mclass_info, mat_struct)
|
100 |
+
|
101 |
+
from ._streams import ZlibInputStream
|
102 |
+
|
103 |
+
|
104 |
+
def _has_struct(elem):
|
105 |
+
"""Determine if elem is an array and if first array item is a struct."""
|
106 |
+
return (isinstance(elem, np.ndarray) and (elem.size > 0) and (elem.ndim > 0) and
|
107 |
+
isinstance(elem[0], mat_struct))
|
108 |
+
|
109 |
+
|
110 |
+
def _inspect_cell_array(ndarray):
|
111 |
+
"""Construct lists from cell arrays (loaded as numpy ndarrays), recursing
|
112 |
+
into items if they contain mat_struct objects."""
|
113 |
+
elem_list = []
|
114 |
+
for sub_elem in ndarray:
|
115 |
+
if isinstance(sub_elem, mat_struct):
|
116 |
+
elem_list.append(_matstruct_to_dict(sub_elem))
|
117 |
+
elif _has_struct(sub_elem):
|
118 |
+
elem_list.append(_inspect_cell_array(sub_elem))
|
119 |
+
else:
|
120 |
+
elem_list.append(sub_elem)
|
121 |
+
return elem_list
|
122 |
+
|
123 |
+
|
124 |
+
def _matstruct_to_dict(matobj):
|
125 |
+
"""Construct nested dicts from mat_struct objects."""
|
126 |
+
d = {}
|
127 |
+
for f in matobj._fieldnames:
|
128 |
+
elem = matobj.__dict__[f]
|
129 |
+
if isinstance(elem, mat_struct):
|
130 |
+
d[f] = _matstruct_to_dict(elem)
|
131 |
+
elif _has_struct(elem):
|
132 |
+
d[f] = _inspect_cell_array(elem)
|
133 |
+
else:
|
134 |
+
d[f] = elem
|
135 |
+
return d
|
136 |
+
|
137 |
+
|
138 |
+
def _simplify_cells(d):
|
139 |
+
"""Convert mat objects in dict to nested dicts."""
|
140 |
+
for key in d:
|
141 |
+
if isinstance(d[key], mat_struct):
|
142 |
+
d[key] = _matstruct_to_dict(d[key])
|
143 |
+
elif _has_struct(d[key]):
|
144 |
+
d[key] = _inspect_cell_array(d[key])
|
145 |
+
return d
|
146 |
+
|
147 |
+
|
148 |
+
class MatFile5Reader(MatFileReader):
|
149 |
+
''' Reader for Mat 5 mat files
|
150 |
+
Adds the following attribute to base class
|
151 |
+
|
152 |
+
uint16_codec - char codec to use for uint16 char arrays
|
153 |
+
(defaults to system default codec)
|
154 |
+
|
155 |
+
Uses variable reader that has the following standard interface (see
|
156 |
+
abstract class in ``miobase``::
|
157 |
+
|
158 |
+
__init__(self, file_reader)
|
159 |
+
read_header(self)
|
160 |
+
array_from_header(self)
|
161 |
+
|
162 |
+
and added interface::
|
163 |
+
|
164 |
+
set_stream(self, stream)
|
165 |
+
read_full_tag(self)
|
166 |
+
|
167 |
+
'''
|
168 |
+
@docfiller
|
169 |
+
def __init__(self,
|
170 |
+
mat_stream,
|
171 |
+
byte_order=None,
|
172 |
+
mat_dtype=False,
|
173 |
+
squeeze_me=False,
|
174 |
+
chars_as_strings=True,
|
175 |
+
matlab_compatible=False,
|
176 |
+
struct_as_record=True,
|
177 |
+
verify_compressed_data_integrity=True,
|
178 |
+
uint16_codec=None,
|
179 |
+
simplify_cells=False):
|
180 |
+
'''Initializer for matlab 5 file format reader
|
181 |
+
|
182 |
+
%(matstream_arg)s
|
183 |
+
%(load_args)s
|
184 |
+
%(struct_arg)s
|
185 |
+
uint16_codec : {None, string}
|
186 |
+
Set codec to use for uint16 char arrays (e.g., 'utf-8').
|
187 |
+
Use system default codec if None
|
188 |
+
'''
|
189 |
+
super().__init__(
|
190 |
+
mat_stream,
|
191 |
+
byte_order,
|
192 |
+
mat_dtype,
|
193 |
+
squeeze_me,
|
194 |
+
chars_as_strings,
|
195 |
+
matlab_compatible,
|
196 |
+
struct_as_record,
|
197 |
+
verify_compressed_data_integrity,
|
198 |
+
simplify_cells)
|
199 |
+
# Set uint16 codec
|
200 |
+
if not uint16_codec:
|
201 |
+
uint16_codec = sys.getdefaultencoding()
|
202 |
+
self.uint16_codec = uint16_codec
|
203 |
+
# placeholders for readers - see initialize_read method
|
204 |
+
self._file_reader = None
|
205 |
+
self._matrix_reader = None
|
206 |
+
|
207 |
+
def guess_byte_order(self):
|
208 |
+
''' Guess byte order.
|
209 |
+
Sets stream pointer to 0'''
|
210 |
+
self.mat_stream.seek(126)
|
211 |
+
mi = self.mat_stream.read(2)
|
212 |
+
self.mat_stream.seek(0)
|
213 |
+
return mi == b'IM' and '<' or '>'
|
214 |
+
|
215 |
+
def read_file_header(self):
|
216 |
+
''' Read in mat 5 file header '''
|
217 |
+
hdict = {}
|
218 |
+
hdr_dtype = MDTYPES[self.byte_order]['dtypes']['file_header']
|
219 |
+
hdr = read_dtype(self.mat_stream, hdr_dtype)
|
220 |
+
hdict['__header__'] = hdr['description'].item().strip(b' \t\n\000')
|
221 |
+
v_major = hdr['version'] >> 8
|
222 |
+
v_minor = hdr['version'] & 0xFF
|
223 |
+
hdict['__version__'] = '%d.%d' % (v_major, v_minor)
|
224 |
+
return hdict
|
225 |
+
|
226 |
+
def initialize_read(self):
|
227 |
+
''' Run when beginning read of variables
|
228 |
+
|
229 |
+
Sets up readers from parameters in `self`
|
230 |
+
'''
|
231 |
+
# reader for top level stream. We need this extra top-level
|
232 |
+
# reader because we use the matrix_reader object to contain
|
233 |
+
# compressed matrices (so they have their own stream)
|
234 |
+
self._file_reader = VarReader5(self)
|
235 |
+
# reader for matrix streams
|
236 |
+
self._matrix_reader = VarReader5(self)
|
237 |
+
|
238 |
+
def read_var_header(self):
|
239 |
+
''' Read header, return header, next position
|
240 |
+
|
241 |
+
Header has to define at least .name and .is_global
|
242 |
+
|
243 |
+
Parameters
|
244 |
+
----------
|
245 |
+
None
|
246 |
+
|
247 |
+
Returns
|
248 |
+
-------
|
249 |
+
header : object
|
250 |
+
object that can be passed to self.read_var_array, and that
|
251 |
+
has attributes .name and .is_global
|
252 |
+
next_position : int
|
253 |
+
position in stream of next variable
|
254 |
+
'''
|
255 |
+
mdtype, byte_count = self._file_reader.read_full_tag()
|
256 |
+
if not byte_count > 0:
|
257 |
+
raise ValueError("Did not read any bytes")
|
258 |
+
next_pos = self.mat_stream.tell() + byte_count
|
259 |
+
if mdtype == miCOMPRESSED:
|
260 |
+
# Make new stream from compressed data
|
261 |
+
stream = ZlibInputStream(self.mat_stream, byte_count)
|
262 |
+
self._matrix_reader.set_stream(stream)
|
263 |
+
check_stream_limit = self.verify_compressed_data_integrity
|
264 |
+
mdtype, byte_count = self._matrix_reader.read_full_tag()
|
265 |
+
else:
|
266 |
+
check_stream_limit = False
|
267 |
+
self._matrix_reader.set_stream(self.mat_stream)
|
268 |
+
if not mdtype == miMATRIX:
|
269 |
+
raise TypeError('Expecting miMATRIX type here, got %d' % mdtype)
|
270 |
+
header = self._matrix_reader.read_header(check_stream_limit)
|
271 |
+
return header, next_pos
|
272 |
+
|
273 |
+
def read_var_array(self, header, process=True):
|
274 |
+
''' Read array, given `header`
|
275 |
+
|
276 |
+
Parameters
|
277 |
+
----------
|
278 |
+
header : header object
|
279 |
+
object with fields defining variable header
|
280 |
+
process : {True, False} bool, optional
|
281 |
+
If True, apply recursive post-processing during loading of
|
282 |
+
array.
|
283 |
+
|
284 |
+
Returns
|
285 |
+
-------
|
286 |
+
arr : array
|
287 |
+
array with post-processing applied or not according to
|
288 |
+
`process`.
|
289 |
+
'''
|
290 |
+
return self._matrix_reader.array_from_header(header, process)
|
291 |
+
|
292 |
+
def get_variables(self, variable_names=None):
|
293 |
+
''' get variables from stream as dictionary
|
294 |
+
|
295 |
+
variable_names - optional list of variable names to get
|
296 |
+
|
297 |
+
If variable_names is None, then get all variables in file
|
298 |
+
'''
|
299 |
+
if isinstance(variable_names, str):
|
300 |
+
variable_names = [variable_names]
|
301 |
+
elif variable_names is not None:
|
302 |
+
variable_names = list(variable_names)
|
303 |
+
|
304 |
+
self.mat_stream.seek(0)
|
305 |
+
# Here we pass all the parameters in self to the reading objects
|
306 |
+
self.initialize_read()
|
307 |
+
mdict = self.read_file_header()
|
308 |
+
mdict['__globals__'] = []
|
309 |
+
while not self.end_of_stream():
|
310 |
+
hdr, next_position = self.read_var_header()
|
311 |
+
name = 'None' if hdr.name is None else hdr.name.decode('latin1')
|
312 |
+
if name in mdict:
|
313 |
+
warnings.warn('Duplicate variable name "%s" in stream'
|
314 |
+
' - replacing previous with new\n'
|
315 |
+
'Consider mio5.varmats_from_mat to split '
|
316 |
+
'file into single variable files' % name,
|
317 |
+
MatReadWarning, stacklevel=2)
|
318 |
+
if name == '':
|
319 |
+
# can only be a matlab 7 function workspace
|
320 |
+
name = '__function_workspace__'
|
321 |
+
# We want to keep this raw because mat_dtype processing
|
322 |
+
# will break the format (uint8 as mxDOUBLE_CLASS)
|
323 |
+
process = False
|
324 |
+
else:
|
325 |
+
process = True
|
326 |
+
if variable_names is not None and name not in variable_names:
|
327 |
+
self.mat_stream.seek(next_position)
|
328 |
+
continue
|
329 |
+
try:
|
330 |
+
res = self.read_var_array(hdr, process)
|
331 |
+
except MatReadError as err:
|
332 |
+
warnings.warn(
|
333 |
+
f'Unreadable variable "{name}", because "{err}"',
|
334 |
+
Warning, stacklevel=2)
|
335 |
+
res = "Read error: %s" % err
|
336 |
+
self.mat_stream.seek(next_position)
|
337 |
+
mdict[name] = res
|
338 |
+
if hdr.is_global:
|
339 |
+
mdict['__globals__'].append(name)
|
340 |
+
if variable_names is not None:
|
341 |
+
variable_names.remove(name)
|
342 |
+
if len(variable_names) == 0:
|
343 |
+
break
|
344 |
+
if self.simplify_cells:
|
345 |
+
return _simplify_cells(mdict)
|
346 |
+
else:
|
347 |
+
return mdict
|
348 |
+
|
349 |
+
def list_variables(self):
|
350 |
+
''' list variables from stream '''
|
351 |
+
self.mat_stream.seek(0)
|
352 |
+
# Here we pass all the parameters in self to the reading objects
|
353 |
+
self.initialize_read()
|
354 |
+
self.read_file_header()
|
355 |
+
vars = []
|
356 |
+
while not self.end_of_stream():
|
357 |
+
hdr, next_position = self.read_var_header()
|
358 |
+
name = 'None' if hdr.name is None else hdr.name.decode('latin1')
|
359 |
+
if name == '':
|
360 |
+
# can only be a matlab 7 function workspace
|
361 |
+
name = '__function_workspace__'
|
362 |
+
|
363 |
+
shape = self._matrix_reader.shape_from_header(hdr)
|
364 |
+
if hdr.is_logical:
|
365 |
+
info = 'logical'
|
366 |
+
else:
|
367 |
+
info = mclass_info.get(hdr.mclass, 'unknown')
|
368 |
+
vars.append((name, shape, info))
|
369 |
+
|
370 |
+
self.mat_stream.seek(next_position)
|
371 |
+
return vars
|
372 |
+
|
373 |
+
|
374 |
+
def varmats_from_mat(file_obj):
|
375 |
+
""" Pull variables out of mat 5 file as a sequence of mat file objects
|
376 |
+
|
377 |
+
This can be useful with a difficult mat file, containing unreadable
|
378 |
+
variables. This routine pulls the variables out in raw form and puts them,
|
379 |
+
unread, back into a file stream for saving or reading. Another use is the
|
380 |
+
pathological case where there is more than one variable of the same name in
|
381 |
+
the file; this routine returns the duplicates, whereas the standard reader
|
382 |
+
will overwrite duplicates in the returned dictionary.
|
383 |
+
|
384 |
+
The file pointer in `file_obj` will be undefined. File pointers for the
|
385 |
+
returned file-like objects are set at 0.
|
386 |
+
|
387 |
+
Parameters
|
388 |
+
----------
|
389 |
+
file_obj : file-like
|
390 |
+
file object containing mat file
|
391 |
+
|
392 |
+
Returns
|
393 |
+
-------
|
394 |
+
named_mats : list
|
395 |
+
list contains tuples of (name, BytesIO) where BytesIO is a file-like
|
396 |
+
object containing mat file contents as for a single variable. The
|
397 |
+
BytesIO contains a string with the original header and a single var. If
|
398 |
+
``var_file_obj`` is an individual BytesIO instance, then save as a mat
|
399 |
+
file with something like ``open('test.mat',
|
400 |
+
'wb').write(var_file_obj.read())``
|
401 |
+
|
402 |
+
Examples
|
403 |
+
--------
|
404 |
+
>>> import scipy.io
|
405 |
+
>>> import numpy as np
|
406 |
+
>>> from io import BytesIO
|
407 |
+
>>> from scipy.io.matlab._mio5 import varmats_from_mat
|
408 |
+
>>> mat_fileobj = BytesIO()
|
409 |
+
>>> scipy.io.savemat(mat_fileobj, {'b': np.arange(10), 'a': 'a string'})
|
410 |
+
>>> varmats = varmats_from_mat(mat_fileobj)
|
411 |
+
>>> sorted([name for name, str_obj in varmats])
|
412 |
+
['a', 'b']
|
413 |
+
"""
|
414 |
+
rdr = MatFile5Reader(file_obj)
|
415 |
+
file_obj.seek(0)
|
416 |
+
# Raw read of top-level file header
|
417 |
+
hdr_len = MDTYPES[native_code]['dtypes']['file_header'].itemsize
|
418 |
+
raw_hdr = file_obj.read(hdr_len)
|
419 |
+
# Initialize variable reading
|
420 |
+
file_obj.seek(0)
|
421 |
+
rdr.initialize_read()
|
422 |
+
rdr.read_file_header()
|
423 |
+
next_position = file_obj.tell()
|
424 |
+
named_mats = []
|
425 |
+
while not rdr.end_of_stream():
|
426 |
+
start_position = next_position
|
427 |
+
hdr, next_position = rdr.read_var_header()
|
428 |
+
name = 'None' if hdr.name is None else hdr.name.decode('latin1')
|
429 |
+
# Read raw variable string
|
430 |
+
file_obj.seek(start_position)
|
431 |
+
byte_count = next_position - start_position
|
432 |
+
var_str = file_obj.read(byte_count)
|
433 |
+
# write to stringio object
|
434 |
+
out_obj = BytesIO()
|
435 |
+
out_obj.write(raw_hdr)
|
436 |
+
out_obj.write(var_str)
|
437 |
+
out_obj.seek(0)
|
438 |
+
named_mats.append((name, out_obj))
|
439 |
+
return named_mats
|
440 |
+
|
441 |
+
|
442 |
+
class EmptyStructMarker:
|
443 |
+
""" Class to indicate presence of empty matlab struct on output """
|
444 |
+
|
445 |
+
|
446 |
+
def to_writeable(source):
|
447 |
+
''' Convert input object ``source`` to something we can write
|
448 |
+
|
449 |
+
Parameters
|
450 |
+
----------
|
451 |
+
source : object
|
452 |
+
|
453 |
+
Returns
|
454 |
+
-------
|
455 |
+
arr : None or ndarray or EmptyStructMarker
|
456 |
+
If `source` cannot be converted to something we can write to a matfile,
|
457 |
+
return None. If `source` is equivalent to an empty dictionary, return
|
458 |
+
``EmptyStructMarker``. Otherwise return `source` converted to an
|
459 |
+
ndarray with contents for writing to matfile.
|
460 |
+
'''
|
461 |
+
if isinstance(source, np.ndarray):
|
462 |
+
return source
|
463 |
+
if source is None:
|
464 |
+
return None
|
465 |
+
if hasattr(source, "__array__"):
|
466 |
+
return np.asarray(source)
|
467 |
+
# Objects that implement mappings
|
468 |
+
is_mapping = (hasattr(source, 'keys') and hasattr(source, 'values') and
|
469 |
+
hasattr(source, 'items'))
|
470 |
+
# Objects that don't implement mappings, but do have dicts
|
471 |
+
if isinstance(source, np.generic):
|
472 |
+
# NumPy scalars are never mappings (PyPy issue workaround)
|
473 |
+
pass
|
474 |
+
elif not is_mapping and hasattr(source, '__dict__'):
|
475 |
+
source = {key: value for key, value in source.__dict__.items()
|
476 |
+
if not key.startswith('_')}
|
477 |
+
is_mapping = True
|
478 |
+
if is_mapping:
|
479 |
+
dtype = []
|
480 |
+
values = []
|
481 |
+
for field, value in source.items():
|
482 |
+
if (isinstance(field, str) and
|
483 |
+
field[0] not in '_0123456789'):
|
484 |
+
dtype.append((str(field), object))
|
485 |
+
values.append(value)
|
486 |
+
if dtype:
|
487 |
+
return np.array([tuple(values)], dtype)
|
488 |
+
else:
|
489 |
+
return EmptyStructMarker
|
490 |
+
# Next try and convert to an array
|
491 |
+
try:
|
492 |
+
narr = np.asanyarray(source)
|
493 |
+
except ValueError:
|
494 |
+
narr = np.asanyarray(source, dtype=object)
|
495 |
+
if narr.dtype.type in (object, np.object_) and \
|
496 |
+
narr.shape == () and narr == source:
|
497 |
+
# No interesting conversion possible
|
498 |
+
return None
|
499 |
+
return narr
|
500 |
+
|
501 |
+
|
502 |
+
# Native byte ordered dtypes for convenience for writers
|
503 |
+
NDT_FILE_HDR = MDTYPES[native_code]['dtypes']['file_header']
|
504 |
+
NDT_TAG_FULL = MDTYPES[native_code]['dtypes']['tag_full']
|
505 |
+
NDT_TAG_SMALL = MDTYPES[native_code]['dtypes']['tag_smalldata']
|
506 |
+
NDT_ARRAY_FLAGS = MDTYPES[native_code]['dtypes']['array_flags']
|
507 |
+
|
508 |
+
|
509 |
+
class VarWriter5:
|
510 |
+
''' Generic matlab matrix writing class '''
|
511 |
+
mat_tag = np.zeros((), NDT_TAG_FULL)
|
512 |
+
mat_tag['mdtype'] = miMATRIX
|
513 |
+
|
514 |
+
def __init__(self, file_writer):
|
515 |
+
self.file_stream = file_writer.file_stream
|
516 |
+
self.unicode_strings = file_writer.unicode_strings
|
517 |
+
self.long_field_names = file_writer.long_field_names
|
518 |
+
self.oned_as = file_writer.oned_as
|
519 |
+
# These are used for top level writes, and unset after
|
520 |
+
self._var_name = None
|
521 |
+
self._var_is_global = False
|
522 |
+
|
523 |
+
def write_bytes(self, arr):
|
524 |
+
self.file_stream.write(arr.tobytes(order='F'))
|
525 |
+
|
526 |
+
def write_string(self, s):
|
527 |
+
self.file_stream.write(s)
|
528 |
+
|
529 |
+
def write_element(self, arr, mdtype=None):
|
530 |
+
''' write tag and data '''
|
531 |
+
if mdtype is None:
|
532 |
+
mdtype = NP_TO_MTYPES[arr.dtype.str[1:]]
|
533 |
+
# Array needs to be in native byte order
|
534 |
+
if arr.dtype.byteorder == swapped_code:
|
535 |
+
arr = arr.byteswap().view(arr.dtype.newbyteorder())
|
536 |
+
byte_count = arr.size*arr.itemsize
|
537 |
+
if byte_count <= 4:
|
538 |
+
self.write_smalldata_element(arr, mdtype, byte_count)
|
539 |
+
else:
|
540 |
+
self.write_regular_element(arr, mdtype, byte_count)
|
541 |
+
|
542 |
+
def write_smalldata_element(self, arr, mdtype, byte_count):
|
543 |
+
# write tag with embedded data
|
544 |
+
tag = np.zeros((), NDT_TAG_SMALL)
|
545 |
+
tag['byte_count_mdtype'] = (byte_count << 16) + mdtype
|
546 |
+
# if arr.tobytes is < 4, the element will be zero-padded as needed.
|
547 |
+
tag['data'] = arr.tobytes(order='F')
|
548 |
+
self.write_bytes(tag)
|
549 |
+
|
550 |
+
def write_regular_element(self, arr, mdtype, byte_count):
|
551 |
+
# write tag, data
|
552 |
+
tag = np.zeros((), NDT_TAG_FULL)
|
553 |
+
tag['mdtype'] = mdtype
|
554 |
+
tag['byte_count'] = byte_count
|
555 |
+
self.write_bytes(tag)
|
556 |
+
self.write_bytes(arr)
|
557 |
+
# pad to next 64-bit boundary
|
558 |
+
bc_mod_8 = byte_count % 8
|
559 |
+
if bc_mod_8:
|
560 |
+
self.file_stream.write(b'\x00' * (8-bc_mod_8))
|
561 |
+
|
562 |
+
def write_header(self,
|
563 |
+
shape,
|
564 |
+
mclass,
|
565 |
+
is_complex=False,
|
566 |
+
is_logical=False,
|
567 |
+
nzmax=0):
|
568 |
+
''' Write header for given data options
|
569 |
+
shape : sequence
|
570 |
+
array shape
|
571 |
+
mclass - mat5 matrix class
|
572 |
+
is_complex - True if matrix is complex
|
573 |
+
is_logical - True if matrix is logical
|
574 |
+
nzmax - max non zero elements for sparse arrays
|
575 |
+
|
576 |
+
We get the name and the global flag from the object, and reset
|
577 |
+
them to defaults after we've used them
|
578 |
+
'''
|
579 |
+
# get name and is_global from one-shot object store
|
580 |
+
name = self._var_name
|
581 |
+
is_global = self._var_is_global
|
582 |
+
# initialize the top-level matrix tag, store position
|
583 |
+
self._mat_tag_pos = self.file_stream.tell()
|
584 |
+
self.write_bytes(self.mat_tag)
|
585 |
+
# write array flags (complex, global, logical, class, nzmax)
|
586 |
+
af = np.zeros((), NDT_ARRAY_FLAGS)
|
587 |
+
af['data_type'] = miUINT32
|
588 |
+
af['byte_count'] = 8
|
589 |
+
flags = is_complex << 3 | is_global << 2 | is_logical << 1
|
590 |
+
af['flags_class'] = mclass | flags << 8
|
591 |
+
af['nzmax'] = nzmax
|
592 |
+
self.write_bytes(af)
|
593 |
+
# shape
|
594 |
+
self.write_element(np.array(shape, dtype='i4'))
|
595 |
+
# write name
|
596 |
+
name = np.asarray(name)
|
597 |
+
if name == '': # empty string zero-terminated
|
598 |
+
self.write_smalldata_element(name, miINT8, 0)
|
599 |
+
else:
|
600 |
+
self.write_element(name, miINT8)
|
601 |
+
# reset the one-shot store to defaults
|
602 |
+
self._var_name = ''
|
603 |
+
self._var_is_global = False
|
604 |
+
|
605 |
+
def update_matrix_tag(self, start_pos):
|
606 |
+
curr_pos = self.file_stream.tell()
|
607 |
+
self.file_stream.seek(start_pos)
|
608 |
+
byte_count = curr_pos - start_pos - 8
|
609 |
+
if byte_count >= 2**32:
|
610 |
+
raise MatWriteError("Matrix too large to save with Matlab "
|
611 |
+
"5 format")
|
612 |
+
self.mat_tag['byte_count'] = byte_count
|
613 |
+
self.write_bytes(self.mat_tag)
|
614 |
+
self.file_stream.seek(curr_pos)
|
615 |
+
|
616 |
+
def write_top(self, arr, name, is_global):
|
617 |
+
""" Write variable at top level of mat file
|
618 |
+
|
619 |
+
Parameters
|
620 |
+
----------
|
621 |
+
arr : array_like
|
622 |
+
array-like object to create writer for
|
623 |
+
name : str, optional
|
624 |
+
name as it will appear in matlab workspace
|
625 |
+
default is empty string
|
626 |
+
is_global : {False, True}, optional
|
627 |
+
whether variable will be global on load into matlab
|
628 |
+
"""
|
629 |
+
# these are set before the top-level header write, and unset at
|
630 |
+
# the end of the same write, because they do not apply for lower levels
|
631 |
+
self._var_is_global = is_global
|
632 |
+
self._var_name = name
|
633 |
+
# write the header and data
|
634 |
+
self.write(arr)
|
635 |
+
|
636 |
+
def write(self, arr):
|
637 |
+
''' Write `arr` to stream at top and sub levels
|
638 |
+
|
639 |
+
Parameters
|
640 |
+
----------
|
641 |
+
arr : array_like
|
642 |
+
array-like object to create writer for
|
643 |
+
'''
|
644 |
+
# store position, so we can update the matrix tag
|
645 |
+
mat_tag_pos = self.file_stream.tell()
|
646 |
+
# First check if these are sparse
|
647 |
+
if scipy.sparse.issparse(arr):
|
648 |
+
self.write_sparse(arr)
|
649 |
+
self.update_matrix_tag(mat_tag_pos)
|
650 |
+
return
|
651 |
+
# Try to convert things that aren't arrays
|
652 |
+
narr = to_writeable(arr)
|
653 |
+
if narr is None:
|
654 |
+
raise TypeError(f'Could not convert {arr} (type {type(arr)}) to array')
|
655 |
+
if isinstance(narr, MatlabObject):
|
656 |
+
self.write_object(narr)
|
657 |
+
elif isinstance(narr, MatlabFunction):
|
658 |
+
raise MatWriteError('Cannot write matlab functions')
|
659 |
+
elif narr is EmptyStructMarker: # empty struct array
|
660 |
+
self.write_empty_struct()
|
661 |
+
elif narr.dtype.fields: # struct array
|
662 |
+
self.write_struct(narr)
|
663 |
+
elif narr.dtype.hasobject: # cell array
|
664 |
+
self.write_cells(narr)
|
665 |
+
elif narr.dtype.kind in ('U', 'S'):
|
666 |
+
if self.unicode_strings:
|
667 |
+
codec = 'UTF8'
|
668 |
+
else:
|
669 |
+
codec = 'ascii'
|
670 |
+
self.write_char(narr, codec)
|
671 |
+
else:
|
672 |
+
self.write_numeric(narr)
|
673 |
+
self.update_matrix_tag(mat_tag_pos)
|
674 |
+
|
675 |
+
def write_numeric(self, arr):
|
676 |
+
imagf = arr.dtype.kind == 'c'
|
677 |
+
logif = arr.dtype.kind == 'b'
|
678 |
+
try:
|
679 |
+
mclass = NP_TO_MXTYPES[arr.dtype.str[1:]]
|
680 |
+
except KeyError:
|
681 |
+
# No matching matlab type, probably complex256 / float128 / float96
|
682 |
+
# Cast data to complex128 / float64.
|
683 |
+
if imagf:
|
684 |
+
arr = arr.astype('c128')
|
685 |
+
elif logif:
|
686 |
+
arr = arr.astype('i1') # Should only contain 0/1
|
687 |
+
else:
|
688 |
+
arr = arr.astype('f8')
|
689 |
+
mclass = mxDOUBLE_CLASS
|
690 |
+
self.write_header(matdims(arr, self.oned_as),
|
691 |
+
mclass,
|
692 |
+
is_complex=imagf,
|
693 |
+
is_logical=logif)
|
694 |
+
if imagf:
|
695 |
+
self.write_element(arr.real)
|
696 |
+
self.write_element(arr.imag)
|
697 |
+
else:
|
698 |
+
self.write_element(arr)
|
699 |
+
|
700 |
+
def write_char(self, arr, codec='ascii'):
|
701 |
+
''' Write string array `arr` with given `codec`
|
702 |
+
'''
|
703 |
+
if arr.size == 0 or np.all(arr == ''):
|
704 |
+
# This an empty string array or a string array containing
|
705 |
+
# only empty strings. Matlab cannot distinguish between a
|
706 |
+
# string array that is empty, and a string array containing
|
707 |
+
# only empty strings, because it stores strings as arrays of
|
708 |
+
# char. There is no way of having an array of char that is
|
709 |
+
# not empty, but contains an empty string. We have to
|
710 |
+
# special-case the array-with-empty-strings because even
|
711 |
+
# empty strings have zero padding, which would otherwise
|
712 |
+
# appear in matlab as a string with a space.
|
713 |
+
shape = (0,) * np.max([arr.ndim, 2])
|
714 |
+
self.write_header(shape, mxCHAR_CLASS)
|
715 |
+
self.write_smalldata_element(arr, miUTF8, 0)
|
716 |
+
return
|
717 |
+
# non-empty string.
|
718 |
+
#
|
719 |
+
# Convert to char array
|
720 |
+
arr = arr_to_chars(arr)
|
721 |
+
# We have to write the shape directly, because we are going
|
722 |
+
# recode the characters, and the resulting stream of chars
|
723 |
+
# may have a different length
|
724 |
+
shape = arr.shape
|
725 |
+
self.write_header(shape, mxCHAR_CLASS)
|
726 |
+
if arr.dtype.kind == 'U' and arr.size:
|
727 |
+
# Make one long string from all the characters. We need to
|
728 |
+
# transpose here, because we're flattening the array, before
|
729 |
+
# we write the bytes. The bytes have to be written in
|
730 |
+
# Fortran order.
|
731 |
+
n_chars = np.prod(shape)
|
732 |
+
st_arr = np.ndarray(shape=(),
|
733 |
+
dtype=arr_dtype_number(arr, n_chars),
|
734 |
+
buffer=arr.T.copy()) # Fortran order
|
735 |
+
# Recode with codec to give byte string
|
736 |
+
st = st_arr.item().encode(codec)
|
737 |
+
# Reconstruct as 1-D byte array
|
738 |
+
arr = np.ndarray(shape=(len(st),),
|
739 |
+
dtype='S1',
|
740 |
+
buffer=st)
|
741 |
+
self.write_element(arr, mdtype=miUTF8)
|
742 |
+
|
743 |
+
def write_sparse(self, arr):
|
744 |
+
''' Sparse matrices are 2D
|
745 |
+
'''
|
746 |
+
A = arr.tocsc() # convert to sparse CSC format
|
747 |
+
A.sort_indices() # MATLAB expects sorted row indices
|
748 |
+
is_complex = (A.dtype.kind == 'c')
|
749 |
+
is_logical = (A.dtype.kind == 'b')
|
750 |
+
nz = A.nnz
|
751 |
+
self.write_header(matdims(arr, self.oned_as),
|
752 |
+
mxSPARSE_CLASS,
|
753 |
+
is_complex=is_complex,
|
754 |
+
is_logical=is_logical,
|
755 |
+
# matlab won't load file with 0 nzmax
|
756 |
+
nzmax=1 if nz == 0 else nz)
|
757 |
+
self.write_element(A.indices.astype('i4'))
|
758 |
+
self.write_element(A.indptr.astype('i4'))
|
759 |
+
self.write_element(A.data.real)
|
760 |
+
if is_complex:
|
761 |
+
self.write_element(A.data.imag)
|
762 |
+
|
763 |
+
def write_cells(self, arr):
|
764 |
+
self.write_header(matdims(arr, self.oned_as),
|
765 |
+
mxCELL_CLASS)
|
766 |
+
# loop over data, column major
|
767 |
+
A = np.atleast_2d(arr).flatten('F')
|
768 |
+
for el in A:
|
769 |
+
self.write(el)
|
770 |
+
|
771 |
+
def write_empty_struct(self):
|
772 |
+
self.write_header((1, 1), mxSTRUCT_CLASS)
|
773 |
+
# max field name length set to 1 in an example matlab struct
|
774 |
+
self.write_element(np.array(1, dtype=np.int32))
|
775 |
+
# Field names element is empty
|
776 |
+
self.write_element(np.array([], dtype=np.int8))
|
777 |
+
|
778 |
+
def write_struct(self, arr):
|
779 |
+
self.write_header(matdims(arr, self.oned_as),
|
780 |
+
mxSTRUCT_CLASS)
|
781 |
+
self._write_items(arr)
|
782 |
+
|
783 |
+
def _write_items(self, arr):
|
784 |
+
# write fieldnames
|
785 |
+
fieldnames = [f[0] for f in arr.dtype.descr]
|
786 |
+
length = max([len(fieldname) for fieldname in fieldnames])+1
|
787 |
+
max_length = (self.long_field_names and 64) or 32
|
788 |
+
if length > max_length:
|
789 |
+
raise ValueError("Field names are restricted to %d characters" %
|
790 |
+
(max_length-1))
|
791 |
+
self.write_element(np.array([length], dtype='i4'))
|
792 |
+
self.write_element(
|
793 |
+
np.array(fieldnames, dtype='S%d' % (length)),
|
794 |
+
mdtype=miINT8)
|
795 |
+
A = np.atleast_2d(arr).flatten('F')
|
796 |
+
for el in A:
|
797 |
+
for f in fieldnames:
|
798 |
+
self.write(el[f])
|
799 |
+
|
800 |
+
def write_object(self, arr):
|
801 |
+
'''Same as writing structs, except different mx class, and extra
|
802 |
+
classname element after header
|
803 |
+
'''
|
804 |
+
self.write_header(matdims(arr, self.oned_as),
|
805 |
+
mxOBJECT_CLASS)
|
806 |
+
self.write_element(np.array(arr.classname, dtype='S'),
|
807 |
+
mdtype=miINT8)
|
808 |
+
self._write_items(arr)
|
809 |
+
|
810 |
+
|
811 |
+
class MatFile5Writer:
|
812 |
+
''' Class for writing mat5 files '''
|
813 |
+
|
814 |
+
@docfiller
|
815 |
+
def __init__(self, file_stream,
|
816 |
+
do_compression=False,
|
817 |
+
unicode_strings=False,
|
818 |
+
global_vars=None,
|
819 |
+
long_field_names=False,
|
820 |
+
oned_as='row'):
|
821 |
+
''' Initialize writer for matlab 5 format files
|
822 |
+
|
823 |
+
Parameters
|
824 |
+
----------
|
825 |
+
%(do_compression)s
|
826 |
+
%(unicode_strings)s
|
827 |
+
global_vars : None or sequence of strings, optional
|
828 |
+
Names of variables to be marked as global for matlab
|
829 |
+
%(long_fields)s
|
830 |
+
%(oned_as)s
|
831 |
+
'''
|
832 |
+
self.file_stream = file_stream
|
833 |
+
self.do_compression = do_compression
|
834 |
+
self.unicode_strings = unicode_strings
|
835 |
+
if global_vars:
|
836 |
+
self.global_vars = global_vars
|
837 |
+
else:
|
838 |
+
self.global_vars = []
|
839 |
+
self.long_field_names = long_field_names
|
840 |
+
self.oned_as = oned_as
|
841 |
+
self._matrix_writer = None
|
842 |
+
|
843 |
+
def write_file_header(self):
|
844 |
+
# write header
|
845 |
+
hdr = np.zeros((), NDT_FILE_HDR)
|
846 |
+
hdr['description'] = (f'MATLAB 5.0 MAT-file Platform: {os.name}, '
|
847 |
+
f'Created on: {time.asctime()}')
|
848 |
+
hdr['version'] = 0x0100
|
849 |
+
hdr['endian_test'] = np.ndarray(shape=(),
|
850 |
+
dtype='S2',
|
851 |
+
buffer=np.uint16(0x4d49))
|
852 |
+
self.file_stream.write(hdr.tobytes())
|
853 |
+
|
854 |
+
def put_variables(self, mdict, write_header=None):
|
855 |
+
''' Write variables in `mdict` to stream
|
856 |
+
|
857 |
+
Parameters
|
858 |
+
----------
|
859 |
+
mdict : mapping
|
860 |
+
mapping with method ``items`` returns name, contents pairs where
|
861 |
+
``name`` which will appear in the matlab workspace in file load, and
|
862 |
+
``contents`` is something writeable to a matlab file, such as a NumPy
|
863 |
+
array.
|
864 |
+
write_header : {None, True, False}, optional
|
865 |
+
If True, then write the matlab file header before writing the
|
866 |
+
variables. If None (the default) then write the file header
|
867 |
+
if we are at position 0 in the stream. By setting False
|
868 |
+
here, and setting the stream position to the end of the file,
|
869 |
+
you can append variables to a matlab file
|
870 |
+
'''
|
871 |
+
# write header if requested, or None and start of file
|
872 |
+
if write_header is None:
|
873 |
+
write_header = self.file_stream.tell() == 0
|
874 |
+
if write_header:
|
875 |
+
self.write_file_header()
|
876 |
+
self._matrix_writer = VarWriter5(self)
|
877 |
+
for name, var in mdict.items():
|
878 |
+
if name[0] == '_':
|
879 |
+
continue
|
880 |
+
is_global = name in self.global_vars
|
881 |
+
if self.do_compression:
|
882 |
+
stream = BytesIO()
|
883 |
+
self._matrix_writer.file_stream = stream
|
884 |
+
self._matrix_writer.write_top(var, name.encode('latin1'), is_global)
|
885 |
+
out_str = zlib.compress(stream.getvalue())
|
886 |
+
tag = np.empty((), NDT_TAG_FULL)
|
887 |
+
tag['mdtype'] = miCOMPRESSED
|
888 |
+
tag['byte_count'] = len(out_str)
|
889 |
+
self.file_stream.write(tag.tobytes())
|
890 |
+
self.file_stream.write(out_str)
|
891 |
+
else: # not compressing
|
892 |
+
self._matrix_writer.write_top(var, name.encode('latin1'), is_global)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio5_params.py
ADDED
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
''' Constants and classes for matlab 5 read and write
|
2 |
+
|
3 |
+
See also mio5_utils.pyx where these same constants arise as c enums.
|
4 |
+
|
5 |
+
If you make changes in this file, don't forget to change mio5_utils.pyx
|
6 |
+
'''
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from ._miobase import convert_dtypes
|
10 |
+
|
11 |
+
|
12 |
+
__all__ = [
|
13 |
+
'MDTYPES', 'MatlabFunction', 'MatlabObject', 'MatlabOpaque',
|
14 |
+
'NP_TO_MTYPES', 'NP_TO_MXTYPES', 'OPAQUE_DTYPE', 'codecs_template',
|
15 |
+
'mat_struct', 'mclass_dtypes_template', 'mclass_info', 'mdtypes_template',
|
16 |
+
'miCOMPRESSED', 'miDOUBLE', 'miINT16', 'miINT32', 'miINT64', 'miINT8',
|
17 |
+
'miMATRIX', 'miSINGLE', 'miUINT16', 'miUINT32', 'miUINT64', 'miUINT8',
|
18 |
+
'miUTF16', 'miUTF32', 'miUTF8', 'mxCELL_CLASS', 'mxCHAR_CLASS',
|
19 |
+
'mxDOUBLE_CLASS', 'mxFUNCTION_CLASS', 'mxINT16_CLASS', 'mxINT32_CLASS',
|
20 |
+
'mxINT64_CLASS', 'mxINT8_CLASS', 'mxOBJECT_CLASS',
|
21 |
+
'mxOBJECT_CLASS_FROM_MATRIX_H', 'mxOPAQUE_CLASS', 'mxSINGLE_CLASS',
|
22 |
+
'mxSPARSE_CLASS', 'mxSTRUCT_CLASS', 'mxUINT16_CLASS', 'mxUINT32_CLASS',
|
23 |
+
'mxUINT64_CLASS', 'mxUINT8_CLASS'
|
24 |
+
]
|
25 |
+
miINT8 = 1
|
26 |
+
miUINT8 = 2
|
27 |
+
miINT16 = 3
|
28 |
+
miUINT16 = 4
|
29 |
+
miINT32 = 5
|
30 |
+
miUINT32 = 6
|
31 |
+
miSINGLE = 7
|
32 |
+
miDOUBLE = 9
|
33 |
+
miINT64 = 12
|
34 |
+
miUINT64 = 13
|
35 |
+
miMATRIX = 14
|
36 |
+
miCOMPRESSED = 15
|
37 |
+
miUTF8 = 16
|
38 |
+
miUTF16 = 17
|
39 |
+
miUTF32 = 18
|
40 |
+
|
41 |
+
mxCELL_CLASS = 1
|
42 |
+
mxSTRUCT_CLASS = 2
|
43 |
+
# The March 2008 edition of "Matlab 7 MAT-File Format" says that
|
44 |
+
# mxOBJECT_CLASS = 3, whereas matrix.h says that mxLOGICAL = 3.
|
45 |
+
# Matlab 2008a appears to save logicals as type 9, so we assume that
|
46 |
+
# the document is correct. See type 18, below.
|
47 |
+
mxOBJECT_CLASS = 3
|
48 |
+
mxCHAR_CLASS = 4
|
49 |
+
mxSPARSE_CLASS = 5
|
50 |
+
mxDOUBLE_CLASS = 6
|
51 |
+
mxSINGLE_CLASS = 7
|
52 |
+
mxINT8_CLASS = 8
|
53 |
+
mxUINT8_CLASS = 9
|
54 |
+
mxINT16_CLASS = 10
|
55 |
+
mxUINT16_CLASS = 11
|
56 |
+
mxINT32_CLASS = 12
|
57 |
+
mxUINT32_CLASS = 13
|
58 |
+
# The following are not in the March 2008 edition of "Matlab 7
|
59 |
+
# MAT-File Format," but were guessed from matrix.h.
|
60 |
+
mxINT64_CLASS = 14
|
61 |
+
mxUINT64_CLASS = 15
|
62 |
+
mxFUNCTION_CLASS = 16
|
63 |
+
# Not doing anything with these at the moment.
|
64 |
+
mxOPAQUE_CLASS = 17 # This appears to be a function workspace
|
65 |
+
# Thread 'saving/loading symbol table of annymous functions',
|
66 |
+
# octave-maintainers, April-May 2007
|
67 |
+
# https://lists.gnu.org/archive/html/octave-maintainers/2007-04/msg00031.html
|
68 |
+
# https://lists.gnu.org/archive/html/octave-maintainers/2007-05/msg00032.html
|
69 |
+
# (Was/Deprecated: https://www-old.cae.wisc.edu/pipermail/octave-maintainers/2007-May/002824.html)
|
70 |
+
mxOBJECT_CLASS_FROM_MATRIX_H = 18
|
71 |
+
|
72 |
+
mdtypes_template = {
|
73 |
+
miINT8: 'i1',
|
74 |
+
miUINT8: 'u1',
|
75 |
+
miINT16: 'i2',
|
76 |
+
miUINT16: 'u2',
|
77 |
+
miINT32: 'i4',
|
78 |
+
miUINT32: 'u4',
|
79 |
+
miSINGLE: 'f4',
|
80 |
+
miDOUBLE: 'f8',
|
81 |
+
miINT64: 'i8',
|
82 |
+
miUINT64: 'u8',
|
83 |
+
miUTF8: 'u1',
|
84 |
+
miUTF16: 'u2',
|
85 |
+
miUTF32: 'u4',
|
86 |
+
'file_header': [('description', 'S116'),
|
87 |
+
('subsystem_offset', 'i8'),
|
88 |
+
('version', 'u2'),
|
89 |
+
('endian_test', 'S2')],
|
90 |
+
'tag_full': [('mdtype', 'u4'), ('byte_count', 'u4')],
|
91 |
+
'tag_smalldata':[('byte_count_mdtype', 'u4'), ('data', 'S4')],
|
92 |
+
'array_flags': [('data_type', 'u4'),
|
93 |
+
('byte_count', 'u4'),
|
94 |
+
('flags_class','u4'),
|
95 |
+
('nzmax', 'u4')],
|
96 |
+
'U1': 'U1',
|
97 |
+
}
|
98 |
+
|
99 |
+
mclass_dtypes_template = {
|
100 |
+
mxINT8_CLASS: 'i1',
|
101 |
+
mxUINT8_CLASS: 'u1',
|
102 |
+
mxINT16_CLASS: 'i2',
|
103 |
+
mxUINT16_CLASS: 'u2',
|
104 |
+
mxINT32_CLASS: 'i4',
|
105 |
+
mxUINT32_CLASS: 'u4',
|
106 |
+
mxINT64_CLASS: 'i8',
|
107 |
+
mxUINT64_CLASS: 'u8',
|
108 |
+
mxSINGLE_CLASS: 'f4',
|
109 |
+
mxDOUBLE_CLASS: 'f8',
|
110 |
+
}
|
111 |
+
|
112 |
+
mclass_info = {
|
113 |
+
mxINT8_CLASS: 'int8',
|
114 |
+
mxUINT8_CLASS: 'uint8',
|
115 |
+
mxINT16_CLASS: 'int16',
|
116 |
+
mxUINT16_CLASS: 'uint16',
|
117 |
+
mxINT32_CLASS: 'int32',
|
118 |
+
mxUINT32_CLASS: 'uint32',
|
119 |
+
mxINT64_CLASS: 'int64',
|
120 |
+
mxUINT64_CLASS: 'uint64',
|
121 |
+
mxSINGLE_CLASS: 'single',
|
122 |
+
mxDOUBLE_CLASS: 'double',
|
123 |
+
mxCELL_CLASS: 'cell',
|
124 |
+
mxSTRUCT_CLASS: 'struct',
|
125 |
+
mxOBJECT_CLASS: 'object',
|
126 |
+
mxCHAR_CLASS: 'char',
|
127 |
+
mxSPARSE_CLASS: 'sparse',
|
128 |
+
mxFUNCTION_CLASS: 'function',
|
129 |
+
mxOPAQUE_CLASS: 'opaque',
|
130 |
+
}
|
131 |
+
|
132 |
+
NP_TO_MTYPES = {
|
133 |
+
'f8': miDOUBLE,
|
134 |
+
'c32': miDOUBLE,
|
135 |
+
'c24': miDOUBLE,
|
136 |
+
'c16': miDOUBLE,
|
137 |
+
'f4': miSINGLE,
|
138 |
+
'c8': miSINGLE,
|
139 |
+
'i8': miINT64,
|
140 |
+
'i4': miINT32,
|
141 |
+
'i2': miINT16,
|
142 |
+
'i1': miINT8,
|
143 |
+
'u8': miUINT64,
|
144 |
+
'u4': miUINT32,
|
145 |
+
'u2': miUINT16,
|
146 |
+
'u1': miUINT8,
|
147 |
+
'S1': miUINT8,
|
148 |
+
'U1': miUTF16,
|
149 |
+
'b1': miUINT8, # not standard but seems MATLAB uses this (gh-4022)
|
150 |
+
}
|
151 |
+
|
152 |
+
|
153 |
+
NP_TO_MXTYPES = {
|
154 |
+
'f8': mxDOUBLE_CLASS,
|
155 |
+
'c32': mxDOUBLE_CLASS,
|
156 |
+
'c24': mxDOUBLE_CLASS,
|
157 |
+
'c16': mxDOUBLE_CLASS,
|
158 |
+
'f4': mxSINGLE_CLASS,
|
159 |
+
'c8': mxSINGLE_CLASS,
|
160 |
+
'i8': mxINT64_CLASS,
|
161 |
+
'i4': mxINT32_CLASS,
|
162 |
+
'i2': mxINT16_CLASS,
|
163 |
+
'i1': mxINT8_CLASS,
|
164 |
+
'u8': mxUINT64_CLASS,
|
165 |
+
'u4': mxUINT32_CLASS,
|
166 |
+
'u2': mxUINT16_CLASS,
|
167 |
+
'u1': mxUINT8_CLASS,
|
168 |
+
'S1': mxUINT8_CLASS,
|
169 |
+
'b1': mxUINT8_CLASS, # not standard but seems MATLAB uses this
|
170 |
+
}
|
171 |
+
|
172 |
+
''' Before release v7.1 (release 14) matlab (TM) used the system
|
173 |
+
default character encoding scheme padded out to 16-bits. Release 14
|
174 |
+
and later use Unicode. When saving character data, R14 checks if it
|
175 |
+
can be encoded in 7-bit ascii, and saves in that format if so.'''
|
176 |
+
|
177 |
+
codecs_template = {
|
178 |
+
miUTF8: {'codec': 'utf_8', 'width': 1},
|
179 |
+
miUTF16: {'codec': 'utf_16', 'width': 2},
|
180 |
+
miUTF32: {'codec': 'utf_32','width': 4},
|
181 |
+
}
|
182 |
+
|
183 |
+
|
184 |
+
def _convert_codecs(template, byte_order):
|
185 |
+
''' Convert codec template mapping to byte order
|
186 |
+
|
187 |
+
Set codecs not on this system to None
|
188 |
+
|
189 |
+
Parameters
|
190 |
+
----------
|
191 |
+
template : mapping
|
192 |
+
key, value are respectively codec name, and root name for codec
|
193 |
+
(without byte order suffix)
|
194 |
+
byte_order : {'<', '>'}
|
195 |
+
code for little or big endian
|
196 |
+
|
197 |
+
Returns
|
198 |
+
-------
|
199 |
+
codecs : dict
|
200 |
+
key, value are name, codec (as in .encode(codec))
|
201 |
+
'''
|
202 |
+
codecs = {}
|
203 |
+
postfix = byte_order == '<' and '_le' or '_be'
|
204 |
+
for k, v in template.items():
|
205 |
+
codec = v['codec']
|
206 |
+
try:
|
207 |
+
" ".encode(codec)
|
208 |
+
except LookupError:
|
209 |
+
codecs[k] = None
|
210 |
+
continue
|
211 |
+
if v['width'] > 1:
|
212 |
+
codec += postfix
|
213 |
+
codecs[k] = codec
|
214 |
+
return codecs.copy()
|
215 |
+
|
216 |
+
|
217 |
+
MDTYPES = {}
|
218 |
+
for _bytecode in '<>':
|
219 |
+
_def = {'dtypes': convert_dtypes(mdtypes_template, _bytecode),
|
220 |
+
'classes': convert_dtypes(mclass_dtypes_template, _bytecode),
|
221 |
+
'codecs': _convert_codecs(codecs_template, _bytecode)}
|
222 |
+
MDTYPES[_bytecode] = _def
|
223 |
+
|
224 |
+
|
225 |
+
class mat_struct:
|
226 |
+
"""Placeholder for holding read data from structs.
|
227 |
+
|
228 |
+
We use instances of this class when the user passes False as a value to the
|
229 |
+
``struct_as_record`` parameter of the :func:`scipy.io.loadmat` function.
|
230 |
+
"""
|
231 |
+
pass
|
232 |
+
|
233 |
+
|
234 |
+
class MatlabObject(np.ndarray):
|
235 |
+
"""Subclass of ndarray to signal this is a matlab object.
|
236 |
+
|
237 |
+
This is a simple subclass of :class:`numpy.ndarray` meant to be used
|
238 |
+
by :func:`scipy.io.loadmat` and should not be instantiated directly.
|
239 |
+
"""
|
240 |
+
|
241 |
+
def __new__(cls, input_array, classname=None):
|
242 |
+
# Input array is an already formed ndarray instance
|
243 |
+
# We first cast to be our class type
|
244 |
+
obj = np.asarray(input_array).view(cls)
|
245 |
+
# add the new attribute to the created instance
|
246 |
+
obj.classname = classname
|
247 |
+
# Finally, we must return the newly created object:
|
248 |
+
return obj
|
249 |
+
|
250 |
+
def __array_finalize__(self,obj):
|
251 |
+
# reset the attribute from passed original object
|
252 |
+
self.classname = getattr(obj, 'classname', None)
|
253 |
+
# We do not need to return anything
|
254 |
+
|
255 |
+
|
256 |
+
class MatlabFunction(np.ndarray):
|
257 |
+
"""Subclass for a MATLAB function.
|
258 |
+
|
259 |
+
This is a simple subclass of :class:`numpy.ndarray` meant to be used
|
260 |
+
by :func:`scipy.io.loadmat` and should not be directly instantiated.
|
261 |
+
"""
|
262 |
+
|
263 |
+
def __new__(cls, input_array):
|
264 |
+
obj = np.asarray(input_array).view(cls)
|
265 |
+
return obj
|
266 |
+
|
267 |
+
|
268 |
+
class MatlabOpaque(np.ndarray):
|
269 |
+
"""Subclass for a MATLAB opaque matrix.
|
270 |
+
|
271 |
+
This is a simple subclass of :class:`numpy.ndarray` meant to be used
|
272 |
+
by :func:`scipy.io.loadmat` and should not be directly instantiated.
|
273 |
+
"""
|
274 |
+
|
275 |
+
def __new__(cls, input_array):
|
276 |
+
obj = np.asarray(input_array).view(cls)
|
277 |
+
return obj
|
278 |
+
|
279 |
+
|
280 |
+
OPAQUE_DTYPE = np.dtype(
|
281 |
+
[('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')])
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio5_utils.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (265 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_mio_utils.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (73.3 kB). View file
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Authors: Travis Oliphant, Matthew Brett
|
2 |
+
|
3 |
+
"""
|
4 |
+
Base classes for MATLAB file stream reading.
|
5 |
+
|
6 |
+
MATLAB is a registered trademark of the Mathworks inc.
|
7 |
+
"""
|
8 |
+
|
9 |
+
import numpy as np
|
10 |
+
from scipy._lib import doccer
|
11 |
+
|
12 |
+
from . import _byteordercodes as boc
|
13 |
+
|
14 |
+
__all__ = [
|
15 |
+
'MatFileReader', 'MatReadError', 'MatReadWarning',
|
16 |
+
'MatVarReader', 'MatWriteError', 'arr_dtype_number',
|
17 |
+
'arr_to_chars', 'convert_dtypes', 'doc_dict',
|
18 |
+
'docfiller', 'get_matfile_version',
|
19 |
+
'matdims', 'read_dtype'
|
20 |
+
]
|
21 |
+
|
22 |
+
class MatReadError(Exception):
|
23 |
+
"""Exception indicating a read issue."""
|
24 |
+
|
25 |
+
|
26 |
+
class MatWriteError(Exception):
|
27 |
+
"""Exception indicating a write issue."""
|
28 |
+
|
29 |
+
|
30 |
+
class MatReadWarning(UserWarning):
|
31 |
+
"""Warning class for read issues."""
|
32 |
+
|
33 |
+
|
34 |
+
doc_dict = \
|
35 |
+
{'file_arg':
|
36 |
+
'''file_name : str
|
37 |
+
Name of the mat file (do not need .mat extension if
|
38 |
+
appendmat==True) Can also pass open file-like object.''',
|
39 |
+
'append_arg':
|
40 |
+
'''appendmat : bool, optional
|
41 |
+
True to append the .mat extension to the end of the given
|
42 |
+
filename, if not already present. Default is True.''',
|
43 |
+
'load_args':
|
44 |
+
'''byte_order : str or None, optional
|
45 |
+
None by default, implying byte order guessed from mat
|
46 |
+
file. Otherwise can be one of ('native', '=', 'little', '<',
|
47 |
+
'BIG', '>').
|
48 |
+
mat_dtype : bool, optional
|
49 |
+
If True, return arrays in same dtype as would be loaded into
|
50 |
+
MATLAB (instead of the dtype with which they are saved).
|
51 |
+
squeeze_me : bool, optional
|
52 |
+
Whether to squeeze unit matrix dimensions or not.
|
53 |
+
chars_as_strings : bool, optional
|
54 |
+
Whether to convert char arrays to string arrays.
|
55 |
+
matlab_compatible : bool, optional
|
56 |
+
Returns matrices as would be loaded by MATLAB (implies
|
57 |
+
squeeze_me=False, chars_as_strings=False, mat_dtype=True,
|
58 |
+
struct_as_record=True).''',
|
59 |
+
'struct_arg':
|
60 |
+
'''struct_as_record : bool, optional
|
61 |
+
Whether to load MATLAB structs as NumPy record arrays, or as
|
62 |
+
old-style NumPy arrays with dtype=object. Setting this flag to
|
63 |
+
False replicates the behavior of SciPy version 0.7.x (returning
|
64 |
+
numpy object arrays). The default setting is True, because it
|
65 |
+
allows easier round-trip load and save of MATLAB files.''',
|
66 |
+
'matstream_arg':
|
67 |
+
'''mat_stream : file-like
|
68 |
+
Object with file API, open for reading.''',
|
69 |
+
'long_fields':
|
70 |
+
'''long_field_names : bool, optional
|
71 |
+
* False - maximum field name length in a structure is 31 characters
|
72 |
+
which is the documented maximum length. This is the default.
|
73 |
+
* True - maximum field name length in a structure is 63 characters
|
74 |
+
which works for MATLAB 7.6''',
|
75 |
+
'do_compression':
|
76 |
+
'''do_compression : bool, optional
|
77 |
+
Whether to compress matrices on write. Default is False.''',
|
78 |
+
'oned_as':
|
79 |
+
'''oned_as : {'row', 'column'}, optional
|
80 |
+
If 'column', write 1-D NumPy arrays as column vectors.
|
81 |
+
If 'row', write 1D NumPy arrays as row vectors.''',
|
82 |
+
'unicode_strings':
|
83 |
+
'''unicode_strings : bool, optional
|
84 |
+
If True, write strings as Unicode, else MATLAB usual encoding.'''}
|
85 |
+
|
86 |
+
docfiller = doccer.filldoc(doc_dict)
|
87 |
+
|
88 |
+
'''
|
89 |
+
|
90 |
+
Note on architecture
|
91 |
+
======================
|
92 |
+
|
93 |
+
There are three sets of parameters relevant for reading files. The
|
94 |
+
first are *file read parameters* - containing options that are common
|
95 |
+
for reading the whole file, and therefore every variable within that
|
96 |
+
file. At the moment these are:
|
97 |
+
|
98 |
+
* mat_stream
|
99 |
+
* dtypes (derived from byte code)
|
100 |
+
* byte_order
|
101 |
+
* chars_as_strings
|
102 |
+
* squeeze_me
|
103 |
+
* struct_as_record (MATLAB 5 files)
|
104 |
+
* class_dtypes (derived from order code, MATLAB 5 files)
|
105 |
+
* codecs (MATLAB 5 files)
|
106 |
+
* uint16_codec (MATLAB 5 files)
|
107 |
+
|
108 |
+
Another set of parameters are those that apply only to the current
|
109 |
+
variable being read - the *header*:
|
110 |
+
|
111 |
+
* header related variables (different for v4 and v5 mat files)
|
112 |
+
* is_complex
|
113 |
+
* mclass
|
114 |
+
* var_stream
|
115 |
+
|
116 |
+
With the header, we need ``next_position`` to tell us where the next
|
117 |
+
variable in the stream is.
|
118 |
+
|
119 |
+
Then, for each element in a matrix, there can be *element read
|
120 |
+
parameters*. An element is, for example, one element in a MATLAB cell
|
121 |
+
array. At the moment, these are:
|
122 |
+
|
123 |
+
* mat_dtype
|
124 |
+
|
125 |
+
The file-reading object contains the *file read parameters*. The
|
126 |
+
*header* is passed around as a data object, or may be read and discarded
|
127 |
+
in a single function. The *element read parameters* - the mat_dtype in
|
128 |
+
this instance, is passed into a general post-processing function - see
|
129 |
+
``mio_utils`` for details.
|
130 |
+
'''
|
131 |
+
|
132 |
+
|
133 |
+
def convert_dtypes(dtype_template, order_code):
|
134 |
+
''' Convert dtypes in mapping to given order
|
135 |
+
|
136 |
+
Parameters
|
137 |
+
----------
|
138 |
+
dtype_template : mapping
|
139 |
+
mapping with values returning numpy dtype from ``np.dtype(val)``
|
140 |
+
order_code : str
|
141 |
+
an order code suitable for using in ``dtype.newbyteorder()``
|
142 |
+
|
143 |
+
Returns
|
144 |
+
-------
|
145 |
+
dtypes : mapping
|
146 |
+
mapping where values have been replaced by
|
147 |
+
``np.dtype(val).newbyteorder(order_code)``
|
148 |
+
|
149 |
+
'''
|
150 |
+
dtypes = dtype_template.copy()
|
151 |
+
for k in dtypes:
|
152 |
+
dtypes[k] = np.dtype(dtypes[k]).newbyteorder(order_code)
|
153 |
+
return dtypes
|
154 |
+
|
155 |
+
|
156 |
+
def read_dtype(mat_stream, a_dtype):
|
157 |
+
"""
|
158 |
+
Generic get of byte stream data of known type
|
159 |
+
|
160 |
+
Parameters
|
161 |
+
----------
|
162 |
+
mat_stream : file_like object
|
163 |
+
MATLAB (tm) mat file stream
|
164 |
+
a_dtype : dtype
|
165 |
+
dtype of array to read. `a_dtype` is assumed to be correct
|
166 |
+
endianness.
|
167 |
+
|
168 |
+
Returns
|
169 |
+
-------
|
170 |
+
arr : ndarray
|
171 |
+
Array of dtype `a_dtype` read from stream.
|
172 |
+
|
173 |
+
"""
|
174 |
+
num_bytes = a_dtype.itemsize
|
175 |
+
arr = np.ndarray(shape=(),
|
176 |
+
dtype=a_dtype,
|
177 |
+
buffer=mat_stream.read(num_bytes),
|
178 |
+
order='F')
|
179 |
+
return arr
|
180 |
+
|
181 |
+
|
182 |
+
def matfile_version(file_name, *, appendmat=True):
|
183 |
+
"""
|
184 |
+
Return major, minor tuple depending on apparent mat file type
|
185 |
+
|
186 |
+
Where:
|
187 |
+
|
188 |
+
#. 0,x -> version 4 format mat files
|
189 |
+
#. 1,x -> version 5 format mat files
|
190 |
+
#. 2,x -> version 7.3 format mat files (HDF format)
|
191 |
+
|
192 |
+
Parameters
|
193 |
+
----------
|
194 |
+
file_name : str
|
195 |
+
Name of the mat file (do not need .mat extension if
|
196 |
+
appendmat==True). Can also pass open file-like object.
|
197 |
+
appendmat : bool, optional
|
198 |
+
True to append the .mat extension to the end of the given
|
199 |
+
filename, if not already present. Default is True.
|
200 |
+
|
201 |
+
Returns
|
202 |
+
-------
|
203 |
+
major_version : {0, 1, 2}
|
204 |
+
major MATLAB File format version
|
205 |
+
minor_version : int
|
206 |
+
minor MATLAB file format version
|
207 |
+
|
208 |
+
Raises
|
209 |
+
------
|
210 |
+
MatReadError
|
211 |
+
If the file is empty.
|
212 |
+
ValueError
|
213 |
+
The matfile version is unknown.
|
214 |
+
|
215 |
+
Notes
|
216 |
+
-----
|
217 |
+
Has the side effect of setting the file read pointer to 0
|
218 |
+
"""
|
219 |
+
from ._mio import _open_file_context
|
220 |
+
with _open_file_context(file_name, appendmat=appendmat) as fileobj:
|
221 |
+
return _get_matfile_version(fileobj)
|
222 |
+
|
223 |
+
|
224 |
+
get_matfile_version = matfile_version
|
225 |
+
|
226 |
+
|
227 |
+
def _get_matfile_version(fileobj):
|
228 |
+
# Mat4 files have a zero somewhere in first 4 bytes
|
229 |
+
fileobj.seek(0)
|
230 |
+
mopt_bytes = fileobj.read(4)
|
231 |
+
if len(mopt_bytes) == 0:
|
232 |
+
raise MatReadError("Mat file appears to be empty")
|
233 |
+
mopt_ints = np.ndarray(shape=(4,), dtype=np.uint8, buffer=mopt_bytes)
|
234 |
+
if 0 in mopt_ints:
|
235 |
+
fileobj.seek(0)
|
236 |
+
return (0,0)
|
237 |
+
# For 5 format or 7.3 format we need to read an integer in the
|
238 |
+
# header. Bytes 124 through 128 contain a version integer and an
|
239 |
+
# endian test string
|
240 |
+
fileobj.seek(124)
|
241 |
+
tst_str = fileobj.read(4)
|
242 |
+
fileobj.seek(0)
|
243 |
+
maj_ind = int(tst_str[2] == b'I'[0])
|
244 |
+
maj_val = int(tst_str[maj_ind])
|
245 |
+
min_val = int(tst_str[1 - maj_ind])
|
246 |
+
ret = (maj_val, min_val)
|
247 |
+
if maj_val in (1, 2):
|
248 |
+
return ret
|
249 |
+
raise ValueError('Unknown mat file type, version {}, {}'.format(*ret))
|
250 |
+
|
251 |
+
|
252 |
+
def matdims(arr, oned_as='column'):
|
253 |
+
"""
|
254 |
+
Determine equivalent MATLAB dimensions for given array
|
255 |
+
|
256 |
+
Parameters
|
257 |
+
----------
|
258 |
+
arr : ndarray
|
259 |
+
Input array
|
260 |
+
oned_as : {'column', 'row'}, optional
|
261 |
+
Whether 1-D arrays are returned as MATLAB row or column matrices.
|
262 |
+
Default is 'column'.
|
263 |
+
|
264 |
+
Returns
|
265 |
+
-------
|
266 |
+
dims : tuple
|
267 |
+
Shape tuple, in the form MATLAB expects it.
|
268 |
+
|
269 |
+
Notes
|
270 |
+
-----
|
271 |
+
We had to decide what shape a 1 dimensional array would be by
|
272 |
+
default. ``np.atleast_2d`` thinks it is a row vector. The
|
273 |
+
default for a vector in MATLAB (e.g., ``>> 1:12``) is a row vector.
|
274 |
+
|
275 |
+
Versions of scipy up to and including 0.11 resulted (accidentally)
|
276 |
+
in 1-D arrays being read as column vectors. For the moment, we
|
277 |
+
maintain the same tradition here.
|
278 |
+
|
279 |
+
Examples
|
280 |
+
--------
|
281 |
+
>>> import numpy as np
|
282 |
+
>>> from scipy.io.matlab._miobase import matdims
|
283 |
+
>>> matdims(np.array(1)) # NumPy scalar
|
284 |
+
(1, 1)
|
285 |
+
>>> matdims(np.array([1])) # 1-D array, 1 element
|
286 |
+
(1, 1)
|
287 |
+
>>> matdims(np.array([1,2])) # 1-D array, 2 elements
|
288 |
+
(2, 1)
|
289 |
+
>>> matdims(np.array([[2],[3]])) # 2-D array, column vector
|
290 |
+
(2, 1)
|
291 |
+
>>> matdims(np.array([[2,3]])) # 2-D array, row vector
|
292 |
+
(1, 2)
|
293 |
+
>>> matdims(np.array([[[2,3]]])) # 3-D array, rowish vector
|
294 |
+
(1, 1, 2)
|
295 |
+
>>> matdims(np.array([])) # empty 1-D array
|
296 |
+
(0, 0)
|
297 |
+
>>> matdims(np.array([[]])) # empty 2-D array
|
298 |
+
(0, 0)
|
299 |
+
>>> matdims(np.array([[[]]])) # empty 3-D array
|
300 |
+
(0, 0, 0)
|
301 |
+
|
302 |
+
Optional argument flips 1-D shape behavior.
|
303 |
+
|
304 |
+
>>> matdims(np.array([1,2]), 'row') # 1-D array, 2 elements
|
305 |
+
(1, 2)
|
306 |
+
|
307 |
+
The argument has to make sense though
|
308 |
+
|
309 |
+
>>> matdims(np.array([1,2]), 'bizarre')
|
310 |
+
Traceback (most recent call last):
|
311 |
+
...
|
312 |
+
ValueError: 1-D option "bizarre" is strange
|
313 |
+
|
314 |
+
"""
|
315 |
+
shape = arr.shape
|
316 |
+
if shape == (): # scalar
|
317 |
+
return (1, 1)
|
318 |
+
if len(shape) == 1: # 1D
|
319 |
+
if shape[0] == 0:
|
320 |
+
return (0, 0)
|
321 |
+
elif oned_as == 'column':
|
322 |
+
return shape + (1,)
|
323 |
+
elif oned_as == 'row':
|
324 |
+
return (1,) + shape
|
325 |
+
else:
|
326 |
+
raise ValueError('1-D option "%s" is strange'
|
327 |
+
% oned_as)
|
328 |
+
return shape
|
329 |
+
|
330 |
+
|
331 |
+
class MatVarReader:
|
332 |
+
''' Abstract class defining required interface for var readers'''
|
333 |
+
def __init__(self, file_reader):
|
334 |
+
pass
|
335 |
+
|
336 |
+
def read_header(self):
|
337 |
+
''' Returns header '''
|
338 |
+
pass
|
339 |
+
|
340 |
+
def array_from_header(self, header):
|
341 |
+
''' Reads array given header '''
|
342 |
+
pass
|
343 |
+
|
344 |
+
|
345 |
+
class MatFileReader:
|
346 |
+
""" Base object for reading mat files
|
347 |
+
|
348 |
+
To make this class functional, you will need to override the
|
349 |
+
following methods:
|
350 |
+
|
351 |
+
matrix_getter_factory - gives object to fetch next matrix from stream
|
352 |
+
guess_byte_order - guesses file byte order from file
|
353 |
+
"""
|
354 |
+
|
355 |
+
@docfiller
|
356 |
+
def __init__(self, mat_stream,
|
357 |
+
byte_order=None,
|
358 |
+
mat_dtype=False,
|
359 |
+
squeeze_me=False,
|
360 |
+
chars_as_strings=True,
|
361 |
+
matlab_compatible=False,
|
362 |
+
struct_as_record=True,
|
363 |
+
verify_compressed_data_integrity=True,
|
364 |
+
simplify_cells=False):
|
365 |
+
'''
|
366 |
+
Initializer for mat file reader
|
367 |
+
|
368 |
+
mat_stream : file-like
|
369 |
+
object with file API, open for reading
|
370 |
+
%(load_args)s
|
371 |
+
'''
|
372 |
+
# Initialize stream
|
373 |
+
self.mat_stream = mat_stream
|
374 |
+
self.dtypes = {}
|
375 |
+
if not byte_order:
|
376 |
+
byte_order = self.guess_byte_order()
|
377 |
+
else:
|
378 |
+
byte_order = boc.to_numpy_code(byte_order)
|
379 |
+
self.byte_order = byte_order
|
380 |
+
self.struct_as_record = struct_as_record
|
381 |
+
if matlab_compatible:
|
382 |
+
self.set_matlab_compatible()
|
383 |
+
else:
|
384 |
+
self.squeeze_me = squeeze_me
|
385 |
+
self.chars_as_strings = chars_as_strings
|
386 |
+
self.mat_dtype = mat_dtype
|
387 |
+
self.verify_compressed_data_integrity = verify_compressed_data_integrity
|
388 |
+
self.simplify_cells = simplify_cells
|
389 |
+
if simplify_cells:
|
390 |
+
self.squeeze_me = True
|
391 |
+
self.struct_as_record = False
|
392 |
+
|
393 |
+
def set_matlab_compatible(self):
|
394 |
+
''' Sets options to return arrays as MATLAB loads them '''
|
395 |
+
self.mat_dtype = True
|
396 |
+
self.squeeze_me = False
|
397 |
+
self.chars_as_strings = False
|
398 |
+
|
399 |
+
def guess_byte_order(self):
|
400 |
+
''' As we do not know what file type we have, assume native '''
|
401 |
+
return boc.native_code
|
402 |
+
|
403 |
+
def end_of_stream(self):
|
404 |
+
b = self.mat_stream.read(1)
|
405 |
+
curpos = self.mat_stream.tell()
|
406 |
+
self.mat_stream.seek(curpos-1)
|
407 |
+
return len(b) == 0
|
408 |
+
|
409 |
+
|
410 |
+
def arr_dtype_number(arr, num):
|
411 |
+
''' Return dtype for given number of items per element'''
|
412 |
+
return np.dtype(arr.dtype.str[:2] + str(num))
|
413 |
+
|
414 |
+
|
415 |
+
def arr_to_chars(arr):
|
416 |
+
''' Convert string array to char array '''
|
417 |
+
dims = list(arr.shape)
|
418 |
+
if not dims:
|
419 |
+
dims = [1]
|
420 |
+
dims.append(int(arr.dtype.str[2:]))
|
421 |
+
arr = np.ndarray(shape=dims,
|
422 |
+
dtype=arr_dtype_number(arr, 1),
|
423 |
+
buffer=arr)
|
424 |
+
empties = [arr == np.array('', dtype=arr.dtype)]
|
425 |
+
if not np.any(empties):
|
426 |
+
return arr
|
427 |
+
arr = arr.copy()
|
428 |
+
arr[tuple(empties)] = ' '
|
429 |
+
return arr
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/_streams.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (147 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.io.matlab` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
__all__ = [ # noqa: F822
|
8 |
+
'mat_reader_factory', 'loadmat', 'savemat', 'whosmat',
|
9 |
+
'contextmanager', 'docfiller',
|
10 |
+
'MatFile4Reader', 'MatFile4Writer', 'MatFile5Reader', 'MatFile5Writer'
|
11 |
+
]
|
12 |
+
|
13 |
+
def __dir__():
|
14 |
+
return __all__
|
15 |
+
|
16 |
+
|
17 |
+
def __getattr__(name):
|
18 |
+
return _sub_module_deprecation(sub_package="io.matlab", module="mio",
|
19 |
+
private_modules=["_mio"], all=__all__,
|
20 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio4.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.io.matlab` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
__all__ = [ # noqa: F822
|
8 |
+
'MatFile4Reader', 'MatFile4Writer', 'SYS_LITTLE_ENDIAN',
|
9 |
+
'VarHeader4', 'VarReader4', 'VarWriter4', 'arr_to_2d', 'mclass_info',
|
10 |
+
'mdtypes_template', 'miDOUBLE', 'miINT16', 'miINT32', 'miSINGLE',
|
11 |
+
'miUINT16', 'miUINT8', 'mxCHAR_CLASS', 'mxFULL_CLASS', 'mxSPARSE_CLASS',
|
12 |
+
'np_to_mtypes', 'order_codes', 'MatFileReader', 'docfiller',
|
13 |
+
'matdims', 'read_dtype', 'convert_dtypes', 'arr_to_chars',
|
14 |
+
'arr_dtype_number', 'squeeze_element', 'chars_to_strings'
|
15 |
+
]
|
16 |
+
|
17 |
+
def __dir__():
|
18 |
+
return __all__
|
19 |
+
|
20 |
+
|
21 |
+
def __getattr__(name):
|
22 |
+
return _sub_module_deprecation(sub_package="io.matlab", module="mio4",
|
23 |
+
private_modules=["_mio4"], all=__all__,
|
24 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio5.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.io.matlab` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
__all__ = [ # noqa: F822
|
8 |
+
'mclass_info', 'mxCHAR_CLASS', 'mxSPARSE_CLASS',
|
9 |
+
'BytesIO', 'native_code',
|
10 |
+
'swapped_code', 'MatFileReader', 'docfiller', 'matdims',
|
11 |
+
'read_dtype', 'arr_to_chars', 'arr_dtype_number', 'MatWriteError',
|
12 |
+
'MatReadError', 'MatReadWarning', 'VarReader5', 'MatlabObject',
|
13 |
+
'MatlabFunction', 'MDTYPES', 'NP_TO_MTYPES', 'NP_TO_MXTYPES',
|
14 |
+
'miCOMPRESSED', 'miMATRIX', 'miINT8', 'miUTF8', 'miUINT32',
|
15 |
+
'mxCELL_CLASS', 'mxSTRUCT_CLASS', 'mxOBJECT_CLASS', 'mxDOUBLE_CLASS',
|
16 |
+
'mat_struct', 'ZlibInputStream', 'MatFile5Reader', 'varmats_from_mat',
|
17 |
+
'EmptyStructMarker', 'to_writeable', 'NDT_FILE_HDR', 'NDT_TAG_FULL',
|
18 |
+
'NDT_TAG_SMALL', 'NDT_ARRAY_FLAGS', 'VarWriter5', 'MatFile5Writer'
|
19 |
+
]
|
20 |
+
|
21 |
+
def __dir__():
|
22 |
+
return __all__
|
23 |
+
|
24 |
+
|
25 |
+
def __getattr__(name):
|
26 |
+
return _sub_module_deprecation(sub_package="io.matlab", module="mio5",
|
27 |
+
private_modules=["_mio5"], all=__all__,
|
28 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio5_utils.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.io.matlab` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
__all__ = [ # noqa: F822
|
8 |
+
'VarHeader5', 'VarReader5', 'byteswap_u4', 'chars_to_strings',
|
9 |
+
'csc_matrix', 'mio5p', 'pycopy', 'swapped_code', 'squeeze_element'
|
10 |
+
]
|
11 |
+
|
12 |
+
def __dir__():
|
13 |
+
return __all__
|
14 |
+
|
15 |
+
|
16 |
+
def __getattr__(name):
|
17 |
+
return _sub_module_deprecation(sub_package="io.matlab", module="mio5_utils",
|
18 |
+
private_modules=["_mio5_utils"], all=__all__,
|
19 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/mio_utils.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.io.matlab` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
__all__ = ['squeeze_element', 'chars_to_strings'] # noqa: F822
|
8 |
+
|
9 |
+
|
10 |
+
def __dir__():
|
11 |
+
return __all__
|
12 |
+
|
13 |
+
|
14 |
+
def __getattr__(name):
|
15 |
+
return _sub_module_deprecation(sub_package="io.matlab", module="mio_utils",
|
16 |
+
private_modules=["_mio_utils"], all=__all__,
|
17 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/miobase.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
2 |
+
# Use the `scipy.io.matlab` namespace for importing the functions
|
3 |
+
# included below.
|
4 |
+
|
5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
6 |
+
|
7 |
+
__all__ = [ # noqa: F822
|
8 |
+
'MatFileReader', 'MatReadError', 'MatReadWarning',
|
9 |
+
'MatVarReader', 'MatWriteError', 'arr_dtype_number',
|
10 |
+
'arr_to_chars', 'convert_dtypes', 'doc_dict',
|
11 |
+
'docfiller', 'get_matfile_version',
|
12 |
+
'matdims', 'read_dtype', 'doccer', 'boc'
|
13 |
+
]
|
14 |
+
|
15 |
+
def __dir__():
|
16 |
+
return __all__
|
17 |
+
|
18 |
+
|
19 |
+
def __getattr__(name):
|
20 |
+
return _sub_module_deprecation(sub_package="io.matlab", module="miobase",
|
21 |
+
private_modules=["_miobase"], all=__all__,
|
22 |
+
attribute=name)
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/bad_miuint32.mat
ADDED
Binary file (272 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/big_endian.mat
ADDED
Binary file (273 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/corrupted_zlib_data.mat
ADDED
Binary file (3.45 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/logical_sparse.mat
ADDED
Binary file (208 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/miuint32_for_miint32.mat
ADDED
Binary file (272 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/miutf8_array_name.mat
ADDED
Binary file (208 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/nasty_duplicate_fieldnames.mat
ADDED
Binary file (8.17 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/parabola.mat
ADDED
Binary file (729 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/some_functions.mat
ADDED
Binary file (1.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/test3dmatrix_7.4_GLNX86.mat
ADDED
Binary file (213 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/test_skip_variable.mat
ADDED
Binary file (20.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcell_6.1_SOL2.mat
ADDED
Binary file (536 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcellnest_6.1_SOL2.mat
ADDED
Binary file (568 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcellnest_6.5.1_GLNX86.mat
ADDED
Binary file (568 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/scipy/io/matlab/tests/data/testcellnest_7.1_GLNX86.mat
ADDED
Binary file (228 Bytes). View file
|
|