applied-ai-018 commited on
Commit
5c6dd28
·
verified ·
1 Parent(s): 953e096

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg.pt +3 -0
  4. ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg_sq.pt +3 -0
  5. ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg.pt +3 -0
  6. ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  7. ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt +3 -0
  8. venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/scipy/io/__init__.py +116 -0
  11. venv/lib/python3.10/site-packages/scipy/io/_fortran.py +354 -0
  12. venv/lib/python3.10/site-packages/scipy/io/_idl.py +918 -0
  13. venv/lib/python3.10/site-packages/scipy/io/_mmio.py +961 -0
  14. venv/lib/python3.10/site-packages/scipy/io/harwell_boeing.py +21 -0
  15. venv/lib/python3.10/site-packages/scipy/io/idl.py +20 -0
  16. venv/lib/python3.10/site-packages/scipy/io/mmio.py +20 -0
  17. venv/lib/python3.10/site-packages/scipy/io/netcdf.py +25 -0
  18. venv/lib/python3.10/site-packages/scipy/io/tests/__init__.py +0 -0
  19. venv/lib/python3.10/site-packages/scipy/io/tests/data/Transparent Busy.ani +0 -0
  20. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav +0 -0
  21. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_2d.sav +0 -0
  22. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav +0 -0
  23. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_4d.sav +0 -0
  24. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav +0 -0
  25. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_6d.sav +0 -0
  26. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_7d.sav +0 -0
  27. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_8d.sav +0 -0
  28. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav +0 -0
  29. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav +0 -0
  30. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav +0 -0
  31. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav +0 -0
  32. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav +0 -0
  33. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav +0 -0
  34. venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav +0 -0
  35. venv/lib/python3.10/site-packages/scipy/io/tests/data/example_1.nc +0 -0
  36. venv/lib/python3.10/site-packages/scipy/io/tests/data/example_2.nc +0 -0
  37. venv/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc +0 -0
  38. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat +0 -0
  39. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat +0 -0
  40. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat +0 -0
  41. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat +0 -0
  42. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat +0 -0
  43. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat +0 -0
  44. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat +0 -0
  45. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat +0 -0
  46. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat +0 -0
  47. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat +0 -0
  48. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat +0 -0
  49. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat +0 -0
  50. venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat +0 -0
ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f07b309d3553ae9fd5e99c2f44a80c2640179e14a747a7268f3a5df00621cdf2
3
+ size 9372
ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ff625f47bced33b98757679996399de33e2c91d05c1feeaf13de810ff2232de
3
+ size 9387
ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:646552e221ebc7421a53ada64f1d1505daabaf2b22ca4ef2d3a12d1e7c7e189c
3
+ size 16778396
ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f7af86e6739da6582dedcf651017239eaaa364ea9c2ed6578ba8004dcc17ae7
3
+ size 16778411
ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:686bbc5205bf3d92f059bc47acebe4bbe9050cb9fbea263b30603159e56445c6
3
+ size 9372
ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a142cc7046accc32efdc0ceb6409dca534088b765ff3d184c71620f5bd4874b9
3
+ size 9387
ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc09d9e918c81a8be10dd753e767177d5fdb658fe034c01c3205569aae720ad6
3
+ size 33555612
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (183 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ==================================
3
+ Input and output (:mod:`scipy.io`)
4
+ ==================================
5
+
6
+ .. currentmodule:: scipy.io
7
+
8
+ SciPy has many modules, classes, and functions available to read data
9
+ from and write data to a variety of file formats.
10
+
11
+ .. seealso:: `NumPy IO routines <https://www.numpy.org/devdocs/reference/routines.io.html>`__
12
+
13
+ MATLAB® files
14
+ =============
15
+
16
+ .. autosummary::
17
+ :toctree: generated/
18
+
19
+ loadmat - Read a MATLAB style mat file (version 4 through 7.1)
20
+ savemat - Write a MATLAB style mat file (version 4 through 7.1)
21
+ whosmat - List contents of a MATLAB style mat file (version 4 through 7.1)
22
+
23
+ For low-level MATLAB reading and writing utilities, see `scipy.io.matlab`.
24
+
25
+ IDL® files
26
+ ==========
27
+
28
+ .. autosummary::
29
+ :toctree: generated/
30
+
31
+ readsav - Read an IDL 'save' file
32
+
33
+ Matrix Market files
34
+ ===================
35
+
36
+ .. autosummary::
37
+ :toctree: generated/
38
+
39
+ mminfo - Query matrix info from Matrix Market formatted file
40
+ mmread - Read matrix from Matrix Market formatted file
41
+ mmwrite - Write matrix to Matrix Market formatted file
42
+
43
+ Unformatted Fortran files
44
+ ===============================
45
+
46
+ .. autosummary::
47
+ :toctree: generated/
48
+
49
+ FortranFile - A file object for unformatted sequential Fortran files
50
+ FortranEOFError - Exception indicating the end of a well-formed file
51
+ FortranFormattingError - Exception indicating an inappropriate end
52
+
53
+ Netcdf
54
+ ======
55
+
56
+ .. autosummary::
57
+ :toctree: generated/
58
+
59
+ netcdf_file - A file object for NetCDF data
60
+ netcdf_variable - A data object for the netcdf module
61
+
62
+ Harwell-Boeing files
63
+ ====================
64
+
65
+ .. autosummary::
66
+ :toctree: generated/
67
+
68
+ hb_read -- read H-B file
69
+ hb_write -- write H-B file
70
+
71
+ Wav sound files (:mod:`scipy.io.wavfile`)
72
+ =========================================
73
+
74
+ .. module:: scipy.io.wavfile
75
+
76
+ .. autosummary::
77
+ :toctree: generated/
78
+
79
+ read
80
+ write
81
+ WavFileWarning
82
+
83
+ Arff files (:mod:`scipy.io.arff`)
84
+ =================================
85
+
86
+ .. module:: scipy.io.arff
87
+
88
+ .. autosummary::
89
+ :toctree: generated/
90
+
91
+ loadarff
92
+ MetaData
93
+ ArffError
94
+ ParseArffError
95
+ """
96
+ # matfile read and write
97
+ from .matlab import loadmat, savemat, whosmat
98
+
99
+ # netCDF file support
100
+ from ._netcdf import netcdf_file, netcdf_variable
101
+
102
+ # Fortran file support
103
+ from ._fortran import FortranFile, FortranEOFError, FortranFormattingError
104
+
105
+ from ._fast_matrix_market import mminfo, mmread, mmwrite
106
+ from ._idl import readsav
107
+ from ._harwell_boeing import hb_read, hb_write
108
+
109
+ # Deprecated namespaces, to be removed in v2.0.0
110
+ from . import arff, harwell_boeing, idl, mmio, netcdf, wavfile
111
+
112
+ __all__ = [s for s in dir() if not s.startswith('_')]
113
+
114
+ from scipy._lib._testutils import PytestTester
115
+ test = PytestTester(__name__)
116
+ del PytestTester
venv/lib/python3.10/site-packages/scipy/io/_fortran.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module to read / write Fortran unformatted sequential files.
3
+
4
+ This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz.
5
+
6
+ """
7
+ import warnings
8
+ import numpy as np
9
+
10
+ __all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError']
11
+
12
+
13
+ class FortranEOFError(TypeError, OSError):
14
+ """Indicates that the file ended properly.
15
+
16
+ This error descends from TypeError because the code used to raise
17
+ TypeError (and this was the only way to know that the file had
18
+ ended) so users might have ``except TypeError:``.
19
+
20
+ """
21
+ pass
22
+
23
+
24
+ class FortranFormattingError(TypeError, OSError):
25
+ """Indicates that the file ended mid-record.
26
+
27
+ Descends from TypeError for backward compatibility.
28
+
29
+ """
30
+ pass
31
+
32
+
33
+ class FortranFile:
34
+ """
35
+ A file object for unformatted sequential files from Fortran code.
36
+
37
+ Parameters
38
+ ----------
39
+ filename : file or str
40
+ Open file object or filename.
41
+ mode : {'r', 'w'}, optional
42
+ Read-write mode, default is 'r'.
43
+ header_dtype : dtype, optional
44
+ Data type of the header. Size and endianness must match the input/output file.
45
+
46
+ Notes
47
+ -----
48
+ These files are broken up into records of unspecified types. The size of
49
+ each record is given at the start (although the size of this header is not
50
+ standard) and the data is written onto disk without any formatting. Fortran
51
+ compilers supporting the BACKSPACE statement will write a second copy of
52
+ the size to facilitate backwards seeking.
53
+
54
+ This class only supports files written with both sizes for the record.
55
+ It also does not support the subrecords used in Intel and gfortran compilers
56
+ for records which are greater than 2GB with a 4-byte header.
57
+
58
+ An example of an unformatted sequential file in Fortran would be written as::
59
+
60
+ OPEN(1, FILE=myfilename, FORM='unformatted')
61
+
62
+ WRITE(1) myvariable
63
+
64
+ Since this is a non-standard file format, whose contents depend on the
65
+ compiler and the endianness of the machine, caution is advised. Files from
66
+ gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.
67
+
68
+ Consider using Fortran direct-access files or files from the newer Stream
69
+ I/O, which can be easily read by `numpy.fromfile`.
70
+
71
+ Examples
72
+ --------
73
+ To create an unformatted sequential Fortran file:
74
+
75
+ >>> from scipy.io import FortranFile
76
+ >>> import numpy as np
77
+ >>> f = FortranFile('test.unf', 'w')
78
+ >>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
79
+ >>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
80
+ >>> f.close()
81
+
82
+ To read this file:
83
+
84
+ >>> f = FortranFile('test.unf', 'r')
85
+ >>> print(f.read_ints(np.int32))
86
+ [1 2 3 4 5]
87
+ >>> print(f.read_reals(float).reshape((5,4), order="F"))
88
+ [[0. 0.05263158 0.10526316 0.15789474]
89
+ [0.21052632 0.26315789 0.31578947 0.36842105]
90
+ [0.42105263 0.47368421 0.52631579 0.57894737]
91
+ [0.63157895 0.68421053 0.73684211 0.78947368]
92
+ [0.84210526 0.89473684 0.94736842 1. ]]
93
+ >>> f.close()
94
+
95
+ Or, in Fortran::
96
+
97
+ integer :: a(5), i
98
+ double precision :: b(5,4)
99
+ open(1, file='test.unf', form='unformatted')
100
+ read(1) a
101
+ read(1) b
102
+ close(1)
103
+ write(*,*) a
104
+ do i = 1, 5
105
+ write(*,*) b(i,:)
106
+ end do
107
+
108
+ """
109
+ def __init__(self, filename, mode='r', header_dtype=np.uint32):
110
+ if header_dtype is None:
111
+ raise ValueError('Must specify dtype')
112
+
113
+ header_dtype = np.dtype(header_dtype)
114
+ if header_dtype.kind != 'u':
115
+ warnings.warn("Given a dtype which is not unsigned.", stacklevel=2)
116
+
117
+ if mode not in 'rw' or len(mode) != 1:
118
+ raise ValueError('mode must be either r or w')
119
+
120
+ if hasattr(filename, 'seek'):
121
+ self._fp = filename
122
+ else:
123
+ self._fp = open(filename, '%sb' % mode)
124
+
125
+ self._header_dtype = header_dtype
126
+
127
+ def _read_size(self, eof_ok=False):
128
+ n = self._header_dtype.itemsize
129
+ b = self._fp.read(n)
130
+ if (not b) and eof_ok:
131
+ raise FortranEOFError("End of file occurred at end of record")
132
+ elif len(b) < n:
133
+ raise FortranFormattingError(
134
+ "End of file in the middle of the record size")
135
+ return int(np.frombuffer(b, dtype=self._header_dtype, count=1)[0])
136
+
137
+ def write_record(self, *items):
138
+ """
139
+ Write a record (including sizes) to the file.
140
+
141
+ Parameters
142
+ ----------
143
+ *items : array_like
144
+ The data arrays to write.
145
+
146
+ Notes
147
+ -----
148
+ Writes data items to a file::
149
+
150
+ write_record(a.T, b.T, c.T, ...)
151
+
152
+ write(1) a, b, c, ...
153
+
154
+ Note that data in multidimensional arrays is written in
155
+ row-major order --- to make them read correctly by Fortran
156
+ programs, you need to transpose the arrays yourself when
157
+ writing them.
158
+
159
+ """
160
+ items = tuple(np.asarray(item) for item in items)
161
+ total_size = sum(item.nbytes for item in items)
162
+
163
+ nb = np.array([total_size], dtype=self._header_dtype)
164
+
165
+ nb.tofile(self._fp)
166
+ for item in items:
167
+ item.tofile(self._fp)
168
+ nb.tofile(self._fp)
169
+
170
+ def read_record(self, *dtypes, **kwargs):
171
+ """
172
+ Reads a record of a given type from the file.
173
+
174
+ Parameters
175
+ ----------
176
+ *dtypes : dtypes, optional
177
+ Data type(s) specifying the size and endianness of the data.
178
+
179
+ Returns
180
+ -------
181
+ data : ndarray
182
+ A 1-D array object.
183
+
184
+ Raises
185
+ ------
186
+ FortranEOFError
187
+ To signal that no further records are available
188
+ FortranFormattingError
189
+ To signal that the end of the file was encountered
190
+ part-way through a record
191
+
192
+ Notes
193
+ -----
194
+ If the record contains a multidimensional array, you can specify
195
+ the size in the dtype. For example::
196
+
197
+ INTEGER var(5,4)
198
+
199
+ can be read with::
200
+
201
+ read_record('(4,5)i4').T
202
+
203
+ Note that this function does **not** assume the file data is in Fortran
204
+ column major order, so you need to (i) swap the order of dimensions
205
+ when reading and (ii) transpose the resulting array.
206
+
207
+ Alternatively, you can read the data as a 1-D array and handle the
208
+ ordering yourself. For example::
209
+
210
+ read_record('i4').reshape(5, 4, order='F')
211
+
212
+ For records that contain several variables or mixed types (as opposed
213
+ to single scalar or array types), give them as separate arguments::
214
+
215
+ double precision :: a
216
+ integer :: b
217
+ write(1) a, b
218
+
219
+ record = f.read_record('<f4', '<i4')
220
+ a = record[0] # first number
221
+ b = record[1] # second number
222
+
223
+ and if any of the variables are arrays, the shape can be specified as
224
+ the third item in the relevant dtype::
225
+
226
+ double precision :: a
227
+ integer :: b(3,4)
228
+ write(1) a, b
229
+
230
+ record = f.read_record('<f4', np.dtype(('<i4', (4, 3))))
231
+ a = record[0]
232
+ b = record[1].T
233
+
234
+ NumPy also supports a short syntax for this kind of type::
235
+
236
+ record = f.read_record('<f4', '(3,3)<i4')
237
+
238
+ See Also
239
+ --------
240
+ read_reals
241
+ read_ints
242
+
243
+ """
244
+ dtype = kwargs.pop('dtype', None)
245
+ if kwargs:
246
+ raise ValueError(f"Unknown keyword arguments {tuple(kwargs.keys())}")
247
+
248
+ if dtype is not None:
249
+ dtypes = dtypes + (dtype,)
250
+ elif not dtypes:
251
+ raise ValueError('Must specify at least one dtype')
252
+
253
+ first_size = self._read_size(eof_ok=True)
254
+
255
+ dtypes = tuple(np.dtype(dtype) for dtype in dtypes)
256
+ block_size = sum(dtype.itemsize for dtype in dtypes)
257
+
258
+ num_blocks, remainder = divmod(first_size, block_size)
259
+ if remainder != 0:
260
+ raise ValueError(f'Size obtained ({first_size}) is not a multiple of the '
261
+ f'dtypes given ({block_size}).')
262
+
263
+ if len(dtypes) != 1 and first_size != block_size:
264
+ # Fortran does not write mixed type array items in interleaved order,
265
+ # and it's not possible to guess the sizes of the arrays that were written.
266
+ # The user must specify the exact sizes of each of the arrays.
267
+ raise ValueError(f'Size obtained ({first_size}) does not match with the '
268
+ f'expected size ({block_size}) of multi-item record')
269
+
270
+ data = []
271
+ for dtype in dtypes:
272
+ r = np.fromfile(self._fp, dtype=dtype, count=num_blocks)
273
+ if len(r) != num_blocks:
274
+ raise FortranFormattingError(
275
+ "End of file in the middle of a record")
276
+ if dtype.shape != ():
277
+ # Squeeze outmost block dimension for array items
278
+ if num_blocks == 1:
279
+ assert r.shape == (1,) + dtype.shape
280
+ r = r[0]
281
+
282
+ data.append(r)
283
+
284
+ second_size = self._read_size()
285
+ if first_size != second_size:
286
+ raise ValueError('Sizes do not agree in the header and footer for '
287
+ 'this record - check header dtype')
288
+
289
+ # Unpack result
290
+ if len(dtypes) == 1:
291
+ return data[0]
292
+ else:
293
+ return tuple(data)
294
+
295
+ def read_ints(self, dtype='i4'):
296
+ """
297
+ Reads a record of a given type from the file, defaulting to an integer
298
+ type (``INTEGER*4`` in Fortran).
299
+
300
+ Parameters
301
+ ----------
302
+ dtype : dtype, optional
303
+ Data type specifying the size and endianness of the data.
304
+
305
+ Returns
306
+ -------
307
+ data : ndarray
308
+ A 1-D array object.
309
+
310
+ See Also
311
+ --------
312
+ read_reals
313
+ read_record
314
+
315
+ """
316
+ return self.read_record(dtype)
317
+
318
+ def read_reals(self, dtype='f8'):
319
+ """
320
+ Reads a record of a given type from the file, defaulting to a floating
321
+ point number (``real*8`` in Fortran).
322
+
323
+ Parameters
324
+ ----------
325
+ dtype : dtype, optional
326
+ Data type specifying the size and endianness of the data.
327
+
328
+ Returns
329
+ -------
330
+ data : ndarray
331
+ A 1-D array object.
332
+
333
+ See Also
334
+ --------
335
+ read_ints
336
+ read_record
337
+
338
+ """
339
+ return self.read_record(dtype)
340
+
341
+ def close(self):
342
+ """
343
+ Closes the file. It is unsupported to call any other methods off this
344
+ object after closing it. Note that this class supports the 'with'
345
+ statement in modern versions of Python, to call this automatically
346
+
347
+ """
348
+ self._fp.close()
349
+
350
+ def __enter__(self):
351
+ return self
352
+
353
+ def __exit__(self, type, value, tb):
354
+ self.close()
venv/lib/python3.10/site-packages/scipy/io/_idl.py ADDED
@@ -0,0 +1,918 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IDLSave - a python module to read IDL 'save' files
2
+ # Copyright (c) 2010 Thomas P. Robitaille
3
+
4
+ # Many thanks to Craig Markwardt for publishing the Unofficial Format
5
+ # Specification for IDL .sav files, without which this Python module would not
6
+ # exist (http://cow.physics.wisc.edu/~craigm/idl/savefmt).
7
+
8
+ # This code was developed by with permission from ITT Visual Information
9
+ # Systems. IDL(r) is a registered trademark of ITT Visual Information Systems,
10
+ # Inc. for their Interactive Data Language software.
11
+
12
+ # Permission is hereby granted, free of charge, to any person obtaining a
13
+ # copy of this software and associated documentation files (the "Software"),
14
+ # to deal in the Software without restriction, including without limitation
15
+ # the rights to use, copy, modify, merge, publish, distribute, sublicense,
16
+ # and/or sell copies of the Software, and to permit persons to whom the
17
+ # Software is furnished to do so, subject to the following conditions:
18
+
19
+ # The above copyright notice and this permission notice shall be included in
20
+ # all copies or substantial portions of the Software.
21
+
22
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28
+ # DEALINGS IN THE SOFTWARE.
29
+
30
+ __all__ = ['readsav']
31
+
32
+ import struct
33
+ import numpy as np
34
+ import tempfile
35
+ import zlib
36
+ import warnings
37
+
38
+ # Define the different data types that can be found in an IDL save file
39
+ DTYPE_DICT = {1: '>u1',
40
+ 2: '>i2',
41
+ 3: '>i4',
42
+ 4: '>f4',
43
+ 5: '>f8',
44
+ 6: '>c8',
45
+ 7: '|O',
46
+ 8: '|O',
47
+ 9: '>c16',
48
+ 10: '|O',
49
+ 11: '|O',
50
+ 12: '>u2',
51
+ 13: '>u4',
52
+ 14: '>i8',
53
+ 15: '>u8'}
54
+
55
+ # Define the different record types that can be found in an IDL save file
56
+ RECTYPE_DICT = {0: "START_MARKER",
57
+ 1: "COMMON_VARIABLE",
58
+ 2: "VARIABLE",
59
+ 3: "SYSTEM_VARIABLE",
60
+ 6: "END_MARKER",
61
+ 10: "TIMESTAMP",
62
+ 12: "COMPILED",
63
+ 13: "IDENTIFICATION",
64
+ 14: "VERSION",
65
+ 15: "HEAP_HEADER",
66
+ 16: "HEAP_DATA",
67
+ 17: "PROMOTE64",
68
+ 19: "NOTICE",
69
+ 20: "DESCRIPTION"}
70
+
71
+ # Define a dictionary to contain structure definitions
72
+ STRUCT_DICT = {}
73
+
74
+
75
+ def _align_32(f):
76
+ '''Align to the next 32-bit position in a file'''
77
+
78
+ pos = f.tell()
79
+ if pos % 4 != 0:
80
+ f.seek(pos + 4 - pos % 4)
81
+ return
82
+
83
+
84
+ def _skip_bytes(f, n):
85
+ '''Skip `n` bytes'''
86
+ f.read(n)
87
+ return
88
+
89
+
90
+ def _read_bytes(f, n):
91
+ '''Read the next `n` bytes'''
92
+ return f.read(n)
93
+
94
+
95
+ def _read_byte(f):
96
+ '''Read a single byte'''
97
+ return np.uint8(struct.unpack('>B', f.read(4)[:1])[0])
98
+
99
+
100
+ def _read_long(f):
101
+ '''Read a signed 32-bit integer'''
102
+ return np.int32(struct.unpack('>l', f.read(4))[0])
103
+
104
+
105
+ def _read_int16(f):
106
+ '''Read a signed 16-bit integer'''
107
+ return np.int16(struct.unpack('>h', f.read(4)[2:4])[0])
108
+
109
+
110
+ def _read_int32(f):
111
+ '''Read a signed 32-bit integer'''
112
+ return np.int32(struct.unpack('>i', f.read(4))[0])
113
+
114
+
115
+ def _read_int64(f):
116
+ '''Read a signed 64-bit integer'''
117
+ return np.int64(struct.unpack('>q', f.read(8))[0])
118
+
119
+
120
+ def _read_uint16(f):
121
+ '''Read an unsigned 16-bit integer'''
122
+ return np.uint16(struct.unpack('>H', f.read(4)[2:4])[0])
123
+
124
+
125
+ def _read_uint32(f):
126
+ '''Read an unsigned 32-bit integer'''
127
+ return np.uint32(struct.unpack('>I', f.read(4))[0])
128
+
129
+
130
+ def _read_uint64(f):
131
+ '''Read an unsigned 64-bit integer'''
132
+ return np.uint64(struct.unpack('>Q', f.read(8))[0])
133
+
134
+
135
+ def _read_float32(f):
136
+ '''Read a 32-bit float'''
137
+ return np.float32(struct.unpack('>f', f.read(4))[0])
138
+
139
+
140
+ def _read_float64(f):
141
+ '''Read a 64-bit float'''
142
+ return np.float64(struct.unpack('>d', f.read(8))[0])
143
+
144
+
145
+ class Pointer:
146
+ '''Class used to define pointers'''
147
+
148
+ def __init__(self, index):
149
+ self.index = index
150
+ return
151
+
152
+
153
+ class ObjectPointer(Pointer):
154
+ '''Class used to define object pointers'''
155
+ pass
156
+
157
+
158
+ def _read_string(f):
159
+ '''Read a string'''
160
+ length = _read_long(f)
161
+ if length > 0:
162
+ chars = _read_bytes(f, length).decode('latin1')
163
+ _align_32(f)
164
+ else:
165
+ chars = ''
166
+ return chars
167
+
168
+
169
+ def _read_string_data(f):
170
+ '''Read a data string (length is specified twice)'''
171
+ length = _read_long(f)
172
+ if length > 0:
173
+ length = _read_long(f)
174
+ string_data = _read_bytes(f, length)
175
+ _align_32(f)
176
+ else:
177
+ string_data = ''
178
+ return string_data
179
+
180
+
181
+ def _read_data(f, dtype):
182
+ '''Read a variable with a specified data type'''
183
+ if dtype == 1:
184
+ if _read_int32(f) != 1:
185
+ raise Exception("Error occurred while reading byte variable")
186
+ return _read_byte(f)
187
+ elif dtype == 2:
188
+ return _read_int16(f)
189
+ elif dtype == 3:
190
+ return _read_int32(f)
191
+ elif dtype == 4:
192
+ return _read_float32(f)
193
+ elif dtype == 5:
194
+ return _read_float64(f)
195
+ elif dtype == 6:
196
+ real = _read_float32(f)
197
+ imag = _read_float32(f)
198
+ return np.complex64(real + imag * 1j)
199
+ elif dtype == 7:
200
+ return _read_string_data(f)
201
+ elif dtype == 8:
202
+ raise Exception("Should not be here - please report this")
203
+ elif dtype == 9:
204
+ real = _read_float64(f)
205
+ imag = _read_float64(f)
206
+ return np.complex128(real + imag * 1j)
207
+ elif dtype == 10:
208
+ return Pointer(_read_int32(f))
209
+ elif dtype == 11:
210
+ return ObjectPointer(_read_int32(f))
211
+ elif dtype == 12:
212
+ return _read_uint16(f)
213
+ elif dtype == 13:
214
+ return _read_uint32(f)
215
+ elif dtype == 14:
216
+ return _read_int64(f)
217
+ elif dtype == 15:
218
+ return _read_uint64(f)
219
+ else:
220
+ raise Exception("Unknown IDL type: %i - please report this" % dtype)
221
+
222
+
223
+ def _read_structure(f, array_desc, struct_desc):
224
+ '''
225
+ Read a structure, with the array and structure descriptors given as
226
+ `array_desc` and `structure_desc` respectively.
227
+ '''
228
+
229
+ nrows = array_desc['nelements']
230
+ columns = struct_desc['tagtable']
231
+
232
+ dtype = []
233
+ for col in columns:
234
+ if col['structure'] or col['array']:
235
+ dtype.append(((col['name'].lower(), col['name']), np.object_))
236
+ else:
237
+ if col['typecode'] in DTYPE_DICT:
238
+ dtype.append(((col['name'].lower(), col['name']),
239
+ DTYPE_DICT[col['typecode']]))
240
+ else:
241
+ raise Exception("Variable type %i not implemented" %
242
+ col['typecode'])
243
+
244
+ structure = np.rec.recarray((nrows, ), dtype=dtype)
245
+
246
+ for i in range(nrows):
247
+ for col in columns:
248
+ dtype = col['typecode']
249
+ if col['structure']:
250
+ structure[col['name']][i] = _read_structure(f,
251
+ struct_desc['arrtable'][col['name']],
252
+ struct_desc['structtable'][col['name']])
253
+ elif col['array']:
254
+ structure[col['name']][i] = _read_array(f, dtype,
255
+ struct_desc['arrtable'][col['name']])
256
+ else:
257
+ structure[col['name']][i] = _read_data(f, dtype)
258
+
259
+ # Reshape structure if needed
260
+ if array_desc['ndims'] > 1:
261
+ dims = array_desc['dims'][:int(array_desc['ndims'])]
262
+ dims.reverse()
263
+ structure = structure.reshape(dims)
264
+
265
+ return structure
266
+
267
+
268
+ def _read_array(f, typecode, array_desc):
269
+ '''
270
+ Read an array of type `typecode`, with the array descriptor given as
271
+ `array_desc`.
272
+ '''
273
+
274
+ if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]:
275
+
276
+ if typecode == 1:
277
+ nbytes = _read_int32(f)
278
+ if nbytes != array_desc['nbytes']:
279
+ warnings.warn("Not able to verify number of bytes from header",
280
+ stacklevel=3)
281
+
282
+ # Read bytes as numpy array
283
+ array = np.frombuffer(f.read(array_desc['nbytes']),
284
+ dtype=DTYPE_DICT[typecode])
285
+
286
+ elif typecode in [2, 12]:
287
+
288
+ # These are 2 byte types, need to skip every two as they are not packed
289
+
290
+ array = np.frombuffer(f.read(array_desc['nbytes']*2),
291
+ dtype=DTYPE_DICT[typecode])[1::2]
292
+
293
+ else:
294
+
295
+ # Read bytes into list
296
+ array = []
297
+ for i in range(array_desc['nelements']):
298
+ dtype = typecode
299
+ data = _read_data(f, dtype)
300
+ array.append(data)
301
+
302
+ array = np.array(array, dtype=np.object_)
303
+
304
+ # Reshape array if needed
305
+ if array_desc['ndims'] > 1:
306
+ dims = array_desc['dims'][:int(array_desc['ndims'])]
307
+ dims.reverse()
308
+ array = array.reshape(dims)
309
+
310
+ # Go to next alignment position
311
+ _align_32(f)
312
+
313
+ return array
314
+
315
+
316
+ def _read_record(f):
317
+ '''Function to read in a full record'''
318
+
319
+ record = {'rectype': _read_long(f)}
320
+
321
+ nextrec = _read_uint32(f)
322
+ nextrec += _read_uint32(f).astype(np.int64) * 2**32
323
+
324
+ _skip_bytes(f, 4)
325
+
326
+ if record['rectype'] not in RECTYPE_DICT:
327
+ raise Exception("Unknown RECTYPE: %i" % record['rectype'])
328
+
329
+ record['rectype'] = RECTYPE_DICT[record['rectype']]
330
+
331
+ if record['rectype'] in ["VARIABLE", "HEAP_DATA"]:
332
+
333
+ if record['rectype'] == "VARIABLE":
334
+ record['varname'] = _read_string(f)
335
+ else:
336
+ record['heap_index'] = _read_long(f)
337
+ _skip_bytes(f, 4)
338
+
339
+ rectypedesc = _read_typedesc(f)
340
+
341
+ if rectypedesc['typecode'] == 0:
342
+
343
+ if nextrec == f.tell():
344
+ record['data'] = None # Indicates NULL value
345
+ else:
346
+ raise ValueError("Unexpected type code: 0")
347
+
348
+ else:
349
+
350
+ varstart = _read_long(f)
351
+ if varstart != 7:
352
+ raise Exception("VARSTART is not 7")
353
+
354
+ if rectypedesc['structure']:
355
+ record['data'] = _read_structure(f, rectypedesc['array_desc'],
356
+ rectypedesc['struct_desc'])
357
+ elif rectypedesc['array']:
358
+ record['data'] = _read_array(f, rectypedesc['typecode'],
359
+ rectypedesc['array_desc'])
360
+ else:
361
+ dtype = rectypedesc['typecode']
362
+ record['data'] = _read_data(f, dtype)
363
+
364
+ elif record['rectype'] == "TIMESTAMP":
365
+
366
+ _skip_bytes(f, 4*256)
367
+ record['date'] = _read_string(f)
368
+ record['user'] = _read_string(f)
369
+ record['host'] = _read_string(f)
370
+
371
+ elif record['rectype'] == "VERSION":
372
+
373
+ record['format'] = _read_long(f)
374
+ record['arch'] = _read_string(f)
375
+ record['os'] = _read_string(f)
376
+ record['release'] = _read_string(f)
377
+
378
+ elif record['rectype'] == "IDENTIFICATON":
379
+
380
+ record['author'] = _read_string(f)
381
+ record['title'] = _read_string(f)
382
+ record['idcode'] = _read_string(f)
383
+
384
+ elif record['rectype'] == "NOTICE":
385
+
386
+ record['notice'] = _read_string(f)
387
+
388
+ elif record['rectype'] == "DESCRIPTION":
389
+
390
+ record['description'] = _read_string_data(f)
391
+
392
+ elif record['rectype'] == "HEAP_HEADER":
393
+
394
+ record['nvalues'] = _read_long(f)
395
+ record['indices'] = [_read_long(f) for _ in range(record['nvalues'])]
396
+
397
+ elif record['rectype'] == "COMMONBLOCK":
398
+
399
+ record['nvars'] = _read_long(f)
400
+ record['name'] = _read_string(f)
401
+ record['varnames'] = [_read_string(f) for _ in range(record['nvars'])]
402
+
403
+ elif record['rectype'] == "END_MARKER":
404
+
405
+ record['end'] = True
406
+
407
+ elif record['rectype'] == "UNKNOWN":
408
+
409
+ warnings.warn("Skipping UNKNOWN record", stacklevel=3)
410
+
411
+ elif record['rectype'] == "SYSTEM_VARIABLE":
412
+
413
+ warnings.warn("Skipping SYSTEM_VARIABLE record", stacklevel=3)
414
+
415
+ else:
416
+
417
+ raise Exception(f"record['rectype']={record['rectype']} not implemented")
418
+
419
+ f.seek(nextrec)
420
+
421
+ return record
422
+
423
+
424
+ def _read_typedesc(f):
425
+ '''Function to read in a type descriptor'''
426
+
427
+ typedesc = {'typecode': _read_long(f), 'varflags': _read_long(f)}
428
+
429
+ if typedesc['varflags'] & 2 == 2:
430
+ raise Exception("System variables not implemented")
431
+
432
+ typedesc['array'] = typedesc['varflags'] & 4 == 4
433
+ typedesc['structure'] = typedesc['varflags'] & 32 == 32
434
+
435
+ if typedesc['structure']:
436
+ typedesc['array_desc'] = _read_arraydesc(f)
437
+ typedesc['struct_desc'] = _read_structdesc(f)
438
+ elif typedesc['array']:
439
+ typedesc['array_desc'] = _read_arraydesc(f)
440
+
441
+ return typedesc
442
+
443
+
444
+ def _read_arraydesc(f):
445
+ '''Function to read in an array descriptor'''
446
+
447
+ arraydesc = {'arrstart': _read_long(f)}
448
+
449
+ if arraydesc['arrstart'] == 8:
450
+
451
+ _skip_bytes(f, 4)
452
+
453
+ arraydesc['nbytes'] = _read_long(f)
454
+ arraydesc['nelements'] = _read_long(f)
455
+ arraydesc['ndims'] = _read_long(f)
456
+
457
+ _skip_bytes(f, 8)
458
+
459
+ arraydesc['nmax'] = _read_long(f)
460
+
461
+ arraydesc['dims'] = [_read_long(f) for _ in range(arraydesc['nmax'])]
462
+
463
+ elif arraydesc['arrstart'] == 18:
464
+
465
+ warnings.warn("Using experimental 64-bit array read", stacklevel=3)
466
+
467
+ _skip_bytes(f, 8)
468
+
469
+ arraydesc['nbytes'] = _read_uint64(f)
470
+ arraydesc['nelements'] = _read_uint64(f)
471
+ arraydesc['ndims'] = _read_long(f)
472
+
473
+ _skip_bytes(f, 8)
474
+
475
+ arraydesc['nmax'] = 8
476
+
477
+ arraydesc['dims'] = []
478
+ for d in range(arraydesc['nmax']):
479
+ v = _read_long(f)
480
+ if v != 0:
481
+ raise Exception("Expected a zero in ARRAY_DESC")
482
+ arraydesc['dims'].append(_read_long(f))
483
+
484
+ else:
485
+
486
+ raise Exception("Unknown ARRSTART: %i" % arraydesc['arrstart'])
487
+
488
+ return arraydesc
489
+
490
+
491
+ def _read_structdesc(f):
492
+ '''Function to read in a structure descriptor'''
493
+
494
+ structdesc = {}
495
+
496
+ structstart = _read_long(f)
497
+ if structstart != 9:
498
+ raise Exception("STRUCTSTART should be 9")
499
+
500
+ structdesc['name'] = _read_string(f)
501
+ predef = _read_long(f)
502
+ structdesc['ntags'] = _read_long(f)
503
+ structdesc['nbytes'] = _read_long(f)
504
+
505
+ structdesc['predef'] = predef & 1
506
+ structdesc['inherits'] = predef & 2
507
+ structdesc['is_super'] = predef & 4
508
+
509
+ if not structdesc['predef']:
510
+
511
+ structdesc['tagtable'] = [_read_tagdesc(f)
512
+ for _ in range(structdesc['ntags'])]
513
+
514
+ for tag in structdesc['tagtable']:
515
+ tag['name'] = _read_string(f)
516
+
517
+ structdesc['arrtable'] = {tag['name']: _read_arraydesc(f)
518
+ for tag in structdesc['tagtable']
519
+ if tag['array']}
520
+
521
+ structdesc['structtable'] = {tag['name']: _read_structdesc(f)
522
+ for tag in structdesc['tagtable']
523
+ if tag['structure']}
524
+
525
+ if structdesc['inherits'] or structdesc['is_super']:
526
+ structdesc['classname'] = _read_string(f)
527
+ structdesc['nsupclasses'] = _read_long(f)
528
+ structdesc['supclassnames'] = [
529
+ _read_string(f) for _ in range(structdesc['nsupclasses'])]
530
+ structdesc['supclasstable'] = [
531
+ _read_structdesc(f) for _ in range(structdesc['nsupclasses'])]
532
+
533
+ STRUCT_DICT[structdesc['name']] = structdesc
534
+
535
+ else:
536
+
537
+ if structdesc['name'] not in STRUCT_DICT:
538
+ raise Exception("PREDEF=1 but can't find definition")
539
+
540
+ structdesc = STRUCT_DICT[structdesc['name']]
541
+
542
+ return structdesc
543
+
544
+
545
+ def _read_tagdesc(f):
546
+ '''Function to read in a tag descriptor'''
547
+
548
+ tagdesc = {'offset': _read_long(f)}
549
+
550
+ if tagdesc['offset'] == -1:
551
+ tagdesc['offset'] = _read_uint64(f)
552
+
553
+ tagdesc['typecode'] = _read_long(f)
554
+ tagflags = _read_long(f)
555
+
556
+ tagdesc['array'] = tagflags & 4 == 4
557
+ tagdesc['structure'] = tagflags & 32 == 32
558
+ tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT
559
+ # Assume '10'x is scalar
560
+
561
+ return tagdesc
562
+
563
+
564
+ def _replace_heap(variable, heap):
565
+
566
+ if isinstance(variable, Pointer):
567
+
568
+ while isinstance(variable, Pointer):
569
+
570
+ if variable.index == 0:
571
+ variable = None
572
+ else:
573
+ if variable.index in heap:
574
+ variable = heap[variable.index]
575
+ else:
576
+ warnings.warn("Variable referenced by pointer not found "
577
+ "in heap: variable will be set to None",
578
+ stacklevel=3)
579
+ variable = None
580
+
581
+ replace, new = _replace_heap(variable, heap)
582
+
583
+ if replace:
584
+ variable = new
585
+
586
+ return True, variable
587
+
588
+ elif isinstance(variable, np.rec.recarray):
589
+
590
+ # Loop over records
591
+ for ir, record in enumerate(variable):
592
+
593
+ replace, new = _replace_heap(record, heap)
594
+
595
+ if replace:
596
+ variable[ir] = new
597
+
598
+ return False, variable
599
+
600
+ elif isinstance(variable, np.record):
601
+
602
+ # Loop over values
603
+ for iv, value in enumerate(variable):
604
+
605
+ replace, new = _replace_heap(value, heap)
606
+
607
+ if replace:
608
+ variable[iv] = new
609
+
610
+ return False, variable
611
+
612
+ elif isinstance(variable, np.ndarray):
613
+
614
+ # Loop over values if type is np.object_
615
+ if variable.dtype.type is np.object_:
616
+
617
+ for iv in range(variable.size):
618
+
619
+ replace, new = _replace_heap(variable.item(iv), heap)
620
+
621
+ if replace:
622
+ variable.reshape(-1)[iv] = new
623
+
624
+ return False, variable
625
+
626
+ else:
627
+
628
+ return False, variable
629
+
630
+
631
+ class AttrDict(dict):
632
+ '''
633
+ A case-insensitive dictionary with access via item, attribute, and call
634
+ notations:
635
+
636
+ >>> from scipy.io._idl import AttrDict
637
+ >>> d = AttrDict()
638
+ >>> d['Variable'] = 123
639
+ >>> d['Variable']
640
+ 123
641
+ >>> d.Variable
642
+ 123
643
+ >>> d.variable
644
+ 123
645
+ >>> d('VARIABLE')
646
+ 123
647
+ >>> d['missing']
648
+ Traceback (most recent error last):
649
+ ...
650
+ KeyError: 'missing'
651
+ >>> d.missing
652
+ Traceback (most recent error last):
653
+ ...
654
+ AttributeError: 'AttrDict' object has no attribute 'missing'
655
+ '''
656
+
657
+ def __init__(self, init={}):
658
+ dict.__init__(self, init)
659
+
660
+ def __getitem__(self, name):
661
+ return super().__getitem__(name.lower())
662
+
663
+ def __setitem__(self, key, value):
664
+ return super().__setitem__(key.lower(), value)
665
+
666
+ def __getattr__(self, name):
667
+ try:
668
+ return self.__getitem__(name)
669
+ except KeyError:
670
+ raise AttributeError(
671
+ f"'{type(self)}' object has no attribute '{name}'") from None
672
+
673
+ __setattr__ = __setitem__
674
+ __call__ = __getitem__
675
+
676
+
677
+ def readsav(file_name, idict=None, python_dict=False,
678
+ uncompressed_file_name=None, verbose=False):
679
+ """
680
+ Read an IDL .sav file.
681
+
682
+ Parameters
683
+ ----------
684
+ file_name : str
685
+ Name of the IDL save file.
686
+ idict : dict, optional
687
+ Dictionary in which to insert .sav file variables.
688
+ python_dict : bool, optional
689
+ By default, the object return is not a Python dictionary, but a
690
+ case-insensitive dictionary with item, attribute, and call access
691
+ to variables. To get a standard Python dictionary, set this option
692
+ to True.
693
+ uncompressed_file_name : str, optional
694
+ This option only has an effect for .sav files written with the
695
+ /compress option. If a file name is specified, compressed .sav
696
+ files are uncompressed to this file. Otherwise, readsav will use
697
+ the `tempfile` module to determine a temporary filename
698
+ automatically, and will remove the temporary file upon successfully
699
+ reading it in.
700
+ verbose : bool, optional
701
+ Whether to print out information about the save file, including
702
+ the records read, and available variables.
703
+
704
+ Returns
705
+ -------
706
+ idl_dict : AttrDict or dict
707
+ If `python_dict` is set to False (default), this function returns a
708
+ case-insensitive dictionary with item, attribute, and call access
709
+ to variables. If `python_dict` is set to True, this function
710
+ returns a Python dictionary with all variable names in lowercase.
711
+ If `idict` was specified, then variables are written to the
712
+ dictionary specified, and the updated dictionary is returned.
713
+
714
+ Examples
715
+ --------
716
+ >>> from os.path import dirname, join as pjoin
717
+ >>> import scipy.io as sio
718
+ >>> from scipy.io import readsav
719
+
720
+ Get the filename for an example .sav file from the tests/data directory.
721
+
722
+ >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
723
+ >>> sav_fname = pjoin(data_dir, 'array_float32_1d.sav')
724
+
725
+ Load the .sav file contents.
726
+
727
+ >>> sav_data = readsav(sav_fname)
728
+
729
+ Get keys of the .sav file contents.
730
+
731
+ >>> print(sav_data.keys())
732
+ dict_keys(['array1d'])
733
+
734
+ Access a content with a key.
735
+
736
+ >>> print(sav_data['array1d'])
737
+ [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
738
+ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
739
+ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
740
+ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
741
+ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
742
+ 0. 0. 0.]
743
+
744
+ """
745
+
746
+ # Initialize record and variable holders
747
+ records = []
748
+ if python_dict or idict:
749
+ variables = {}
750
+ else:
751
+ variables = AttrDict()
752
+
753
+ # Open the IDL file
754
+ f = open(file_name, 'rb')
755
+
756
+ # Read the signature, which should be 'SR'
757
+ signature = _read_bytes(f, 2)
758
+ if signature != b'SR':
759
+ raise Exception("Invalid SIGNATURE: %s" % signature)
760
+
761
+ # Next, the record format, which is '\x00\x04' for normal .sav
762
+ # files, and '\x00\x06' for compressed .sav files.
763
+ recfmt = _read_bytes(f, 2)
764
+
765
+ if recfmt == b'\x00\x04':
766
+ pass
767
+
768
+ elif recfmt == b'\x00\x06':
769
+
770
+ if verbose:
771
+ print("IDL Save file is compressed")
772
+
773
+ if uncompressed_file_name:
774
+ fout = open(uncompressed_file_name, 'w+b')
775
+ else:
776
+ fout = tempfile.NamedTemporaryFile(suffix='.sav')
777
+
778
+ if verbose:
779
+ print(" -> expanding to %s" % fout.name)
780
+
781
+ # Write header
782
+ fout.write(b'SR\x00\x04')
783
+
784
+ # Cycle through records
785
+ while True:
786
+
787
+ # Read record type
788
+ rectype = _read_long(f)
789
+ fout.write(struct.pack('>l', int(rectype)))
790
+
791
+ # Read position of next record and return as int
792
+ nextrec = _read_uint32(f)
793
+ nextrec += _read_uint32(f).astype(np.int64) * 2**32
794
+
795
+ # Read the unknown 4 bytes
796
+ unknown = f.read(4)
797
+
798
+ # Check if the end of the file has been reached
799
+ if RECTYPE_DICT[rectype] == 'END_MARKER':
800
+ modval = np.int64(2**32)
801
+ fout.write(struct.pack('>I', int(nextrec) % modval))
802
+ fout.write(
803
+ struct.pack('>I', int((nextrec - (nextrec % modval)) / modval))
804
+ )
805
+ fout.write(unknown)
806
+ break
807
+
808
+ # Find current position
809
+ pos = f.tell()
810
+
811
+ # Decompress record
812
+ rec_string = zlib.decompress(f.read(nextrec-pos))
813
+
814
+ # Find new position of next record
815
+ nextrec = fout.tell() + len(rec_string) + 12
816
+
817
+ # Write out record
818
+ fout.write(struct.pack('>I', int(nextrec % 2**32)))
819
+ fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32)))
820
+ fout.write(unknown)
821
+ fout.write(rec_string)
822
+
823
+ # Close the original compressed file
824
+ f.close()
825
+
826
+ # Set f to be the decompressed file, and skip the first four bytes
827
+ f = fout
828
+ f.seek(4)
829
+
830
+ else:
831
+ raise Exception("Invalid RECFMT: %s" % recfmt)
832
+
833
+ # Loop through records, and add them to the list
834
+ while True:
835
+ r = _read_record(f)
836
+ records.append(r)
837
+ if 'end' in r:
838
+ if r['end']:
839
+ break
840
+
841
+ # Close the file
842
+ f.close()
843
+
844
+ # Find heap data variables
845
+ heap = {}
846
+ for r in records:
847
+ if r['rectype'] == "HEAP_DATA":
848
+ heap[r['heap_index']] = r['data']
849
+
850
+ # Find all variables
851
+ for r in records:
852
+ if r['rectype'] == "VARIABLE":
853
+ replace, new = _replace_heap(r['data'], heap)
854
+ if replace:
855
+ r['data'] = new
856
+ variables[r['varname'].lower()] = r['data']
857
+
858
+ if verbose:
859
+
860
+ # Print out timestamp info about the file
861
+ for record in records:
862
+ if record['rectype'] == "TIMESTAMP":
863
+ print("-"*50)
864
+ print("Date: %s" % record['date'])
865
+ print("User: %s" % record['user'])
866
+ print("Host: %s" % record['host'])
867
+ break
868
+
869
+ # Print out version info about the file
870
+ for record in records:
871
+ if record['rectype'] == "VERSION":
872
+ print("-"*50)
873
+ print("Format: %s" % record['format'])
874
+ print("Architecture: %s" % record['arch'])
875
+ print("Operating System: %s" % record['os'])
876
+ print("IDL Version: %s" % record['release'])
877
+ break
878
+
879
+ # Print out identification info about the file
880
+ for record in records:
881
+ if record['rectype'] == "IDENTIFICATON":
882
+ print("-"*50)
883
+ print("Author: %s" % record['author'])
884
+ print("Title: %s" % record['title'])
885
+ print("ID Code: %s" % record['idcode'])
886
+ break
887
+
888
+ # Print out descriptions saved with the file
889
+ for record in records:
890
+ if record['rectype'] == "DESCRIPTION":
891
+ print("-"*50)
892
+ print("Description: %s" % record['description'])
893
+ break
894
+
895
+ print("-"*50)
896
+ print("Successfully read %i records of which:" %
897
+ (len(records)))
898
+
899
+ # Create convenience list of record types
900
+ rectypes = [r['rectype'] for r in records]
901
+
902
+ for rt in set(rectypes):
903
+ if rt != 'END_MARKER':
904
+ print(" - %i are of type %s" % (rectypes.count(rt), rt))
905
+ print("-"*50)
906
+
907
+ if 'VARIABLE' in rectypes:
908
+ print("Available variables:")
909
+ for var in variables:
910
+ print(f" - {var} [{type(variables[var])}]")
911
+ print("-"*50)
912
+
913
+ if idict:
914
+ for var in variables:
915
+ idict[var] = variables[var]
916
+ return idict
917
+ else:
918
+ return variables
venv/lib/python3.10/site-packages/scipy/io/_mmio.py ADDED
@@ -0,0 +1,961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Matrix Market I/O in Python.
3
+ See http://math.nist.gov/MatrixMarket/formats.html
4
+ for information about the Matrix Market format.
5
+ """
6
+ #
7
+ # Author: Pearu Peterson <[email protected]>
8
+ # Created: October, 2004
9
+ #
10
+ # References:
11
+ # http://math.nist.gov/MatrixMarket/
12
+ #
13
+ import os
14
+
15
+ import numpy as np
16
+ from numpy import (asarray, real, imag, conj, zeros, ndarray, concatenate,
17
+ ones, can_cast)
18
+
19
+ from scipy.sparse import coo_matrix, issparse
20
+
21
+ __all__ = ['mminfo', 'mmread', 'mmwrite', 'MMFile']
22
+
23
+
24
+ # -----------------------------------------------------------------------------
25
+ def asstr(s):
26
+ if isinstance(s, bytes):
27
+ return s.decode('latin1')
28
+ return str(s)
29
+
30
+
31
+ def mminfo(source):
32
+ """
33
+ Return size and storage parameters from Matrix Market file-like 'source'.
34
+
35
+ Parameters
36
+ ----------
37
+ source : str or file-like
38
+ Matrix Market filename (extension .mtx) or open file-like object
39
+
40
+ Returns
41
+ -------
42
+ rows : int
43
+ Number of matrix rows.
44
+ cols : int
45
+ Number of matrix columns.
46
+ entries : int
47
+ Number of non-zero entries of a sparse matrix
48
+ or rows*cols for a dense matrix.
49
+ format : str
50
+ Either 'coordinate' or 'array'.
51
+ field : str
52
+ Either 'real', 'complex', 'pattern', or 'integer'.
53
+ symmetry : str
54
+ Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
55
+
56
+ Examples
57
+ --------
58
+ >>> from io import StringIO
59
+ >>> from scipy.io import mminfo
60
+
61
+ >>> text = '''%%MatrixMarket matrix coordinate real general
62
+ ... 5 5 7
63
+ ... 2 3 1.0
64
+ ... 3 4 2.0
65
+ ... 3 5 3.0
66
+ ... 4 1 4.0
67
+ ... 4 2 5.0
68
+ ... 4 3 6.0
69
+ ... 4 4 7.0
70
+ ... '''
71
+
72
+
73
+ ``mminfo(source)`` returns the number of rows, number of columns,
74
+ format, field type and symmetry attribute of the source file.
75
+
76
+ >>> mminfo(StringIO(text))
77
+ (5, 5, 7, 'coordinate', 'real', 'general')
78
+ """
79
+ return MMFile.info(source)
80
+
81
+ # -----------------------------------------------------------------------------
82
+
83
+
84
+ def mmread(source):
85
+ """
86
+ Reads the contents of a Matrix Market file-like 'source' into a matrix.
87
+
88
+ Parameters
89
+ ----------
90
+ source : str or file-like
91
+ Matrix Market filename (extensions .mtx, .mtz.gz)
92
+ or open file-like object.
93
+
94
+ Returns
95
+ -------
96
+ a : ndarray or coo_matrix
97
+ Dense or sparse matrix depending on the matrix format in the
98
+ Matrix Market file.
99
+
100
+ Examples
101
+ --------
102
+ >>> from io import StringIO
103
+ >>> from scipy.io import mmread
104
+
105
+ >>> text = '''%%MatrixMarket matrix coordinate real general
106
+ ... 5 5 7
107
+ ... 2 3 1.0
108
+ ... 3 4 2.0
109
+ ... 3 5 3.0
110
+ ... 4 1 4.0
111
+ ... 4 2 5.0
112
+ ... 4 3 6.0
113
+ ... 4 4 7.0
114
+ ... '''
115
+
116
+ ``mmread(source)`` returns the data as sparse matrix in COO format.
117
+
118
+ >>> m = mmread(StringIO(text))
119
+ >>> m
120
+ <5x5 sparse matrix of type '<class 'numpy.float64'>'
121
+ with 7 stored elements in COOrdinate format>
122
+ >>> m.A
123
+ array([[0., 0., 0., 0., 0.],
124
+ [0., 0., 1., 0., 0.],
125
+ [0., 0., 0., 2., 3.],
126
+ [4., 5., 6., 7., 0.],
127
+ [0., 0., 0., 0., 0.]])
128
+ """
129
+ return MMFile().read(source)
130
+
131
+ # -----------------------------------------------------------------------------
132
+
133
+
134
+ def mmwrite(target, a, comment='', field=None, precision=None, symmetry=None):
135
+ r"""
136
+ Writes the sparse or dense array `a` to Matrix Market file-like `target`.
137
+
138
+ Parameters
139
+ ----------
140
+ target : str or file-like
141
+ Matrix Market filename (extension .mtx) or open file-like object.
142
+ a : array like
143
+ Sparse or dense 2-D array.
144
+ comment : str, optional
145
+ Comments to be prepended to the Matrix Market file.
146
+ field : None or str, optional
147
+ Either 'real', 'complex', 'pattern', or 'integer'.
148
+ precision : None or int, optional
149
+ Number of digits to display for real or complex values.
150
+ symmetry : None or str, optional
151
+ Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
152
+ If symmetry is None the symmetry type of 'a' is determined by its
153
+ values.
154
+
155
+ Returns
156
+ -------
157
+ None
158
+
159
+ Examples
160
+ --------
161
+ >>> from io import BytesIO
162
+ >>> import numpy as np
163
+ >>> from scipy.sparse import coo_matrix
164
+ >>> from scipy.io import mmwrite
165
+
166
+ Write a small NumPy array to a matrix market file. The file will be
167
+ written in the ``'array'`` format.
168
+
169
+ >>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]])
170
+ >>> target = BytesIO()
171
+ >>> mmwrite(target, a)
172
+ >>> print(target.getvalue().decode('latin1'))
173
+ %%MatrixMarket matrix array real general
174
+ %
175
+ 2 4
176
+ 1.0000000000000000e+00
177
+ 0.0000000000000000e+00
178
+ 0.0000000000000000e+00
179
+ 2.5000000000000000e+00
180
+ 0.0000000000000000e+00
181
+ 0.0000000000000000e+00
182
+ 0.0000000000000000e+00
183
+ 6.2500000000000000e+00
184
+
185
+ Add a comment to the output file, and set the precision to 3.
186
+
187
+ >>> target = BytesIO()
188
+ >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3)
189
+ >>> print(target.getvalue().decode('latin1'))
190
+ %%MatrixMarket matrix array real general
191
+ %
192
+ % Some test data.
193
+ %
194
+ 2 4
195
+ 1.000e+00
196
+ 0.000e+00
197
+ 0.000e+00
198
+ 2.500e+00
199
+ 0.000e+00
200
+ 0.000e+00
201
+ 0.000e+00
202
+ 6.250e+00
203
+
204
+ Convert to a sparse matrix before calling ``mmwrite``. This will
205
+ result in the output format being ``'coordinate'`` rather than
206
+ ``'array'``.
207
+
208
+ >>> target = BytesIO()
209
+ >>> mmwrite(target, coo_matrix(a), precision=3)
210
+ >>> print(target.getvalue().decode('latin1'))
211
+ %%MatrixMarket matrix coordinate real general
212
+ %
213
+ 2 4 3
214
+ 1 1 1.00e+00
215
+ 2 2 2.50e+00
216
+ 2 4 6.25e+00
217
+
218
+ Write a complex Hermitian array to a matrix market file. Note that
219
+ only six values are actually written to the file; the other values
220
+ are implied by the symmetry.
221
+
222
+ >>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]])
223
+ >>> z
224
+ array([[ 3. +0.j, 1. +2.j, 4. -3.j],
225
+ [ 1. -2.j, 1. +0.j, -0. -5.j],
226
+ [ 4. +3.j, 0. +5.j, 2.5+0.j]])
227
+
228
+ >>> target = BytesIO()
229
+ >>> mmwrite(target, z, precision=2)
230
+ >>> print(target.getvalue().decode('latin1'))
231
+ %%MatrixMarket matrix array complex hermitian
232
+ %
233
+ 3 3
234
+ 3.00e+00 0.00e+00
235
+ 1.00e+00 -2.00e+00
236
+ 4.00e+00 3.00e+00
237
+ 1.00e+00 0.00e+00
238
+ 0.00e+00 5.00e+00
239
+ 2.50e+00 0.00e+00
240
+
241
+ """
242
+ MMFile().write(target, a, comment, field, precision, symmetry)
243
+
244
+
245
+ ###############################################################################
246
+ class MMFile:
247
+ __slots__ = ('_rows',
248
+ '_cols',
249
+ '_entries',
250
+ '_format',
251
+ '_field',
252
+ '_symmetry')
253
+
254
+ @property
255
+ def rows(self):
256
+ return self._rows
257
+
258
+ @property
259
+ def cols(self):
260
+ return self._cols
261
+
262
+ @property
263
+ def entries(self):
264
+ return self._entries
265
+
266
+ @property
267
+ def format(self):
268
+ return self._format
269
+
270
+ @property
271
+ def field(self):
272
+ return self._field
273
+
274
+ @property
275
+ def symmetry(self):
276
+ return self._symmetry
277
+
278
+ @property
279
+ def has_symmetry(self):
280
+ return self._symmetry in (self.SYMMETRY_SYMMETRIC,
281
+ self.SYMMETRY_SKEW_SYMMETRIC,
282
+ self.SYMMETRY_HERMITIAN)
283
+
284
+ # format values
285
+ FORMAT_COORDINATE = 'coordinate'
286
+ FORMAT_ARRAY = 'array'
287
+ FORMAT_VALUES = (FORMAT_COORDINATE, FORMAT_ARRAY)
288
+
289
+ @classmethod
290
+ def _validate_format(self, format):
291
+ if format not in self.FORMAT_VALUES:
292
+ msg = f'unknown format type {format}, must be one of {self.FORMAT_VALUES}'
293
+ raise ValueError(msg)
294
+
295
+ # field values
296
+ FIELD_INTEGER = 'integer'
297
+ FIELD_UNSIGNED = 'unsigned-integer'
298
+ FIELD_REAL = 'real'
299
+ FIELD_COMPLEX = 'complex'
300
+ FIELD_PATTERN = 'pattern'
301
+ FIELD_VALUES = (FIELD_INTEGER, FIELD_UNSIGNED, FIELD_REAL, FIELD_COMPLEX,
302
+ FIELD_PATTERN)
303
+
304
+ @classmethod
305
+ def _validate_field(self, field):
306
+ if field not in self.FIELD_VALUES:
307
+ msg = f'unknown field type {field}, must be one of {self.FIELD_VALUES}'
308
+ raise ValueError(msg)
309
+
310
+ # symmetry values
311
+ SYMMETRY_GENERAL = 'general'
312
+ SYMMETRY_SYMMETRIC = 'symmetric'
313
+ SYMMETRY_SKEW_SYMMETRIC = 'skew-symmetric'
314
+ SYMMETRY_HERMITIAN = 'hermitian'
315
+ SYMMETRY_VALUES = (SYMMETRY_GENERAL, SYMMETRY_SYMMETRIC,
316
+ SYMMETRY_SKEW_SYMMETRIC, SYMMETRY_HERMITIAN)
317
+
318
+ @classmethod
319
+ def _validate_symmetry(self, symmetry):
320
+ if symmetry not in self.SYMMETRY_VALUES:
321
+ raise ValueError(f'unknown symmetry type {symmetry}, '
322
+ f'must be one of {self.SYMMETRY_VALUES}')
323
+
324
+ DTYPES_BY_FIELD = {FIELD_INTEGER: 'intp',
325
+ FIELD_UNSIGNED: 'uint64',
326
+ FIELD_REAL: 'd',
327
+ FIELD_COMPLEX: 'D',
328
+ FIELD_PATTERN: 'd'}
329
+
330
+ # -------------------------------------------------------------------------
331
+ @staticmethod
332
+ def reader():
333
+ pass
334
+
335
+ # -------------------------------------------------------------------------
336
+ @staticmethod
337
+ def writer():
338
+ pass
339
+
340
+ # -------------------------------------------------------------------------
341
+ @classmethod
342
+ def info(self, source):
343
+ """
344
+ Return size, storage parameters from Matrix Market file-like 'source'.
345
+
346
+ Parameters
347
+ ----------
348
+ source : str or file-like
349
+ Matrix Market filename (extension .mtx) or open file-like object
350
+
351
+ Returns
352
+ -------
353
+ rows : int
354
+ Number of matrix rows.
355
+ cols : int
356
+ Number of matrix columns.
357
+ entries : int
358
+ Number of non-zero entries of a sparse matrix
359
+ or rows*cols for a dense matrix.
360
+ format : str
361
+ Either 'coordinate' or 'array'.
362
+ field : str
363
+ Either 'real', 'complex', 'pattern', or 'integer'.
364
+ symmetry : str
365
+ Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
366
+ """
367
+
368
+ stream, close_it = self._open(source)
369
+
370
+ try:
371
+
372
+ # read and validate header line
373
+ line = stream.readline()
374
+ mmid, matrix, format, field, symmetry = \
375
+ (asstr(part.strip()) for part in line.split())
376
+ if not mmid.startswith('%%MatrixMarket'):
377
+ raise ValueError('source is not in Matrix Market format')
378
+ if not matrix.lower() == 'matrix':
379
+ raise ValueError("Problem reading file header: " + line)
380
+
381
+ # http://math.nist.gov/MatrixMarket/formats.html
382
+ if format.lower() == 'array':
383
+ format = self.FORMAT_ARRAY
384
+ elif format.lower() == 'coordinate':
385
+ format = self.FORMAT_COORDINATE
386
+
387
+ # skip comments
388
+ # line.startswith('%')
389
+ while line:
390
+ if line.lstrip() and line.lstrip()[0] in ['%', 37]:
391
+ line = stream.readline()
392
+ else:
393
+ break
394
+
395
+ # skip empty lines
396
+ while not line.strip():
397
+ line = stream.readline()
398
+
399
+ split_line = line.split()
400
+ if format == self.FORMAT_ARRAY:
401
+ if not len(split_line) == 2:
402
+ raise ValueError("Header line not of length 2: " +
403
+ line.decode('ascii'))
404
+ rows, cols = map(int, split_line)
405
+ entries = rows * cols
406
+ else:
407
+ if not len(split_line) == 3:
408
+ raise ValueError("Header line not of length 3: " +
409
+ line.decode('ascii'))
410
+ rows, cols, entries = map(int, split_line)
411
+
412
+ return (rows, cols, entries, format, field.lower(),
413
+ symmetry.lower())
414
+
415
+ finally:
416
+ if close_it:
417
+ stream.close()
418
+
419
+ # -------------------------------------------------------------------------
420
+ @staticmethod
421
+ def _open(filespec, mode='rb'):
422
+ """ Return an open file stream for reading based on source.
423
+
424
+ If source is a file name, open it (after trying to find it with mtx and
425
+ gzipped mtx extensions). Otherwise, just return source.
426
+
427
+ Parameters
428
+ ----------
429
+ filespec : str or file-like
430
+ String giving file name or file-like object
431
+ mode : str, optional
432
+ Mode with which to open file, if `filespec` is a file name.
433
+
434
+ Returns
435
+ -------
436
+ fobj : file-like
437
+ Open file-like object.
438
+ close_it : bool
439
+ True if the calling function should close this file when done,
440
+ false otherwise.
441
+ """
442
+ # If 'filespec' is path-like (str, pathlib.Path, os.DirEntry, other class
443
+ # implementing a '__fspath__' method), try to convert it to str. If this
444
+ # fails by throwing a 'TypeError', assume it's an open file handle and
445
+ # return it as-is.
446
+ try:
447
+ filespec = os.fspath(filespec)
448
+ except TypeError:
449
+ return filespec, False
450
+
451
+ # 'filespec' is definitely a str now
452
+
453
+ # open for reading
454
+ if mode[0] == 'r':
455
+
456
+ # determine filename plus extension
457
+ if not os.path.isfile(filespec):
458
+ if os.path.isfile(filespec+'.mtx'):
459
+ filespec = filespec + '.mtx'
460
+ elif os.path.isfile(filespec+'.mtx.gz'):
461
+ filespec = filespec + '.mtx.gz'
462
+ elif os.path.isfile(filespec+'.mtx.bz2'):
463
+ filespec = filespec + '.mtx.bz2'
464
+ # open filename
465
+ if filespec.endswith('.gz'):
466
+ import gzip
467
+ stream = gzip.open(filespec, mode)
468
+ elif filespec.endswith('.bz2'):
469
+ import bz2
470
+ stream = bz2.BZ2File(filespec, 'rb')
471
+ else:
472
+ stream = open(filespec, mode)
473
+
474
+ # open for writing
475
+ else:
476
+ if filespec[-4:] != '.mtx':
477
+ filespec = filespec + '.mtx'
478
+ stream = open(filespec, mode)
479
+
480
+ return stream, True
481
+
482
+ # -------------------------------------------------------------------------
483
+ @staticmethod
484
+ def _get_symmetry(a):
485
+ m, n = a.shape
486
+ if m != n:
487
+ return MMFile.SYMMETRY_GENERAL
488
+ issymm = True
489
+ isskew = True
490
+ isherm = a.dtype.char in 'FD'
491
+
492
+ # sparse input
493
+ if issparse(a):
494
+ # check if number of nonzero entries of lower and upper triangle
495
+ # matrix are equal
496
+ a = a.tocoo()
497
+ (row, col) = a.nonzero()
498
+ if (row < col).sum() != (row > col).sum():
499
+ return MMFile.SYMMETRY_GENERAL
500
+
501
+ # define iterator over symmetric pair entries
502
+ a = a.todok()
503
+
504
+ def symm_iterator():
505
+ for ((i, j), aij) in a.items():
506
+ if i > j:
507
+ aji = a[j, i]
508
+ yield (aij, aji, False)
509
+ elif i == j:
510
+ yield (aij, aij, True)
511
+
512
+ # non-sparse input
513
+ else:
514
+ # define iterator over symmetric pair entries
515
+ def symm_iterator():
516
+ for j in range(n):
517
+ for i in range(j, n):
518
+ aij, aji = a[i][j], a[j][i]
519
+ yield (aij, aji, i == j)
520
+
521
+ # check for symmetry
522
+ # yields aij, aji, is_diagonal
523
+ for (aij, aji, is_diagonal) in symm_iterator():
524
+ if isskew and is_diagonal and aij != 0:
525
+ isskew = False
526
+ else:
527
+ if issymm and aij != aji:
528
+ issymm = False
529
+ with np.errstate(over="ignore"):
530
+ # This can give a warning for uint dtypes, so silence that
531
+ if isskew and aij != -aji:
532
+ isskew = False
533
+ if isherm and aij != conj(aji):
534
+ isherm = False
535
+ if not (issymm or isskew or isherm):
536
+ break
537
+
538
+ # return symmetry value
539
+ if issymm:
540
+ return MMFile.SYMMETRY_SYMMETRIC
541
+ if isskew:
542
+ return MMFile.SYMMETRY_SKEW_SYMMETRIC
543
+ if isherm:
544
+ return MMFile.SYMMETRY_HERMITIAN
545
+ return MMFile.SYMMETRY_GENERAL
546
+
547
+ # -------------------------------------------------------------------------
548
+ @staticmethod
549
+ def _field_template(field, precision):
550
+ return {MMFile.FIELD_REAL: '%%.%ie\n' % precision,
551
+ MMFile.FIELD_INTEGER: '%i\n',
552
+ MMFile.FIELD_UNSIGNED: '%u\n',
553
+ MMFile.FIELD_COMPLEX: '%%.%ie %%.%ie\n' %
554
+ (precision, precision)
555
+ }.get(field, None)
556
+
557
+ # -------------------------------------------------------------------------
558
+ def __init__(self, **kwargs):
559
+ self._init_attrs(**kwargs)
560
+
561
+ # -------------------------------------------------------------------------
562
+ def read(self, source):
563
+ """
564
+ Reads the contents of a Matrix Market file-like 'source' into a matrix.
565
+
566
+ Parameters
567
+ ----------
568
+ source : str or file-like
569
+ Matrix Market filename (extensions .mtx, .mtz.gz)
570
+ or open file object.
571
+
572
+ Returns
573
+ -------
574
+ a : ndarray or coo_matrix
575
+ Dense or sparse matrix depending on the matrix format in the
576
+ Matrix Market file.
577
+ """
578
+ stream, close_it = self._open(source)
579
+
580
+ try:
581
+ self._parse_header(stream)
582
+ return self._parse_body(stream)
583
+
584
+ finally:
585
+ if close_it:
586
+ stream.close()
587
+
588
+ # -------------------------------------------------------------------------
589
+ def write(self, target, a, comment='', field=None, precision=None,
590
+ symmetry=None):
591
+ """
592
+ Writes sparse or dense array `a` to Matrix Market file-like `target`.
593
+
594
+ Parameters
595
+ ----------
596
+ target : str or file-like
597
+ Matrix Market filename (extension .mtx) or open file-like object.
598
+ a : array like
599
+ Sparse or dense 2-D array.
600
+ comment : str, optional
601
+ Comments to be prepended to the Matrix Market file.
602
+ field : None or str, optional
603
+ Either 'real', 'complex', 'pattern', or 'integer'.
604
+ precision : None or int, optional
605
+ Number of digits to display for real or complex values.
606
+ symmetry : None or str, optional
607
+ Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'.
608
+ If symmetry is None the symmetry type of 'a' is determined by its
609
+ values.
610
+ """
611
+
612
+ stream, close_it = self._open(target, 'wb')
613
+
614
+ try:
615
+ self._write(stream, a, comment, field, precision, symmetry)
616
+
617
+ finally:
618
+ if close_it:
619
+ stream.close()
620
+ else:
621
+ stream.flush()
622
+
623
+ # -------------------------------------------------------------------------
624
+ def _init_attrs(self, **kwargs):
625
+ """
626
+ Initialize each attributes with the corresponding keyword arg value
627
+ or a default of None
628
+ """
629
+
630
+ attrs = self.__class__.__slots__
631
+ public_attrs = [attr[1:] for attr in attrs]
632
+ invalid_keys = set(kwargs.keys()) - set(public_attrs)
633
+
634
+ if invalid_keys:
635
+ raise ValueError('''found {} invalid keyword arguments, please only
636
+ use {}'''.format(tuple(invalid_keys),
637
+ public_attrs))
638
+
639
+ for attr in attrs:
640
+ setattr(self, attr, kwargs.get(attr[1:], None))
641
+
642
+ # -------------------------------------------------------------------------
643
+ def _parse_header(self, stream):
644
+ rows, cols, entries, format, field, symmetry = \
645
+ self.__class__.info(stream)
646
+ self._init_attrs(rows=rows, cols=cols, entries=entries, format=format,
647
+ field=field, symmetry=symmetry)
648
+
649
+ # -------------------------------------------------------------------------
650
+ def _parse_body(self, stream):
651
+ rows, cols, entries, format, field, symm = (self.rows, self.cols,
652
+ self.entries, self.format,
653
+ self.field, self.symmetry)
654
+
655
+ dtype = self.DTYPES_BY_FIELD.get(field, None)
656
+
657
+ has_symmetry = self.has_symmetry
658
+ is_integer = field == self.FIELD_INTEGER
659
+ is_unsigned_integer = field == self.FIELD_UNSIGNED
660
+ is_complex = field == self.FIELD_COMPLEX
661
+ is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC
662
+ is_herm = symm == self.SYMMETRY_HERMITIAN
663
+ is_pattern = field == self.FIELD_PATTERN
664
+
665
+ if format == self.FORMAT_ARRAY:
666
+ a = zeros((rows, cols), dtype=dtype)
667
+ line = 1
668
+ i, j = 0, 0
669
+ if is_skew:
670
+ a[i, j] = 0
671
+ if i < rows - 1:
672
+ i += 1
673
+ while line:
674
+ line = stream.readline()
675
+ # line.startswith('%')
676
+ if not line or line[0] in ['%', 37] or not line.strip():
677
+ continue
678
+ if is_integer:
679
+ aij = int(line)
680
+ elif is_unsigned_integer:
681
+ aij = int(line)
682
+ elif is_complex:
683
+ aij = complex(*map(float, line.split()))
684
+ else:
685
+ aij = float(line)
686
+ a[i, j] = aij
687
+ if has_symmetry and i != j:
688
+ if is_skew:
689
+ a[j, i] = -aij
690
+ elif is_herm:
691
+ a[j, i] = conj(aij)
692
+ else:
693
+ a[j, i] = aij
694
+ if i < rows-1:
695
+ i = i + 1
696
+ else:
697
+ j = j + 1
698
+ if not has_symmetry:
699
+ i = 0
700
+ else:
701
+ i = j
702
+ if is_skew:
703
+ a[i, j] = 0
704
+ if i < rows-1:
705
+ i += 1
706
+
707
+ if is_skew:
708
+ if not (i in [0, j] and j == cols - 1):
709
+ raise ValueError("Parse error, did not read all lines.")
710
+ else:
711
+ if not (i in [0, j] and j == cols):
712
+ raise ValueError("Parse error, did not read all lines.")
713
+
714
+ elif format == self.FORMAT_COORDINATE:
715
+ # Read sparse COOrdinate format
716
+
717
+ if entries == 0:
718
+ # empty matrix
719
+ return coo_matrix((rows, cols), dtype=dtype)
720
+
721
+ I = zeros(entries, dtype='intc')
722
+ J = zeros(entries, dtype='intc')
723
+ if is_pattern:
724
+ V = ones(entries, dtype='int8')
725
+ elif is_integer:
726
+ V = zeros(entries, dtype='intp')
727
+ elif is_unsigned_integer:
728
+ V = zeros(entries, dtype='uint64')
729
+ elif is_complex:
730
+ V = zeros(entries, dtype='complex')
731
+ else:
732
+ V = zeros(entries, dtype='float')
733
+
734
+ entry_number = 0
735
+ for line in stream:
736
+ # line.startswith('%')
737
+ if not line or line[0] in ['%', 37] or not line.strip():
738
+ continue
739
+
740
+ if entry_number+1 > entries:
741
+ raise ValueError("'entries' in header is smaller than "
742
+ "number of entries")
743
+ l = line.split()
744
+ I[entry_number], J[entry_number] = map(int, l[:2])
745
+
746
+ if not is_pattern:
747
+ if is_integer:
748
+ V[entry_number] = int(l[2])
749
+ elif is_unsigned_integer:
750
+ V[entry_number] = int(l[2])
751
+ elif is_complex:
752
+ V[entry_number] = complex(*map(float, l[2:]))
753
+ else:
754
+ V[entry_number] = float(l[2])
755
+ entry_number += 1
756
+ if entry_number < entries:
757
+ raise ValueError("'entries' in header is larger than "
758
+ "number of entries")
759
+
760
+ I -= 1 # adjust indices (base 1 -> base 0)
761
+ J -= 1
762
+
763
+ if has_symmetry:
764
+ mask = (I != J) # off diagonal mask
765
+ od_I = I[mask]
766
+ od_J = J[mask]
767
+ od_V = V[mask]
768
+
769
+ I = concatenate((I, od_J))
770
+ J = concatenate((J, od_I))
771
+
772
+ if is_skew:
773
+ od_V *= -1
774
+ elif is_herm:
775
+ od_V = od_V.conjugate()
776
+
777
+ V = concatenate((V, od_V))
778
+
779
+ a = coo_matrix((V, (I, J)), shape=(rows, cols), dtype=dtype)
780
+ else:
781
+ raise NotImplementedError(format)
782
+
783
+ return a
784
+
785
+ # ------------------------------------------------------------------------
786
+ def _write(self, stream, a, comment='', field=None, precision=None,
787
+ symmetry=None):
788
+ if isinstance(a, list) or isinstance(a, ndarray) or \
789
+ isinstance(a, tuple) or hasattr(a, '__array__'):
790
+ rep = self.FORMAT_ARRAY
791
+ a = asarray(a)
792
+ if len(a.shape) != 2:
793
+ raise ValueError('Expected 2 dimensional array')
794
+ rows, cols = a.shape
795
+
796
+ if field is not None:
797
+
798
+ if field == self.FIELD_INTEGER:
799
+ if not can_cast(a.dtype, 'intp'):
800
+ raise OverflowError("mmwrite does not support integer "
801
+ "dtypes larger than native 'intp'.")
802
+ a = a.astype('intp')
803
+ elif field == self.FIELD_REAL:
804
+ if a.dtype.char not in 'fd':
805
+ a = a.astype('d')
806
+ elif field == self.FIELD_COMPLEX:
807
+ if a.dtype.char not in 'FD':
808
+ a = a.astype('D')
809
+
810
+ else:
811
+ if not issparse(a):
812
+ raise ValueError('unknown matrix type: %s' % type(a))
813
+
814
+ rep = 'coordinate'
815
+ rows, cols = a.shape
816
+
817
+ typecode = a.dtype.char
818
+
819
+ if precision is None:
820
+ if typecode in 'fF':
821
+ precision = 8
822
+ else:
823
+ precision = 16
824
+ if field is None:
825
+ kind = a.dtype.kind
826
+ if kind == 'i':
827
+ if not can_cast(a.dtype, 'intp'):
828
+ raise OverflowError("mmwrite does not support integer "
829
+ "dtypes larger than native 'intp'.")
830
+ field = 'integer'
831
+ elif kind == 'f':
832
+ field = 'real'
833
+ elif kind == 'c':
834
+ field = 'complex'
835
+ elif kind == 'u':
836
+ field = 'unsigned-integer'
837
+ else:
838
+ raise TypeError('unexpected dtype kind ' + kind)
839
+
840
+ if symmetry is None:
841
+ symmetry = self._get_symmetry(a)
842
+
843
+ # validate rep, field, and symmetry
844
+ self.__class__._validate_format(rep)
845
+ self.__class__._validate_field(field)
846
+ self.__class__._validate_symmetry(symmetry)
847
+
848
+ # write initial header line
849
+ data = f'%%MatrixMarket matrix {rep} {field} {symmetry}\n'
850
+ stream.write(data.encode('latin1'))
851
+
852
+ # write comments
853
+ for line in comment.split('\n'):
854
+ data = '%%%s\n' % (line)
855
+ stream.write(data.encode('latin1'))
856
+
857
+ template = self._field_template(field, precision)
858
+ # write dense format
859
+ if rep == self.FORMAT_ARRAY:
860
+ # write shape spec
861
+ data = '%i %i\n' % (rows, cols)
862
+ stream.write(data.encode('latin1'))
863
+
864
+ if field in (self.FIELD_INTEGER, self.FIELD_REAL,
865
+ self.FIELD_UNSIGNED):
866
+ if symmetry == self.SYMMETRY_GENERAL:
867
+ for j in range(cols):
868
+ for i in range(rows):
869
+ data = template % a[i, j]
870
+ stream.write(data.encode('latin1'))
871
+
872
+ elif symmetry == self.SYMMETRY_SKEW_SYMMETRIC:
873
+ for j in range(cols):
874
+ for i in range(j + 1, rows):
875
+ data = template % a[i, j]
876
+ stream.write(data.encode('latin1'))
877
+
878
+ else:
879
+ for j in range(cols):
880
+ for i in range(j, rows):
881
+ data = template % a[i, j]
882
+ stream.write(data.encode('latin1'))
883
+
884
+ elif field == self.FIELD_COMPLEX:
885
+
886
+ if symmetry == self.SYMMETRY_GENERAL:
887
+ for j in range(cols):
888
+ for i in range(rows):
889
+ aij = a[i, j]
890
+ data = template % (real(aij), imag(aij))
891
+ stream.write(data.encode('latin1'))
892
+ else:
893
+ for j in range(cols):
894
+ for i in range(j, rows):
895
+ aij = a[i, j]
896
+ data = template % (real(aij), imag(aij))
897
+ stream.write(data.encode('latin1'))
898
+
899
+ elif field == self.FIELD_PATTERN:
900
+ raise ValueError('pattern type inconsisted with dense format')
901
+
902
+ else:
903
+ raise TypeError('Unknown field type %s' % field)
904
+
905
+ # write sparse format
906
+ else:
907
+ coo = a.tocoo() # convert to COOrdinate format
908
+
909
+ # if symmetry format used, remove values above main diagonal
910
+ if symmetry != self.SYMMETRY_GENERAL:
911
+ lower_triangle_mask = coo.row >= coo.col
912
+ coo = coo_matrix((coo.data[lower_triangle_mask],
913
+ (coo.row[lower_triangle_mask],
914
+ coo.col[lower_triangle_mask])),
915
+ shape=coo.shape)
916
+
917
+ # write shape spec
918
+ data = '%i %i %i\n' % (rows, cols, coo.nnz)
919
+ stream.write(data.encode('latin1'))
920
+
921
+ template = self._field_template(field, precision-1)
922
+
923
+ if field == self.FIELD_PATTERN:
924
+ for r, c in zip(coo.row+1, coo.col+1):
925
+ data = "%i %i\n" % (r, c)
926
+ stream.write(data.encode('latin1'))
927
+ elif field in (self.FIELD_INTEGER, self.FIELD_REAL,
928
+ self.FIELD_UNSIGNED):
929
+ for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
930
+ data = ("%i %i " % (r, c)) + (template % d)
931
+ stream.write(data.encode('latin1'))
932
+ elif field == self.FIELD_COMPLEX:
933
+ for r, c, d in zip(coo.row+1, coo.col+1, coo.data):
934
+ data = ("%i %i " % (r, c)) + (template % (d.real, d.imag))
935
+ stream.write(data.encode('latin1'))
936
+ else:
937
+ raise TypeError('Unknown field type %s' % field)
938
+
939
+
940
+ def _is_fromfile_compatible(stream):
941
+ """
942
+ Check whether `stream` is compatible with numpy.fromfile.
943
+
944
+ Passing a gzipped file object to ``fromfile/fromstring`` doesn't work with
945
+ Python 3.
946
+ """
947
+
948
+ bad_cls = []
949
+ try:
950
+ import gzip
951
+ bad_cls.append(gzip.GzipFile)
952
+ except ImportError:
953
+ pass
954
+ try:
955
+ import bz2
956
+ bad_cls.append(bz2.BZ2File)
957
+ except ImportError:
958
+ pass
959
+
960
+ bad_cls = tuple(bad_cls)
961
+ return not isinstance(stream, bad_cls)
venv/lib/python3.10/site-packages/scipy/io/harwell_boeing.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.io` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'MalformedHeader', 'hb_read', 'hb_write', 'HBInfo',
9
+ 'HBFile', 'HBMatrixType', 'FortranFormatParser', 'IntFormat',
10
+ 'ExpFormat', 'BadFortranFormat', 'hb'
11
+ ]
12
+
13
+
14
+ def __dir__():
15
+ return __all__
16
+
17
+
18
+ def __getattr__(name):
19
+ return _sub_module_deprecation(sub_package="io", module="harwell_boeing",
20
+ private_modules=["_harwell_boeing"], all=__all__,
21
+ attribute=name)
venv/lib/python3.10/site-packages/scipy/io/idl.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` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'readsav', 'DTYPE_DICT', 'RECTYPE_DICT', 'STRUCT_DICT',
9
+ 'Pointer', 'ObjectPointer', 'AttrDict'
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ return _sub_module_deprecation(sub_package="io", module="idl",
19
+ private_modules=["_idl"], all=__all__,
20
+ attribute=name)
venv/lib/python3.10/site-packages/scipy/io/mmio.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` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'mminfo', 'mmread', 'mmwrite', 'MMFile',
9
+ 'coo_matrix', 'asstr'
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ return _sub_module_deprecation(sub_package="io", module="mmio",
19
+ private_modules=["_mmio"], all=__all__,
20
+ attribute=name)
venv/lib/python3.10/site-packages/scipy/io/netcdf.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.io` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'netcdf_file', 'netcdf_variable',
9
+ 'array', 'LITTLE_ENDIAN', 'IS_PYPY', 'ABSENT', 'ZERO',
10
+ 'NC_BYTE', 'NC_CHAR', 'NC_SHORT', 'NC_INT', 'NC_FLOAT',
11
+ 'NC_DOUBLE', 'NC_DIMENSION', 'NC_VARIABLE', 'NC_ATTRIBUTE',
12
+ 'FILL_BYTE', 'FILL_CHAR', 'FILL_SHORT', 'FILL_INT', 'FILL_FLOAT',
13
+ 'FILL_DOUBLE', 'TYPEMAP', 'FILLMAP', 'REVERSE', 'NetCDFFile',
14
+ 'NetCDFVariable'
15
+ ]
16
+
17
+
18
+ def __dir__():
19
+ return __all__
20
+
21
+
22
+ def __getattr__(name):
23
+ return _sub_module_deprecation(sub_package="io", module="netcdf",
24
+ private_modules=["_netcdf"], all=__all__,
25
+ attribute=name)
venv/lib/python3.10/site-packages/scipy/io/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/scipy/io/tests/data/Transparent Busy.ani ADDED
Binary file (4.36 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav ADDED
Binary file (2.63 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_2d.sav ADDED
Binary file (3.19 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav ADDED
Binary file (13.8 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_4d.sav ADDED
Binary file (6.62 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav ADDED
Binary file (7.9 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_6d.sav ADDED
Binary file (19.4 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_7d.sav ADDED
Binary file (3.29 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_8d.sav ADDED
Binary file (13.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav ADDED
Binary file (2.69 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav ADDED
Binary file (3.26 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav ADDED
Binary file (6.68 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav ADDED
Binary file (7.96 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav ADDED
Binary file (19.5 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav ADDED
Binary file (3.35 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav ADDED
Binary file (13.7 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/example_1.nc ADDED
Binary file (1.74 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/example_2.nc ADDED
Binary file (272 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc ADDED
Binary file (1.42 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat ADDED
Binary file (451 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat ADDED
Binary file (40 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat ADDED
Binary file (888 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat ADDED
Binary file (26.4 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat ADDED
Binary file (16 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat ADDED
Binary file (48 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat ADDED
Binary file (64 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat ADDED
Binary file (128 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat ADDED
Binary file (448 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat ADDED
Binary file (13.2 kB). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat ADDED
Binary file (12 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat ADDED
Binary file (28 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat ADDED
Binary file (36 Bytes). View file