Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- parrot/lib/python3.10/site-packages/numpy/random/tests/data/generator_pcg64_np121.pkl.gz +3 -0
- parrot/lib/python3.10/site-packages/scipy/io/__init__.py +116 -0
- parrot/lib/python3.10/site-packages/scipy/io/_fortran.py +354 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__init__.py +7 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__pycache__/_fortran_format_parser.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__pycache__/hb.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py +309 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py +574 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py +74 -0
- parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py +65 -0
- parrot/lib/python3.10/site-packages/scipy/io/_idl.py +918 -0
- parrot/lib/python3.10/site-packages/scipy/io/_mmio.py +961 -0
- parrot/lib/python3.10/site-packages/scipy/io/_test_fortran.cpython-310-x86_64-linux-gnu.so +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/idl.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/io/mmio.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/io/netcdf.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav +0 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/test_fortran.py +236 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/test_idl.py +481 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/test_mmio.py +803 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/test_netcdf.py +546 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/test_paths.py +93 -0
- parrot/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py +457 -0
- parrot/lib/python3.10/site-packages/scipy/io/wavfile.py +891 -0
- parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc +0 -0
parrot/lib/python3.10/site-packages/numpy/random/tests/data/generator_pcg64_np121.pkl.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:11f43e5fbd0a9078010055f6a483dc09497830d3f564d44e697394ef9bdd8aa3
|
| 3 |
+
size 203
|
parrot/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
|
parrot/lib/python3.10/site-packages/scipy/io/_fortran.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .hb import hb_read, hb_write
|
| 2 |
+
|
| 3 |
+
__all__ = ["hb_read", "hb_write"]
|
| 4 |
+
|
| 5 |
+
from scipy._lib._testutils import PytestTester
|
| 6 |
+
test = PytestTester(__name__)
|
| 7 |
+
del PytestTester
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (351 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__pycache__/_fortran_format_parser.cpython-310.pyc
ADDED
|
Binary file (8.9 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__pycache__/hb.cpython-310.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py
ADDED
|
@@ -0,0 +1,309 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Preliminary module to handle Fortran formats for IO. Does not use this outside
|
| 3 |
+
scipy.sparse io for now, until the API is deemed reasonable.
|
| 4 |
+
|
| 5 |
+
The *Format classes handle conversion between Fortran and Python format, and
|
| 6 |
+
FortranFormatParser can create *Format instances from raw Fortran format
|
| 7 |
+
strings (e.g. '(3I4)', '(10I3)', etc...)
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["BadFortranFormat", "FortranFormatParser", "IntFormat", "ExpFormat"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
TOKENS = {
|
| 18 |
+
"LPAR": r"\(",
|
| 19 |
+
"RPAR": r"\)",
|
| 20 |
+
"INT_ID": r"I",
|
| 21 |
+
"EXP_ID": r"E",
|
| 22 |
+
"INT": r"\d+",
|
| 23 |
+
"DOT": r"\.",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BadFortranFormat(SyntaxError):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def number_digits(n):
|
| 32 |
+
return int(np.floor(np.log10(np.abs(n))) + 1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class IntFormat:
|
| 36 |
+
@classmethod
|
| 37 |
+
def from_number(cls, n, min=None):
|
| 38 |
+
"""Given an integer, returns a "reasonable" IntFormat instance to represent
|
| 39 |
+
any number between 0 and n if n > 0, -n and n if n < 0
|
| 40 |
+
|
| 41 |
+
Parameters
|
| 42 |
+
----------
|
| 43 |
+
n : int
|
| 44 |
+
max number one wants to be able to represent
|
| 45 |
+
min : int
|
| 46 |
+
minimum number of characters to use for the format
|
| 47 |
+
|
| 48 |
+
Returns
|
| 49 |
+
-------
|
| 50 |
+
res : IntFormat
|
| 51 |
+
IntFormat instance with reasonable (see Notes) computed width
|
| 52 |
+
|
| 53 |
+
Notes
|
| 54 |
+
-----
|
| 55 |
+
Reasonable should be understood as the minimal string length necessary
|
| 56 |
+
without losing precision. For example, IntFormat.from_number(1) will
|
| 57 |
+
return an IntFormat instance of width 2, so that any 0 and 1 may be
|
| 58 |
+
represented as 1-character strings without loss of information.
|
| 59 |
+
"""
|
| 60 |
+
width = number_digits(n) + 1
|
| 61 |
+
if n < 0:
|
| 62 |
+
width += 1
|
| 63 |
+
repeat = 80 // width
|
| 64 |
+
return cls(width, min, repeat=repeat)
|
| 65 |
+
|
| 66 |
+
def __init__(self, width, min=None, repeat=None):
|
| 67 |
+
self.width = width
|
| 68 |
+
self.repeat = repeat
|
| 69 |
+
self.min = min
|
| 70 |
+
|
| 71 |
+
def __repr__(self):
|
| 72 |
+
r = "IntFormat("
|
| 73 |
+
if self.repeat:
|
| 74 |
+
r += "%d" % self.repeat
|
| 75 |
+
r += "I%d" % self.width
|
| 76 |
+
if self.min:
|
| 77 |
+
r += ".%d" % self.min
|
| 78 |
+
return r + ")"
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def fortran_format(self):
|
| 82 |
+
r = "("
|
| 83 |
+
if self.repeat:
|
| 84 |
+
r += "%d" % self.repeat
|
| 85 |
+
r += "I%d" % self.width
|
| 86 |
+
if self.min:
|
| 87 |
+
r += ".%d" % self.min
|
| 88 |
+
return r + ")"
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def python_format(self):
|
| 92 |
+
return "%" + str(self.width) + "d"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ExpFormat:
|
| 96 |
+
@classmethod
|
| 97 |
+
def from_number(cls, n, min=None):
|
| 98 |
+
"""Given a float number, returns a "reasonable" ExpFormat instance to
|
| 99 |
+
represent any number between -n and n.
|
| 100 |
+
|
| 101 |
+
Parameters
|
| 102 |
+
----------
|
| 103 |
+
n : float
|
| 104 |
+
max number one wants to be able to represent
|
| 105 |
+
min : int
|
| 106 |
+
minimum number of characters to use for the format
|
| 107 |
+
|
| 108 |
+
Returns
|
| 109 |
+
-------
|
| 110 |
+
res : ExpFormat
|
| 111 |
+
ExpFormat instance with reasonable (see Notes) computed width
|
| 112 |
+
|
| 113 |
+
Notes
|
| 114 |
+
-----
|
| 115 |
+
Reasonable should be understood as the minimal string length necessary
|
| 116 |
+
to avoid losing precision.
|
| 117 |
+
"""
|
| 118 |
+
# len of one number in exp format: sign + 1|0 + "." +
|
| 119 |
+
# number of digit for fractional part + 'E' + sign of exponent +
|
| 120 |
+
# len of exponent
|
| 121 |
+
finfo = np.finfo(n.dtype)
|
| 122 |
+
# Number of digits for fractional part
|
| 123 |
+
n_prec = finfo.precision + 1
|
| 124 |
+
# Number of digits for exponential part
|
| 125 |
+
n_exp = number_digits(np.max(np.abs([finfo.maxexp, finfo.minexp])))
|
| 126 |
+
width = 1 + 1 + n_prec + 1 + n_exp + 1
|
| 127 |
+
if n < 0:
|
| 128 |
+
width += 1
|
| 129 |
+
repeat = int(np.floor(80 / width))
|
| 130 |
+
return cls(width, n_prec, min, repeat=repeat)
|
| 131 |
+
|
| 132 |
+
def __init__(self, width, significand, min=None, repeat=None):
|
| 133 |
+
"""\
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
width : int
|
| 137 |
+
number of characters taken by the string (includes space).
|
| 138 |
+
"""
|
| 139 |
+
self.width = width
|
| 140 |
+
self.significand = significand
|
| 141 |
+
self.repeat = repeat
|
| 142 |
+
self.min = min
|
| 143 |
+
|
| 144 |
+
def __repr__(self):
|
| 145 |
+
r = "ExpFormat("
|
| 146 |
+
if self.repeat:
|
| 147 |
+
r += "%d" % self.repeat
|
| 148 |
+
r += "E%d.%d" % (self.width, self.significand)
|
| 149 |
+
if self.min:
|
| 150 |
+
r += "E%d" % self.min
|
| 151 |
+
return r + ")"
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def fortran_format(self):
|
| 155 |
+
r = "("
|
| 156 |
+
if self.repeat:
|
| 157 |
+
r += "%d" % self.repeat
|
| 158 |
+
r += "E%d.%d" % (self.width, self.significand)
|
| 159 |
+
if self.min:
|
| 160 |
+
r += "E%d" % self.min
|
| 161 |
+
return r + ")"
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def python_format(self):
|
| 165 |
+
return "%" + str(self.width-1) + "." + str(self.significand) + "E"
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Token:
|
| 169 |
+
def __init__(self, type, value, pos):
|
| 170 |
+
self.type = type
|
| 171 |
+
self.value = value
|
| 172 |
+
self.pos = pos
|
| 173 |
+
|
| 174 |
+
def __str__(self):
|
| 175 |
+
return f"""Token('{self.type}', "{self.value}")"""
|
| 176 |
+
|
| 177 |
+
def __repr__(self):
|
| 178 |
+
return self.__str__()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class Tokenizer:
|
| 182 |
+
def __init__(self):
|
| 183 |
+
self.tokens = list(TOKENS.keys())
|
| 184 |
+
self.res = [re.compile(TOKENS[i]) for i in self.tokens]
|
| 185 |
+
|
| 186 |
+
def input(self, s):
|
| 187 |
+
self.data = s
|
| 188 |
+
self.curpos = 0
|
| 189 |
+
self.len = len(s)
|
| 190 |
+
|
| 191 |
+
def next_token(self):
|
| 192 |
+
curpos = self.curpos
|
| 193 |
+
|
| 194 |
+
while curpos < self.len:
|
| 195 |
+
for i, r in enumerate(self.res):
|
| 196 |
+
m = r.match(self.data, curpos)
|
| 197 |
+
if m is None:
|
| 198 |
+
continue
|
| 199 |
+
else:
|
| 200 |
+
self.curpos = m.end()
|
| 201 |
+
return Token(self.tokens[i], m.group(), self.curpos)
|
| 202 |
+
raise SyntaxError("Unknown character at position %d (%s)"
|
| 203 |
+
% (self.curpos, self.data[curpos]))
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# Grammar for fortran format:
|
| 207 |
+
# format : LPAR format_string RPAR
|
| 208 |
+
# format_string : repeated | simple
|
| 209 |
+
# repeated : repeat simple
|
| 210 |
+
# simple : int_fmt | exp_fmt
|
| 211 |
+
# int_fmt : INT_ID width
|
| 212 |
+
# exp_fmt : simple_exp_fmt
|
| 213 |
+
# simple_exp_fmt : EXP_ID width DOT significand
|
| 214 |
+
# extended_exp_fmt : EXP_ID width DOT significand EXP_ID ndigits
|
| 215 |
+
# repeat : INT
|
| 216 |
+
# width : INT
|
| 217 |
+
# significand : INT
|
| 218 |
+
# ndigits : INT
|
| 219 |
+
|
| 220 |
+
# Naive fortran formatter - parser is hand-made
|
| 221 |
+
class FortranFormatParser:
|
| 222 |
+
"""Parser for Fortran format strings. The parse method returns a *Format
|
| 223 |
+
instance.
|
| 224 |
+
|
| 225 |
+
Notes
|
| 226 |
+
-----
|
| 227 |
+
Only ExpFormat (exponential format for floating values) and IntFormat
|
| 228 |
+
(integer format) for now.
|
| 229 |
+
"""
|
| 230 |
+
def __init__(self):
|
| 231 |
+
self.tokenizer = Tokenizer()
|
| 232 |
+
|
| 233 |
+
def parse(self, s):
|
| 234 |
+
self.tokenizer.input(s)
|
| 235 |
+
|
| 236 |
+
tokens = []
|
| 237 |
+
|
| 238 |
+
try:
|
| 239 |
+
while True:
|
| 240 |
+
t = self.tokenizer.next_token()
|
| 241 |
+
if t is None:
|
| 242 |
+
break
|
| 243 |
+
else:
|
| 244 |
+
tokens.append(t)
|
| 245 |
+
return self._parse_format(tokens)
|
| 246 |
+
except SyntaxError as e:
|
| 247 |
+
raise BadFortranFormat(str(e)) from e
|
| 248 |
+
|
| 249 |
+
def _get_min(self, tokens):
|
| 250 |
+
next = tokens.pop(0)
|
| 251 |
+
if not next.type == "DOT":
|
| 252 |
+
raise SyntaxError()
|
| 253 |
+
next = tokens.pop(0)
|
| 254 |
+
return next.value
|
| 255 |
+
|
| 256 |
+
def _expect(self, token, tp):
|
| 257 |
+
if not token.type == tp:
|
| 258 |
+
raise SyntaxError()
|
| 259 |
+
|
| 260 |
+
def _parse_format(self, tokens):
|
| 261 |
+
if not tokens[0].type == "LPAR":
|
| 262 |
+
raise SyntaxError("Expected left parenthesis at position "
|
| 263 |
+
"%d (got '%s')" % (0, tokens[0].value))
|
| 264 |
+
elif not tokens[-1].type == "RPAR":
|
| 265 |
+
raise SyntaxError("Expected right parenthesis at position "
|
| 266 |
+
"%d (got '%s')" % (len(tokens), tokens[-1].value))
|
| 267 |
+
|
| 268 |
+
tokens = tokens[1:-1]
|
| 269 |
+
types = [t.type for t in tokens]
|
| 270 |
+
if types[0] == "INT":
|
| 271 |
+
repeat = int(tokens.pop(0).value)
|
| 272 |
+
else:
|
| 273 |
+
repeat = None
|
| 274 |
+
|
| 275 |
+
next = tokens.pop(0)
|
| 276 |
+
if next.type == "INT_ID":
|
| 277 |
+
next = self._next(tokens, "INT")
|
| 278 |
+
width = int(next.value)
|
| 279 |
+
if tokens:
|
| 280 |
+
min = int(self._get_min(tokens))
|
| 281 |
+
else:
|
| 282 |
+
min = None
|
| 283 |
+
return IntFormat(width, min, repeat)
|
| 284 |
+
elif next.type == "EXP_ID":
|
| 285 |
+
next = self._next(tokens, "INT")
|
| 286 |
+
width = int(next.value)
|
| 287 |
+
|
| 288 |
+
next = self._next(tokens, "DOT")
|
| 289 |
+
|
| 290 |
+
next = self._next(tokens, "INT")
|
| 291 |
+
significand = int(next.value)
|
| 292 |
+
|
| 293 |
+
if tokens:
|
| 294 |
+
next = self._next(tokens, "EXP_ID")
|
| 295 |
+
|
| 296 |
+
next = self._next(tokens, "INT")
|
| 297 |
+
min = int(next.value)
|
| 298 |
+
else:
|
| 299 |
+
min = None
|
| 300 |
+
return ExpFormat(width, significand, min, repeat)
|
| 301 |
+
else:
|
| 302 |
+
raise SyntaxError("Invalid formatter type %s" % next.value)
|
| 303 |
+
|
| 304 |
+
def _next(self, tokens, tp):
|
| 305 |
+
if not len(tokens) > 0:
|
| 306 |
+
raise SyntaxError()
|
| 307 |
+
next = tokens.pop(0)
|
| 308 |
+
self._expect(next, tp)
|
| 309 |
+
return next
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Implementation of Harwell-Boeing read/write.
|
| 3 |
+
|
| 4 |
+
At the moment not the full Harwell-Boeing format is supported. Supported
|
| 5 |
+
features are:
|
| 6 |
+
|
| 7 |
+
- assembled, non-symmetric, real matrices
|
| 8 |
+
- integer for pointer/indices
|
| 9 |
+
- exponential format for float values, and int format
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
# TODO:
|
| 13 |
+
# - Add more support (symmetric/complex matrices, non-assembled matrices ?)
|
| 14 |
+
|
| 15 |
+
# XXX: reading is reasonably efficient (>= 85 % is in numpy.fromstring), but
|
| 16 |
+
# takes a lot of memory. Being faster would require compiled code.
|
| 17 |
+
# write is not efficient. Although not a terribly exciting task,
|
| 18 |
+
# having reusable facilities to efficiently read/write fortran-formatted files
|
| 19 |
+
# would be useful outside this module.
|
| 20 |
+
|
| 21 |
+
import warnings
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
from scipy.sparse import csc_matrix
|
| 25 |
+
from ._fortran_format_parser import FortranFormatParser, IntFormat, ExpFormat
|
| 26 |
+
|
| 27 |
+
__all__ = ["hb_read", "hb_write"]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MalformedHeader(Exception):
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LineOverflow(Warning):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _nbytes_full(fmt, nlines):
|
| 39 |
+
"""Return the number of bytes to read to get every full lines for the
|
| 40 |
+
given parsed fortran format."""
|
| 41 |
+
return (fmt.repeat * fmt.width + 1) * (nlines - 1)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class HBInfo:
|
| 45 |
+
@classmethod
|
| 46 |
+
def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None):
|
| 47 |
+
"""Create a HBInfo instance from an existing sparse matrix.
|
| 48 |
+
|
| 49 |
+
Parameters
|
| 50 |
+
----------
|
| 51 |
+
m : sparse matrix
|
| 52 |
+
the HBInfo instance will derive its parameters from m
|
| 53 |
+
title : str
|
| 54 |
+
Title to put in the HB header
|
| 55 |
+
key : str
|
| 56 |
+
Key
|
| 57 |
+
mxtype : HBMatrixType
|
| 58 |
+
type of the input matrix
|
| 59 |
+
fmt : dict
|
| 60 |
+
not implemented
|
| 61 |
+
|
| 62 |
+
Returns
|
| 63 |
+
-------
|
| 64 |
+
hb_info : HBInfo instance
|
| 65 |
+
"""
|
| 66 |
+
m = m.tocsc(copy=False)
|
| 67 |
+
|
| 68 |
+
pointer = m.indptr
|
| 69 |
+
indices = m.indices
|
| 70 |
+
values = m.data
|
| 71 |
+
|
| 72 |
+
nrows, ncols = m.shape
|
| 73 |
+
nnon_zeros = m.nnz
|
| 74 |
+
|
| 75 |
+
if fmt is None:
|
| 76 |
+
# +1 because HB use one-based indexing (Fortran), and we will write
|
| 77 |
+
# the indices /pointer as such
|
| 78 |
+
pointer_fmt = IntFormat.from_number(np.max(pointer+1))
|
| 79 |
+
indices_fmt = IntFormat.from_number(np.max(indices+1))
|
| 80 |
+
|
| 81 |
+
if values.dtype.kind in np.typecodes["AllFloat"]:
|
| 82 |
+
values_fmt = ExpFormat.from_number(-np.max(np.abs(values)))
|
| 83 |
+
elif values.dtype.kind in np.typecodes["AllInteger"]:
|
| 84 |
+
values_fmt = IntFormat.from_number(-np.max(np.abs(values)))
|
| 85 |
+
else:
|
| 86 |
+
message = f"type {values.dtype.kind} not implemented yet"
|
| 87 |
+
raise NotImplementedError(message)
|
| 88 |
+
else:
|
| 89 |
+
raise NotImplementedError("fmt argument not supported yet.")
|
| 90 |
+
|
| 91 |
+
if mxtype is None:
|
| 92 |
+
if not np.isrealobj(values):
|
| 93 |
+
raise ValueError("Complex values not supported yet")
|
| 94 |
+
if values.dtype.kind in np.typecodes["AllInteger"]:
|
| 95 |
+
tp = "integer"
|
| 96 |
+
elif values.dtype.kind in np.typecodes["AllFloat"]:
|
| 97 |
+
tp = "real"
|
| 98 |
+
else:
|
| 99 |
+
raise NotImplementedError("type %s for values not implemented"
|
| 100 |
+
% values.dtype)
|
| 101 |
+
mxtype = HBMatrixType(tp, "unsymmetric", "assembled")
|
| 102 |
+
else:
|
| 103 |
+
raise ValueError("mxtype argument not handled yet.")
|
| 104 |
+
|
| 105 |
+
def _nlines(fmt, size):
|
| 106 |
+
nlines = size // fmt.repeat
|
| 107 |
+
if nlines * fmt.repeat != size:
|
| 108 |
+
nlines += 1
|
| 109 |
+
return nlines
|
| 110 |
+
|
| 111 |
+
pointer_nlines = _nlines(pointer_fmt, pointer.size)
|
| 112 |
+
indices_nlines = _nlines(indices_fmt, indices.size)
|
| 113 |
+
values_nlines = _nlines(values_fmt, values.size)
|
| 114 |
+
|
| 115 |
+
total_nlines = pointer_nlines + indices_nlines + values_nlines
|
| 116 |
+
|
| 117 |
+
return cls(title, key,
|
| 118 |
+
total_nlines, pointer_nlines, indices_nlines, values_nlines,
|
| 119 |
+
mxtype, nrows, ncols, nnon_zeros,
|
| 120 |
+
pointer_fmt.fortran_format, indices_fmt.fortran_format,
|
| 121 |
+
values_fmt.fortran_format)
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def from_file(cls, fid):
|
| 125 |
+
"""Create a HBInfo instance from a file object containing a matrix in the
|
| 126 |
+
HB format.
|
| 127 |
+
|
| 128 |
+
Parameters
|
| 129 |
+
----------
|
| 130 |
+
fid : file-like matrix
|
| 131 |
+
File or file-like object containing a matrix in the HB format.
|
| 132 |
+
|
| 133 |
+
Returns
|
| 134 |
+
-------
|
| 135 |
+
hb_info : HBInfo instance
|
| 136 |
+
"""
|
| 137 |
+
# First line
|
| 138 |
+
line = fid.readline().strip("\n")
|
| 139 |
+
if not len(line) > 72:
|
| 140 |
+
raise ValueError("Expected at least 72 characters for first line, "
|
| 141 |
+
"got: \n%s" % line)
|
| 142 |
+
title = line[:72]
|
| 143 |
+
key = line[72:]
|
| 144 |
+
|
| 145 |
+
# Second line
|
| 146 |
+
line = fid.readline().strip("\n")
|
| 147 |
+
if not len(line.rstrip()) >= 56:
|
| 148 |
+
raise ValueError("Expected at least 56 characters for second line, "
|
| 149 |
+
"got: \n%s" % line)
|
| 150 |
+
total_nlines = _expect_int(line[:14])
|
| 151 |
+
pointer_nlines = _expect_int(line[14:28])
|
| 152 |
+
indices_nlines = _expect_int(line[28:42])
|
| 153 |
+
values_nlines = _expect_int(line[42:56])
|
| 154 |
+
|
| 155 |
+
rhs_nlines = line[56:72].strip()
|
| 156 |
+
if rhs_nlines == '':
|
| 157 |
+
rhs_nlines = 0
|
| 158 |
+
else:
|
| 159 |
+
rhs_nlines = _expect_int(rhs_nlines)
|
| 160 |
+
if not rhs_nlines == 0:
|
| 161 |
+
raise ValueError("Only files without right hand side supported for "
|
| 162 |
+
"now.")
|
| 163 |
+
|
| 164 |
+
# Third line
|
| 165 |
+
line = fid.readline().strip("\n")
|
| 166 |
+
if not len(line) >= 70:
|
| 167 |
+
raise ValueError("Expected at least 72 character for third line, got:\n"
|
| 168 |
+
"%s" % line)
|
| 169 |
+
|
| 170 |
+
mxtype_s = line[:3].upper()
|
| 171 |
+
if not len(mxtype_s) == 3:
|
| 172 |
+
raise ValueError("mxtype expected to be 3 characters long")
|
| 173 |
+
|
| 174 |
+
mxtype = HBMatrixType.from_fortran(mxtype_s)
|
| 175 |
+
if mxtype.value_type not in ["real", "integer"]:
|
| 176 |
+
raise ValueError("Only real or integer matrices supported for "
|
| 177 |
+
"now (detected %s)" % mxtype)
|
| 178 |
+
if not mxtype.structure == "unsymmetric":
|
| 179 |
+
raise ValueError("Only unsymmetric matrices supported for "
|
| 180 |
+
"now (detected %s)" % mxtype)
|
| 181 |
+
if not mxtype.storage == "assembled":
|
| 182 |
+
raise ValueError("Only assembled matrices supported for now")
|
| 183 |
+
|
| 184 |
+
if not line[3:14] == " " * 11:
|
| 185 |
+
raise ValueError("Malformed data for third line: %s" % line)
|
| 186 |
+
|
| 187 |
+
nrows = _expect_int(line[14:28])
|
| 188 |
+
ncols = _expect_int(line[28:42])
|
| 189 |
+
nnon_zeros = _expect_int(line[42:56])
|
| 190 |
+
nelementals = _expect_int(line[56:70])
|
| 191 |
+
if not nelementals == 0:
|
| 192 |
+
raise ValueError("Unexpected value %d for nltvl (last entry of line 3)"
|
| 193 |
+
% nelementals)
|
| 194 |
+
|
| 195 |
+
# Fourth line
|
| 196 |
+
line = fid.readline().strip("\n")
|
| 197 |
+
|
| 198 |
+
ct = line.split()
|
| 199 |
+
if not len(ct) == 3:
|
| 200 |
+
raise ValueError("Expected 3 formats, got %s" % ct)
|
| 201 |
+
|
| 202 |
+
return cls(title, key,
|
| 203 |
+
total_nlines, pointer_nlines, indices_nlines, values_nlines,
|
| 204 |
+
mxtype, nrows, ncols, nnon_zeros,
|
| 205 |
+
ct[0], ct[1], ct[2],
|
| 206 |
+
rhs_nlines, nelementals)
|
| 207 |
+
|
| 208 |
+
def __init__(self, title, key,
|
| 209 |
+
total_nlines, pointer_nlines, indices_nlines, values_nlines,
|
| 210 |
+
mxtype, nrows, ncols, nnon_zeros,
|
| 211 |
+
pointer_format_str, indices_format_str, values_format_str,
|
| 212 |
+
right_hand_sides_nlines=0, nelementals=0):
|
| 213 |
+
"""Do not use this directly, but the class ctrs (from_* functions)."""
|
| 214 |
+
self.title = title
|
| 215 |
+
self.key = key
|
| 216 |
+
if title is None:
|
| 217 |
+
title = "No Title"
|
| 218 |
+
if len(title) > 72:
|
| 219 |
+
raise ValueError("title cannot be > 72 characters")
|
| 220 |
+
|
| 221 |
+
if key is None:
|
| 222 |
+
key = "|No Key"
|
| 223 |
+
if len(key) > 8:
|
| 224 |
+
warnings.warn("key is > 8 characters (key is %s)" % key,
|
| 225 |
+
LineOverflow, stacklevel=3)
|
| 226 |
+
|
| 227 |
+
self.total_nlines = total_nlines
|
| 228 |
+
self.pointer_nlines = pointer_nlines
|
| 229 |
+
self.indices_nlines = indices_nlines
|
| 230 |
+
self.values_nlines = values_nlines
|
| 231 |
+
|
| 232 |
+
parser = FortranFormatParser()
|
| 233 |
+
pointer_format = parser.parse(pointer_format_str)
|
| 234 |
+
if not isinstance(pointer_format, IntFormat):
|
| 235 |
+
raise ValueError("Expected int format for pointer format, got %s"
|
| 236 |
+
% pointer_format)
|
| 237 |
+
|
| 238 |
+
indices_format = parser.parse(indices_format_str)
|
| 239 |
+
if not isinstance(indices_format, IntFormat):
|
| 240 |
+
raise ValueError("Expected int format for indices format, got %s" %
|
| 241 |
+
indices_format)
|
| 242 |
+
|
| 243 |
+
values_format = parser.parse(values_format_str)
|
| 244 |
+
if isinstance(values_format, ExpFormat):
|
| 245 |
+
if mxtype.value_type not in ["real", "complex"]:
|
| 246 |
+
raise ValueError(f"Inconsistency between matrix type {mxtype} and "
|
| 247 |
+
f"value type {values_format}")
|
| 248 |
+
values_dtype = np.float64
|
| 249 |
+
elif isinstance(values_format, IntFormat):
|
| 250 |
+
if mxtype.value_type not in ["integer"]:
|
| 251 |
+
raise ValueError(f"Inconsistency between matrix type {mxtype} and "
|
| 252 |
+
f"value type {values_format}")
|
| 253 |
+
# XXX: fortran int -> dtype association ?
|
| 254 |
+
values_dtype = int
|
| 255 |
+
else:
|
| 256 |
+
raise ValueError(f"Unsupported format for values {values_format!r}")
|
| 257 |
+
|
| 258 |
+
self.pointer_format = pointer_format
|
| 259 |
+
self.indices_format = indices_format
|
| 260 |
+
self.values_format = values_format
|
| 261 |
+
|
| 262 |
+
self.pointer_dtype = np.int32
|
| 263 |
+
self.indices_dtype = np.int32
|
| 264 |
+
self.values_dtype = values_dtype
|
| 265 |
+
|
| 266 |
+
self.pointer_nlines = pointer_nlines
|
| 267 |
+
self.pointer_nbytes_full = _nbytes_full(pointer_format, pointer_nlines)
|
| 268 |
+
|
| 269 |
+
self.indices_nlines = indices_nlines
|
| 270 |
+
self.indices_nbytes_full = _nbytes_full(indices_format, indices_nlines)
|
| 271 |
+
|
| 272 |
+
self.values_nlines = values_nlines
|
| 273 |
+
self.values_nbytes_full = _nbytes_full(values_format, values_nlines)
|
| 274 |
+
|
| 275 |
+
self.nrows = nrows
|
| 276 |
+
self.ncols = ncols
|
| 277 |
+
self.nnon_zeros = nnon_zeros
|
| 278 |
+
self.nelementals = nelementals
|
| 279 |
+
self.mxtype = mxtype
|
| 280 |
+
|
| 281 |
+
def dump(self):
|
| 282 |
+
"""Gives the header corresponding to this instance as a string."""
|
| 283 |
+
header = [self.title.ljust(72) + self.key.ljust(8)]
|
| 284 |
+
|
| 285 |
+
header.append("%14d%14d%14d%14d" %
|
| 286 |
+
(self.total_nlines, self.pointer_nlines,
|
| 287 |
+
self.indices_nlines, self.values_nlines))
|
| 288 |
+
header.append("%14s%14d%14d%14d%14d" %
|
| 289 |
+
(self.mxtype.fortran_format.ljust(14), self.nrows,
|
| 290 |
+
self.ncols, self.nnon_zeros, 0))
|
| 291 |
+
|
| 292 |
+
pffmt = self.pointer_format.fortran_format
|
| 293 |
+
iffmt = self.indices_format.fortran_format
|
| 294 |
+
vffmt = self.values_format.fortran_format
|
| 295 |
+
header.append("%16s%16s%20s" %
|
| 296 |
+
(pffmt.ljust(16), iffmt.ljust(16), vffmt.ljust(20)))
|
| 297 |
+
return "\n".join(header)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _expect_int(value, msg=None):
|
| 301 |
+
try:
|
| 302 |
+
return int(value)
|
| 303 |
+
except ValueError as e:
|
| 304 |
+
if msg is None:
|
| 305 |
+
msg = "Expected an int, got %s"
|
| 306 |
+
raise ValueError(msg % value) from e
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _read_hb_data(content, header):
|
| 310 |
+
# XXX: look at a way to reduce memory here (big string creation)
|
| 311 |
+
ptr_string = "".join([content.read(header.pointer_nbytes_full),
|
| 312 |
+
content.readline()])
|
| 313 |
+
ptr = np.fromstring(ptr_string,
|
| 314 |
+
dtype=int, sep=' ')
|
| 315 |
+
|
| 316 |
+
ind_string = "".join([content.read(header.indices_nbytes_full),
|
| 317 |
+
content.readline()])
|
| 318 |
+
ind = np.fromstring(ind_string,
|
| 319 |
+
dtype=int, sep=' ')
|
| 320 |
+
|
| 321 |
+
val_string = "".join([content.read(header.values_nbytes_full),
|
| 322 |
+
content.readline()])
|
| 323 |
+
val = np.fromstring(val_string,
|
| 324 |
+
dtype=header.values_dtype, sep=' ')
|
| 325 |
+
|
| 326 |
+
try:
|
| 327 |
+
return csc_matrix((val, ind-1, ptr-1),
|
| 328 |
+
shape=(header.nrows, header.ncols))
|
| 329 |
+
except ValueError as e:
|
| 330 |
+
raise e
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _write_data(m, fid, header):
|
| 334 |
+
m = m.tocsc(copy=False)
|
| 335 |
+
|
| 336 |
+
def write_array(f, ar, nlines, fmt):
|
| 337 |
+
# ar_nlines is the number of full lines, n is the number of items per
|
| 338 |
+
# line, ffmt the fortran format
|
| 339 |
+
pyfmt = fmt.python_format
|
| 340 |
+
pyfmt_full = pyfmt * fmt.repeat
|
| 341 |
+
|
| 342 |
+
# for each array to write, we first write the full lines, and special
|
| 343 |
+
# case for partial line
|
| 344 |
+
full = ar[:(nlines - 1) * fmt.repeat]
|
| 345 |
+
for row in full.reshape((nlines-1, fmt.repeat)):
|
| 346 |
+
f.write(pyfmt_full % tuple(row) + "\n")
|
| 347 |
+
nremain = ar.size - full.size
|
| 348 |
+
if nremain > 0:
|
| 349 |
+
f.write((pyfmt * nremain) % tuple(ar[ar.size - nremain:]) + "\n")
|
| 350 |
+
|
| 351 |
+
fid.write(header.dump())
|
| 352 |
+
fid.write("\n")
|
| 353 |
+
# +1 is for Fortran one-based indexing
|
| 354 |
+
write_array(fid, m.indptr+1, header.pointer_nlines,
|
| 355 |
+
header.pointer_format)
|
| 356 |
+
write_array(fid, m.indices+1, header.indices_nlines,
|
| 357 |
+
header.indices_format)
|
| 358 |
+
write_array(fid, m.data, header.values_nlines,
|
| 359 |
+
header.values_format)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class HBMatrixType:
|
| 363 |
+
"""Class to hold the matrix type."""
|
| 364 |
+
# q2f* translates qualified names to Fortran character
|
| 365 |
+
_q2f_type = {
|
| 366 |
+
"real": "R",
|
| 367 |
+
"complex": "C",
|
| 368 |
+
"pattern": "P",
|
| 369 |
+
"integer": "I",
|
| 370 |
+
}
|
| 371 |
+
_q2f_structure = {
|
| 372 |
+
"symmetric": "S",
|
| 373 |
+
"unsymmetric": "U",
|
| 374 |
+
"hermitian": "H",
|
| 375 |
+
"skewsymmetric": "Z",
|
| 376 |
+
"rectangular": "R"
|
| 377 |
+
}
|
| 378 |
+
_q2f_storage = {
|
| 379 |
+
"assembled": "A",
|
| 380 |
+
"elemental": "E",
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
_f2q_type = {j: i for i, j in _q2f_type.items()}
|
| 384 |
+
_f2q_structure = {j: i for i, j in _q2f_structure.items()}
|
| 385 |
+
_f2q_storage = {j: i for i, j in _q2f_storage.items()}
|
| 386 |
+
|
| 387 |
+
@classmethod
|
| 388 |
+
def from_fortran(cls, fmt):
|
| 389 |
+
if not len(fmt) == 3:
|
| 390 |
+
raise ValueError("Fortran format for matrix type should be 3 "
|
| 391 |
+
"characters long")
|
| 392 |
+
try:
|
| 393 |
+
value_type = cls._f2q_type[fmt[0]]
|
| 394 |
+
structure = cls._f2q_structure[fmt[1]]
|
| 395 |
+
storage = cls._f2q_storage[fmt[2]]
|
| 396 |
+
return cls(value_type, structure, storage)
|
| 397 |
+
except KeyError as e:
|
| 398 |
+
raise ValueError("Unrecognized format %s" % fmt) from e
|
| 399 |
+
|
| 400 |
+
def __init__(self, value_type, structure, storage="assembled"):
|
| 401 |
+
self.value_type = value_type
|
| 402 |
+
self.structure = structure
|
| 403 |
+
self.storage = storage
|
| 404 |
+
|
| 405 |
+
if value_type not in self._q2f_type:
|
| 406 |
+
raise ValueError("Unrecognized type %s" % value_type)
|
| 407 |
+
if structure not in self._q2f_structure:
|
| 408 |
+
raise ValueError("Unrecognized structure %s" % structure)
|
| 409 |
+
if storage not in self._q2f_storage:
|
| 410 |
+
raise ValueError("Unrecognized storage %s" % storage)
|
| 411 |
+
|
| 412 |
+
@property
|
| 413 |
+
def fortran_format(self):
|
| 414 |
+
return self._q2f_type[self.value_type] + \
|
| 415 |
+
self._q2f_structure[self.structure] + \
|
| 416 |
+
self._q2f_storage[self.storage]
|
| 417 |
+
|
| 418 |
+
def __repr__(self):
|
| 419 |
+
return f"HBMatrixType({self.value_type}, {self.structure}, {self.storage})"
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
class HBFile:
|
| 423 |
+
def __init__(self, file, hb_info=None):
|
| 424 |
+
"""Create a HBFile instance.
|
| 425 |
+
|
| 426 |
+
Parameters
|
| 427 |
+
----------
|
| 428 |
+
file : file-object
|
| 429 |
+
StringIO work as well
|
| 430 |
+
hb_info : HBInfo, optional
|
| 431 |
+
Should be given as an argument for writing, in which case the file
|
| 432 |
+
should be writable.
|
| 433 |
+
"""
|
| 434 |
+
self._fid = file
|
| 435 |
+
if hb_info is None:
|
| 436 |
+
self._hb_info = HBInfo.from_file(file)
|
| 437 |
+
else:
|
| 438 |
+
#raise OSError("file %s is not writable, and hb_info "
|
| 439 |
+
# "was given." % file)
|
| 440 |
+
self._hb_info = hb_info
|
| 441 |
+
|
| 442 |
+
@property
|
| 443 |
+
def title(self):
|
| 444 |
+
return self._hb_info.title
|
| 445 |
+
|
| 446 |
+
@property
|
| 447 |
+
def key(self):
|
| 448 |
+
return self._hb_info.key
|
| 449 |
+
|
| 450 |
+
@property
|
| 451 |
+
def type(self):
|
| 452 |
+
return self._hb_info.mxtype.value_type
|
| 453 |
+
|
| 454 |
+
@property
|
| 455 |
+
def structure(self):
|
| 456 |
+
return self._hb_info.mxtype.structure
|
| 457 |
+
|
| 458 |
+
@property
|
| 459 |
+
def storage(self):
|
| 460 |
+
return self._hb_info.mxtype.storage
|
| 461 |
+
|
| 462 |
+
def read_matrix(self):
|
| 463 |
+
return _read_hb_data(self._fid, self._hb_info)
|
| 464 |
+
|
| 465 |
+
def write_matrix(self, m):
|
| 466 |
+
return _write_data(m, self._fid, self._hb_info)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def hb_read(path_or_open_file):
|
| 470 |
+
"""Read HB-format file.
|
| 471 |
+
|
| 472 |
+
Parameters
|
| 473 |
+
----------
|
| 474 |
+
path_or_open_file : path-like or file-like
|
| 475 |
+
If a file-like object, it is used as-is. Otherwise, it is opened
|
| 476 |
+
before reading.
|
| 477 |
+
|
| 478 |
+
Returns
|
| 479 |
+
-------
|
| 480 |
+
data : scipy.sparse.csc_matrix instance
|
| 481 |
+
The data read from the HB file as a sparse matrix.
|
| 482 |
+
|
| 483 |
+
Notes
|
| 484 |
+
-----
|
| 485 |
+
At the moment not the full Harwell-Boeing format is supported. Supported
|
| 486 |
+
features are:
|
| 487 |
+
|
| 488 |
+
- assembled, non-symmetric, real matrices
|
| 489 |
+
- integer for pointer/indices
|
| 490 |
+
- exponential format for float values, and int format
|
| 491 |
+
|
| 492 |
+
Examples
|
| 493 |
+
--------
|
| 494 |
+
We can read and write a harwell-boeing format file:
|
| 495 |
+
|
| 496 |
+
>>> from scipy.io import hb_read, hb_write
|
| 497 |
+
>>> from scipy.sparse import csr_array, eye
|
| 498 |
+
>>> data = csr_array(eye(3)) # create a sparse array
|
| 499 |
+
>>> hb_write("data.hb", data) # write a hb file
|
| 500 |
+
>>> print(hb_read("data.hb")) # read a hb file
|
| 501 |
+
<Compressed Sparse Column sparse matrix of dtype 'float64'
|
| 502 |
+
with 3 stored elements and shape (3, 3)>
|
| 503 |
+
Coords Values
|
| 504 |
+
(0, 0) 1.0
|
| 505 |
+
(1, 1) 1.0
|
| 506 |
+
(2, 2) 1.0
|
| 507 |
+
"""
|
| 508 |
+
def _get_matrix(fid):
|
| 509 |
+
hb = HBFile(fid)
|
| 510 |
+
return hb.read_matrix()
|
| 511 |
+
|
| 512 |
+
if hasattr(path_or_open_file, 'read'):
|
| 513 |
+
return _get_matrix(path_or_open_file)
|
| 514 |
+
else:
|
| 515 |
+
with open(path_or_open_file) as f:
|
| 516 |
+
return _get_matrix(f)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def hb_write(path_or_open_file, m, hb_info=None):
|
| 520 |
+
"""Write HB-format file.
|
| 521 |
+
|
| 522 |
+
Parameters
|
| 523 |
+
----------
|
| 524 |
+
path_or_open_file : path-like or file-like
|
| 525 |
+
If a file-like object, it is used as-is. Otherwise, it is opened
|
| 526 |
+
before writing.
|
| 527 |
+
m : sparse-matrix
|
| 528 |
+
the sparse matrix to write
|
| 529 |
+
hb_info : HBInfo
|
| 530 |
+
contains the meta-data for write
|
| 531 |
+
|
| 532 |
+
Returns
|
| 533 |
+
-------
|
| 534 |
+
None
|
| 535 |
+
|
| 536 |
+
Notes
|
| 537 |
+
-----
|
| 538 |
+
At the moment not the full Harwell-Boeing format is supported. Supported
|
| 539 |
+
features are:
|
| 540 |
+
|
| 541 |
+
- assembled, non-symmetric, real matrices
|
| 542 |
+
- integer for pointer/indices
|
| 543 |
+
- exponential format for float values, and int format
|
| 544 |
+
|
| 545 |
+
Examples
|
| 546 |
+
--------
|
| 547 |
+
We can read and write a harwell-boeing format file:
|
| 548 |
+
|
| 549 |
+
>>> from scipy.io import hb_read, hb_write
|
| 550 |
+
>>> from scipy.sparse import csr_array, eye
|
| 551 |
+
>>> data = csr_array(eye(3)) # create a sparse array
|
| 552 |
+
>>> hb_write("data.hb", data) # write a hb file
|
| 553 |
+
>>> print(hb_read("data.hb")) # read a hb file
|
| 554 |
+
<Compressed Sparse Column sparse matrix of dtype 'float64'
|
| 555 |
+
with 3 stored elements and shape (3, 3)>
|
| 556 |
+
Coords Values
|
| 557 |
+
(0, 0) 1.0
|
| 558 |
+
(1, 1) 1.0
|
| 559 |
+
(2, 2) 1.0
|
| 560 |
+
"""
|
| 561 |
+
m = m.tocsc(copy=False)
|
| 562 |
+
|
| 563 |
+
if hb_info is None:
|
| 564 |
+
hb_info = HBInfo.from_data(m)
|
| 565 |
+
|
| 566 |
+
def _set_matrix(fid):
|
| 567 |
+
hb = HBFile(fid, hb_info)
|
| 568 |
+
return hb.write_matrix(m)
|
| 569 |
+
|
| 570 |
+
if hasattr(path_or_open_file, 'write'):
|
| 571 |
+
return _set_matrix(path_or_open_file)
|
| 572 |
+
else:
|
| 573 |
+
with open(path_or_open_file, 'w') as f:
|
| 574 |
+
return _set_matrix(f)
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__init__.py
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (182 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc
ADDED
|
Binary file (4.27 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc
ADDED
|
Binary file (2.91 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from numpy.testing import assert_equal
|
| 4 |
+
from pytest import raises as assert_raises
|
| 5 |
+
|
| 6 |
+
from scipy.io._harwell_boeing._fortran_format_parser import (
|
| 7 |
+
FortranFormatParser, IntFormat, ExpFormat, BadFortranFormat)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestFortranFormatParser:
|
| 11 |
+
def setup_method(self):
|
| 12 |
+
self.parser = FortranFormatParser()
|
| 13 |
+
|
| 14 |
+
def _test_equal(self, format, ref):
|
| 15 |
+
ret = self.parser.parse(format)
|
| 16 |
+
assert_equal(ret.__dict__, ref.__dict__)
|
| 17 |
+
|
| 18 |
+
def test_simple_int(self):
|
| 19 |
+
self._test_equal("(I4)", IntFormat(4))
|
| 20 |
+
|
| 21 |
+
def test_simple_repeated_int(self):
|
| 22 |
+
self._test_equal("(3I4)", IntFormat(4, repeat=3))
|
| 23 |
+
|
| 24 |
+
def test_simple_exp(self):
|
| 25 |
+
self._test_equal("(E4.3)", ExpFormat(4, 3))
|
| 26 |
+
|
| 27 |
+
def test_exp_exp(self):
|
| 28 |
+
self._test_equal("(E8.3E3)", ExpFormat(8, 3, 3))
|
| 29 |
+
|
| 30 |
+
def test_repeat_exp(self):
|
| 31 |
+
self._test_equal("(2E4.3)", ExpFormat(4, 3, repeat=2))
|
| 32 |
+
|
| 33 |
+
def test_repeat_exp_exp(self):
|
| 34 |
+
self._test_equal("(2E8.3E3)", ExpFormat(8, 3, 3, repeat=2))
|
| 35 |
+
|
| 36 |
+
def test_wrong_formats(self):
|
| 37 |
+
def _test_invalid(bad_format):
|
| 38 |
+
assert_raises(BadFortranFormat, lambda: self.parser.parse(bad_format))
|
| 39 |
+
_test_invalid("I4")
|
| 40 |
+
_test_invalid("(E4)")
|
| 41 |
+
_test_invalid("(E4.)")
|
| 42 |
+
_test_invalid("(E4.E3)")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TestIntFormat:
|
| 46 |
+
def test_to_fortran(self):
|
| 47 |
+
f = [IntFormat(10), IntFormat(12, 10), IntFormat(12, 10, 3)]
|
| 48 |
+
res = ["(I10)", "(I12.10)", "(3I12.10)"]
|
| 49 |
+
|
| 50 |
+
for i, j in zip(f, res):
|
| 51 |
+
assert_equal(i.fortran_format, j)
|
| 52 |
+
|
| 53 |
+
def test_from_number(self):
|
| 54 |
+
f = [10, -12, 123456789]
|
| 55 |
+
r_f = [IntFormat(3, repeat=26), IntFormat(4, repeat=20),
|
| 56 |
+
IntFormat(10, repeat=8)]
|
| 57 |
+
for i, j in zip(f, r_f):
|
| 58 |
+
assert_equal(IntFormat.from_number(i).__dict__, j.__dict__)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class TestExpFormat:
|
| 62 |
+
def test_to_fortran(self):
|
| 63 |
+
f = [ExpFormat(10, 5), ExpFormat(12, 10), ExpFormat(12, 10, min=3),
|
| 64 |
+
ExpFormat(10, 5, repeat=3)]
|
| 65 |
+
res = ["(E10.5)", "(E12.10)", "(E12.10E3)", "(3E10.5)"]
|
| 66 |
+
|
| 67 |
+
for i, j in zip(f, res):
|
| 68 |
+
assert_equal(i.fortran_format, j)
|
| 69 |
+
|
| 70 |
+
def test_from_number(self):
|
| 71 |
+
f = np.array([1.0, -1.2])
|
| 72 |
+
r_f = [ExpFormat(24, 16, repeat=3), ExpFormat(25, 16, repeat=3)]
|
| 73 |
+
for i, j in zip(f, r_f):
|
| 74 |
+
assert_equal(ExpFormat.from_number(i).__dict__, j.__dict__)
|
parrot/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from io import StringIO
|
| 2 |
+
import tempfile
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from numpy.testing import assert_equal, \
|
| 7 |
+
assert_array_almost_equal_nulp
|
| 8 |
+
|
| 9 |
+
from scipy.sparse import coo_matrix, csc_matrix, rand
|
| 10 |
+
|
| 11 |
+
from scipy.io import hb_read, hb_write
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
SIMPLE = """\
|
| 15 |
+
No Title |No Key
|
| 16 |
+
9 4 1 4
|
| 17 |
+
RUA 100 100 10 0
|
| 18 |
+
(26I3) (26I3) (3E23.15)
|
| 19 |
+
1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
|
| 20 |
+
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
|
| 21 |
+
3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9
|
| 22 |
+
9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11
|
| 23 |
+
37 71 89 18 30 45 70 19 25 52
|
| 24 |
+
2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01
|
| 25 |
+
6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01
|
| 26 |
+
4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01
|
| 27 |
+
6.912334991524289e-01
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
SIMPLE_MATRIX = coo_matrix(
|
| 31 |
+
((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799,
|
| 32 |
+
0.0661749042483, 0.887037034319, 0.419647859016,
|
| 33 |
+
0.564960307211, 0.993442388709, 0.691233499152,),
|
| 34 |
+
(np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51],
|
| 35 |
+
[0, 4, 58, 61, 61, 72, 72, 73, 99, 99]]))))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def assert_csc_almost_equal(r, l):
|
| 39 |
+
r = csc_matrix(r)
|
| 40 |
+
l = csc_matrix(l)
|
| 41 |
+
assert_equal(r.indptr, l.indptr)
|
| 42 |
+
assert_equal(r.indices, l.indices)
|
| 43 |
+
assert_array_almost_equal_nulp(r.data, l.data, 10000)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestHBReader:
|
| 47 |
+
def test_simple(self):
|
| 48 |
+
m = hb_read(StringIO(SIMPLE))
|
| 49 |
+
assert_csc_almost_equal(m, SIMPLE_MATRIX)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class TestHBReadWrite:
|
| 53 |
+
|
| 54 |
+
def check_save_load(self, value):
|
| 55 |
+
with tempfile.NamedTemporaryFile(mode='w+t') as file:
|
| 56 |
+
hb_write(file, value)
|
| 57 |
+
file.file.seek(0)
|
| 58 |
+
value_loaded = hb_read(file)
|
| 59 |
+
assert_csc_almost_equal(value, value_loaded)
|
| 60 |
+
|
| 61 |
+
def test_simple(self):
|
| 62 |
+
random_matrix = rand(10, 100, 0.1)
|
| 63 |
+
for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'):
|
| 64 |
+
matrix = random_matrix.as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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
parrot/lib/python3.10/site-packages/scipy/io/_mmio.py
ADDED
|
@@ -0,0 +1,961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 <pearu@cens.ioc.ee>
|
| 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)
|
parrot/lib/python3.10/site-packages/scipy/io/_test_fortran.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (63.5 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/idl.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` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["readsav"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="idl",
|
| 16 |
+
private_modules=["_idl"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/io/mmio.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` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["mminfo", "mmread", "mmwrite"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="mmio",
|
| 16 |
+
private_modules=["_mmio"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/io/netcdf.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` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ["netcdf_file", "netcdf_variable"] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="io", module="netcdf",
|
| 16 |
+
private_modules=["_netcdf"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/io/tests/__init__.py
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (166 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-310.pyc
ADDED
|
Binary file (7.64 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-310.pyc
ADDED
|
Binary file (19.1 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-310.pyc
ADDED
|
Binary file (3.77 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav
ADDED
|
Binary file (2.63 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav
ADDED
|
Binary file (13.8 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav
ADDED
|
Binary file (7.9 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav
ADDED
|
Binary file (13.8 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav
ADDED
|
Binary file (6.68 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat
ADDED
|
Binary file (128 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat
ADDED
|
Binary file (12 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav
ADDED
|
Binary file (2.08 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav
ADDED
|
Binary file (2.08 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_string.sav
ADDED
|
Binary file (2.12 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav
ADDED
|
Binary file (2.07 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav
ADDED
|
Binary file (2.94 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav
ADDED
|
Binary file (2.41 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav
ADDED
|
Binary file (2.49 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav
ADDED
|
Binary file (3.24 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/io/tests/test_fortran.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 9 |
+
from numpy.testing import assert_equal, assert_allclose
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
from scipy.io import (FortranFile,
|
| 14 |
+
_test_fortran,
|
| 15 |
+
FortranEOFError,
|
| 16 |
+
FortranFormattingError)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
DATA_PATH = path.join(path.dirname(__file__), 'data')
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_fortranfiles_read():
|
| 23 |
+
for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
|
| 24 |
+
m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
|
| 25 |
+
if not m:
|
| 26 |
+
raise RuntimeError("Couldn't match %s filename to regex" % filename)
|
| 27 |
+
|
| 28 |
+
dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))
|
| 29 |
+
|
| 30 |
+
dtype = m.group(1).replace('s', '<')
|
| 31 |
+
|
| 32 |
+
f = FortranFile(filename, 'r', '<u4')
|
| 33 |
+
data = f.read_record(dtype=dtype).reshape(dims, order='F')
|
| 34 |
+
f.close()
|
| 35 |
+
|
| 36 |
+
expected = np.arange(np.prod(dims)).reshape(dims).astype(dtype)
|
| 37 |
+
assert_equal(data, expected)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_fortranfiles_mixed_record():
|
| 41 |
+
filename = path.join(DATA_PATH, "fortran-mixed.dat")
|
| 42 |
+
with FortranFile(filename, 'r', '<u4') as f:
|
| 43 |
+
record = f.read_record('<i4,<f4,<i8,2<f8')
|
| 44 |
+
|
| 45 |
+
assert_equal(record['f0'][0], 1)
|
| 46 |
+
assert_allclose(record['f1'][0], 2.3)
|
| 47 |
+
assert_equal(record['f2'][0], 4)
|
| 48 |
+
assert_allclose(record['f3'][0], [5.6, 7.8])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_fortranfiles_write():
|
| 52 |
+
for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")):
|
| 53 |
+
m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I)
|
| 54 |
+
if not m:
|
| 55 |
+
raise RuntimeError("Couldn't match %s filename to regex" % filename)
|
| 56 |
+
dims = (int(m.group(2)), int(m.group(3)), int(m.group(4)))
|
| 57 |
+
|
| 58 |
+
dtype = m.group(1).replace('s', '<')
|
| 59 |
+
data = np.arange(np.prod(dims)).reshape(dims).astype(dtype)
|
| 60 |
+
|
| 61 |
+
tmpdir = tempfile.mkdtemp()
|
| 62 |
+
try:
|
| 63 |
+
testFile = path.join(tmpdir,path.basename(filename))
|
| 64 |
+
f = FortranFile(testFile, 'w','<u4')
|
| 65 |
+
f.write_record(data.T)
|
| 66 |
+
f.close()
|
| 67 |
+
originalfile = open(filename, 'rb')
|
| 68 |
+
newfile = open(testFile, 'rb')
|
| 69 |
+
assert_equal(originalfile.read(), newfile.read(),
|
| 70 |
+
err_msg=filename)
|
| 71 |
+
originalfile.close()
|
| 72 |
+
newfile.close()
|
| 73 |
+
finally:
|
| 74 |
+
shutil.rmtree(tmpdir)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_fortranfile_read_mixed_record():
|
| 78 |
+
# The data file fortran-3x3d-2i.dat contains the program that
|
| 79 |
+
# produced it at the end.
|
| 80 |
+
#
|
| 81 |
+
# double precision :: a(3,3)
|
| 82 |
+
# integer :: b(2)
|
| 83 |
+
# ...
|
| 84 |
+
# open(1, file='fortran-3x3d-2i.dat', form='unformatted')
|
| 85 |
+
# write(1) a, b
|
| 86 |
+
# close(1)
|
| 87 |
+
#
|
| 88 |
+
|
| 89 |
+
filename = path.join(DATA_PATH, "fortran-3x3d-2i.dat")
|
| 90 |
+
with FortranFile(filename, 'r', '<u4') as f:
|
| 91 |
+
record = f.read_record('(3,3)<f8', '2<i4')
|
| 92 |
+
|
| 93 |
+
ax = np.arange(3*3).reshape(3, 3).astype(np.float64)
|
| 94 |
+
bx = np.array([-1, -2], dtype=np.int32)
|
| 95 |
+
|
| 96 |
+
assert_equal(record[0], ax.T)
|
| 97 |
+
assert_equal(record[1], bx.T)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_fortranfile_write_mixed_record(tmpdir):
|
| 101 |
+
tf = path.join(str(tmpdir), 'test.dat')
|
| 102 |
+
|
| 103 |
+
r1 = (('f4', 'f4', 'i4'), (np.float32(2), np.float32(3), np.int32(100)))
|
| 104 |
+
r2 = (('4f4', '(3,3)f4', '8i4'),
|
| 105 |
+
(np.random.randint(255, size=[4]).astype(np.float32),
|
| 106 |
+
np.random.randint(255, size=[3, 3]).astype(np.float32),
|
| 107 |
+
np.random.randint(255, size=[8]).astype(np.int32)))
|
| 108 |
+
records = [r1, r2]
|
| 109 |
+
|
| 110 |
+
for dtype, a in records:
|
| 111 |
+
with FortranFile(tf, 'w') as f:
|
| 112 |
+
f.write_record(*a)
|
| 113 |
+
|
| 114 |
+
with FortranFile(tf, 'r') as f:
|
| 115 |
+
b = f.read_record(*dtype)
|
| 116 |
+
|
| 117 |
+
assert_equal(len(a), len(b))
|
| 118 |
+
|
| 119 |
+
for aa, bb in zip(a, b):
|
| 120 |
+
assert_equal(bb, aa)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_fortran_roundtrip(tmpdir):
|
| 124 |
+
filename = path.join(str(tmpdir), 'test.dat')
|
| 125 |
+
|
| 126 |
+
np.random.seed(1)
|
| 127 |
+
|
| 128 |
+
# double precision
|
| 129 |
+
m, n, k = 5, 3, 2
|
| 130 |
+
a = np.random.randn(m, n, k)
|
| 131 |
+
with FortranFile(filename, 'w') as f:
|
| 132 |
+
f.write_record(a.T)
|
| 133 |
+
a2 = _test_fortran.read_unformatted_double(m, n, k, filename)
|
| 134 |
+
with FortranFile(filename, 'r') as f:
|
| 135 |
+
a3 = f.read_record('(2,3,5)f8').T
|
| 136 |
+
assert_equal(a2, a)
|
| 137 |
+
assert_equal(a3, a)
|
| 138 |
+
|
| 139 |
+
# integer
|
| 140 |
+
m, n, k = 5, 3, 2
|
| 141 |
+
a = np.random.randn(m, n, k).astype(np.int32)
|
| 142 |
+
with FortranFile(filename, 'w') as f:
|
| 143 |
+
f.write_record(a.T)
|
| 144 |
+
a2 = _test_fortran.read_unformatted_int(m, n, k, filename)
|
| 145 |
+
with FortranFile(filename, 'r') as f:
|
| 146 |
+
a3 = f.read_record('(2,3,5)i4').T
|
| 147 |
+
assert_equal(a2, a)
|
| 148 |
+
assert_equal(a3, a)
|
| 149 |
+
|
| 150 |
+
# mixed
|
| 151 |
+
m, n, k = 5, 3, 2
|
| 152 |
+
a = np.random.randn(m, n)
|
| 153 |
+
b = np.random.randn(k).astype(np.intc)
|
| 154 |
+
with FortranFile(filename, 'w') as f:
|
| 155 |
+
f.write_record(a.T, b.T)
|
| 156 |
+
a2, b2 = _test_fortran.read_unformatted_mixed(m, n, k, filename)
|
| 157 |
+
with FortranFile(filename, 'r') as f:
|
| 158 |
+
a3, b3 = f.read_record('(3,5)f8', '2i4')
|
| 159 |
+
a3 = a3.T
|
| 160 |
+
assert_equal(a2, a)
|
| 161 |
+
assert_equal(a3, a)
|
| 162 |
+
assert_equal(b2, b)
|
| 163 |
+
assert_equal(b3, b)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_fortran_eof_ok(tmpdir):
|
| 167 |
+
filename = path.join(str(tmpdir), "scratch")
|
| 168 |
+
np.random.seed(1)
|
| 169 |
+
with FortranFile(filename, 'w') as f:
|
| 170 |
+
f.write_record(np.random.randn(5))
|
| 171 |
+
f.write_record(np.random.randn(3))
|
| 172 |
+
with FortranFile(filename, 'r') as f:
|
| 173 |
+
assert len(f.read_reals()) == 5
|
| 174 |
+
assert len(f.read_reals()) == 3
|
| 175 |
+
with pytest.raises(FortranEOFError):
|
| 176 |
+
f.read_reals()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_fortran_eof_broken_size(tmpdir):
|
| 180 |
+
filename = path.join(str(tmpdir), "scratch")
|
| 181 |
+
np.random.seed(1)
|
| 182 |
+
with FortranFile(filename, 'w') as f:
|
| 183 |
+
f.write_record(np.random.randn(5))
|
| 184 |
+
f.write_record(np.random.randn(3))
|
| 185 |
+
with open(filename, "ab") as f:
|
| 186 |
+
f.write(b"\xff")
|
| 187 |
+
with FortranFile(filename, 'r') as f:
|
| 188 |
+
assert len(f.read_reals()) == 5
|
| 189 |
+
assert len(f.read_reals()) == 3
|
| 190 |
+
with pytest.raises(FortranFormattingError):
|
| 191 |
+
f.read_reals()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def test_fortran_bogus_size(tmpdir):
|
| 195 |
+
filename = path.join(str(tmpdir), "scratch")
|
| 196 |
+
np.random.seed(1)
|
| 197 |
+
with FortranFile(filename, 'w') as f:
|
| 198 |
+
f.write_record(np.random.randn(5))
|
| 199 |
+
f.write_record(np.random.randn(3))
|
| 200 |
+
with open(filename, "w+b") as f:
|
| 201 |
+
f.write(b"\xff\xff")
|
| 202 |
+
with FortranFile(filename, 'r') as f:
|
| 203 |
+
with pytest.raises(FortranFormattingError):
|
| 204 |
+
f.read_reals()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def test_fortran_eof_broken_record(tmpdir):
|
| 208 |
+
filename = path.join(str(tmpdir), "scratch")
|
| 209 |
+
np.random.seed(1)
|
| 210 |
+
with FortranFile(filename, 'w') as f:
|
| 211 |
+
f.write_record(np.random.randn(5))
|
| 212 |
+
f.write_record(np.random.randn(3))
|
| 213 |
+
with open(filename, "ab") as f:
|
| 214 |
+
f.truncate(path.getsize(filename)-20)
|
| 215 |
+
with FortranFile(filename, 'r') as f:
|
| 216 |
+
assert len(f.read_reals()) == 5
|
| 217 |
+
with pytest.raises(FortranFormattingError):
|
| 218 |
+
f.read_reals()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def test_fortran_eof_multidimensional(tmpdir):
|
| 222 |
+
filename = path.join(str(tmpdir), "scratch")
|
| 223 |
+
n, m, q = 3, 5, 7
|
| 224 |
+
dt = np.dtype([("field", np.float64, (n, m))])
|
| 225 |
+
a = np.zeros(q, dtype=dt)
|
| 226 |
+
with FortranFile(filename, 'w') as f:
|
| 227 |
+
f.write_record(a[0])
|
| 228 |
+
f.write_record(a)
|
| 229 |
+
f.write_record(a)
|
| 230 |
+
with open(filename, "ab") as f:
|
| 231 |
+
f.truncate(path.getsize(filename)-20)
|
| 232 |
+
with FortranFile(filename, 'r') as f:
|
| 233 |
+
assert len(f.read_record(dtype=dt)) == 1
|
| 234 |
+
assert len(f.read_record(dtype=dt)) == q
|
| 235 |
+
with pytest.raises(FortranFormattingError):
|
| 236 |
+
f.read_record(dtype=dt)
|
parrot/lib/python3.10/site-packages/scipy/io/tests/test_idl.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from os import path
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.testing import (assert_equal, assert_array_equal,
|
| 6 |
+
assert_, suppress_warnings)
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from scipy.io import readsav
|
| 10 |
+
from scipy.io import _idl
|
| 11 |
+
|
| 12 |
+
DATA_PATH = path.join(path.dirname(__file__), 'data')
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def assert_identical(a, b):
|
| 16 |
+
"""Assert whether value AND type are the same"""
|
| 17 |
+
assert_equal(a, b)
|
| 18 |
+
if isinstance(b, str):
|
| 19 |
+
assert_equal(type(a), type(b))
|
| 20 |
+
else:
|
| 21 |
+
assert_equal(np.asarray(a).dtype.type, np.asarray(b).dtype.type)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def assert_array_identical(a, b):
|
| 25 |
+
"""Assert whether values AND type are the same"""
|
| 26 |
+
assert_array_equal(a, b)
|
| 27 |
+
assert_equal(a.dtype.type, b.dtype.type)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# Define vectorized ID function for pointer arrays
|
| 31 |
+
vect_id = np.vectorize(id)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestIdict:
|
| 35 |
+
|
| 36 |
+
def test_idict(self):
|
| 37 |
+
custom_dict = {'a': np.int16(999)}
|
| 38 |
+
original_id = id(custom_dict)
|
| 39 |
+
s = readsav(path.join(DATA_PATH, 'scalar_byte.sav'),
|
| 40 |
+
idict=custom_dict, verbose=False)
|
| 41 |
+
assert_equal(original_id, id(s))
|
| 42 |
+
assert_('a' in s)
|
| 43 |
+
assert_identical(s['a'], np.int16(999))
|
| 44 |
+
assert_identical(s['i8u'], np.uint8(234))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class TestScalars:
|
| 48 |
+
# Test that scalar values are read in with the correct value and type
|
| 49 |
+
|
| 50 |
+
def test_byte(self):
|
| 51 |
+
s = readsav(path.join(DATA_PATH, 'scalar_byte.sav'), verbose=False)
|
| 52 |
+
assert_identical(s.i8u, np.uint8(234))
|
| 53 |
+
|
| 54 |
+
def test_int16(self):
|
| 55 |
+
s = readsav(path.join(DATA_PATH, 'scalar_int16.sav'), verbose=False)
|
| 56 |
+
assert_identical(s.i16s, np.int16(-23456))
|
| 57 |
+
|
| 58 |
+
def test_int32(self):
|
| 59 |
+
s = readsav(path.join(DATA_PATH, 'scalar_int32.sav'), verbose=False)
|
| 60 |
+
assert_identical(s.i32s, np.int32(-1234567890))
|
| 61 |
+
|
| 62 |
+
def test_float32(self):
|
| 63 |
+
s = readsav(path.join(DATA_PATH, 'scalar_float32.sav'), verbose=False)
|
| 64 |
+
assert_identical(s.f32, np.float32(-3.1234567e+37))
|
| 65 |
+
|
| 66 |
+
def test_float64(self):
|
| 67 |
+
s = readsav(path.join(DATA_PATH, 'scalar_float64.sav'), verbose=False)
|
| 68 |
+
assert_identical(s.f64, np.float64(-1.1976931348623157e+307))
|
| 69 |
+
|
| 70 |
+
def test_complex32(self):
|
| 71 |
+
s = readsav(path.join(DATA_PATH, 'scalar_complex32.sav'), verbose=False)
|
| 72 |
+
assert_identical(s.c32, np.complex64(3.124442e13-2.312442e31j))
|
| 73 |
+
|
| 74 |
+
def test_bytes(self):
|
| 75 |
+
s = readsav(path.join(DATA_PATH, 'scalar_string.sav'), verbose=False)
|
| 76 |
+
msg = "The quick brown fox jumps over the lazy python"
|
| 77 |
+
assert_identical(s.s, np.bytes_(msg))
|
| 78 |
+
|
| 79 |
+
def test_structure(self):
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
def test_complex64(self):
|
| 83 |
+
s = readsav(path.join(DATA_PATH, 'scalar_complex64.sav'), verbose=False)
|
| 84 |
+
assert_identical(
|
| 85 |
+
s.c64,
|
| 86 |
+
np.complex128(1.1987253647623157e+112-5.1987258887729157e+307j)
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
def test_heap_pointer(self):
|
| 90 |
+
pass
|
| 91 |
+
|
| 92 |
+
def test_object_reference(self):
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
def test_uint16(self):
|
| 96 |
+
s = readsav(path.join(DATA_PATH, 'scalar_uint16.sav'), verbose=False)
|
| 97 |
+
assert_identical(s.i16u, np.uint16(65511))
|
| 98 |
+
|
| 99 |
+
def test_uint32(self):
|
| 100 |
+
s = readsav(path.join(DATA_PATH, 'scalar_uint32.sav'), verbose=False)
|
| 101 |
+
assert_identical(s.i32u, np.uint32(4294967233))
|
| 102 |
+
|
| 103 |
+
def test_int64(self):
|
| 104 |
+
s = readsav(path.join(DATA_PATH, 'scalar_int64.sav'), verbose=False)
|
| 105 |
+
assert_identical(s.i64s, np.int64(-9223372036854774567))
|
| 106 |
+
|
| 107 |
+
def test_uint64(self):
|
| 108 |
+
s = readsav(path.join(DATA_PATH, 'scalar_uint64.sav'), verbose=False)
|
| 109 |
+
assert_identical(s.i64u, np.uint64(18446744073709529285))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class TestCompressed(TestScalars):
|
| 113 |
+
# Test that compressed .sav files can be read in
|
| 114 |
+
|
| 115 |
+
def test_compressed(self):
|
| 116 |
+
s = readsav(path.join(DATA_PATH, 'various_compressed.sav'), verbose=False)
|
| 117 |
+
|
| 118 |
+
assert_identical(s.i8u, np.uint8(234))
|
| 119 |
+
assert_identical(s.f32, np.float32(-3.1234567e+37))
|
| 120 |
+
assert_identical(
|
| 121 |
+
s.c64,
|
| 122 |
+
np.complex128(1.1987253647623157e+112-5.1987258887729157e+307j)
|
| 123 |
+
)
|
| 124 |
+
assert_equal(s.array5d.shape, (4, 3, 4, 6, 5))
|
| 125 |
+
assert_identical(s.arrays.a[0], np.array([1, 2, 3], dtype=np.int16))
|
| 126 |
+
assert_identical(s.arrays.b[0], np.array([4., 5., 6., 7.], dtype=np.float32))
|
| 127 |
+
assert_identical(s.arrays.c[0],
|
| 128 |
+
np.array([np.complex64(1+2j), np.complex64(7+8j)]))
|
| 129 |
+
assert_identical(s.arrays.d[0],
|
| 130 |
+
np.array([b"cheese", b"bacon", b"spam"], dtype=object))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class TestArrayDimensions:
|
| 134 |
+
# Test that multi-dimensional arrays are read in with the correct dimensions
|
| 135 |
+
|
| 136 |
+
def test_1d(self):
|
| 137 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_1d.sav'), verbose=False)
|
| 138 |
+
assert_equal(s.array1d.shape, (123, ))
|
| 139 |
+
|
| 140 |
+
def test_2d(self):
|
| 141 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_2d.sav'), verbose=False)
|
| 142 |
+
assert_equal(s.array2d.shape, (22, 12))
|
| 143 |
+
|
| 144 |
+
def test_3d(self):
|
| 145 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_3d.sav'), verbose=False)
|
| 146 |
+
assert_equal(s.array3d.shape, (11, 22, 12))
|
| 147 |
+
|
| 148 |
+
def test_4d(self):
|
| 149 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_4d.sav'), verbose=False)
|
| 150 |
+
assert_equal(s.array4d.shape, (4, 5, 8, 7))
|
| 151 |
+
|
| 152 |
+
def test_5d(self):
|
| 153 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_5d.sav'), verbose=False)
|
| 154 |
+
assert_equal(s.array5d.shape, (4, 3, 4, 6, 5))
|
| 155 |
+
|
| 156 |
+
def test_6d(self):
|
| 157 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_6d.sav'), verbose=False)
|
| 158 |
+
assert_equal(s.array6d.shape, (3, 6, 4, 5, 3, 4))
|
| 159 |
+
|
| 160 |
+
def test_7d(self):
|
| 161 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_7d.sav'), verbose=False)
|
| 162 |
+
assert_equal(s.array7d.shape, (2, 1, 2, 3, 4, 3, 2))
|
| 163 |
+
|
| 164 |
+
def test_8d(self):
|
| 165 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_8d.sav'), verbose=False)
|
| 166 |
+
assert_equal(s.array8d.shape, (4, 3, 2, 1, 2, 3, 5, 4))
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class TestStructures:
|
| 170 |
+
|
| 171 |
+
def test_scalars(self):
|
| 172 |
+
s = readsav(path.join(DATA_PATH, 'struct_scalars.sav'), verbose=False)
|
| 173 |
+
assert_identical(s.scalars.a, np.array(np.int16(1)))
|
| 174 |
+
assert_identical(s.scalars.b, np.array(np.int32(2)))
|
| 175 |
+
assert_identical(s.scalars.c, np.array(np.float32(3.)))
|
| 176 |
+
assert_identical(s.scalars.d, np.array(np.float64(4.)))
|
| 177 |
+
assert_identical(s.scalars.e, np.array([b"spam"], dtype=object))
|
| 178 |
+
assert_identical(s.scalars.f, np.array(np.complex64(-1.+3j)))
|
| 179 |
+
|
| 180 |
+
def test_scalars_replicated(self):
|
| 181 |
+
s = readsav(path.join(DATA_PATH, 'struct_scalars_replicated.sav'),
|
| 182 |
+
verbose=False)
|
| 183 |
+
assert_identical(s.scalars_rep.a, np.repeat(np.int16(1), 5))
|
| 184 |
+
assert_identical(s.scalars_rep.b, np.repeat(np.int32(2), 5))
|
| 185 |
+
assert_identical(s.scalars_rep.c, np.repeat(np.float32(3.), 5))
|
| 186 |
+
assert_identical(s.scalars_rep.d, np.repeat(np.float64(4.), 5))
|
| 187 |
+
assert_identical(s.scalars_rep.e, np.repeat(b"spam", 5).astype(object))
|
| 188 |
+
assert_identical(s.scalars_rep.f, np.repeat(np.complex64(-1.+3j), 5))
|
| 189 |
+
|
| 190 |
+
def test_scalars_replicated_3d(self):
|
| 191 |
+
s = readsav(path.join(DATA_PATH, 'struct_scalars_replicated_3d.sav'),
|
| 192 |
+
verbose=False)
|
| 193 |
+
assert_identical(s.scalars_rep.a, np.repeat(np.int16(1), 24).reshape(4, 3, 2))
|
| 194 |
+
assert_identical(s.scalars_rep.b, np.repeat(np.int32(2), 24).reshape(4, 3, 2))
|
| 195 |
+
assert_identical(s.scalars_rep.c,
|
| 196 |
+
np.repeat(np.float32(3.), 24).reshape(4, 3, 2))
|
| 197 |
+
assert_identical(s.scalars_rep.d,
|
| 198 |
+
np.repeat(np.float64(4.), 24).reshape(4, 3, 2))
|
| 199 |
+
assert_identical(s.scalars_rep.e,
|
| 200 |
+
np.repeat(b"spam", 24).reshape(4, 3, 2).astype(object))
|
| 201 |
+
assert_identical(s.scalars_rep.f,
|
| 202 |
+
np.repeat(np.complex64(-1.+3j), 24).reshape(4, 3, 2))
|
| 203 |
+
|
| 204 |
+
def test_arrays(self):
|
| 205 |
+
s = readsav(path.join(DATA_PATH, 'struct_arrays.sav'), verbose=False)
|
| 206 |
+
assert_array_identical(s.arrays.a[0], np.array([1, 2, 3], dtype=np.int16))
|
| 207 |
+
assert_array_identical(s.arrays.b[0],
|
| 208 |
+
np.array([4., 5., 6., 7.], dtype=np.float32))
|
| 209 |
+
assert_array_identical(s.arrays.c[0],
|
| 210 |
+
np.array([np.complex64(1+2j), np.complex64(7+8j)]))
|
| 211 |
+
assert_array_identical(s.arrays.d[0],
|
| 212 |
+
np.array([b"cheese", b"bacon", b"spam"], dtype=object))
|
| 213 |
+
|
| 214 |
+
def test_arrays_replicated(self):
|
| 215 |
+
s = readsav(path.join(DATA_PATH, 'struct_arrays_replicated.sav'), verbose=False)
|
| 216 |
+
|
| 217 |
+
# Check column types
|
| 218 |
+
assert_(s.arrays_rep.a.dtype.type is np.object_)
|
| 219 |
+
assert_(s.arrays_rep.b.dtype.type is np.object_)
|
| 220 |
+
assert_(s.arrays_rep.c.dtype.type is np.object_)
|
| 221 |
+
assert_(s.arrays_rep.d.dtype.type is np.object_)
|
| 222 |
+
|
| 223 |
+
# Check column shapes
|
| 224 |
+
assert_equal(s.arrays_rep.a.shape, (5, ))
|
| 225 |
+
assert_equal(s.arrays_rep.b.shape, (5, ))
|
| 226 |
+
assert_equal(s.arrays_rep.c.shape, (5, ))
|
| 227 |
+
assert_equal(s.arrays_rep.d.shape, (5, ))
|
| 228 |
+
|
| 229 |
+
# Check values
|
| 230 |
+
for i in range(5):
|
| 231 |
+
assert_array_identical(s.arrays_rep.a[i],
|
| 232 |
+
np.array([1, 2, 3], dtype=np.int16))
|
| 233 |
+
assert_array_identical(s.arrays_rep.b[i],
|
| 234 |
+
np.array([4., 5., 6., 7.], dtype=np.float32))
|
| 235 |
+
assert_array_identical(s.arrays_rep.c[i],
|
| 236 |
+
np.array([np.complex64(1+2j),
|
| 237 |
+
np.complex64(7+8j)]))
|
| 238 |
+
assert_array_identical(s.arrays_rep.d[i],
|
| 239 |
+
np.array([b"cheese", b"bacon", b"spam"],
|
| 240 |
+
dtype=object))
|
| 241 |
+
|
| 242 |
+
def test_arrays_replicated_3d(self):
|
| 243 |
+
s = readsav(path.join(DATA_PATH, 'struct_arrays_replicated_3d.sav'),
|
| 244 |
+
verbose=False)
|
| 245 |
+
|
| 246 |
+
# Check column types
|
| 247 |
+
assert_(s.arrays_rep.a.dtype.type is np.object_)
|
| 248 |
+
assert_(s.arrays_rep.b.dtype.type is np.object_)
|
| 249 |
+
assert_(s.arrays_rep.c.dtype.type is np.object_)
|
| 250 |
+
assert_(s.arrays_rep.d.dtype.type is np.object_)
|
| 251 |
+
|
| 252 |
+
# Check column shapes
|
| 253 |
+
assert_equal(s.arrays_rep.a.shape, (4, 3, 2))
|
| 254 |
+
assert_equal(s.arrays_rep.b.shape, (4, 3, 2))
|
| 255 |
+
assert_equal(s.arrays_rep.c.shape, (4, 3, 2))
|
| 256 |
+
assert_equal(s.arrays_rep.d.shape, (4, 3, 2))
|
| 257 |
+
|
| 258 |
+
# Check values
|
| 259 |
+
for i in range(4):
|
| 260 |
+
for j in range(3):
|
| 261 |
+
for k in range(2):
|
| 262 |
+
assert_array_identical(s.arrays_rep.a[i, j, k],
|
| 263 |
+
np.array([1, 2, 3], dtype=np.int16))
|
| 264 |
+
assert_array_identical(s.arrays_rep.b[i, j, k],
|
| 265 |
+
np.array([4., 5., 6., 7.],
|
| 266 |
+
dtype=np.float32))
|
| 267 |
+
assert_array_identical(s.arrays_rep.c[i, j, k],
|
| 268 |
+
np.array([np.complex64(1+2j),
|
| 269 |
+
np.complex64(7+8j)]))
|
| 270 |
+
assert_array_identical(s.arrays_rep.d[i, j, k],
|
| 271 |
+
np.array([b"cheese", b"bacon", b"spam"],
|
| 272 |
+
dtype=object))
|
| 273 |
+
|
| 274 |
+
def test_inheritance(self):
|
| 275 |
+
s = readsav(path.join(DATA_PATH, 'struct_inherit.sav'), verbose=False)
|
| 276 |
+
assert_identical(s.fc.x, np.array([0], dtype=np.int16))
|
| 277 |
+
assert_identical(s.fc.y, np.array([0], dtype=np.int16))
|
| 278 |
+
assert_identical(s.fc.r, np.array([0], dtype=np.int16))
|
| 279 |
+
assert_identical(s.fc.c, np.array([4], dtype=np.int16))
|
| 280 |
+
|
| 281 |
+
def test_arrays_corrupt_idl80(self):
|
| 282 |
+
# test byte arrays with missing nbyte information from IDL 8.0 .sav file
|
| 283 |
+
with suppress_warnings() as sup:
|
| 284 |
+
sup.filter(UserWarning, "Not able to verify number of bytes from header")
|
| 285 |
+
s = readsav(path.join(DATA_PATH,'struct_arrays_byte_idl80.sav'),
|
| 286 |
+
verbose=False)
|
| 287 |
+
|
| 288 |
+
assert_identical(s.y.x[0], np.array([55,66], dtype=np.uint8))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class TestPointers:
|
| 292 |
+
# Check that pointers in .sav files produce references to the same object in Python
|
| 293 |
+
|
| 294 |
+
def test_pointers(self):
|
| 295 |
+
s = readsav(path.join(DATA_PATH, 'scalar_heap_pointer.sav'), verbose=False)
|
| 296 |
+
assert_identical(
|
| 297 |
+
s.c64_pointer1,
|
| 298 |
+
np.complex128(1.1987253647623157e+112-5.1987258887729157e+307j)
|
| 299 |
+
)
|
| 300 |
+
assert_identical(
|
| 301 |
+
s.c64_pointer2,
|
| 302 |
+
np.complex128(1.1987253647623157e+112-5.1987258887729157e+307j)
|
| 303 |
+
)
|
| 304 |
+
assert_(s.c64_pointer1 is s.c64_pointer2)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
class TestPointerArray:
|
| 308 |
+
# Test that pointers in arrays are correctly read in
|
| 309 |
+
|
| 310 |
+
def test_1d(self):
|
| 311 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_1d.sav'), verbose=False)
|
| 312 |
+
assert_equal(s.array1d.shape, (123, ))
|
| 313 |
+
assert_(np.all(s.array1d == np.float32(4.)))
|
| 314 |
+
assert_(np.all(vect_id(s.array1d) == id(s.array1d[0])))
|
| 315 |
+
|
| 316 |
+
def test_2d(self):
|
| 317 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_2d.sav'), verbose=False)
|
| 318 |
+
assert_equal(s.array2d.shape, (22, 12))
|
| 319 |
+
assert_(np.all(s.array2d == np.float32(4.)))
|
| 320 |
+
assert_(np.all(vect_id(s.array2d) == id(s.array2d[0,0])))
|
| 321 |
+
|
| 322 |
+
def test_3d(self):
|
| 323 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_3d.sav'), verbose=False)
|
| 324 |
+
assert_equal(s.array3d.shape, (11, 22, 12))
|
| 325 |
+
assert_(np.all(s.array3d == np.float32(4.)))
|
| 326 |
+
assert_(np.all(vect_id(s.array3d) == id(s.array3d[0,0,0])))
|
| 327 |
+
|
| 328 |
+
def test_4d(self):
|
| 329 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_4d.sav'), verbose=False)
|
| 330 |
+
assert_equal(s.array4d.shape, (4, 5, 8, 7))
|
| 331 |
+
assert_(np.all(s.array4d == np.float32(4.)))
|
| 332 |
+
assert_(np.all(vect_id(s.array4d) == id(s.array4d[0,0,0,0])))
|
| 333 |
+
|
| 334 |
+
def test_5d(self):
|
| 335 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_5d.sav'), verbose=False)
|
| 336 |
+
assert_equal(s.array5d.shape, (4, 3, 4, 6, 5))
|
| 337 |
+
assert_(np.all(s.array5d == np.float32(4.)))
|
| 338 |
+
assert_(np.all(vect_id(s.array5d) == id(s.array5d[0,0,0,0,0])))
|
| 339 |
+
|
| 340 |
+
def test_6d(self):
|
| 341 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_6d.sav'), verbose=False)
|
| 342 |
+
assert_equal(s.array6d.shape, (3, 6, 4, 5, 3, 4))
|
| 343 |
+
assert_(np.all(s.array6d == np.float32(4.)))
|
| 344 |
+
assert_(np.all(vect_id(s.array6d) == id(s.array6d[0,0,0,0,0,0])))
|
| 345 |
+
|
| 346 |
+
def test_7d(self):
|
| 347 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_7d.sav'), verbose=False)
|
| 348 |
+
assert_equal(s.array7d.shape, (2, 1, 2, 3, 4, 3, 2))
|
| 349 |
+
assert_(np.all(s.array7d == np.float32(4.)))
|
| 350 |
+
assert_(np.all(vect_id(s.array7d) == id(s.array7d[0,0,0,0,0,0,0])))
|
| 351 |
+
|
| 352 |
+
def test_8d(self):
|
| 353 |
+
s = readsav(path.join(DATA_PATH, 'array_float32_pointer_8d.sav'), verbose=False)
|
| 354 |
+
assert_equal(s.array8d.shape, (4, 3, 2, 1, 2, 3, 5, 4))
|
| 355 |
+
assert_(np.all(s.array8d == np.float32(4.)))
|
| 356 |
+
assert_(np.all(vect_id(s.array8d) == id(s.array8d[0,0,0,0,0,0,0,0])))
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class TestPointerStructures:
|
| 360 |
+
# Test that structures are correctly read in
|
| 361 |
+
|
| 362 |
+
def test_scalars(self):
|
| 363 |
+
s = readsav(path.join(DATA_PATH, 'struct_pointers.sav'), verbose=False)
|
| 364 |
+
assert_identical(s.pointers.g, np.array(np.float32(4.), dtype=np.object_))
|
| 365 |
+
assert_identical(s.pointers.h, np.array(np.float32(4.), dtype=np.object_))
|
| 366 |
+
assert_(id(s.pointers.g[0]) == id(s.pointers.h[0]))
|
| 367 |
+
|
| 368 |
+
def test_pointers_replicated(self):
|
| 369 |
+
s = readsav(path.join(DATA_PATH, 'struct_pointers_replicated.sav'),
|
| 370 |
+
verbose=False)
|
| 371 |
+
assert_identical(s.pointers_rep.g,
|
| 372 |
+
np.repeat(np.float32(4.), 5).astype(np.object_))
|
| 373 |
+
assert_identical(s.pointers_rep.h,
|
| 374 |
+
np.repeat(np.float32(4.), 5).astype(np.object_))
|
| 375 |
+
assert_(np.all(vect_id(s.pointers_rep.g) == vect_id(s.pointers_rep.h)))
|
| 376 |
+
|
| 377 |
+
def test_pointers_replicated_3d(self):
|
| 378 |
+
s = readsav(path.join(DATA_PATH, 'struct_pointers_replicated_3d.sav'),
|
| 379 |
+
verbose=False)
|
| 380 |
+
s_expect = np.repeat(np.float32(4.), 24).reshape(4, 3, 2).astype(np.object_)
|
| 381 |
+
assert_identical(s.pointers_rep.g, s_expect)
|
| 382 |
+
assert_identical(s.pointers_rep.h, s_expect)
|
| 383 |
+
assert_(np.all(vect_id(s.pointers_rep.g) == vect_id(s.pointers_rep.h)))
|
| 384 |
+
|
| 385 |
+
def test_arrays(self):
|
| 386 |
+
s = readsav(path.join(DATA_PATH, 'struct_pointer_arrays.sav'), verbose=False)
|
| 387 |
+
assert_array_identical(s.arrays.g[0],
|
| 388 |
+
np.repeat(np.float32(4.), 2).astype(np.object_))
|
| 389 |
+
assert_array_identical(s.arrays.h[0],
|
| 390 |
+
np.repeat(np.float32(4.), 3).astype(np.object_))
|
| 391 |
+
assert_(np.all(vect_id(s.arrays.g[0]) == id(s.arrays.g[0][0])))
|
| 392 |
+
assert_(np.all(vect_id(s.arrays.h[0]) == id(s.arrays.h[0][0])))
|
| 393 |
+
assert_(id(s.arrays.g[0][0]) == id(s.arrays.h[0][0]))
|
| 394 |
+
|
| 395 |
+
def test_arrays_replicated(self):
|
| 396 |
+
s = readsav(path.join(DATA_PATH, 'struct_pointer_arrays_replicated.sav'),
|
| 397 |
+
verbose=False)
|
| 398 |
+
|
| 399 |
+
# Check column types
|
| 400 |
+
assert_(s.arrays_rep.g.dtype.type is np.object_)
|
| 401 |
+
assert_(s.arrays_rep.h.dtype.type is np.object_)
|
| 402 |
+
|
| 403 |
+
# Check column shapes
|
| 404 |
+
assert_equal(s.arrays_rep.g.shape, (5, ))
|
| 405 |
+
assert_equal(s.arrays_rep.h.shape, (5, ))
|
| 406 |
+
|
| 407 |
+
# Check values
|
| 408 |
+
for i in range(5):
|
| 409 |
+
assert_array_identical(s.arrays_rep.g[i],
|
| 410 |
+
np.repeat(np.float32(4.), 2).astype(np.object_))
|
| 411 |
+
assert_array_identical(s.arrays_rep.h[i],
|
| 412 |
+
np.repeat(np.float32(4.), 3).astype(np.object_))
|
| 413 |
+
assert_(np.all(vect_id(s.arrays_rep.g[i]) == id(s.arrays_rep.g[0][0])))
|
| 414 |
+
assert_(np.all(vect_id(s.arrays_rep.h[i]) == id(s.arrays_rep.h[0][0])))
|
| 415 |
+
|
| 416 |
+
def test_arrays_replicated_3d(self):
|
| 417 |
+
pth = path.join(DATA_PATH, 'struct_pointer_arrays_replicated_3d.sav')
|
| 418 |
+
s = readsav(pth, verbose=False)
|
| 419 |
+
|
| 420 |
+
# Check column types
|
| 421 |
+
assert_(s.arrays_rep.g.dtype.type is np.object_)
|
| 422 |
+
assert_(s.arrays_rep.h.dtype.type is np.object_)
|
| 423 |
+
|
| 424 |
+
# Check column shapes
|
| 425 |
+
assert_equal(s.arrays_rep.g.shape, (4, 3, 2))
|
| 426 |
+
assert_equal(s.arrays_rep.h.shape, (4, 3, 2))
|
| 427 |
+
|
| 428 |
+
# Check values
|
| 429 |
+
for i in range(4):
|
| 430 |
+
for j in range(3):
|
| 431 |
+
for k in range(2):
|
| 432 |
+
assert_array_identical(s.arrays_rep.g[i, j, k],
|
| 433 |
+
np.repeat(np.float32(4.), 2).astype(np.object_))
|
| 434 |
+
assert_array_identical(s.arrays_rep.h[i, j, k],
|
| 435 |
+
np.repeat(np.float32(4.), 3).astype(np.object_))
|
| 436 |
+
g0 = vect_id(s.arrays_rep.g[i, j, k])
|
| 437 |
+
g1 = id(s.arrays_rep.g[0, 0, 0][0])
|
| 438 |
+
assert np.all(g0 == g1)
|
| 439 |
+
h0 = vect_id(s.arrays_rep.h[i, j, k])
|
| 440 |
+
h1 = id(s.arrays_rep.h[0, 0, 0][0])
|
| 441 |
+
assert np.all(h0 == h1)
|
| 442 |
+
class TestTags:
|
| 443 |
+
'''Test that sav files with description tag read at all'''
|
| 444 |
+
|
| 445 |
+
def test_description(self):
|
| 446 |
+
s = readsav(path.join(DATA_PATH, 'scalar_byte_descr.sav'), verbose=False)
|
| 447 |
+
assert_identical(s.i8u, np.uint8(234))
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def test_null_pointer():
|
| 451 |
+
# Regression test for null pointers.
|
| 452 |
+
s = readsav(path.join(DATA_PATH, 'null_pointer.sav'), verbose=False)
|
| 453 |
+
assert_identical(s.point, None)
|
| 454 |
+
assert_identical(s.check, np.int16(5))
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def test_invalid_pointer():
|
| 458 |
+
# Regression test for invalid pointers (gh-4613).
|
| 459 |
+
|
| 460 |
+
# In some files in the wild, pointers can sometimes refer to a heap
|
| 461 |
+
# variable that does not exist. In that case, we now gracefully fail for
|
| 462 |
+
# that variable and replace the variable with None and emit a warning.
|
| 463 |
+
# Since it's difficult to artificially produce such files, the file used
|
| 464 |
+
# here has been edited to force the pointer reference to be invalid.
|
| 465 |
+
with warnings.catch_warnings(record=True) as w:
|
| 466 |
+
warnings.simplefilter("always")
|
| 467 |
+
s = readsav(path.join(DATA_PATH, 'invalid_pointer.sav'), verbose=False)
|
| 468 |
+
assert_(len(w) == 1)
|
| 469 |
+
assert_(str(w[0].message) == ("Variable referenced by pointer not found in "
|
| 470 |
+
"heap: variable will be set to None"))
|
| 471 |
+
assert_identical(s['a'], np.array([None, None]))
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def test_attrdict():
|
| 475 |
+
d = _idl.AttrDict({'one': 1})
|
| 476 |
+
assert d['one'] == 1
|
| 477 |
+
assert d.one == 1
|
| 478 |
+
with pytest.raises(KeyError):
|
| 479 |
+
d['two']
|
| 480 |
+
with pytest.raises(AttributeError, match='has no attribute'):
|
| 481 |
+
d.two
|
parrot/lib/python3.10/site-packages/scipy/io/tests/test_mmio.py
ADDED
|
@@ -0,0 +1,803 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tempfile import mkdtemp
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
import shutil
|
| 5 |
+
import textwrap
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from numpy import array, transpose, pi
|
| 9 |
+
from numpy.testing import (assert_equal, assert_allclose,
|
| 10 |
+
assert_array_equal, assert_array_almost_equal)
|
| 11 |
+
import pytest
|
| 12 |
+
from pytest import raises as assert_raises
|
| 13 |
+
|
| 14 |
+
import scipy.sparse
|
| 15 |
+
import scipy.io._mmio
|
| 16 |
+
import scipy.io._fast_matrix_market as fmm
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
parametrize_args = [('integer', 'int'),
|
| 20 |
+
('unsigned-integer', 'uint')]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# Run the entire test suite on both _mmio and _fast_matrix_market implementations
|
| 24 |
+
@pytest.fixture(scope='module', params=(scipy.io._mmio, fmm), autouse=True)
|
| 25 |
+
def implementations(request):
|
| 26 |
+
global mminfo
|
| 27 |
+
global mmread
|
| 28 |
+
global mmwrite
|
| 29 |
+
mminfo = request.param.mminfo
|
| 30 |
+
mmread = request.param.mmread
|
| 31 |
+
mmwrite = request.param.mmwrite
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TestMMIOArray:
|
| 35 |
+
def setup_method(self):
|
| 36 |
+
self.tmpdir = mkdtemp()
|
| 37 |
+
self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
|
| 38 |
+
|
| 39 |
+
def teardown_method(self):
|
| 40 |
+
shutil.rmtree(self.tmpdir)
|
| 41 |
+
|
| 42 |
+
def check(self, a, info):
|
| 43 |
+
mmwrite(self.fn, a)
|
| 44 |
+
assert_equal(mminfo(self.fn), info)
|
| 45 |
+
b = mmread(self.fn)
|
| 46 |
+
assert_array_almost_equal(a, b)
|
| 47 |
+
|
| 48 |
+
def check_exact(self, a, info):
|
| 49 |
+
mmwrite(self.fn, a)
|
| 50 |
+
assert_equal(mminfo(self.fn), info)
|
| 51 |
+
b = mmread(self.fn)
|
| 52 |
+
assert_equal(a, b)
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 55 |
+
def test_simple_integer(self, typeval, dtype):
|
| 56 |
+
self.check_exact(array([[1, 2], [3, 4]], dtype=dtype),
|
| 57 |
+
(2, 2, 4, 'array', typeval, 'general'))
|
| 58 |
+
|
| 59 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 60 |
+
def test_32bit_integer(self, typeval, dtype):
|
| 61 |
+
a = array([[2**31-1, 2**31-2], [2**31-3, 2**31-4]], dtype=dtype)
|
| 62 |
+
self.check_exact(a, (2, 2, 4, 'array', typeval, 'general'))
|
| 63 |
+
|
| 64 |
+
def test_64bit_integer(self):
|
| 65 |
+
a = array([[2**31, 2**32], [2**63-2, 2**63-1]], dtype=np.int64)
|
| 66 |
+
if (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite:
|
| 67 |
+
assert_raises(OverflowError, mmwrite, self.fn, a)
|
| 68 |
+
else:
|
| 69 |
+
self.check_exact(a, (2, 2, 4, 'array', 'integer', 'general'))
|
| 70 |
+
|
| 71 |
+
def test_64bit_unsigned_integer(self):
|
| 72 |
+
a = array([[2**31, 2**32], [2**64-2, 2**64-1]], dtype=np.uint64)
|
| 73 |
+
self.check_exact(a, (2, 2, 4, 'array', 'unsigned-integer', 'general'))
|
| 74 |
+
|
| 75 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 76 |
+
def test_simple_upper_triangle_integer(self, typeval, dtype):
|
| 77 |
+
self.check_exact(array([[0, 1], [0, 0]], dtype=dtype),
|
| 78 |
+
(2, 2, 4, 'array', typeval, 'general'))
|
| 79 |
+
|
| 80 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 81 |
+
def test_simple_lower_triangle_integer(self, typeval, dtype):
|
| 82 |
+
self.check_exact(array([[0, 0], [1, 0]], dtype=dtype),
|
| 83 |
+
(2, 2, 4, 'array', typeval, 'general'))
|
| 84 |
+
|
| 85 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 86 |
+
def test_simple_rectangular_integer(self, typeval, dtype):
|
| 87 |
+
self.check_exact(array([[1, 2, 3], [4, 5, 6]], dtype=dtype),
|
| 88 |
+
(2, 3, 6, 'array', typeval, 'general'))
|
| 89 |
+
|
| 90 |
+
def test_simple_rectangular_float(self):
|
| 91 |
+
self.check([[1, 2], [3.5, 4], [5, 6]],
|
| 92 |
+
(3, 2, 6, 'array', 'real', 'general'))
|
| 93 |
+
|
| 94 |
+
def test_simple_float(self):
|
| 95 |
+
self.check([[1, 2], [3, 4.0]],
|
| 96 |
+
(2, 2, 4, 'array', 'real', 'general'))
|
| 97 |
+
|
| 98 |
+
def test_simple_complex(self):
|
| 99 |
+
self.check([[1, 2], [3, 4j]],
|
| 100 |
+
(2, 2, 4, 'array', 'complex', 'general'))
|
| 101 |
+
|
| 102 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 103 |
+
def test_simple_symmetric_integer(self, typeval, dtype):
|
| 104 |
+
self.check_exact(array([[1, 2], [2, 4]], dtype=dtype),
|
| 105 |
+
(2, 2, 4, 'array', typeval, 'symmetric'))
|
| 106 |
+
|
| 107 |
+
def test_simple_skew_symmetric_integer(self):
|
| 108 |
+
self.check_exact([[0, 2], [-2, 0]],
|
| 109 |
+
(2, 2, 4, 'array', 'integer', 'skew-symmetric'))
|
| 110 |
+
|
| 111 |
+
def test_simple_skew_symmetric_float(self):
|
| 112 |
+
self.check(array([[0, 2], [-2.0, 0.0]], 'f'),
|
| 113 |
+
(2, 2, 4, 'array', 'real', 'skew-symmetric'))
|
| 114 |
+
|
| 115 |
+
def test_simple_hermitian_complex(self):
|
| 116 |
+
self.check([[1, 2+3j], [2-3j, 4]],
|
| 117 |
+
(2, 2, 4, 'array', 'complex', 'hermitian'))
|
| 118 |
+
|
| 119 |
+
def test_random_symmetric_float(self):
|
| 120 |
+
sz = (20, 20)
|
| 121 |
+
a = np.random.random(sz)
|
| 122 |
+
a = a + transpose(a)
|
| 123 |
+
self.check(a, (20, 20, 400, 'array', 'real', 'symmetric'))
|
| 124 |
+
|
| 125 |
+
def test_random_rectangular_float(self):
|
| 126 |
+
sz = (20, 15)
|
| 127 |
+
a = np.random.random(sz)
|
| 128 |
+
self.check(a, (20, 15, 300, 'array', 'real', 'general'))
|
| 129 |
+
|
| 130 |
+
@pytest.mark.fail_slow(5)
|
| 131 |
+
def test_bad_number_of_array_header_fields(self):
|
| 132 |
+
s = """\
|
| 133 |
+
%%MatrixMarket matrix array real general
|
| 134 |
+
3 3 999
|
| 135 |
+
1.0
|
| 136 |
+
2.0
|
| 137 |
+
3.0
|
| 138 |
+
4.0
|
| 139 |
+
5.0
|
| 140 |
+
6.0
|
| 141 |
+
7.0
|
| 142 |
+
8.0
|
| 143 |
+
9.0
|
| 144 |
+
"""
|
| 145 |
+
text = textwrap.dedent(s).encode('ascii')
|
| 146 |
+
with pytest.raises(ValueError, match='not of length 2'):
|
| 147 |
+
scipy.io.mmread(io.BytesIO(text))
|
| 148 |
+
|
| 149 |
+
def test_gh13634_non_skew_symmetric_int(self):
|
| 150 |
+
self.check_exact(array([[1, 2], [-2, 99]], dtype=np.int32),
|
| 151 |
+
(2, 2, 4, 'array', 'integer', 'general'))
|
| 152 |
+
|
| 153 |
+
def test_gh13634_non_skew_symmetric_float(self):
|
| 154 |
+
self.check(array([[1, 2], [-2, 99.]], dtype=np.float32),
|
| 155 |
+
(2, 2, 4, 'array', 'real', 'general'))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class TestMMIOSparseCSR(TestMMIOArray):
|
| 159 |
+
def setup_method(self):
|
| 160 |
+
self.tmpdir = mkdtemp()
|
| 161 |
+
self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
|
| 162 |
+
|
| 163 |
+
def teardown_method(self):
|
| 164 |
+
shutil.rmtree(self.tmpdir)
|
| 165 |
+
|
| 166 |
+
def check(self, a, info):
|
| 167 |
+
mmwrite(self.fn, a)
|
| 168 |
+
assert_equal(mminfo(self.fn), info)
|
| 169 |
+
b = mmread(self.fn)
|
| 170 |
+
assert_array_almost_equal(a.toarray(), b.toarray())
|
| 171 |
+
|
| 172 |
+
def check_exact(self, a, info):
|
| 173 |
+
mmwrite(self.fn, a)
|
| 174 |
+
assert_equal(mminfo(self.fn), info)
|
| 175 |
+
b = mmread(self.fn)
|
| 176 |
+
assert_equal(a.toarray(), b.toarray())
|
| 177 |
+
|
| 178 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 179 |
+
def test_simple_integer(self, typeval, dtype):
|
| 180 |
+
self.check_exact(scipy.sparse.csr_matrix([[1, 2], [3, 4]], dtype=dtype),
|
| 181 |
+
(2, 2, 4, 'coordinate', typeval, 'general'))
|
| 182 |
+
|
| 183 |
+
def test_32bit_integer(self):
|
| 184 |
+
a = scipy.sparse.csr_matrix(array([[2**31-1, -2**31+2],
|
| 185 |
+
[2**31-3, 2**31-4]],
|
| 186 |
+
dtype=np.int32))
|
| 187 |
+
self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general'))
|
| 188 |
+
|
| 189 |
+
def test_64bit_integer(self):
|
| 190 |
+
a = scipy.sparse.csr_matrix(array([[2**32+1, 2**32+1],
|
| 191 |
+
[-2**63+2, 2**63-2]],
|
| 192 |
+
dtype=np.int64))
|
| 193 |
+
if (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite:
|
| 194 |
+
assert_raises(OverflowError, mmwrite, self.fn, a)
|
| 195 |
+
else:
|
| 196 |
+
self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general'))
|
| 197 |
+
|
| 198 |
+
def test_32bit_unsigned_integer(self):
|
| 199 |
+
a = scipy.sparse.csr_matrix(array([[2**31-1, 2**31-2],
|
| 200 |
+
[2**31-3, 2**31-4]],
|
| 201 |
+
dtype=np.uint32))
|
| 202 |
+
self.check_exact(a, (2, 2, 4, 'coordinate', 'unsigned-integer', 'general'))
|
| 203 |
+
|
| 204 |
+
def test_64bit_unsigned_integer(self):
|
| 205 |
+
a = scipy.sparse.csr_matrix(array([[2**32+1, 2**32+1],
|
| 206 |
+
[2**64-2, 2**64-1]],
|
| 207 |
+
dtype=np.uint64))
|
| 208 |
+
self.check_exact(a, (2, 2, 4, 'coordinate', 'unsigned-integer', 'general'))
|
| 209 |
+
|
| 210 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 211 |
+
def test_simple_upper_triangle_integer(self, typeval, dtype):
|
| 212 |
+
self.check_exact(scipy.sparse.csr_matrix([[0, 1], [0, 0]], dtype=dtype),
|
| 213 |
+
(2, 2, 1, 'coordinate', typeval, 'general'))
|
| 214 |
+
|
| 215 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 216 |
+
def test_simple_lower_triangle_integer(self, typeval, dtype):
|
| 217 |
+
self.check_exact(scipy.sparse.csr_matrix([[0, 0], [1, 0]], dtype=dtype),
|
| 218 |
+
(2, 2, 1, 'coordinate', typeval, 'general'))
|
| 219 |
+
|
| 220 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 221 |
+
def test_simple_rectangular_integer(self, typeval, dtype):
|
| 222 |
+
self.check_exact(scipy.sparse.csr_matrix([[1, 2, 3], [4, 5, 6]], dtype=dtype),
|
| 223 |
+
(2, 3, 6, 'coordinate', typeval, 'general'))
|
| 224 |
+
|
| 225 |
+
def test_simple_rectangular_float(self):
|
| 226 |
+
self.check(scipy.sparse.csr_matrix([[1, 2], [3.5, 4], [5, 6]]),
|
| 227 |
+
(3, 2, 6, 'coordinate', 'real', 'general'))
|
| 228 |
+
|
| 229 |
+
def test_simple_float(self):
|
| 230 |
+
self.check(scipy.sparse.csr_matrix([[1, 2], [3, 4.0]]),
|
| 231 |
+
(2, 2, 4, 'coordinate', 'real', 'general'))
|
| 232 |
+
|
| 233 |
+
def test_simple_complex(self):
|
| 234 |
+
self.check(scipy.sparse.csr_matrix([[1, 2], [3, 4j]]),
|
| 235 |
+
(2, 2, 4, 'coordinate', 'complex', 'general'))
|
| 236 |
+
|
| 237 |
+
@pytest.mark.parametrize('typeval, dtype', parametrize_args)
|
| 238 |
+
def test_simple_symmetric_integer(self, typeval, dtype):
|
| 239 |
+
self.check_exact(scipy.sparse.csr_matrix([[1, 2], [2, 4]], dtype=dtype),
|
| 240 |
+
(2, 2, 3, 'coordinate', typeval, 'symmetric'))
|
| 241 |
+
|
| 242 |
+
def test_simple_skew_symmetric_integer(self):
|
| 243 |
+
self.check_exact(scipy.sparse.csr_matrix([[0, 2], [-2, 0]]),
|
| 244 |
+
(2, 2, 1, 'coordinate', 'integer', 'skew-symmetric'))
|
| 245 |
+
|
| 246 |
+
def test_simple_skew_symmetric_float(self):
|
| 247 |
+
self.check(scipy.sparse.csr_matrix(array([[0, 2], [-2.0, 0]], 'f')),
|
| 248 |
+
(2, 2, 1, 'coordinate', 'real', 'skew-symmetric'))
|
| 249 |
+
|
| 250 |
+
def test_simple_hermitian_complex(self):
|
| 251 |
+
self.check(scipy.sparse.csr_matrix([[1, 2+3j], [2-3j, 4]]),
|
| 252 |
+
(2, 2, 3, 'coordinate', 'complex', 'hermitian'))
|
| 253 |
+
|
| 254 |
+
def test_random_symmetric_float(self):
|
| 255 |
+
sz = (20, 20)
|
| 256 |
+
a = np.random.random(sz)
|
| 257 |
+
a = a + transpose(a)
|
| 258 |
+
a = scipy.sparse.csr_matrix(a)
|
| 259 |
+
self.check(a, (20, 20, 210, 'coordinate', 'real', 'symmetric'))
|
| 260 |
+
|
| 261 |
+
def test_random_rectangular_float(self):
|
| 262 |
+
sz = (20, 15)
|
| 263 |
+
a = np.random.random(sz)
|
| 264 |
+
a = scipy.sparse.csr_matrix(a)
|
| 265 |
+
self.check(a, (20, 15, 300, 'coordinate', 'real', 'general'))
|
| 266 |
+
|
| 267 |
+
def test_simple_pattern(self):
|
| 268 |
+
a = scipy.sparse.csr_matrix([[0, 1.5], [3.0, 2.5]])
|
| 269 |
+
p = np.zeros_like(a.toarray())
|
| 270 |
+
p[a.toarray() > 0] = 1
|
| 271 |
+
info = (2, 2, 3, 'coordinate', 'pattern', 'general')
|
| 272 |
+
mmwrite(self.fn, a, field='pattern')
|
| 273 |
+
assert_equal(mminfo(self.fn), info)
|
| 274 |
+
b = mmread(self.fn)
|
| 275 |
+
assert_array_almost_equal(p, b.toarray())
|
| 276 |
+
|
| 277 |
+
def test_gh13634_non_skew_symmetric_int(self):
|
| 278 |
+
a = scipy.sparse.csr_matrix([[1, 2], [-2, 99]], dtype=np.int32)
|
| 279 |
+
self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general'))
|
| 280 |
+
|
| 281 |
+
def test_gh13634_non_skew_symmetric_float(self):
|
| 282 |
+
a = scipy.sparse.csr_matrix([[1, 2], [-2, 99.]], dtype=np.float32)
|
| 283 |
+
self.check(a, (2, 2, 4, 'coordinate', 'real', 'general'))
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
_32bit_integer_dense_example = '''\
|
| 287 |
+
%%MatrixMarket matrix array integer general
|
| 288 |
+
2 2
|
| 289 |
+
2147483647
|
| 290 |
+
2147483646
|
| 291 |
+
2147483647
|
| 292 |
+
2147483646
|
| 293 |
+
'''
|
| 294 |
+
|
| 295 |
+
_32bit_integer_sparse_example = '''\
|
| 296 |
+
%%MatrixMarket matrix coordinate integer symmetric
|
| 297 |
+
2 2 2
|
| 298 |
+
1 1 2147483647
|
| 299 |
+
2 2 2147483646
|
| 300 |
+
'''
|
| 301 |
+
|
| 302 |
+
_64bit_integer_dense_example = '''\
|
| 303 |
+
%%MatrixMarket matrix array integer general
|
| 304 |
+
2 2
|
| 305 |
+
2147483648
|
| 306 |
+
-9223372036854775806
|
| 307 |
+
-2147483648
|
| 308 |
+
9223372036854775807
|
| 309 |
+
'''
|
| 310 |
+
|
| 311 |
+
_64bit_integer_sparse_general_example = '''\
|
| 312 |
+
%%MatrixMarket matrix coordinate integer general
|
| 313 |
+
2 2 3
|
| 314 |
+
1 1 2147483648
|
| 315 |
+
1 2 9223372036854775807
|
| 316 |
+
2 2 9223372036854775807
|
| 317 |
+
'''
|
| 318 |
+
|
| 319 |
+
_64bit_integer_sparse_symmetric_example = '''\
|
| 320 |
+
%%MatrixMarket matrix coordinate integer symmetric
|
| 321 |
+
2 2 3
|
| 322 |
+
1 1 2147483648
|
| 323 |
+
1 2 -9223372036854775807
|
| 324 |
+
2 2 9223372036854775807
|
| 325 |
+
'''
|
| 326 |
+
|
| 327 |
+
_64bit_integer_sparse_skew_example = '''\
|
| 328 |
+
%%MatrixMarket matrix coordinate integer skew-symmetric
|
| 329 |
+
2 2 3
|
| 330 |
+
1 1 2147483648
|
| 331 |
+
1 2 -9223372036854775807
|
| 332 |
+
2 2 9223372036854775807
|
| 333 |
+
'''
|
| 334 |
+
|
| 335 |
+
_over64bit_integer_dense_example = '''\
|
| 336 |
+
%%MatrixMarket matrix array integer general
|
| 337 |
+
2 2
|
| 338 |
+
2147483648
|
| 339 |
+
9223372036854775807
|
| 340 |
+
2147483648
|
| 341 |
+
9223372036854775808
|
| 342 |
+
'''
|
| 343 |
+
|
| 344 |
+
_over64bit_integer_sparse_example = '''\
|
| 345 |
+
%%MatrixMarket matrix coordinate integer symmetric
|
| 346 |
+
2 2 2
|
| 347 |
+
1 1 2147483648
|
| 348 |
+
2 2 19223372036854775808
|
| 349 |
+
'''
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class TestMMIOReadLargeIntegers:
|
| 353 |
+
def setup_method(self):
|
| 354 |
+
self.tmpdir = mkdtemp()
|
| 355 |
+
self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
|
| 356 |
+
|
| 357 |
+
def teardown_method(self):
|
| 358 |
+
shutil.rmtree(self.tmpdir)
|
| 359 |
+
|
| 360 |
+
def check_read(self, example, a, info, dense, over32, over64):
|
| 361 |
+
with open(self.fn, 'w') as f:
|
| 362 |
+
f.write(example)
|
| 363 |
+
assert_equal(mminfo(self.fn), info)
|
| 364 |
+
if ((over32 and (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite)
|
| 365 |
+
or over64):
|
| 366 |
+
assert_raises(OverflowError, mmread, self.fn)
|
| 367 |
+
else:
|
| 368 |
+
b = mmread(self.fn)
|
| 369 |
+
if not dense:
|
| 370 |
+
b = b.toarray()
|
| 371 |
+
assert_equal(a, b)
|
| 372 |
+
|
| 373 |
+
def test_read_32bit_integer_dense(self):
|
| 374 |
+
a = array([[2**31-1, 2**31-1],
|
| 375 |
+
[2**31-2, 2**31-2]], dtype=np.int64)
|
| 376 |
+
self.check_read(_32bit_integer_dense_example,
|
| 377 |
+
a,
|
| 378 |
+
(2, 2, 4, 'array', 'integer', 'general'),
|
| 379 |
+
dense=True,
|
| 380 |
+
over32=False,
|
| 381 |
+
over64=False)
|
| 382 |
+
|
| 383 |
+
def test_read_32bit_integer_sparse(self):
|
| 384 |
+
a = array([[2**31-1, 0],
|
| 385 |
+
[0, 2**31-2]], dtype=np.int64)
|
| 386 |
+
self.check_read(_32bit_integer_sparse_example,
|
| 387 |
+
a,
|
| 388 |
+
(2, 2, 2, 'coordinate', 'integer', 'symmetric'),
|
| 389 |
+
dense=False,
|
| 390 |
+
over32=False,
|
| 391 |
+
over64=False)
|
| 392 |
+
|
| 393 |
+
def test_read_64bit_integer_dense(self):
|
| 394 |
+
a = array([[2**31, -2**31],
|
| 395 |
+
[-2**63+2, 2**63-1]], dtype=np.int64)
|
| 396 |
+
self.check_read(_64bit_integer_dense_example,
|
| 397 |
+
a,
|
| 398 |
+
(2, 2, 4, 'array', 'integer', 'general'),
|
| 399 |
+
dense=True,
|
| 400 |
+
over32=True,
|
| 401 |
+
over64=False)
|
| 402 |
+
|
| 403 |
+
def test_read_64bit_integer_sparse_general(self):
|
| 404 |
+
a = array([[2**31, 2**63-1],
|
| 405 |
+
[0, 2**63-1]], dtype=np.int64)
|
| 406 |
+
self.check_read(_64bit_integer_sparse_general_example,
|
| 407 |
+
a,
|
| 408 |
+
(2, 2, 3, 'coordinate', 'integer', 'general'),
|
| 409 |
+
dense=False,
|
| 410 |
+
over32=True,
|
| 411 |
+
over64=False)
|
| 412 |
+
|
| 413 |
+
def test_read_64bit_integer_sparse_symmetric(self):
|
| 414 |
+
a = array([[2**31, -2**63+1],
|
| 415 |
+
[-2**63+1, 2**63-1]], dtype=np.int64)
|
| 416 |
+
self.check_read(_64bit_integer_sparse_symmetric_example,
|
| 417 |
+
a,
|
| 418 |
+
(2, 2, 3, 'coordinate', 'integer', 'symmetric'),
|
| 419 |
+
dense=False,
|
| 420 |
+
over32=True,
|
| 421 |
+
over64=False)
|
| 422 |
+
|
| 423 |
+
def test_read_64bit_integer_sparse_skew(self):
|
| 424 |
+
a = array([[2**31, -2**63+1],
|
| 425 |
+
[2**63-1, 2**63-1]], dtype=np.int64)
|
| 426 |
+
self.check_read(_64bit_integer_sparse_skew_example,
|
| 427 |
+
a,
|
| 428 |
+
(2, 2, 3, 'coordinate', 'integer', 'skew-symmetric'),
|
| 429 |
+
dense=False,
|
| 430 |
+
over32=True,
|
| 431 |
+
over64=False)
|
| 432 |
+
|
| 433 |
+
def test_read_over64bit_integer_dense(self):
|
| 434 |
+
self.check_read(_over64bit_integer_dense_example,
|
| 435 |
+
None,
|
| 436 |
+
(2, 2, 4, 'array', 'integer', 'general'),
|
| 437 |
+
dense=True,
|
| 438 |
+
over32=True,
|
| 439 |
+
over64=True)
|
| 440 |
+
|
| 441 |
+
def test_read_over64bit_integer_sparse(self):
|
| 442 |
+
self.check_read(_over64bit_integer_sparse_example,
|
| 443 |
+
None,
|
| 444 |
+
(2, 2, 2, 'coordinate', 'integer', 'symmetric'),
|
| 445 |
+
dense=False,
|
| 446 |
+
over32=True,
|
| 447 |
+
over64=True)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
_general_example = '''\
|
| 451 |
+
%%MatrixMarket matrix coordinate real general
|
| 452 |
+
%=================================================================================
|
| 453 |
+
%
|
| 454 |
+
% This ASCII file represents a sparse MxN matrix with L
|
| 455 |
+
% nonzeros in the following Matrix Market format:
|
| 456 |
+
%
|
| 457 |
+
% +----------------------------------------------+
|
| 458 |
+
% |%%MatrixMarket matrix coordinate real general | <--- header line
|
| 459 |
+
% |% | <--+
|
| 460 |
+
% |% comments | |-- 0 or more comment lines
|
| 461 |
+
% |% | <--+
|
| 462 |
+
% | M N L | <--- rows, columns, entries
|
| 463 |
+
% | I1 J1 A(I1, J1) | <--+
|
| 464 |
+
% | I2 J2 A(I2, J2) | |
|
| 465 |
+
% | I3 J3 A(I3, J3) | |-- L lines
|
| 466 |
+
% | . . . | |
|
| 467 |
+
% | IL JL A(IL, JL) | <--+
|
| 468 |
+
% +----------------------------------------------+
|
| 469 |
+
%
|
| 470 |
+
% Indices are 1-based, i.e. A(1,1) is the first element.
|
| 471 |
+
%
|
| 472 |
+
%=================================================================================
|
| 473 |
+
5 5 8
|
| 474 |
+
1 1 1.000e+00
|
| 475 |
+
2 2 1.050e+01
|
| 476 |
+
3 3 1.500e-02
|
| 477 |
+
1 4 6.000e+00
|
| 478 |
+
4 2 2.505e+02
|
| 479 |
+
4 4 -2.800e+02
|
| 480 |
+
4 5 3.332e+01
|
| 481 |
+
5 5 1.200e+01
|
| 482 |
+
'''
|
| 483 |
+
|
| 484 |
+
_hermitian_example = '''\
|
| 485 |
+
%%MatrixMarket matrix coordinate complex hermitian
|
| 486 |
+
5 5 7
|
| 487 |
+
1 1 1.0 0
|
| 488 |
+
2 2 10.5 0
|
| 489 |
+
4 2 250.5 22.22
|
| 490 |
+
3 3 1.5e-2 0
|
| 491 |
+
4 4 -2.8e2 0
|
| 492 |
+
5 5 12. 0
|
| 493 |
+
5 4 0 33.32
|
| 494 |
+
'''
|
| 495 |
+
|
| 496 |
+
_skew_example = '''\
|
| 497 |
+
%%MatrixMarket matrix coordinate real skew-symmetric
|
| 498 |
+
5 5 7
|
| 499 |
+
1 1 1.0
|
| 500 |
+
2 2 10.5
|
| 501 |
+
4 2 250.5
|
| 502 |
+
3 3 1.5e-2
|
| 503 |
+
4 4 -2.8e2
|
| 504 |
+
5 5 12.
|
| 505 |
+
5 4 0
|
| 506 |
+
'''
|
| 507 |
+
|
| 508 |
+
_symmetric_example = '''\
|
| 509 |
+
%%MatrixMarket matrix coordinate real symmetric
|
| 510 |
+
5 5 7
|
| 511 |
+
1 1 1.0
|
| 512 |
+
2 2 10.5
|
| 513 |
+
4 2 250.5
|
| 514 |
+
3 3 1.5e-2
|
| 515 |
+
4 4 -2.8e2
|
| 516 |
+
5 5 12.
|
| 517 |
+
5 4 8
|
| 518 |
+
'''
|
| 519 |
+
|
| 520 |
+
_symmetric_pattern_example = '''\
|
| 521 |
+
%%MatrixMarket matrix coordinate pattern symmetric
|
| 522 |
+
5 5 7
|
| 523 |
+
1 1
|
| 524 |
+
2 2
|
| 525 |
+
4 2
|
| 526 |
+
3 3
|
| 527 |
+
4 4
|
| 528 |
+
5 5
|
| 529 |
+
5 4
|
| 530 |
+
'''
|
| 531 |
+
|
| 532 |
+
# example (without comment lines) from Figure 1 in
|
| 533 |
+
# https://math.nist.gov/MatrixMarket/reports/MMformat.ps
|
| 534 |
+
_empty_lines_example = '''\
|
| 535 |
+
%%MatrixMarket MATRIX Coordinate Real General
|
| 536 |
+
|
| 537 |
+
5 5 8
|
| 538 |
+
|
| 539 |
+
1 1 1.0
|
| 540 |
+
2 2 10.5
|
| 541 |
+
3 3 1.5e-2
|
| 542 |
+
4 4 -2.8E2
|
| 543 |
+
5 5 12.
|
| 544 |
+
1 4 6
|
| 545 |
+
4 2 250.5
|
| 546 |
+
4 5 33.32
|
| 547 |
+
|
| 548 |
+
'''
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
class TestMMIOCoordinate:
|
| 552 |
+
def setup_method(self):
|
| 553 |
+
self.tmpdir = mkdtemp()
|
| 554 |
+
self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
|
| 555 |
+
|
| 556 |
+
def teardown_method(self):
|
| 557 |
+
shutil.rmtree(self.tmpdir)
|
| 558 |
+
|
| 559 |
+
def check_read(self, example, a, info):
|
| 560 |
+
f = open(self.fn, 'w')
|
| 561 |
+
f.write(example)
|
| 562 |
+
f.close()
|
| 563 |
+
assert_equal(mminfo(self.fn), info)
|
| 564 |
+
b = mmread(self.fn).toarray()
|
| 565 |
+
assert_array_almost_equal(a, b)
|
| 566 |
+
|
| 567 |
+
def test_read_general(self):
|
| 568 |
+
a = [[1, 0, 0, 6, 0],
|
| 569 |
+
[0, 10.5, 0, 0, 0],
|
| 570 |
+
[0, 0, .015, 0, 0],
|
| 571 |
+
[0, 250.5, 0, -280, 33.32],
|
| 572 |
+
[0, 0, 0, 0, 12]]
|
| 573 |
+
self.check_read(_general_example, a,
|
| 574 |
+
(5, 5, 8, 'coordinate', 'real', 'general'))
|
| 575 |
+
|
| 576 |
+
def test_read_hermitian(self):
|
| 577 |
+
a = [[1, 0, 0, 0, 0],
|
| 578 |
+
[0, 10.5, 0, 250.5 - 22.22j, 0],
|
| 579 |
+
[0, 0, .015, 0, 0],
|
| 580 |
+
[0, 250.5 + 22.22j, 0, -280, -33.32j],
|
| 581 |
+
[0, 0, 0, 33.32j, 12]]
|
| 582 |
+
self.check_read(_hermitian_example, a,
|
| 583 |
+
(5, 5, 7, 'coordinate', 'complex', 'hermitian'))
|
| 584 |
+
|
| 585 |
+
def test_read_skew(self):
|
| 586 |
+
a = [[1, 0, 0, 0, 0],
|
| 587 |
+
[0, 10.5, 0, -250.5, 0],
|
| 588 |
+
[0, 0, .015, 0, 0],
|
| 589 |
+
[0, 250.5, 0, -280, 0],
|
| 590 |
+
[0, 0, 0, 0, 12]]
|
| 591 |
+
self.check_read(_skew_example, a,
|
| 592 |
+
(5, 5, 7, 'coordinate', 'real', 'skew-symmetric'))
|
| 593 |
+
|
| 594 |
+
def test_read_symmetric(self):
|
| 595 |
+
a = [[1, 0, 0, 0, 0],
|
| 596 |
+
[0, 10.5, 0, 250.5, 0],
|
| 597 |
+
[0, 0, .015, 0, 0],
|
| 598 |
+
[0, 250.5, 0, -280, 8],
|
| 599 |
+
[0, 0, 0, 8, 12]]
|
| 600 |
+
self.check_read(_symmetric_example, a,
|
| 601 |
+
(5, 5, 7, 'coordinate', 'real', 'symmetric'))
|
| 602 |
+
|
| 603 |
+
def test_read_symmetric_pattern(self):
|
| 604 |
+
a = [[1, 0, 0, 0, 0],
|
| 605 |
+
[0, 1, 0, 1, 0],
|
| 606 |
+
[0, 0, 1, 0, 0],
|
| 607 |
+
[0, 1, 0, 1, 1],
|
| 608 |
+
[0, 0, 0, 1, 1]]
|
| 609 |
+
self.check_read(_symmetric_pattern_example, a,
|
| 610 |
+
(5, 5, 7, 'coordinate', 'pattern', 'symmetric'))
|
| 611 |
+
|
| 612 |
+
def test_read_empty_lines(self):
|
| 613 |
+
a = [[1, 0, 0, 6, 0],
|
| 614 |
+
[0, 10.5, 0, 0, 0],
|
| 615 |
+
[0, 0, .015, 0, 0],
|
| 616 |
+
[0, 250.5, 0, -280, 33.32],
|
| 617 |
+
[0, 0, 0, 0, 12]]
|
| 618 |
+
self.check_read(_empty_lines_example, a,
|
| 619 |
+
(5, 5, 8, 'coordinate', 'real', 'general'))
|
| 620 |
+
|
| 621 |
+
def test_empty_write_read(self):
|
| 622 |
+
# https://github.com/scipy/scipy/issues/1410 (Trac #883)
|
| 623 |
+
|
| 624 |
+
b = scipy.sparse.coo_matrix((10, 10))
|
| 625 |
+
mmwrite(self.fn, b)
|
| 626 |
+
|
| 627 |
+
assert_equal(mminfo(self.fn),
|
| 628 |
+
(10, 10, 0, 'coordinate', 'real', 'symmetric'))
|
| 629 |
+
a = b.toarray()
|
| 630 |
+
b = mmread(self.fn).toarray()
|
| 631 |
+
assert_array_almost_equal(a, b)
|
| 632 |
+
|
| 633 |
+
def test_bzip2_py3(self):
|
| 634 |
+
# test if fix for #2152 works
|
| 635 |
+
try:
|
| 636 |
+
# bz2 module isn't always built when building Python.
|
| 637 |
+
import bz2
|
| 638 |
+
except ImportError:
|
| 639 |
+
return
|
| 640 |
+
I = array([0, 0, 1, 2, 3, 3, 3, 4])
|
| 641 |
+
J = array([0, 3, 1, 2, 1, 3, 4, 4])
|
| 642 |
+
V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
|
| 643 |
+
|
| 644 |
+
b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5))
|
| 645 |
+
|
| 646 |
+
mmwrite(self.fn, b)
|
| 647 |
+
|
| 648 |
+
fn_bzip2 = "%s.bz2" % self.fn
|
| 649 |
+
with open(self.fn, 'rb') as f_in:
|
| 650 |
+
f_out = bz2.BZ2File(fn_bzip2, 'wb')
|
| 651 |
+
f_out.write(f_in.read())
|
| 652 |
+
f_out.close()
|
| 653 |
+
|
| 654 |
+
a = mmread(fn_bzip2).toarray()
|
| 655 |
+
assert_array_almost_equal(a, b.toarray())
|
| 656 |
+
|
| 657 |
+
def test_gzip_py3(self):
|
| 658 |
+
# test if fix for #2152 works
|
| 659 |
+
try:
|
| 660 |
+
# gzip module can be missing from Python installation
|
| 661 |
+
import gzip
|
| 662 |
+
except ImportError:
|
| 663 |
+
return
|
| 664 |
+
I = array([0, 0, 1, 2, 3, 3, 3, 4])
|
| 665 |
+
J = array([0, 3, 1, 2, 1, 3, 4, 4])
|
| 666 |
+
V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
|
| 667 |
+
|
| 668 |
+
b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5))
|
| 669 |
+
|
| 670 |
+
mmwrite(self.fn, b)
|
| 671 |
+
|
| 672 |
+
fn_gzip = "%s.gz" % self.fn
|
| 673 |
+
with open(self.fn, 'rb') as f_in:
|
| 674 |
+
f_out = gzip.open(fn_gzip, 'wb')
|
| 675 |
+
f_out.write(f_in.read())
|
| 676 |
+
f_out.close()
|
| 677 |
+
|
| 678 |
+
a = mmread(fn_gzip).toarray()
|
| 679 |
+
assert_array_almost_equal(a, b.toarray())
|
| 680 |
+
|
| 681 |
+
def test_real_write_read(self):
|
| 682 |
+
I = array([0, 0, 1, 2, 3, 3, 3, 4])
|
| 683 |
+
J = array([0, 3, 1, 2, 1, 3, 4, 4])
|
| 684 |
+
V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
|
| 685 |
+
|
| 686 |
+
b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5))
|
| 687 |
+
|
| 688 |
+
mmwrite(self.fn, b)
|
| 689 |
+
|
| 690 |
+
assert_equal(mminfo(self.fn),
|
| 691 |
+
(5, 5, 8, 'coordinate', 'real', 'general'))
|
| 692 |
+
a = b.toarray()
|
| 693 |
+
b = mmread(self.fn).toarray()
|
| 694 |
+
assert_array_almost_equal(a, b)
|
| 695 |
+
|
| 696 |
+
def test_complex_write_read(self):
|
| 697 |
+
I = array([0, 0, 1, 2, 3, 3, 3, 4])
|
| 698 |
+
J = array([0, 3, 1, 2, 1, 3, 4, 4])
|
| 699 |
+
V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j,
|
| 700 |
+
250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j])
|
| 701 |
+
|
| 702 |
+
b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5))
|
| 703 |
+
|
| 704 |
+
mmwrite(self.fn, b)
|
| 705 |
+
|
| 706 |
+
assert_equal(mminfo(self.fn),
|
| 707 |
+
(5, 5, 8, 'coordinate', 'complex', 'general'))
|
| 708 |
+
a = b.toarray()
|
| 709 |
+
b = mmread(self.fn).toarray()
|
| 710 |
+
assert_array_almost_equal(a, b)
|
| 711 |
+
|
| 712 |
+
def test_sparse_formats(self, tmp_path):
|
| 713 |
+
# Note: `tmp_path` is a pytest fixture, it handles cleanup
|
| 714 |
+
tmpdir = tmp_path / 'sparse_formats'
|
| 715 |
+
tmpdir.mkdir()
|
| 716 |
+
|
| 717 |
+
mats = []
|
| 718 |
+
I = array([0, 0, 1, 2, 3, 3, 3, 4])
|
| 719 |
+
J = array([0, 3, 1, 2, 1, 3, 4, 4])
|
| 720 |
+
|
| 721 |
+
V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0])
|
| 722 |
+
mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)))
|
| 723 |
+
|
| 724 |
+
V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j,
|
| 725 |
+
250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j])
|
| 726 |
+
mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)))
|
| 727 |
+
|
| 728 |
+
for mat in mats:
|
| 729 |
+
expected = mat.toarray()
|
| 730 |
+
for fmt in ['csr', 'csc', 'coo']:
|
| 731 |
+
fname = tmpdir / (fmt + '.mtx')
|
| 732 |
+
mmwrite(fname, mat.asformat(fmt))
|
| 733 |
+
result = mmread(fname).toarray()
|
| 734 |
+
assert_array_almost_equal(result, expected)
|
| 735 |
+
|
| 736 |
+
def test_precision(self):
|
| 737 |
+
test_values = [pi] + [10**(i) for i in range(0, -10, -1)]
|
| 738 |
+
test_precisions = range(1, 10)
|
| 739 |
+
for value in test_values:
|
| 740 |
+
for precision in test_precisions:
|
| 741 |
+
# construct sparse matrix with test value at last main diagonal
|
| 742 |
+
n = 10**precision + 1
|
| 743 |
+
A = scipy.sparse.dok_matrix((n, n))
|
| 744 |
+
A[n-1, n-1] = value
|
| 745 |
+
# write matrix with test precision and read again
|
| 746 |
+
mmwrite(self.fn, A, precision=precision)
|
| 747 |
+
A = scipy.io.mmread(self.fn)
|
| 748 |
+
# check for right entries in matrix
|
| 749 |
+
assert_array_equal(A.row, [n-1])
|
| 750 |
+
assert_array_equal(A.col, [n-1])
|
| 751 |
+
assert_allclose(A.data, [float('%%.%dg' % precision % value)])
|
| 752 |
+
|
| 753 |
+
def test_bad_number_of_coordinate_header_fields(self):
|
| 754 |
+
s = """\
|
| 755 |
+
%%MatrixMarket matrix coordinate real general
|
| 756 |
+
5 5 8 999
|
| 757 |
+
1 1 1.000e+00
|
| 758 |
+
2 2 1.050e+01
|
| 759 |
+
3 3 1.500e-02
|
| 760 |
+
1 4 6.000e+00
|
| 761 |
+
4 2 2.505e+02
|
| 762 |
+
4 4 -2.800e+02
|
| 763 |
+
4 5 3.332e+01
|
| 764 |
+
5 5 1.200e+01
|
| 765 |
+
"""
|
| 766 |
+
text = textwrap.dedent(s).encode('ascii')
|
| 767 |
+
with pytest.raises(ValueError, match='not of length 3'):
|
| 768 |
+
scipy.io.mmread(io.BytesIO(text))
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def test_gh11389():
|
| 772 |
+
mmread(io.StringIO("%%MatrixMarket matrix coordinate complex symmetric\n"
|
| 773 |
+
" 1 1 1\n"
|
| 774 |
+
"1 1 -2.1846000000000e+02 0.0000000000000e+00"))
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def test_gh18123(tmp_path):
|
| 778 |
+
lines = [" %%MatrixMarket matrix coordinate real general\n",
|
| 779 |
+
"5 5 3\n",
|
| 780 |
+
"2 3 1.0\n",
|
| 781 |
+
"3 4 2.0\n",
|
| 782 |
+
"3 5 3.0\n"]
|
| 783 |
+
test_file = tmp_path / "test.mtx"
|
| 784 |
+
with open(test_file, "w") as f:
|
| 785 |
+
f.writelines(lines)
|
| 786 |
+
mmread(test_file)
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def test_threadpoolctl():
|
| 790 |
+
try:
|
| 791 |
+
import threadpoolctl
|
| 792 |
+
if not hasattr(threadpoolctl, "register"):
|
| 793 |
+
pytest.skip("threadpoolctl too old")
|
| 794 |
+
return
|
| 795 |
+
except ImportError:
|
| 796 |
+
pytest.skip("no threadpoolctl")
|
| 797 |
+
return
|
| 798 |
+
|
| 799 |
+
with threadpoolctl.threadpool_limits(limits=4):
|
| 800 |
+
assert_equal(fmm.PARALLELISM, 4)
|
| 801 |
+
|
| 802 |
+
with threadpoolctl.threadpool_limits(limits=2, user_api='scipy'):
|
| 803 |
+
assert_equal(fmm.PARALLELISM, 2)
|
parrot/lib/python3.10/site-packages/scipy/io/tests/test_netcdf.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
''' Tests for netcdf '''
|
| 2 |
+
import os
|
| 3 |
+
from os.path import join as pjoin, dirname
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
+
import warnings
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
from glob import glob
|
| 9 |
+
from contextlib import contextmanager
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from numpy.testing import (assert_, assert_allclose, assert_equal,
|
| 13 |
+
break_cycles, suppress_warnings, IS_PYPY)
|
| 14 |
+
from pytest import raises as assert_raises
|
| 15 |
+
|
| 16 |
+
from scipy.io import netcdf_file
|
| 17 |
+
from scipy._lib._tmpdirs import in_tempdir
|
| 18 |
+
|
| 19 |
+
TEST_DATA_PATH = pjoin(dirname(__file__), 'data')
|
| 20 |
+
|
| 21 |
+
N_EG_ELS = 11 # number of elements for example variable
|
| 22 |
+
VARTYPE_EG = 'b' # var type for example variable
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@contextmanager
|
| 26 |
+
def make_simple(*args, **kwargs):
|
| 27 |
+
f = netcdf_file(*args, **kwargs)
|
| 28 |
+
f.history = 'Created for a test'
|
| 29 |
+
f.createDimension('time', N_EG_ELS)
|
| 30 |
+
time = f.createVariable('time', VARTYPE_EG, ('time',))
|
| 31 |
+
time[:] = np.arange(N_EG_ELS)
|
| 32 |
+
time.units = 'days since 2008-01-01'
|
| 33 |
+
f.flush()
|
| 34 |
+
yield f
|
| 35 |
+
f.close()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def check_simple(ncfileobj):
|
| 39 |
+
'''Example fileobj tests '''
|
| 40 |
+
assert_equal(ncfileobj.history, b'Created for a test')
|
| 41 |
+
time = ncfileobj.variables['time']
|
| 42 |
+
assert_equal(time.units, b'days since 2008-01-01')
|
| 43 |
+
assert_equal(time.shape, (N_EG_ELS,))
|
| 44 |
+
assert_equal(time[-1], N_EG_ELS-1)
|
| 45 |
+
|
| 46 |
+
def assert_mask_matches(arr, expected_mask):
|
| 47 |
+
'''
|
| 48 |
+
Asserts that the mask of arr is effectively the same as expected_mask.
|
| 49 |
+
|
| 50 |
+
In contrast to numpy.ma.testutils.assert_mask_equal, this function allows
|
| 51 |
+
testing the 'mask' of a standard numpy array (the mask in this case is treated
|
| 52 |
+
as all False).
|
| 53 |
+
|
| 54 |
+
Parameters
|
| 55 |
+
----------
|
| 56 |
+
arr : ndarray or MaskedArray
|
| 57 |
+
Array to test.
|
| 58 |
+
expected_mask : array_like of booleans
|
| 59 |
+
A list giving the expected mask.
|
| 60 |
+
'''
|
| 61 |
+
|
| 62 |
+
mask = np.ma.getmaskarray(arr)
|
| 63 |
+
assert_equal(mask, expected_mask)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_read_write_files():
|
| 67 |
+
# test round trip for example file
|
| 68 |
+
cwd = os.getcwd()
|
| 69 |
+
try:
|
| 70 |
+
tmpdir = tempfile.mkdtemp()
|
| 71 |
+
os.chdir(tmpdir)
|
| 72 |
+
with make_simple('simple.nc', 'w') as f:
|
| 73 |
+
pass
|
| 74 |
+
# read the file we just created in 'a' mode
|
| 75 |
+
with netcdf_file('simple.nc', 'a') as f:
|
| 76 |
+
check_simple(f)
|
| 77 |
+
# add something
|
| 78 |
+
f._attributes['appendRan'] = 1
|
| 79 |
+
|
| 80 |
+
# To read the NetCDF file we just created::
|
| 81 |
+
with netcdf_file('simple.nc') as f:
|
| 82 |
+
# Using mmap is the default (but not on pypy)
|
| 83 |
+
assert_equal(f.use_mmap, not IS_PYPY)
|
| 84 |
+
check_simple(f)
|
| 85 |
+
assert_equal(f._attributes['appendRan'], 1)
|
| 86 |
+
|
| 87 |
+
# Read it in append (and check mmap is off)
|
| 88 |
+
with netcdf_file('simple.nc', 'a') as f:
|
| 89 |
+
assert_(not f.use_mmap)
|
| 90 |
+
check_simple(f)
|
| 91 |
+
assert_equal(f._attributes['appendRan'], 1)
|
| 92 |
+
|
| 93 |
+
# Now without mmap
|
| 94 |
+
with netcdf_file('simple.nc', mmap=False) as f:
|
| 95 |
+
# Using mmap is the default
|
| 96 |
+
assert_(not f.use_mmap)
|
| 97 |
+
check_simple(f)
|
| 98 |
+
|
| 99 |
+
# To read the NetCDF file we just created, as file object, no
|
| 100 |
+
# mmap. When n * n_bytes(var_type) is not divisible by 4, this
|
| 101 |
+
# raised an error in pupynere 1.0.12 and scipy rev 5893, because
|
| 102 |
+
# calculated vsize was rounding up in units of 4 - see
|
| 103 |
+
# https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
|
| 104 |
+
with open('simple.nc', 'rb') as fobj:
|
| 105 |
+
with netcdf_file(fobj) as f:
|
| 106 |
+
# by default, don't use mmap for file-like
|
| 107 |
+
assert_(not f.use_mmap)
|
| 108 |
+
check_simple(f)
|
| 109 |
+
|
| 110 |
+
# Read file from fileobj, with mmap
|
| 111 |
+
with suppress_warnings() as sup:
|
| 112 |
+
if IS_PYPY:
|
| 113 |
+
sup.filter(RuntimeWarning,
|
| 114 |
+
"Cannot close a netcdf_file opened with mmap=True.*")
|
| 115 |
+
with open('simple.nc', 'rb') as fobj:
|
| 116 |
+
with netcdf_file(fobj, mmap=True) as f:
|
| 117 |
+
assert_(f.use_mmap)
|
| 118 |
+
check_simple(f)
|
| 119 |
+
|
| 120 |
+
# Again read it in append mode (adding another att)
|
| 121 |
+
with open('simple.nc', 'r+b') as fobj:
|
| 122 |
+
with netcdf_file(fobj, 'a') as f:
|
| 123 |
+
assert_(not f.use_mmap)
|
| 124 |
+
check_simple(f)
|
| 125 |
+
f.createDimension('app_dim', 1)
|
| 126 |
+
var = f.createVariable('app_var', 'i', ('app_dim',))
|
| 127 |
+
var[:] = 42
|
| 128 |
+
|
| 129 |
+
# And... check that app_var made it in...
|
| 130 |
+
with netcdf_file('simple.nc') as f:
|
| 131 |
+
check_simple(f)
|
| 132 |
+
assert_equal(f.variables['app_var'][:], 42)
|
| 133 |
+
|
| 134 |
+
finally:
|
| 135 |
+
if IS_PYPY:
|
| 136 |
+
# windows cannot remove a dead file held by a mmap
|
| 137 |
+
# that has not been collected in PyPy
|
| 138 |
+
break_cycles()
|
| 139 |
+
break_cycles()
|
| 140 |
+
os.chdir(cwd)
|
| 141 |
+
shutil.rmtree(tmpdir)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_read_write_sio():
|
| 145 |
+
eg_sio1 = BytesIO()
|
| 146 |
+
with make_simple(eg_sio1, 'w'):
|
| 147 |
+
str_val = eg_sio1.getvalue()
|
| 148 |
+
|
| 149 |
+
eg_sio2 = BytesIO(str_val)
|
| 150 |
+
with netcdf_file(eg_sio2) as f2:
|
| 151 |
+
check_simple(f2)
|
| 152 |
+
|
| 153 |
+
# Test that error is raised if attempting mmap for sio
|
| 154 |
+
eg_sio3 = BytesIO(str_val)
|
| 155 |
+
assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True)
|
| 156 |
+
# Test 64-bit offset write / read
|
| 157 |
+
eg_sio_64 = BytesIO()
|
| 158 |
+
with make_simple(eg_sio_64, 'w', version=2) as f_64:
|
| 159 |
+
str_val = eg_sio_64.getvalue()
|
| 160 |
+
|
| 161 |
+
eg_sio_64 = BytesIO(str_val)
|
| 162 |
+
with netcdf_file(eg_sio_64) as f_64:
|
| 163 |
+
check_simple(f_64)
|
| 164 |
+
assert_equal(f_64.version_byte, 2)
|
| 165 |
+
# also when version 2 explicitly specified
|
| 166 |
+
eg_sio_64 = BytesIO(str_val)
|
| 167 |
+
with netcdf_file(eg_sio_64, version=2) as f_64:
|
| 168 |
+
check_simple(f_64)
|
| 169 |
+
assert_equal(f_64.version_byte, 2)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_bytes():
|
| 173 |
+
raw_file = BytesIO()
|
| 174 |
+
f = netcdf_file(raw_file, mode='w')
|
| 175 |
+
# Dataset only has a single variable, dimension and attribute to avoid
|
| 176 |
+
# any ambiguity related to order.
|
| 177 |
+
f.a = 'b'
|
| 178 |
+
f.createDimension('dim', 1)
|
| 179 |
+
var = f.createVariable('var', np.int16, ('dim',))
|
| 180 |
+
var[0] = -9999
|
| 181 |
+
var.c = 'd'
|
| 182 |
+
f.sync()
|
| 183 |
+
|
| 184 |
+
actual = raw_file.getvalue()
|
| 185 |
+
|
| 186 |
+
expected = (b'CDF\x01'
|
| 187 |
+
b'\x00\x00\x00\x00'
|
| 188 |
+
b'\x00\x00\x00\x0a'
|
| 189 |
+
b'\x00\x00\x00\x01'
|
| 190 |
+
b'\x00\x00\x00\x03'
|
| 191 |
+
b'dim\x00'
|
| 192 |
+
b'\x00\x00\x00\x01'
|
| 193 |
+
b'\x00\x00\x00\x0c'
|
| 194 |
+
b'\x00\x00\x00\x01'
|
| 195 |
+
b'\x00\x00\x00\x01'
|
| 196 |
+
b'a\x00\x00\x00'
|
| 197 |
+
b'\x00\x00\x00\x02'
|
| 198 |
+
b'\x00\x00\x00\x01'
|
| 199 |
+
b'b\x00\x00\x00'
|
| 200 |
+
b'\x00\x00\x00\x0b'
|
| 201 |
+
b'\x00\x00\x00\x01'
|
| 202 |
+
b'\x00\x00\x00\x03'
|
| 203 |
+
b'var\x00'
|
| 204 |
+
b'\x00\x00\x00\x01'
|
| 205 |
+
b'\x00\x00\x00\x00'
|
| 206 |
+
b'\x00\x00\x00\x0c'
|
| 207 |
+
b'\x00\x00\x00\x01'
|
| 208 |
+
b'\x00\x00\x00\x01'
|
| 209 |
+
b'c\x00\x00\x00'
|
| 210 |
+
b'\x00\x00\x00\x02'
|
| 211 |
+
b'\x00\x00\x00\x01'
|
| 212 |
+
b'd\x00\x00\x00'
|
| 213 |
+
b'\x00\x00\x00\x03'
|
| 214 |
+
b'\x00\x00\x00\x04'
|
| 215 |
+
b'\x00\x00\x00\x78'
|
| 216 |
+
b'\xd8\xf1\x80\x01')
|
| 217 |
+
|
| 218 |
+
assert_equal(actual, expected)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def test_encoded_fill_value():
|
| 222 |
+
with netcdf_file(BytesIO(), mode='w') as f:
|
| 223 |
+
f.createDimension('x', 1)
|
| 224 |
+
var = f.createVariable('var', 'S1', ('x',))
|
| 225 |
+
assert_equal(var._get_encoded_fill_value(), b'\x00')
|
| 226 |
+
var._FillValue = b'\x01'
|
| 227 |
+
assert_equal(var._get_encoded_fill_value(), b'\x01')
|
| 228 |
+
var._FillValue = b'\x00\x00' # invalid, wrong size
|
| 229 |
+
assert_equal(var._get_encoded_fill_value(), b'\x00')
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def test_read_example_data():
|
| 233 |
+
# read any example data files
|
| 234 |
+
for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')):
|
| 235 |
+
with netcdf_file(fname, 'r'):
|
| 236 |
+
pass
|
| 237 |
+
with netcdf_file(fname, 'r', mmap=False):
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def test_itemset_no_segfault_on_readonly():
|
| 242 |
+
# Regression test for ticket #1202.
|
| 243 |
+
# Open the test file in read-only mode.
|
| 244 |
+
|
| 245 |
+
filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
|
| 246 |
+
with suppress_warnings() as sup:
|
| 247 |
+
message = ("Cannot close a netcdf_file opened with mmap=True, when "
|
| 248 |
+
"netcdf_variables or arrays referring to its data still exist")
|
| 249 |
+
sup.filter(RuntimeWarning, message)
|
| 250 |
+
with netcdf_file(filename, 'r', mmap=True) as f:
|
| 251 |
+
time_var = f.variables['time']
|
| 252 |
+
|
| 253 |
+
# time_var.assignValue(42) should raise a RuntimeError--not seg. fault!
|
| 254 |
+
assert_raises(RuntimeError, time_var.assignValue, 42)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def test_appending_issue_gh_8625():
|
| 258 |
+
stream = BytesIO()
|
| 259 |
+
|
| 260 |
+
with make_simple(stream, mode='w') as f:
|
| 261 |
+
f.createDimension('x', 2)
|
| 262 |
+
f.createVariable('x', float, ('x',))
|
| 263 |
+
f.variables['x'][...] = 1
|
| 264 |
+
f.flush()
|
| 265 |
+
contents = stream.getvalue()
|
| 266 |
+
|
| 267 |
+
stream = BytesIO(contents)
|
| 268 |
+
with netcdf_file(stream, mode='a') as f:
|
| 269 |
+
f.variables['x'][...] = 2
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_write_invalid_dtype():
|
| 273 |
+
dtypes = ['int64', 'uint64']
|
| 274 |
+
if np.dtype('int').itemsize == 8: # 64-bit machines
|
| 275 |
+
dtypes.append('int')
|
| 276 |
+
if np.dtype('uint').itemsize == 8: # 64-bit machines
|
| 277 |
+
dtypes.append('uint')
|
| 278 |
+
|
| 279 |
+
with netcdf_file(BytesIO(), 'w') as f:
|
| 280 |
+
f.createDimension('time', N_EG_ELS)
|
| 281 |
+
for dt in dtypes:
|
| 282 |
+
assert_raises(ValueError, f.createVariable, 'time', dt, ('time',))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_flush_rewind():
|
| 286 |
+
stream = BytesIO()
|
| 287 |
+
with make_simple(stream, mode='w') as f:
|
| 288 |
+
f.createDimension('x',4) # x is used in createVariable
|
| 289 |
+
v = f.createVariable('v', 'i2', ['x'])
|
| 290 |
+
v[:] = 1
|
| 291 |
+
f.flush()
|
| 292 |
+
len_single = len(stream.getvalue())
|
| 293 |
+
f.flush()
|
| 294 |
+
len_double = len(stream.getvalue())
|
| 295 |
+
|
| 296 |
+
assert_(len_single == len_double)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def test_dtype_specifiers():
|
| 300 |
+
# Numpy 1.7.0-dev had a bug where 'i2' wouldn't work.
|
| 301 |
+
# Specifying np.int16 or similar only works from the same commit as this
|
| 302 |
+
# comment was made.
|
| 303 |
+
with make_simple(BytesIO(), mode='w') as f:
|
| 304 |
+
f.createDimension('x',4)
|
| 305 |
+
f.createVariable('v1', 'i2', ['x'])
|
| 306 |
+
f.createVariable('v2', np.int16, ['x'])
|
| 307 |
+
f.createVariable('v3', np.dtype(np.int16), ['x'])
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def test_ticket_1720():
|
| 311 |
+
io = BytesIO()
|
| 312 |
+
|
| 313 |
+
items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
|
| 314 |
+
|
| 315 |
+
with netcdf_file(io, 'w') as f:
|
| 316 |
+
f.history = 'Created for a test'
|
| 317 |
+
f.createDimension('float_var', 10)
|
| 318 |
+
float_var = f.createVariable('float_var', 'f', ('float_var',))
|
| 319 |
+
float_var[:] = items
|
| 320 |
+
float_var.units = 'metres'
|
| 321 |
+
f.flush()
|
| 322 |
+
contents = io.getvalue()
|
| 323 |
+
|
| 324 |
+
io = BytesIO(contents)
|
| 325 |
+
with netcdf_file(io, 'r') as f:
|
| 326 |
+
assert_equal(f.history, b'Created for a test')
|
| 327 |
+
float_var = f.variables['float_var']
|
| 328 |
+
assert_equal(float_var.units, b'metres')
|
| 329 |
+
assert_equal(float_var.shape, (10,))
|
| 330 |
+
assert_allclose(float_var[:], items)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def test_mmaps_segfault():
|
| 334 |
+
filename = pjoin(TEST_DATA_PATH, 'example_1.nc')
|
| 335 |
+
|
| 336 |
+
if not IS_PYPY:
|
| 337 |
+
with warnings.catch_warnings():
|
| 338 |
+
warnings.simplefilter("error")
|
| 339 |
+
with netcdf_file(filename, mmap=True) as f:
|
| 340 |
+
x = f.variables['lat'][:]
|
| 341 |
+
# should not raise warnings
|
| 342 |
+
del x
|
| 343 |
+
|
| 344 |
+
def doit():
|
| 345 |
+
with netcdf_file(filename, mmap=True) as f:
|
| 346 |
+
return f.variables['lat'][:]
|
| 347 |
+
|
| 348 |
+
# should not crash
|
| 349 |
+
with suppress_warnings() as sup:
|
| 350 |
+
message = ("Cannot close a netcdf_file opened with mmap=True, when "
|
| 351 |
+
"netcdf_variables or arrays referring to its data still exist")
|
| 352 |
+
sup.filter(RuntimeWarning, message)
|
| 353 |
+
x = doit()
|
| 354 |
+
x.sum()
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def test_zero_dimensional_var():
|
| 358 |
+
io = BytesIO()
|
| 359 |
+
with make_simple(io, 'w') as f:
|
| 360 |
+
v = f.createVariable('zerodim', 'i2', [])
|
| 361 |
+
# This is checking that .isrec returns a boolean - don't simplify it
|
| 362 |
+
# to 'assert not ...'
|
| 363 |
+
assert v.isrec is False, v.isrec
|
| 364 |
+
f.flush()
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def test_byte_gatts():
|
| 368 |
+
# Check that global "string" atts work like they did before py3k
|
| 369 |
+
# unicode and general bytes confusion
|
| 370 |
+
with in_tempdir():
|
| 371 |
+
filename = 'g_byte_atts.nc'
|
| 372 |
+
f = netcdf_file(filename, 'w')
|
| 373 |
+
f._attributes['holy'] = b'grail'
|
| 374 |
+
f._attributes['witch'] = 'floats'
|
| 375 |
+
f.close()
|
| 376 |
+
f = netcdf_file(filename, 'r')
|
| 377 |
+
assert_equal(f._attributes['holy'], b'grail')
|
| 378 |
+
assert_equal(f._attributes['witch'], b'floats')
|
| 379 |
+
f.close()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def test_open_append():
|
| 383 |
+
# open 'w' put one attr
|
| 384 |
+
with in_tempdir():
|
| 385 |
+
filename = 'append_dat.nc'
|
| 386 |
+
f = netcdf_file(filename, 'w')
|
| 387 |
+
f._attributes['Kilroy'] = 'was here'
|
| 388 |
+
f.close()
|
| 389 |
+
|
| 390 |
+
# open again in 'a', read the att and a new one
|
| 391 |
+
f = netcdf_file(filename, 'a')
|
| 392 |
+
assert_equal(f._attributes['Kilroy'], b'was here')
|
| 393 |
+
f._attributes['naughty'] = b'Zoot'
|
| 394 |
+
f.close()
|
| 395 |
+
|
| 396 |
+
# open yet again in 'r' and check both atts
|
| 397 |
+
f = netcdf_file(filename, 'r')
|
| 398 |
+
assert_equal(f._attributes['Kilroy'], b'was here')
|
| 399 |
+
assert_equal(f._attributes['naughty'], b'Zoot')
|
| 400 |
+
f.close()
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def test_append_recordDimension():
|
| 404 |
+
dataSize = 100
|
| 405 |
+
|
| 406 |
+
with in_tempdir():
|
| 407 |
+
# Create file with record time dimension
|
| 408 |
+
with netcdf_file('withRecordDimension.nc', 'w') as f:
|
| 409 |
+
f.createDimension('time', None)
|
| 410 |
+
f.createVariable('time', 'd', ('time',))
|
| 411 |
+
f.createDimension('x', dataSize)
|
| 412 |
+
x = f.createVariable('x', 'd', ('x',))
|
| 413 |
+
x[:] = np.array(range(dataSize))
|
| 414 |
+
f.createDimension('y', dataSize)
|
| 415 |
+
y = f.createVariable('y', 'd', ('y',))
|
| 416 |
+
y[:] = np.array(range(dataSize))
|
| 417 |
+
f.createVariable('testData', 'i', ('time', 'x', 'y'))
|
| 418 |
+
f.flush()
|
| 419 |
+
f.close()
|
| 420 |
+
|
| 421 |
+
for i in range(2):
|
| 422 |
+
# Open the file in append mode and add data
|
| 423 |
+
with netcdf_file('withRecordDimension.nc', 'a') as f:
|
| 424 |
+
f.variables['time'].data = np.append(f.variables["time"].data, i)
|
| 425 |
+
f.variables['testData'][i, :, :] = np.full((dataSize, dataSize), i)
|
| 426 |
+
f.flush()
|
| 427 |
+
|
| 428 |
+
# Read the file and check that append worked
|
| 429 |
+
with netcdf_file('withRecordDimension.nc') as f:
|
| 430 |
+
assert_equal(f.variables['time'][-1], i)
|
| 431 |
+
assert_equal(f.variables['testData'][-1, :, :].copy(),
|
| 432 |
+
np.full((dataSize, dataSize), i))
|
| 433 |
+
assert_equal(f.variables['time'].data.shape[0], i+1)
|
| 434 |
+
assert_equal(f.variables['testData'].data.shape[0], i+1)
|
| 435 |
+
|
| 436 |
+
# Read the file and check that 'data' was not saved as user defined
|
| 437 |
+
# attribute of testData variable during append operation
|
| 438 |
+
with netcdf_file('withRecordDimension.nc') as f:
|
| 439 |
+
with assert_raises(KeyError) as ar:
|
| 440 |
+
f.variables['testData']._attributes['data']
|
| 441 |
+
ex = ar.value
|
| 442 |
+
assert_equal(ex.args[0], 'data')
|
| 443 |
+
|
| 444 |
+
def test_maskandscale():
|
| 445 |
+
t = np.linspace(20, 30, 15)
|
| 446 |
+
t[3] = 100
|
| 447 |
+
tm = np.ma.masked_greater(t, 99)
|
| 448 |
+
fname = pjoin(TEST_DATA_PATH, 'example_2.nc')
|
| 449 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 450 |
+
Temp = f.variables['Temperature']
|
| 451 |
+
assert_equal(Temp.missing_value, 9999)
|
| 452 |
+
assert_equal(Temp.add_offset, 20)
|
| 453 |
+
assert_equal(Temp.scale_factor, np.float32(0.01))
|
| 454 |
+
found = Temp[:].compressed()
|
| 455 |
+
del Temp # Remove ref to mmap, so file can be closed.
|
| 456 |
+
expected = np.round(tm.compressed(), 2)
|
| 457 |
+
assert_allclose(found, expected)
|
| 458 |
+
|
| 459 |
+
with in_tempdir():
|
| 460 |
+
newfname = 'ms.nc'
|
| 461 |
+
f = netcdf_file(newfname, 'w', maskandscale=True)
|
| 462 |
+
f.createDimension('Temperature', len(tm))
|
| 463 |
+
temp = f.createVariable('Temperature', 'i', ('Temperature',))
|
| 464 |
+
temp.missing_value = 9999
|
| 465 |
+
temp.scale_factor = 0.01
|
| 466 |
+
temp.add_offset = 20
|
| 467 |
+
temp[:] = tm
|
| 468 |
+
f.close()
|
| 469 |
+
|
| 470 |
+
with netcdf_file(newfname, maskandscale=True) as f:
|
| 471 |
+
Temp = f.variables['Temperature']
|
| 472 |
+
assert_equal(Temp.missing_value, 9999)
|
| 473 |
+
assert_equal(Temp.add_offset, 20)
|
| 474 |
+
assert_equal(Temp.scale_factor, np.float32(0.01))
|
| 475 |
+
expected = np.round(tm.compressed(), 2)
|
| 476 |
+
found = Temp[:].compressed()
|
| 477 |
+
del Temp
|
| 478 |
+
assert_allclose(found, expected)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
# ------------------------------------------------------------------------
|
| 482 |
+
# Test reading with masked values (_FillValue / missing_value)
|
| 483 |
+
# ------------------------------------------------------------------------
|
| 484 |
+
|
| 485 |
+
def test_read_withValuesNearFillValue():
|
| 486 |
+
# Regression test for ticket #5626
|
| 487 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 488 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 489 |
+
vardata = f.variables['var1_fillval0'][:]
|
| 490 |
+
assert_mask_matches(vardata, [False, True, False])
|
| 491 |
+
|
| 492 |
+
def test_read_withNoFillValue():
|
| 493 |
+
# For a variable with no fill value, reading data with maskandscale=True
|
| 494 |
+
# should return unmasked data
|
| 495 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 496 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 497 |
+
vardata = f.variables['var2_noFillval'][:]
|
| 498 |
+
assert_mask_matches(vardata, [False, False, False])
|
| 499 |
+
assert_equal(vardata, [1,2,3])
|
| 500 |
+
|
| 501 |
+
def test_read_withFillValueAndMissingValue():
|
| 502 |
+
# For a variable with both _FillValue and missing_value, the _FillValue
|
| 503 |
+
# should be used
|
| 504 |
+
IRRELEVANT_VALUE = 9999
|
| 505 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 506 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 507 |
+
vardata = f.variables['var3_fillvalAndMissingValue'][:]
|
| 508 |
+
assert_mask_matches(vardata, [True, False, False])
|
| 509 |
+
assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3])
|
| 510 |
+
|
| 511 |
+
def test_read_withMissingValue():
|
| 512 |
+
# For a variable with missing_value but not _FillValue, the missing_value
|
| 513 |
+
# should be used
|
| 514 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 515 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 516 |
+
vardata = f.variables['var4_missingValue'][:]
|
| 517 |
+
assert_mask_matches(vardata, [False, True, False])
|
| 518 |
+
|
| 519 |
+
def test_read_withFillValNaN():
|
| 520 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 521 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 522 |
+
vardata = f.variables['var5_fillvalNaN'][:]
|
| 523 |
+
assert_mask_matches(vardata, [False, True, False])
|
| 524 |
+
|
| 525 |
+
def test_read_withChar():
|
| 526 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 527 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 528 |
+
vardata = f.variables['var6_char'][:]
|
| 529 |
+
assert_mask_matches(vardata, [False, True, False])
|
| 530 |
+
|
| 531 |
+
def test_read_with2dVar():
|
| 532 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 533 |
+
with netcdf_file(fname, maskandscale=True) as f:
|
| 534 |
+
vardata = f.variables['var7_2d'][:]
|
| 535 |
+
assert_mask_matches(vardata, [[True, False], [False, False], [False, True]])
|
| 536 |
+
|
| 537 |
+
def test_read_withMaskAndScaleFalse():
|
| 538 |
+
# If a variable has a _FillValue (or missing_value) attribute, but is read
|
| 539 |
+
# with maskandscale set to False, the result should be unmasked
|
| 540 |
+
fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc')
|
| 541 |
+
# Open file with mmap=False to avoid problems with closing a mmap'ed file
|
| 542 |
+
# when arrays referring to its data still exist:
|
| 543 |
+
with netcdf_file(fname, maskandscale=False, mmap=False) as f:
|
| 544 |
+
vardata = f.variables['var3_fillvalAndMissingValue'][:]
|
| 545 |
+
assert_mask_matches(vardata, [False, False, False])
|
| 546 |
+
assert_equal(vardata, [1, 2, 3])
|
parrot/lib/python3.10/site-packages/scipy/io/tests/test_paths.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Ensure that we can use pathlib.Path objects in all relevant IO functions.
|
| 3 |
+
"""
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
import scipy.io
|
| 9 |
+
import scipy.io.wavfile
|
| 10 |
+
from scipy._lib._tmpdirs import tempdir
|
| 11 |
+
import scipy.sparse
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestPaths:
|
| 15 |
+
data = np.arange(5).astype(np.int64)
|
| 16 |
+
|
| 17 |
+
def test_savemat(self):
|
| 18 |
+
with tempdir() as temp_dir:
|
| 19 |
+
path = Path(temp_dir) / 'data.mat'
|
| 20 |
+
scipy.io.savemat(path, {'data': self.data})
|
| 21 |
+
assert path.is_file()
|
| 22 |
+
|
| 23 |
+
def test_loadmat(self):
|
| 24 |
+
# Save data with string path, load with pathlib.Path
|
| 25 |
+
with tempdir() as temp_dir:
|
| 26 |
+
path = Path(temp_dir) / 'data.mat'
|
| 27 |
+
scipy.io.savemat(str(path), {'data': self.data})
|
| 28 |
+
|
| 29 |
+
mat_contents = scipy.io.loadmat(path)
|
| 30 |
+
assert (mat_contents['data'] == self.data).all()
|
| 31 |
+
|
| 32 |
+
def test_whosmat(self):
|
| 33 |
+
# Save data with string path, load with pathlib.Path
|
| 34 |
+
with tempdir() as temp_dir:
|
| 35 |
+
path = Path(temp_dir) / 'data.mat'
|
| 36 |
+
scipy.io.savemat(str(path), {'data': self.data})
|
| 37 |
+
|
| 38 |
+
contents = scipy.io.whosmat(path)
|
| 39 |
+
assert contents[0] == ('data', (1, 5), 'int64')
|
| 40 |
+
|
| 41 |
+
def test_readsav(self):
|
| 42 |
+
path = Path(__file__).parent / 'data/scalar_string.sav'
|
| 43 |
+
scipy.io.readsav(path)
|
| 44 |
+
|
| 45 |
+
def test_hb_read(self):
|
| 46 |
+
# Save data with string path, load with pathlib.Path
|
| 47 |
+
with tempdir() as temp_dir:
|
| 48 |
+
data = scipy.sparse.csr_matrix(scipy.sparse.eye(3))
|
| 49 |
+
path = Path(temp_dir) / 'data.hb'
|
| 50 |
+
scipy.io.hb_write(str(path), data)
|
| 51 |
+
|
| 52 |
+
data_new = scipy.io.hb_read(path)
|
| 53 |
+
assert (data_new != data).nnz == 0
|
| 54 |
+
|
| 55 |
+
def test_hb_write(self):
|
| 56 |
+
with tempdir() as temp_dir:
|
| 57 |
+
data = scipy.sparse.csr_matrix(scipy.sparse.eye(3))
|
| 58 |
+
path = Path(temp_dir) / 'data.hb'
|
| 59 |
+
scipy.io.hb_write(path, data)
|
| 60 |
+
assert path.is_file()
|
| 61 |
+
|
| 62 |
+
def test_mmio_read(self):
|
| 63 |
+
# Save data with string path, load with pathlib.Path
|
| 64 |
+
with tempdir() as temp_dir:
|
| 65 |
+
data = scipy.sparse.csr_matrix(scipy.sparse.eye(3))
|
| 66 |
+
path = Path(temp_dir) / 'data.mtx'
|
| 67 |
+
scipy.io.mmwrite(str(path), data)
|
| 68 |
+
|
| 69 |
+
data_new = scipy.io.mmread(path)
|
| 70 |
+
assert (data_new != data).nnz == 0
|
| 71 |
+
|
| 72 |
+
def test_mmio_write(self):
|
| 73 |
+
with tempdir() as temp_dir:
|
| 74 |
+
data = scipy.sparse.csr_matrix(scipy.sparse.eye(3))
|
| 75 |
+
path = Path(temp_dir) / 'data.mtx'
|
| 76 |
+
scipy.io.mmwrite(path, data)
|
| 77 |
+
|
| 78 |
+
def test_netcdf_file(self):
|
| 79 |
+
path = Path(__file__).parent / 'data/example_1.nc'
|
| 80 |
+
scipy.io.netcdf_file(path)
|
| 81 |
+
|
| 82 |
+
def test_wavfile_read(self):
|
| 83 |
+
path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav'
|
| 84 |
+
scipy.io.wavfile.read(path)
|
| 85 |
+
|
| 86 |
+
def test_wavfile_write(self):
|
| 87 |
+
# Read from str path, write to Path
|
| 88 |
+
input_path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav'
|
| 89 |
+
rate, data = scipy.io.wavfile.read(str(input_path))
|
| 90 |
+
|
| 91 |
+
with tempdir() as temp_dir:
|
| 92 |
+
output_path = Path(temp_dir) / input_path.name
|
| 93 |
+
scipy.io.wavfile.write(output_path, rate, data)
|
parrot/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py
ADDED
|
@@ -0,0 +1,457 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy.testing import (assert_equal, assert_, assert_array_equal,
|
| 7 |
+
break_cycles, suppress_warnings, IS_PYPY)
|
| 8 |
+
import pytest
|
| 9 |
+
from pytest import raises, warns
|
| 10 |
+
|
| 11 |
+
from scipy.io import wavfile
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def datafile(fn):
|
| 15 |
+
return os.path.join(os.path.dirname(__file__), 'data', fn)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_read_1():
|
| 19 |
+
# 32-bit PCM (which uses extensible format)
|
| 20 |
+
for mmap in [False, True]:
|
| 21 |
+
filename = 'test-44100Hz-le-1ch-4bytes.wav'
|
| 22 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 23 |
+
|
| 24 |
+
assert_equal(rate, 44100)
|
| 25 |
+
assert_(np.issubdtype(data.dtype, np.int32))
|
| 26 |
+
assert_equal(data.shape, (4410,))
|
| 27 |
+
|
| 28 |
+
del data
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_read_2():
|
| 32 |
+
# 8-bit unsigned PCM
|
| 33 |
+
for mmap in [False, True]:
|
| 34 |
+
filename = 'test-8000Hz-le-2ch-1byteu.wav'
|
| 35 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 36 |
+
|
| 37 |
+
assert_equal(rate, 8000)
|
| 38 |
+
assert_(np.issubdtype(data.dtype, np.uint8))
|
| 39 |
+
assert_equal(data.shape, (800, 2))
|
| 40 |
+
|
| 41 |
+
del data
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_read_3():
|
| 45 |
+
# Little-endian float
|
| 46 |
+
for mmap in [False, True]:
|
| 47 |
+
filename = 'test-44100Hz-2ch-32bit-float-le.wav'
|
| 48 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 49 |
+
|
| 50 |
+
assert_equal(rate, 44100)
|
| 51 |
+
assert_(np.issubdtype(data.dtype, np.float32))
|
| 52 |
+
assert_equal(data.shape, (441, 2))
|
| 53 |
+
|
| 54 |
+
del data
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_read_4():
|
| 58 |
+
# Contains unsupported 'PEAK' chunk
|
| 59 |
+
for mmap in [False, True]:
|
| 60 |
+
with suppress_warnings() as sup:
|
| 61 |
+
sup.filter(wavfile.WavFileWarning,
|
| 62 |
+
"Chunk .non-data. not understood, skipping it")
|
| 63 |
+
filename = 'test-48000Hz-2ch-64bit-float-le-wavex.wav'
|
| 64 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 65 |
+
|
| 66 |
+
assert_equal(rate, 48000)
|
| 67 |
+
assert_(np.issubdtype(data.dtype, np.float64))
|
| 68 |
+
assert_equal(data.shape, (480, 2))
|
| 69 |
+
|
| 70 |
+
del data
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_read_5():
|
| 74 |
+
# Big-endian float
|
| 75 |
+
for mmap in [False, True]:
|
| 76 |
+
filename = 'test-44100Hz-2ch-32bit-float-be.wav'
|
| 77 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 78 |
+
|
| 79 |
+
assert_equal(rate, 44100)
|
| 80 |
+
assert_(np.issubdtype(data.dtype, np.float32))
|
| 81 |
+
assert_(data.dtype.byteorder == '>' or (sys.byteorder == 'big' and
|
| 82 |
+
data.dtype.byteorder == '='))
|
| 83 |
+
assert_equal(data.shape, (441, 2))
|
| 84 |
+
|
| 85 |
+
del data
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_5_bit_odd_size_no_pad():
|
| 89 |
+
# 5-bit, 1 B container, 5 channels, 9 samples, 45 B data chunk
|
| 90 |
+
# Generated by LTspice, which incorrectly omits pad byte, but should be
|
| 91 |
+
# readable anyway
|
| 92 |
+
for mmap in [False, True]:
|
| 93 |
+
filename = 'test-8000Hz-le-5ch-9S-5bit.wav'
|
| 94 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 95 |
+
|
| 96 |
+
assert_equal(rate, 8000)
|
| 97 |
+
assert_(np.issubdtype(data.dtype, np.uint8))
|
| 98 |
+
assert_equal(data.shape, (9, 5))
|
| 99 |
+
|
| 100 |
+
# 8-5 = 3 LSBits should be 0
|
| 101 |
+
assert_equal(data & 0b00000111, 0)
|
| 102 |
+
|
| 103 |
+
# Unsigned
|
| 104 |
+
assert_equal(data.max(), 0b11111000) # Highest possible
|
| 105 |
+
assert_equal(data[0, 0], 128) # Midpoint is 128 for <= 8-bit
|
| 106 |
+
assert_equal(data.min(), 0) # Lowest possible
|
| 107 |
+
|
| 108 |
+
del data
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_12_bit_even_size():
|
| 112 |
+
# 12-bit, 2 B container, 4 channels, 9 samples, 72 B data chunk
|
| 113 |
+
# Generated by LTspice from 1 Vpk sine waves
|
| 114 |
+
for mmap in [False, True]:
|
| 115 |
+
filename = 'test-8000Hz-le-4ch-9S-12bit.wav'
|
| 116 |
+
rate, data = wavfile.read(datafile(filename), mmap=mmap)
|
| 117 |
+
|
| 118 |
+
assert_equal(rate, 8000)
|
| 119 |
+
assert_(np.issubdtype(data.dtype, np.int16))
|
| 120 |
+
assert_equal(data.shape, (9, 4))
|
| 121 |
+
|
| 122 |
+
# 16-12 = 4 LSBits should be 0
|
| 123 |
+
assert_equal(data & 0b00000000_00001111, 0)
|
| 124 |
+
|
| 125 |
+
# Signed
|
| 126 |
+
assert_equal(data.max(), 0b01111111_11110000) # Highest possible
|
| 127 |
+
assert_equal(data[0, 0], 0) # Midpoint is 0 for >= 9-bit
|
| 128 |
+
assert_equal(data.min(), -0b10000000_00000000) # Lowest possible
|
| 129 |
+
|
| 130 |
+
del data
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_24_bit_odd_size_with_pad():
|
| 134 |
+
# 24-bit, 3 B container, 3 channels, 5 samples, 45 B data chunk
|
| 135 |
+
# Should not raise any warnings about the data chunk pad byte
|
| 136 |
+
filename = 'test-8000Hz-le-3ch-5S-24bit.wav'
|
| 137 |
+
rate, data = wavfile.read(datafile(filename), mmap=False)
|
| 138 |
+
|
| 139 |
+
assert_equal(rate, 8000)
|
| 140 |
+
assert_(np.issubdtype(data.dtype, np.int32))
|
| 141 |
+
assert_equal(data.shape, (5, 3))
|
| 142 |
+
|
| 143 |
+
# All LSBytes should be 0
|
| 144 |
+
assert_equal(data & 0xff, 0)
|
| 145 |
+
|
| 146 |
+
# Hand-made max/min samples under different conventions:
|
| 147 |
+
# 2**(N-1) 2**(N-1)-1 LSB
|
| 148 |
+
assert_equal(data, [[-0x8000_0000, -0x7fff_ff00, -0x200],
|
| 149 |
+
[-0x4000_0000, -0x3fff_ff00, -0x100],
|
| 150 |
+
[+0x0000_0000, +0x0000_0000, +0x000],
|
| 151 |
+
[+0x4000_0000, +0x3fff_ff00, +0x100],
|
| 152 |
+
[+0x7fff_ff00, +0x7fff_ff00, +0x200]])
|
| 153 |
+
# ^ clipped
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_20_bit_extra_data():
|
| 157 |
+
# 20-bit, 3 B container, 1 channel, 10 samples, 30 B data chunk
|
| 158 |
+
# with extra data filling container beyond the bit depth
|
| 159 |
+
filename = 'test-8000Hz-le-1ch-10S-20bit-extra.wav'
|
| 160 |
+
rate, data = wavfile.read(datafile(filename), mmap=False)
|
| 161 |
+
|
| 162 |
+
assert_equal(rate, 1234)
|
| 163 |
+
assert_(np.issubdtype(data.dtype, np.int32))
|
| 164 |
+
assert_equal(data.shape, (10,))
|
| 165 |
+
|
| 166 |
+
# All LSBytes should still be 0, because 3 B container in 4 B dtype
|
| 167 |
+
assert_equal(data & 0xff, 0)
|
| 168 |
+
|
| 169 |
+
# But it should load the data beyond 20 bits
|
| 170 |
+
assert_((data & 0xf00).any())
|
| 171 |
+
|
| 172 |
+
# Full-scale positive/negative samples, then being halved each time
|
| 173 |
+
assert_equal(data, [+0x7ffff000, # +full-scale 20-bit
|
| 174 |
+
-0x7ffff000, # -full-scale 20-bit
|
| 175 |
+
+0x7ffff000 >> 1, # +1/2
|
| 176 |
+
-0x7ffff000 >> 1, # -1/2
|
| 177 |
+
+0x7ffff000 >> 2, # +1/4
|
| 178 |
+
-0x7ffff000 >> 2, # -1/4
|
| 179 |
+
+0x7ffff000 >> 3, # +1/8
|
| 180 |
+
-0x7ffff000 >> 3, # -1/8
|
| 181 |
+
+0x7ffff000 >> 4, # +1/16
|
| 182 |
+
-0x7ffff000 >> 4, # -1/16
|
| 183 |
+
])
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def test_36_bit_odd_size():
|
| 187 |
+
# 36-bit, 5 B container, 3 channels, 5 samples, 75 B data chunk + pad
|
| 188 |
+
filename = 'test-8000Hz-le-3ch-5S-36bit.wav'
|
| 189 |
+
rate, data = wavfile.read(datafile(filename), mmap=False)
|
| 190 |
+
|
| 191 |
+
assert_equal(rate, 8000)
|
| 192 |
+
assert_(np.issubdtype(data.dtype, np.int64))
|
| 193 |
+
assert_equal(data.shape, (5, 3))
|
| 194 |
+
|
| 195 |
+
# 28 LSBits should be 0
|
| 196 |
+
assert_equal(data & 0xfffffff, 0)
|
| 197 |
+
|
| 198 |
+
# Hand-made max/min samples under different conventions:
|
| 199 |
+
# Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB
|
| 200 |
+
correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_f000_0000, -0x2000_0000],
|
| 201 |
+
[-0x4000_0000_0000_0000, -0x3fff_ffff_f000_0000, -0x1000_0000],
|
| 202 |
+
[+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000_0000],
|
| 203 |
+
[+0x4000_0000_0000_0000, +0x3fff_ffff_f000_0000, +0x1000_0000],
|
| 204 |
+
[+0x7fff_ffff_f000_0000, +0x7fff_ffff_f000_0000, +0x2000_0000]]
|
| 205 |
+
# ^ clipped
|
| 206 |
+
|
| 207 |
+
assert_equal(data, correct)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_45_bit_even_size():
|
| 211 |
+
# 45-bit, 6 B container, 3 channels, 5 samples, 90 B data chunk
|
| 212 |
+
filename = 'test-8000Hz-le-3ch-5S-45bit.wav'
|
| 213 |
+
rate, data = wavfile.read(datafile(filename), mmap=False)
|
| 214 |
+
|
| 215 |
+
assert_equal(rate, 8000)
|
| 216 |
+
assert_(np.issubdtype(data.dtype, np.int64))
|
| 217 |
+
assert_equal(data.shape, (5, 3))
|
| 218 |
+
|
| 219 |
+
# 19 LSBits should be 0
|
| 220 |
+
assert_equal(data & 0x7ffff, 0)
|
| 221 |
+
|
| 222 |
+
# Hand-made max/min samples under different conventions:
|
| 223 |
+
# Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB
|
| 224 |
+
correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_fff8_0000, -0x10_0000],
|
| 225 |
+
[-0x4000_0000_0000_0000, -0x3fff_ffff_fff8_0000, -0x08_0000],
|
| 226 |
+
[+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x00_0000],
|
| 227 |
+
[+0x4000_0000_0000_0000, +0x3fff_ffff_fff8_0000, +0x08_0000],
|
| 228 |
+
[+0x7fff_ffff_fff8_0000, +0x7fff_ffff_fff8_0000, +0x10_0000]]
|
| 229 |
+
# ^ clipped
|
| 230 |
+
|
| 231 |
+
assert_equal(data, correct)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def test_53_bit_odd_size():
|
| 235 |
+
# 53-bit, 7 B container, 3 channels, 5 samples, 105 B data chunk + pad
|
| 236 |
+
filename = 'test-8000Hz-le-3ch-5S-53bit.wav'
|
| 237 |
+
rate, data = wavfile.read(datafile(filename), mmap=False)
|
| 238 |
+
|
| 239 |
+
assert_equal(rate, 8000)
|
| 240 |
+
assert_(np.issubdtype(data.dtype, np.int64))
|
| 241 |
+
assert_equal(data.shape, (5, 3))
|
| 242 |
+
|
| 243 |
+
# 11 LSBits should be 0
|
| 244 |
+
assert_equal(data & 0x7ff, 0)
|
| 245 |
+
|
| 246 |
+
# Hand-made max/min samples under different conventions:
|
| 247 |
+
# Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB
|
| 248 |
+
correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_f800, -0x1000],
|
| 249 |
+
[-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_f800, -0x0800],
|
| 250 |
+
[+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000],
|
| 251 |
+
[+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_f800, +0x0800],
|
| 252 |
+
[+0x7fff_ffff_ffff_f800, +0x7fff_ffff_ffff_f800, +0x1000]]
|
| 253 |
+
# ^ clipped
|
| 254 |
+
|
| 255 |
+
assert_equal(data, correct)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def test_64_bit_even_size():
|
| 259 |
+
# 64-bit, 8 B container, 3 channels, 5 samples, 120 B data chunk
|
| 260 |
+
for mmap in [False, True]:
|
| 261 |
+
filename = 'test-8000Hz-le-3ch-5S-64bit.wav'
|
| 262 |
+
rate, data = wavfile.read(datafile(filename), mmap=False)
|
| 263 |
+
|
| 264 |
+
assert_equal(rate, 8000)
|
| 265 |
+
assert_(np.issubdtype(data.dtype, np.int64))
|
| 266 |
+
assert_equal(data.shape, (5, 3))
|
| 267 |
+
|
| 268 |
+
# Hand-made max/min samples under different conventions:
|
| 269 |
+
# Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB
|
| 270 |
+
correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_ffff, -0x2],
|
| 271 |
+
[-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_ffff, -0x1],
|
| 272 |
+
[+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0],
|
| 273 |
+
[+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_ffff, +0x1],
|
| 274 |
+
[+0x7fff_ffff_ffff_ffff, +0x7fff_ffff_ffff_ffff, +0x2]]
|
| 275 |
+
# ^ clipped
|
| 276 |
+
|
| 277 |
+
assert_equal(data, correct)
|
| 278 |
+
|
| 279 |
+
del data
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def test_unsupported_mmap():
|
| 283 |
+
# Test containers that cannot be mapped to numpy types
|
| 284 |
+
for filename in {'test-8000Hz-le-3ch-5S-24bit.wav',
|
| 285 |
+
'test-8000Hz-le-3ch-5S-36bit.wav',
|
| 286 |
+
'test-8000Hz-le-3ch-5S-45bit.wav',
|
| 287 |
+
'test-8000Hz-le-3ch-5S-53bit.wav',
|
| 288 |
+
'test-8000Hz-le-1ch-10S-20bit-extra.wav'}:
|
| 289 |
+
with raises(ValueError, match="mmap.*not compatible"):
|
| 290 |
+
rate, data = wavfile.read(datafile(filename), mmap=True)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def test_rifx():
|
| 294 |
+
# Compare equivalent RIFX and RIFF files
|
| 295 |
+
for rifx, riff in {('test-44100Hz-be-1ch-4bytes.wav',
|
| 296 |
+
'test-44100Hz-le-1ch-4bytes.wav'),
|
| 297 |
+
('test-8000Hz-be-3ch-5S-24bit.wav',
|
| 298 |
+
'test-8000Hz-le-3ch-5S-24bit.wav')}:
|
| 299 |
+
rate1, data1 = wavfile.read(datafile(rifx), mmap=False)
|
| 300 |
+
rate2, data2 = wavfile.read(datafile(riff), mmap=False)
|
| 301 |
+
assert_equal(rate1, rate2)
|
| 302 |
+
assert_equal(data1, data2)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def test_rf64():
|
| 306 |
+
# Compare equivalent RF64 and RIFF files
|
| 307 |
+
for rf64, riff in {('test-44100Hz-le-1ch-4bytes-rf64.wav',
|
| 308 |
+
'test-44100Hz-le-1ch-4bytes.wav'),
|
| 309 |
+
('test-8000Hz-le-3ch-5S-24bit-rf64.wav',
|
| 310 |
+
'test-8000Hz-le-3ch-5S-24bit.wav')}:
|
| 311 |
+
rate1, data1 = wavfile.read(datafile(rf64), mmap=False)
|
| 312 |
+
rate2, data2 = wavfile.read(datafile(riff), mmap=False)
|
| 313 |
+
assert_array_equal(rate1, rate2)
|
| 314 |
+
assert_array_equal(data1, data2)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@pytest.mark.xslow
|
| 318 |
+
def test_write_roundtrip_rf64(tmpdir):
|
| 319 |
+
dtype = np.dtype("<i8")
|
| 320 |
+
tmpfile = str(tmpdir.join('temp.wav'))
|
| 321 |
+
rate = 44100
|
| 322 |
+
data = np.random.randint(0, 127, (2**29,)).astype(dtype)
|
| 323 |
+
|
| 324 |
+
wavfile.write(tmpfile, rate, data)
|
| 325 |
+
|
| 326 |
+
rate2, data2 = wavfile.read(tmpfile, mmap=True)
|
| 327 |
+
|
| 328 |
+
assert_equal(rate, rate2)
|
| 329 |
+
msg = f"{data2.dtype} byteorder not in ('<', '=', '|')"
|
| 330 |
+
assert data2.dtype.byteorder in ('<', '=', '|'), msg
|
| 331 |
+
assert_array_equal(data, data2)
|
| 332 |
+
# also test writing (gh-12176)
|
| 333 |
+
data2[0] = 0
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def test_read_unknown_filetype_fail():
|
| 337 |
+
# Not an RIFF
|
| 338 |
+
for mmap in [False, True]:
|
| 339 |
+
filename = 'example_1.nc'
|
| 340 |
+
with open(datafile(filename), 'rb') as fp:
|
| 341 |
+
with raises(ValueError, match="CDF.*'RIFF', 'RIFX', and 'RF64' supported"):
|
| 342 |
+
wavfile.read(fp, mmap=mmap)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def test_read_unknown_riff_form_type():
|
| 346 |
+
# RIFF, but not WAVE form
|
| 347 |
+
for mmap in [False, True]:
|
| 348 |
+
filename = 'Transparent Busy.ani'
|
| 349 |
+
with open(datafile(filename), 'rb') as fp:
|
| 350 |
+
with raises(ValueError, match='Not a WAV file.*ACON'):
|
| 351 |
+
wavfile.read(fp, mmap=mmap)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def test_read_unknown_wave_format():
|
| 355 |
+
# RIFF and WAVE, but not supported format
|
| 356 |
+
for mmap in [False, True]:
|
| 357 |
+
filename = 'test-8000Hz-le-1ch-1byte-ulaw.wav'
|
| 358 |
+
with open(datafile(filename), 'rb') as fp:
|
| 359 |
+
with raises(ValueError, match='Unknown wave file format.*MULAW.*'
|
| 360 |
+
'Supported formats'):
|
| 361 |
+
wavfile.read(fp, mmap=mmap)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def test_read_early_eof_with_data():
|
| 365 |
+
# File ends inside 'data' chunk, but we keep incomplete data
|
| 366 |
+
for mmap in [False, True]:
|
| 367 |
+
filename = 'test-44100Hz-le-1ch-4bytes-early-eof.wav'
|
| 368 |
+
with open(datafile(filename), 'rb') as fp:
|
| 369 |
+
with warns(wavfile.WavFileWarning, match='Reached EOF'):
|
| 370 |
+
rate, data = wavfile.read(fp, mmap=mmap)
|
| 371 |
+
assert data.size > 0
|
| 372 |
+
assert rate == 44100
|
| 373 |
+
# also test writing (gh-12176)
|
| 374 |
+
data[0] = 0
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def test_read_early_eof():
|
| 378 |
+
# File ends after 'fact' chunk at boundary, no data read
|
| 379 |
+
for mmap in [False, True]:
|
| 380 |
+
filename = 'test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav'
|
| 381 |
+
with open(datafile(filename), 'rb') as fp:
|
| 382 |
+
with raises(ValueError, match="Unexpected end of file."):
|
| 383 |
+
wavfile.read(fp, mmap=mmap)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def test_read_incomplete_chunk():
|
| 387 |
+
# File ends inside 'fmt ' chunk ID, no data read
|
| 388 |
+
for mmap in [False, True]:
|
| 389 |
+
filename = 'test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav'
|
| 390 |
+
with open(datafile(filename), 'rb') as fp:
|
| 391 |
+
with raises(ValueError, match="Incomplete chunk ID.*b'f'"):
|
| 392 |
+
wavfile.read(fp, mmap=mmap)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def test_read_inconsistent_header():
|
| 396 |
+
# File header's size fields contradict each other
|
| 397 |
+
for mmap in [False, True]:
|
| 398 |
+
filename = 'test-8000Hz-le-3ch-5S-24bit-inconsistent.wav'
|
| 399 |
+
with open(datafile(filename), 'rb') as fp:
|
| 400 |
+
with raises(ValueError, match="header is invalid"):
|
| 401 |
+
wavfile.read(fp, mmap=mmap)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# signed 8-bit integer PCM is not allowed
|
| 405 |
+
# unsigned > 8-bit integer PCM is not allowed
|
| 406 |
+
# 8- or 16-bit float PCM is not expected
|
| 407 |
+
# g and q are platform-dependent, so not included
|
| 408 |
+
@pytest.mark.parametrize("dt_str", ["<i2", "<i4", "<i8", "<f4", "<f8",
|
| 409 |
+
">i2", ">i4", ">i8", ">f4", ">f8", '|u1'])
|
| 410 |
+
@pytest.mark.parametrize("channels", [1, 2, 5])
|
| 411 |
+
@pytest.mark.parametrize("rate", [8000, 32000])
|
| 412 |
+
@pytest.mark.parametrize("mmap", [False, True])
|
| 413 |
+
@pytest.mark.parametrize("realfile", [False, True])
|
| 414 |
+
def test_write_roundtrip(realfile, mmap, rate, channels, dt_str, tmpdir):
|
| 415 |
+
dtype = np.dtype(dt_str)
|
| 416 |
+
if realfile:
|
| 417 |
+
tmpfile = str(tmpdir.join('temp.wav'))
|
| 418 |
+
else:
|
| 419 |
+
tmpfile = BytesIO()
|
| 420 |
+
data = np.random.rand(100, channels)
|
| 421 |
+
if channels == 1:
|
| 422 |
+
data = data[:, 0]
|
| 423 |
+
if dtype.kind == 'f':
|
| 424 |
+
# The range of the float type should be in [-1, 1]
|
| 425 |
+
data = data.astype(dtype)
|
| 426 |
+
else:
|
| 427 |
+
data = (data*128).astype(dtype)
|
| 428 |
+
|
| 429 |
+
wavfile.write(tmpfile, rate, data)
|
| 430 |
+
|
| 431 |
+
rate2, data2 = wavfile.read(tmpfile, mmap=mmap)
|
| 432 |
+
|
| 433 |
+
assert_equal(rate, rate2)
|
| 434 |
+
assert_(data2.dtype.byteorder in ('<', '=', '|'), msg=data2.dtype)
|
| 435 |
+
assert_array_equal(data, data2)
|
| 436 |
+
# also test writing (gh-12176)
|
| 437 |
+
if realfile:
|
| 438 |
+
data2[0] = 0
|
| 439 |
+
else:
|
| 440 |
+
with pytest.raises(ValueError, match='read-only'):
|
| 441 |
+
data2[0] = 0
|
| 442 |
+
|
| 443 |
+
if realfile and mmap and IS_PYPY and sys.platform == 'win32':
|
| 444 |
+
# windows cannot remove a dead file held by a mmap but not collected
|
| 445 |
+
# in PyPy; since the filename gets reused in this test, clean this up
|
| 446 |
+
break_cycles()
|
| 447 |
+
break_cycles()
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
@pytest.mark.parametrize("dtype", [np.float16])
|
| 451 |
+
def test_wavfile_dtype_unsupported(tmpdir, dtype):
|
| 452 |
+
tmpfile = str(tmpdir.join('temp.wav'))
|
| 453 |
+
rng = np.random.default_rng(1234)
|
| 454 |
+
data = rng.random((100, 5)).astype(dtype)
|
| 455 |
+
rate = 8000
|
| 456 |
+
with pytest.raises(ValueError, match="Unsupported"):
|
| 457 |
+
wavfile.write(tmpfile, rate, data)
|
parrot/lib/python3.10/site-packages/scipy/io/wavfile.py
ADDED
|
@@ -0,0 +1,891 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module to read / write wav files using NumPy arrays
|
| 3 |
+
|
| 4 |
+
Functions
|
| 5 |
+
---------
|
| 6 |
+
`read`: Return the sample rate (in samples/sec) and data from a WAV file.
|
| 7 |
+
|
| 8 |
+
`write`: Write a NumPy array as a WAV file.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
import io
|
| 12 |
+
import sys
|
| 13 |
+
import numpy as np
|
| 14 |
+
import struct
|
| 15 |
+
import warnings
|
| 16 |
+
from enum import IntEnum
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
'WavFileWarning',
|
| 21 |
+
'read',
|
| 22 |
+
'write'
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class WavFileWarning(UserWarning):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class WAVE_FORMAT(IntEnum):
|
| 31 |
+
"""
|
| 32 |
+
WAVE form wFormatTag IDs
|
| 33 |
+
|
| 34 |
+
Complete list is in mmreg.h in Windows 10 SDK. ALAC and OPUS are the
|
| 35 |
+
newest additions, in v10.0.14393 2016-07
|
| 36 |
+
"""
|
| 37 |
+
UNKNOWN = 0x0000
|
| 38 |
+
PCM = 0x0001
|
| 39 |
+
ADPCM = 0x0002
|
| 40 |
+
IEEE_FLOAT = 0x0003
|
| 41 |
+
VSELP = 0x0004
|
| 42 |
+
IBM_CVSD = 0x0005
|
| 43 |
+
ALAW = 0x0006
|
| 44 |
+
MULAW = 0x0007
|
| 45 |
+
DTS = 0x0008
|
| 46 |
+
DRM = 0x0009
|
| 47 |
+
WMAVOICE9 = 0x000A
|
| 48 |
+
WMAVOICE10 = 0x000B
|
| 49 |
+
OKI_ADPCM = 0x0010
|
| 50 |
+
DVI_ADPCM = 0x0011
|
| 51 |
+
IMA_ADPCM = 0x0011 # Duplicate
|
| 52 |
+
MEDIASPACE_ADPCM = 0x0012
|
| 53 |
+
SIERRA_ADPCM = 0x0013
|
| 54 |
+
G723_ADPCM = 0x0014
|
| 55 |
+
DIGISTD = 0x0015
|
| 56 |
+
DIGIFIX = 0x0016
|
| 57 |
+
DIALOGIC_OKI_ADPCM = 0x0017
|
| 58 |
+
MEDIAVISION_ADPCM = 0x0018
|
| 59 |
+
CU_CODEC = 0x0019
|
| 60 |
+
HP_DYN_VOICE = 0x001A
|
| 61 |
+
YAMAHA_ADPCM = 0x0020
|
| 62 |
+
SONARC = 0x0021
|
| 63 |
+
DSPGROUP_TRUESPEECH = 0x0022
|
| 64 |
+
ECHOSC1 = 0x0023
|
| 65 |
+
AUDIOFILE_AF36 = 0x0024
|
| 66 |
+
APTX = 0x0025
|
| 67 |
+
AUDIOFILE_AF10 = 0x0026
|
| 68 |
+
PROSODY_1612 = 0x0027
|
| 69 |
+
LRC = 0x0028
|
| 70 |
+
DOLBY_AC2 = 0x0030
|
| 71 |
+
GSM610 = 0x0031
|
| 72 |
+
MSNAUDIO = 0x0032
|
| 73 |
+
ANTEX_ADPCME = 0x0033
|
| 74 |
+
CONTROL_RES_VQLPC = 0x0034
|
| 75 |
+
DIGIREAL = 0x0035
|
| 76 |
+
DIGIADPCM = 0x0036
|
| 77 |
+
CONTROL_RES_CR10 = 0x0037
|
| 78 |
+
NMS_VBXADPCM = 0x0038
|
| 79 |
+
CS_IMAADPCM = 0x0039
|
| 80 |
+
ECHOSC3 = 0x003A
|
| 81 |
+
ROCKWELL_ADPCM = 0x003B
|
| 82 |
+
ROCKWELL_DIGITALK = 0x003C
|
| 83 |
+
XEBEC = 0x003D
|
| 84 |
+
G721_ADPCM = 0x0040
|
| 85 |
+
G728_CELP = 0x0041
|
| 86 |
+
MSG723 = 0x0042
|
| 87 |
+
INTEL_G723_1 = 0x0043
|
| 88 |
+
INTEL_G729 = 0x0044
|
| 89 |
+
SHARP_G726 = 0x0045
|
| 90 |
+
MPEG = 0x0050
|
| 91 |
+
RT24 = 0x0052
|
| 92 |
+
PAC = 0x0053
|
| 93 |
+
MPEGLAYER3 = 0x0055
|
| 94 |
+
LUCENT_G723 = 0x0059
|
| 95 |
+
CIRRUS = 0x0060
|
| 96 |
+
ESPCM = 0x0061
|
| 97 |
+
VOXWARE = 0x0062
|
| 98 |
+
CANOPUS_ATRAC = 0x0063
|
| 99 |
+
G726_ADPCM = 0x0064
|
| 100 |
+
G722_ADPCM = 0x0065
|
| 101 |
+
DSAT = 0x0066
|
| 102 |
+
DSAT_DISPLAY = 0x0067
|
| 103 |
+
VOXWARE_BYTE_ALIGNED = 0x0069
|
| 104 |
+
VOXWARE_AC8 = 0x0070
|
| 105 |
+
VOXWARE_AC10 = 0x0071
|
| 106 |
+
VOXWARE_AC16 = 0x0072
|
| 107 |
+
VOXWARE_AC20 = 0x0073
|
| 108 |
+
VOXWARE_RT24 = 0x0074
|
| 109 |
+
VOXWARE_RT29 = 0x0075
|
| 110 |
+
VOXWARE_RT29HW = 0x0076
|
| 111 |
+
VOXWARE_VR12 = 0x0077
|
| 112 |
+
VOXWARE_VR18 = 0x0078
|
| 113 |
+
VOXWARE_TQ40 = 0x0079
|
| 114 |
+
VOXWARE_SC3 = 0x007A
|
| 115 |
+
VOXWARE_SC3_1 = 0x007B
|
| 116 |
+
SOFTSOUND = 0x0080
|
| 117 |
+
VOXWARE_TQ60 = 0x0081
|
| 118 |
+
MSRT24 = 0x0082
|
| 119 |
+
G729A = 0x0083
|
| 120 |
+
MVI_MVI2 = 0x0084
|
| 121 |
+
DF_G726 = 0x0085
|
| 122 |
+
DF_GSM610 = 0x0086
|
| 123 |
+
ISIAUDIO = 0x0088
|
| 124 |
+
ONLIVE = 0x0089
|
| 125 |
+
MULTITUDE_FT_SX20 = 0x008A
|
| 126 |
+
INFOCOM_ITS_G721_ADPCM = 0x008B
|
| 127 |
+
CONVEDIA_G729 = 0x008C
|
| 128 |
+
CONGRUENCY = 0x008D
|
| 129 |
+
SBC24 = 0x0091
|
| 130 |
+
DOLBY_AC3_SPDIF = 0x0092
|
| 131 |
+
MEDIASONIC_G723 = 0x0093
|
| 132 |
+
PROSODY_8KBPS = 0x0094
|
| 133 |
+
ZYXEL_ADPCM = 0x0097
|
| 134 |
+
PHILIPS_LPCBB = 0x0098
|
| 135 |
+
PACKED = 0x0099
|
| 136 |
+
MALDEN_PHONYTALK = 0x00A0
|
| 137 |
+
RACAL_RECORDER_GSM = 0x00A1
|
| 138 |
+
RACAL_RECORDER_G720_A = 0x00A2
|
| 139 |
+
RACAL_RECORDER_G723_1 = 0x00A3
|
| 140 |
+
RACAL_RECORDER_TETRA_ACELP = 0x00A4
|
| 141 |
+
NEC_AAC = 0x00B0
|
| 142 |
+
RAW_AAC1 = 0x00FF
|
| 143 |
+
RHETOREX_ADPCM = 0x0100
|
| 144 |
+
IRAT = 0x0101
|
| 145 |
+
VIVO_G723 = 0x0111
|
| 146 |
+
VIVO_SIREN = 0x0112
|
| 147 |
+
PHILIPS_CELP = 0x0120
|
| 148 |
+
PHILIPS_GRUNDIG = 0x0121
|
| 149 |
+
DIGITAL_G723 = 0x0123
|
| 150 |
+
SANYO_LD_ADPCM = 0x0125
|
| 151 |
+
SIPROLAB_ACEPLNET = 0x0130
|
| 152 |
+
SIPROLAB_ACELP4800 = 0x0131
|
| 153 |
+
SIPROLAB_ACELP8V3 = 0x0132
|
| 154 |
+
SIPROLAB_G729 = 0x0133
|
| 155 |
+
SIPROLAB_G729A = 0x0134
|
| 156 |
+
SIPROLAB_KELVIN = 0x0135
|
| 157 |
+
VOICEAGE_AMR = 0x0136
|
| 158 |
+
G726ADPCM = 0x0140
|
| 159 |
+
DICTAPHONE_CELP68 = 0x0141
|
| 160 |
+
DICTAPHONE_CELP54 = 0x0142
|
| 161 |
+
QUALCOMM_PUREVOICE = 0x0150
|
| 162 |
+
QUALCOMM_HALFRATE = 0x0151
|
| 163 |
+
TUBGSM = 0x0155
|
| 164 |
+
MSAUDIO1 = 0x0160
|
| 165 |
+
WMAUDIO2 = 0x0161
|
| 166 |
+
WMAUDIO3 = 0x0162
|
| 167 |
+
WMAUDIO_LOSSLESS = 0x0163
|
| 168 |
+
WMASPDIF = 0x0164
|
| 169 |
+
UNISYS_NAP_ADPCM = 0x0170
|
| 170 |
+
UNISYS_NAP_ULAW = 0x0171
|
| 171 |
+
UNISYS_NAP_ALAW = 0x0172
|
| 172 |
+
UNISYS_NAP_16K = 0x0173
|
| 173 |
+
SYCOM_ACM_SYC008 = 0x0174
|
| 174 |
+
SYCOM_ACM_SYC701_G726L = 0x0175
|
| 175 |
+
SYCOM_ACM_SYC701_CELP54 = 0x0176
|
| 176 |
+
SYCOM_ACM_SYC701_CELP68 = 0x0177
|
| 177 |
+
KNOWLEDGE_ADVENTURE_ADPCM = 0x0178
|
| 178 |
+
FRAUNHOFER_IIS_MPEG2_AAC = 0x0180
|
| 179 |
+
DTS_DS = 0x0190
|
| 180 |
+
CREATIVE_ADPCM = 0x0200
|
| 181 |
+
CREATIVE_FASTSPEECH8 = 0x0202
|
| 182 |
+
CREATIVE_FASTSPEECH10 = 0x0203
|
| 183 |
+
UHER_ADPCM = 0x0210
|
| 184 |
+
ULEAD_DV_AUDIO = 0x0215
|
| 185 |
+
ULEAD_DV_AUDIO_1 = 0x0216
|
| 186 |
+
QUARTERDECK = 0x0220
|
| 187 |
+
ILINK_VC = 0x0230
|
| 188 |
+
RAW_SPORT = 0x0240
|
| 189 |
+
ESST_AC3 = 0x0241
|
| 190 |
+
GENERIC_PASSTHRU = 0x0249
|
| 191 |
+
IPI_HSX = 0x0250
|
| 192 |
+
IPI_RPELP = 0x0251
|
| 193 |
+
CS2 = 0x0260
|
| 194 |
+
SONY_SCX = 0x0270
|
| 195 |
+
SONY_SCY = 0x0271
|
| 196 |
+
SONY_ATRAC3 = 0x0272
|
| 197 |
+
SONY_SPC = 0x0273
|
| 198 |
+
TELUM_AUDIO = 0x0280
|
| 199 |
+
TELUM_IA_AUDIO = 0x0281
|
| 200 |
+
NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285
|
| 201 |
+
FM_TOWNS_SND = 0x0300
|
| 202 |
+
MICRONAS = 0x0350
|
| 203 |
+
MICRONAS_CELP833 = 0x0351
|
| 204 |
+
BTV_DIGITAL = 0x0400
|
| 205 |
+
INTEL_MUSIC_CODER = 0x0401
|
| 206 |
+
INDEO_AUDIO = 0x0402
|
| 207 |
+
QDESIGN_MUSIC = 0x0450
|
| 208 |
+
ON2_VP7_AUDIO = 0x0500
|
| 209 |
+
ON2_VP6_AUDIO = 0x0501
|
| 210 |
+
VME_VMPCM = 0x0680
|
| 211 |
+
TPC = 0x0681
|
| 212 |
+
LIGHTWAVE_LOSSLESS = 0x08AE
|
| 213 |
+
OLIGSM = 0x1000
|
| 214 |
+
OLIADPCM = 0x1001
|
| 215 |
+
OLICELP = 0x1002
|
| 216 |
+
OLISBC = 0x1003
|
| 217 |
+
OLIOPR = 0x1004
|
| 218 |
+
LH_CODEC = 0x1100
|
| 219 |
+
LH_CODEC_CELP = 0x1101
|
| 220 |
+
LH_CODEC_SBC8 = 0x1102
|
| 221 |
+
LH_CODEC_SBC12 = 0x1103
|
| 222 |
+
LH_CODEC_SBC16 = 0x1104
|
| 223 |
+
NORRIS = 0x1400
|
| 224 |
+
ISIAUDIO_2 = 0x1401
|
| 225 |
+
SOUNDSPACE_MUSICOMPRESS = 0x1500
|
| 226 |
+
MPEG_ADTS_AAC = 0x1600
|
| 227 |
+
MPEG_RAW_AAC = 0x1601
|
| 228 |
+
MPEG_LOAS = 0x1602
|
| 229 |
+
NOKIA_MPEG_ADTS_AAC = 0x1608
|
| 230 |
+
NOKIA_MPEG_RAW_AAC = 0x1609
|
| 231 |
+
VODAFONE_MPEG_ADTS_AAC = 0x160A
|
| 232 |
+
VODAFONE_MPEG_RAW_AAC = 0x160B
|
| 233 |
+
MPEG_HEAAC = 0x1610
|
| 234 |
+
VOXWARE_RT24_SPEECH = 0x181C
|
| 235 |
+
SONICFOUNDRY_LOSSLESS = 0x1971
|
| 236 |
+
INNINGS_TELECOM_ADPCM = 0x1979
|
| 237 |
+
LUCENT_SX8300P = 0x1C07
|
| 238 |
+
LUCENT_SX5363S = 0x1C0C
|
| 239 |
+
CUSEEME = 0x1F03
|
| 240 |
+
NTCSOFT_ALF2CM_ACM = 0x1FC4
|
| 241 |
+
DVM = 0x2000
|
| 242 |
+
DTS2 = 0x2001
|
| 243 |
+
MAKEAVIS = 0x3313
|
| 244 |
+
DIVIO_MPEG4_AAC = 0x4143
|
| 245 |
+
NOKIA_ADAPTIVE_MULTIRATE = 0x4201
|
| 246 |
+
DIVIO_G726 = 0x4243
|
| 247 |
+
LEAD_SPEECH = 0x434C
|
| 248 |
+
LEAD_VORBIS = 0x564C
|
| 249 |
+
WAVPACK_AUDIO = 0x5756
|
| 250 |
+
OGG_VORBIS_MODE_1 = 0x674F
|
| 251 |
+
OGG_VORBIS_MODE_2 = 0x6750
|
| 252 |
+
OGG_VORBIS_MODE_3 = 0x6751
|
| 253 |
+
OGG_VORBIS_MODE_1_PLUS = 0x676F
|
| 254 |
+
OGG_VORBIS_MODE_2_PLUS = 0x6770
|
| 255 |
+
OGG_VORBIS_MODE_3_PLUS = 0x6771
|
| 256 |
+
ALAC = 0x6C61
|
| 257 |
+
_3COM_NBX = 0x7000 # Can't have leading digit
|
| 258 |
+
OPUS = 0x704F
|
| 259 |
+
FAAD_AAC = 0x706D
|
| 260 |
+
AMR_NB = 0x7361
|
| 261 |
+
AMR_WB = 0x7362
|
| 262 |
+
AMR_WP = 0x7363
|
| 263 |
+
GSM_AMR_CBR = 0x7A21
|
| 264 |
+
GSM_AMR_VBR_SID = 0x7A22
|
| 265 |
+
COMVERSE_INFOSYS_G723_1 = 0xA100
|
| 266 |
+
COMVERSE_INFOSYS_AVQSBC = 0xA101
|
| 267 |
+
COMVERSE_INFOSYS_SBC = 0xA102
|
| 268 |
+
SYMBOL_G729_A = 0xA103
|
| 269 |
+
VOICEAGE_AMR_WB = 0xA104
|
| 270 |
+
INGENIENT_G726 = 0xA105
|
| 271 |
+
MPEG4_AAC = 0xA106
|
| 272 |
+
ENCORE_G726 = 0xA107
|
| 273 |
+
ZOLL_ASAO = 0xA108
|
| 274 |
+
SPEEX_VOICE = 0xA109
|
| 275 |
+
VIANIX_MASC = 0xA10A
|
| 276 |
+
WM9_SPECTRUM_ANALYZER = 0xA10B
|
| 277 |
+
WMF_SPECTRUM_ANAYZER = 0xA10C
|
| 278 |
+
GSM_610 = 0xA10D
|
| 279 |
+
GSM_620 = 0xA10E
|
| 280 |
+
GSM_660 = 0xA10F
|
| 281 |
+
GSM_690 = 0xA110
|
| 282 |
+
GSM_ADAPTIVE_MULTIRATE_WB = 0xA111
|
| 283 |
+
POLYCOM_G722 = 0xA112
|
| 284 |
+
POLYCOM_G728 = 0xA113
|
| 285 |
+
POLYCOM_G729_A = 0xA114
|
| 286 |
+
POLYCOM_SIREN = 0xA115
|
| 287 |
+
GLOBAL_IP_ILBC = 0xA116
|
| 288 |
+
RADIOTIME_TIME_SHIFT_RADIO = 0xA117
|
| 289 |
+
NICE_ACA = 0xA118
|
| 290 |
+
NICE_ADPCM = 0xA119
|
| 291 |
+
VOCORD_G721 = 0xA11A
|
| 292 |
+
VOCORD_G726 = 0xA11B
|
| 293 |
+
VOCORD_G722_1 = 0xA11C
|
| 294 |
+
VOCORD_G728 = 0xA11D
|
| 295 |
+
VOCORD_G729 = 0xA11E
|
| 296 |
+
VOCORD_G729_A = 0xA11F
|
| 297 |
+
VOCORD_G723_1 = 0xA120
|
| 298 |
+
VOCORD_LBC = 0xA121
|
| 299 |
+
NICE_G728 = 0xA122
|
| 300 |
+
FRACE_TELECOM_G729 = 0xA123
|
| 301 |
+
CODIAN = 0xA124
|
| 302 |
+
FLAC = 0xF1AC
|
| 303 |
+
EXTENSIBLE = 0xFFFE
|
| 304 |
+
DEVELOPMENT = 0xFFFF
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT}
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _raise_bad_format(format_tag):
|
| 311 |
+
try:
|
| 312 |
+
format_name = WAVE_FORMAT(format_tag).name
|
| 313 |
+
except ValueError:
|
| 314 |
+
format_name = f'{format_tag:#06x}'
|
| 315 |
+
raise ValueError(f"Unknown wave file format: {format_name}. Supported "
|
| 316 |
+
"formats: " +
|
| 317 |
+
', '.join(x.name for x in KNOWN_WAVE_FORMATS))
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _read_fmt_chunk(fid, is_big_endian):
|
| 321 |
+
"""
|
| 322 |
+
Returns
|
| 323 |
+
-------
|
| 324 |
+
size : int
|
| 325 |
+
size of format subchunk in bytes (minus 8 for "fmt " and itself)
|
| 326 |
+
format_tag : int
|
| 327 |
+
PCM, float, or compressed format
|
| 328 |
+
channels : int
|
| 329 |
+
number of channels
|
| 330 |
+
fs : int
|
| 331 |
+
sampling frequency in samples per second
|
| 332 |
+
bytes_per_second : int
|
| 333 |
+
overall byte rate for the file
|
| 334 |
+
block_align : int
|
| 335 |
+
bytes per sample, including all channels
|
| 336 |
+
bit_depth : int
|
| 337 |
+
bits per sample
|
| 338 |
+
|
| 339 |
+
Notes
|
| 340 |
+
-----
|
| 341 |
+
Assumes file pointer is immediately after the 'fmt ' id
|
| 342 |
+
"""
|
| 343 |
+
if is_big_endian:
|
| 344 |
+
fmt = '>'
|
| 345 |
+
else:
|
| 346 |
+
fmt = '<'
|
| 347 |
+
|
| 348 |
+
size = struct.unpack(fmt+'I', fid.read(4))[0]
|
| 349 |
+
|
| 350 |
+
if size < 16:
|
| 351 |
+
raise ValueError("Binary structure of wave file is not compliant")
|
| 352 |
+
|
| 353 |
+
res = struct.unpack(fmt+'HHIIHH', fid.read(16))
|
| 354 |
+
bytes_read = 16
|
| 355 |
+
|
| 356 |
+
format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res
|
| 357 |
+
|
| 358 |
+
if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2):
|
| 359 |
+
ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0]
|
| 360 |
+
bytes_read += 2
|
| 361 |
+
if ext_chunk_size >= 22:
|
| 362 |
+
extensible_chunk_data = fid.read(22)
|
| 363 |
+
bytes_read += 22
|
| 364 |
+
raw_guid = extensible_chunk_data[2+4:2+4+16]
|
| 365 |
+
# GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361)
|
| 366 |
+
# MS GUID byte order: first three groups are native byte order,
|
| 367 |
+
# rest is Big Endian
|
| 368 |
+
if is_big_endian:
|
| 369 |
+
tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71'
|
| 370 |
+
else:
|
| 371 |
+
tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71'
|
| 372 |
+
if raw_guid.endswith(tail):
|
| 373 |
+
format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0]
|
| 374 |
+
else:
|
| 375 |
+
raise ValueError("Binary structure of wave file is not compliant")
|
| 376 |
+
|
| 377 |
+
if format_tag not in KNOWN_WAVE_FORMATS:
|
| 378 |
+
_raise_bad_format(format_tag)
|
| 379 |
+
|
| 380 |
+
# move file pointer to next chunk
|
| 381 |
+
if size > bytes_read:
|
| 382 |
+
fid.read(size - bytes_read)
|
| 383 |
+
|
| 384 |
+
# fmt should always be 16, 18 or 40, but handle it just in case
|
| 385 |
+
_handle_pad_byte(fid, size)
|
| 386 |
+
|
| 387 |
+
if format_tag == WAVE_FORMAT.PCM:
|
| 388 |
+
if bytes_per_second != fs * block_align:
|
| 389 |
+
raise ValueError("WAV header is invalid: nAvgBytesPerSec must"
|
| 390 |
+
" equal product of nSamplesPerSec and"
|
| 391 |
+
" nBlockAlign, but file has nSamplesPerSec ="
|
| 392 |
+
f" {fs}, nBlockAlign = {block_align}, and"
|
| 393 |
+
f" nAvgBytesPerSec = {bytes_per_second}")
|
| 394 |
+
|
| 395 |
+
return (size, format_tag, channels, fs, bytes_per_second, block_align,
|
| 396 |
+
bit_depth)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, is_rf64,
|
| 400 |
+
block_align, mmap=False):
|
| 401 |
+
"""
|
| 402 |
+
Notes
|
| 403 |
+
-----
|
| 404 |
+
Assumes file pointer is immediately after the 'data' id
|
| 405 |
+
|
| 406 |
+
It's possible to not use all available bits in a container, or to store
|
| 407 |
+
samples in a container bigger than necessary, so bytes_per_sample uses
|
| 408 |
+
the actual reported container size (nBlockAlign / nChannels). Real-world
|
| 409 |
+
examples:
|
| 410 |
+
|
| 411 |
+
Adobe Audition's "24-bit packed int (type 1, 20-bit)"
|
| 412 |
+
|
| 413 |
+
nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20
|
| 414 |
+
|
| 415 |
+
http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav
|
| 416 |
+
is:
|
| 417 |
+
|
| 418 |
+
nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12
|
| 419 |
+
|
| 420 |
+
http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
|
| 421 |
+
gives an example of:
|
| 422 |
+
|
| 423 |
+
nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20
|
| 424 |
+
"""
|
| 425 |
+
if is_big_endian:
|
| 426 |
+
fmt = '>'
|
| 427 |
+
else:
|
| 428 |
+
fmt = '<'
|
| 429 |
+
|
| 430 |
+
# Size of the data subchunk in bytes
|
| 431 |
+
if not is_rf64:
|
| 432 |
+
size = struct.unpack(fmt+'I', fid.read(4))[0]
|
| 433 |
+
else:
|
| 434 |
+
pos = fid.tell()
|
| 435 |
+
# chunk size is stored in global file header for RF64
|
| 436 |
+
fid.seek(28)
|
| 437 |
+
size = struct.unpack('<Q', fid.read(8))[0]
|
| 438 |
+
fid.seek(pos)
|
| 439 |
+
# skip data chunk size as it is 0xFFFFFFF
|
| 440 |
+
fid.read(4)
|
| 441 |
+
|
| 442 |
+
# Number of bytes per sample (sample container size)
|
| 443 |
+
bytes_per_sample = block_align // channels
|
| 444 |
+
n_samples = size // bytes_per_sample
|
| 445 |
+
|
| 446 |
+
if format_tag == WAVE_FORMAT.PCM:
|
| 447 |
+
if 1 <= bit_depth <= 8:
|
| 448 |
+
dtype = 'u1' # WAV of 8-bit integer or less are unsigned
|
| 449 |
+
elif bytes_per_sample in {3, 5, 6, 7}:
|
| 450 |
+
# No compatible dtype. Load as raw bytes for reshaping later.
|
| 451 |
+
dtype = 'V1'
|
| 452 |
+
elif bit_depth <= 64:
|
| 453 |
+
# Remaining bit depths can map directly to signed numpy dtypes
|
| 454 |
+
dtype = f'{fmt}i{bytes_per_sample}'
|
| 455 |
+
else:
|
| 456 |
+
raise ValueError("Unsupported bit depth: the WAV file "
|
| 457 |
+
f"has {bit_depth}-bit integer data.")
|
| 458 |
+
elif format_tag == WAVE_FORMAT.IEEE_FLOAT:
|
| 459 |
+
if bit_depth in {32, 64}:
|
| 460 |
+
dtype = f'{fmt}f{bytes_per_sample}'
|
| 461 |
+
else:
|
| 462 |
+
raise ValueError("Unsupported bit depth: the WAV file "
|
| 463 |
+
f"has {bit_depth}-bit floating-point data.")
|
| 464 |
+
else:
|
| 465 |
+
_raise_bad_format(format_tag)
|
| 466 |
+
|
| 467 |
+
start = fid.tell()
|
| 468 |
+
if not mmap:
|
| 469 |
+
try:
|
| 470 |
+
count = size if dtype == 'V1' else n_samples
|
| 471 |
+
data = np.fromfile(fid, dtype=dtype, count=count)
|
| 472 |
+
except io.UnsupportedOperation: # not a C-like file
|
| 473 |
+
fid.seek(start, 0) # just in case it seeked, though it shouldn't
|
| 474 |
+
data = np.frombuffer(fid.read(size), dtype=dtype)
|
| 475 |
+
|
| 476 |
+
if dtype == 'V1':
|
| 477 |
+
# Rearrange raw bytes into smallest compatible numpy dtype
|
| 478 |
+
dt = f'{fmt}i4' if bytes_per_sample == 3 else f'{fmt}i8'
|
| 479 |
+
a = np.zeros((len(data) // bytes_per_sample, np.dtype(dt).itemsize),
|
| 480 |
+
dtype='V1')
|
| 481 |
+
if is_big_endian:
|
| 482 |
+
a[:, :bytes_per_sample] = data.reshape((-1, bytes_per_sample))
|
| 483 |
+
else:
|
| 484 |
+
a[:, -bytes_per_sample:] = data.reshape((-1, bytes_per_sample))
|
| 485 |
+
data = a.view(dt).reshape(a.shape[:-1])
|
| 486 |
+
else:
|
| 487 |
+
if bytes_per_sample in {1, 2, 4, 8}:
|
| 488 |
+
start = fid.tell()
|
| 489 |
+
data = np.memmap(fid, dtype=dtype, mode='c', offset=start,
|
| 490 |
+
shape=(n_samples,))
|
| 491 |
+
fid.seek(start + size)
|
| 492 |
+
else:
|
| 493 |
+
raise ValueError("mmap=True not compatible with "
|
| 494 |
+
f"{bytes_per_sample}-byte container size.")
|
| 495 |
+
|
| 496 |
+
_handle_pad_byte(fid, size)
|
| 497 |
+
|
| 498 |
+
if channels > 1:
|
| 499 |
+
data = data.reshape(-1, channels)
|
| 500 |
+
return data
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _skip_unknown_chunk(fid, is_big_endian):
|
| 504 |
+
if is_big_endian:
|
| 505 |
+
fmt = '>I'
|
| 506 |
+
else:
|
| 507 |
+
fmt = '<I'
|
| 508 |
+
|
| 509 |
+
data = fid.read(4)
|
| 510 |
+
# call unpack() and seek() only if we have really read data from file
|
| 511 |
+
# otherwise empty read at the end of the file would trigger
|
| 512 |
+
# unnecessary exception at unpack() call
|
| 513 |
+
# in case data equals somehow to 0, there is no need for seek() anyway
|
| 514 |
+
if data:
|
| 515 |
+
size = struct.unpack(fmt, data)[0]
|
| 516 |
+
fid.seek(size, 1)
|
| 517 |
+
_handle_pad_byte(fid, size)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _read_riff_chunk(fid):
|
| 521 |
+
str1 = fid.read(4) # File signature
|
| 522 |
+
if str1 == b'RIFF':
|
| 523 |
+
is_rf64 = False
|
| 524 |
+
is_big_endian = False
|
| 525 |
+
fmt = '<I'
|
| 526 |
+
elif str1 == b'RIFX':
|
| 527 |
+
is_rf64 = False
|
| 528 |
+
is_big_endian = True
|
| 529 |
+
fmt = '>I'
|
| 530 |
+
elif str1 == b'RF64':
|
| 531 |
+
is_rf64 = True
|
| 532 |
+
is_big_endian = False
|
| 533 |
+
fmt = '<Q'
|
| 534 |
+
else:
|
| 535 |
+
# There are also .wav files with "FFIR" or "XFIR" signatures?
|
| 536 |
+
raise ValueError(f"File format {repr(str1)} not understood. Only "
|
| 537 |
+
"'RIFF', 'RIFX', and 'RF64' supported.")
|
| 538 |
+
# Size of entire file
|
| 539 |
+
if not is_rf64:
|
| 540 |
+
file_size = struct.unpack(fmt, fid.read(4))[0] + 8
|
| 541 |
+
str2 = fid.read(4)
|
| 542 |
+
else:
|
| 543 |
+
# Skip 0xFFFFFFFF (-1) bytes
|
| 544 |
+
fid.read(4)
|
| 545 |
+
str2 = fid.read(4)
|
| 546 |
+
str3 = fid.read(4)
|
| 547 |
+
if str3 != b'ds64':
|
| 548 |
+
raise ValueError("Invalid RF64 file: ds64 chunk not found.")
|
| 549 |
+
ds64_size = struct.unpack("<I", fid.read(4))[0]
|
| 550 |
+
file_size = struct.unpack(fmt, fid.read(8))[0] + 8
|
| 551 |
+
# Ignore additional attributes of ds64 chunk like sample count, tables, etc.
|
| 552 |
+
# and just skip to the next chunk
|
| 553 |
+
fid.seek(ds64_size - 8, 1)
|
| 554 |
+
|
| 555 |
+
if str2 != b'WAVE':
|
| 556 |
+
raise ValueError(f"Not a WAV file. RIFF form type is {repr(str2)}.")
|
| 557 |
+
|
| 558 |
+
return file_size, is_big_endian, is_rf64
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def _handle_pad_byte(fid, size):
|
| 562 |
+
# "If the chunk size is an odd number of bytes, a pad byte with value zero
|
| 563 |
+
# is written after ckData." So we need to seek past this after each chunk.
|
| 564 |
+
if size % 2:
|
| 565 |
+
fid.seek(1, 1)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def read(filename, mmap=False):
|
| 569 |
+
"""
|
| 570 |
+
Open a WAV file.
|
| 571 |
+
|
| 572 |
+
Return the sample rate (in samples/sec) and data from an LPCM WAV file.
|
| 573 |
+
|
| 574 |
+
Parameters
|
| 575 |
+
----------
|
| 576 |
+
filename : string or open file handle
|
| 577 |
+
Input WAV file.
|
| 578 |
+
mmap : bool, optional
|
| 579 |
+
Whether to read data as memory-mapped (default: False). Not compatible
|
| 580 |
+
with some bit depths; see Notes. Only to be used on real files.
|
| 581 |
+
|
| 582 |
+
.. versionadded:: 0.12.0
|
| 583 |
+
|
| 584 |
+
Returns
|
| 585 |
+
-------
|
| 586 |
+
rate : int
|
| 587 |
+
Sample rate of WAV file.
|
| 588 |
+
data : numpy array
|
| 589 |
+
Data read from WAV file. Data-type is determined from the file;
|
| 590 |
+
see Notes. Data is 1-D for 1-channel WAV, or 2-D of shape
|
| 591 |
+
(Nsamples, Nchannels) otherwise. If a file-like input without a
|
| 592 |
+
C-like file descriptor (e.g., :class:`python:io.BytesIO`) is
|
| 593 |
+
passed, this will not be writeable.
|
| 594 |
+
|
| 595 |
+
Notes
|
| 596 |
+
-----
|
| 597 |
+
Common data types: [1]_
|
| 598 |
+
|
| 599 |
+
===================== =========== =========== =============
|
| 600 |
+
WAV format Min Max NumPy dtype
|
| 601 |
+
===================== =========== =========== =============
|
| 602 |
+
32-bit floating-point -1.0 +1.0 float32
|
| 603 |
+
32-bit integer PCM -2147483648 +2147483647 int32
|
| 604 |
+
24-bit integer PCM -2147483648 +2147483392 int32
|
| 605 |
+
16-bit integer PCM -32768 +32767 int16
|
| 606 |
+
8-bit integer PCM 0 255 uint8
|
| 607 |
+
===================== =========== =========== =============
|
| 608 |
+
|
| 609 |
+
WAV files can specify arbitrary bit depth, and this function supports
|
| 610 |
+
reading any integer PCM depth from 1 to 64 bits. Data is returned in the
|
| 611 |
+
smallest compatible numpy int type, in left-justified format. 8-bit and
|
| 612 |
+
lower is unsigned, while 9-bit and higher is signed.
|
| 613 |
+
|
| 614 |
+
For example, 24-bit data will be stored as int32, with the MSB of the
|
| 615 |
+
24-bit data stored at the MSB of the int32, and typically the least
|
| 616 |
+
significant byte is 0x00. (However, if a file actually contains data past
|
| 617 |
+
its specified bit depth, those bits will be read and output, too. [2]_)
|
| 618 |
+
|
| 619 |
+
This bit justification and sign matches WAV's native internal format, which
|
| 620 |
+
allows memory mapping of WAV files that use 1, 2, 4, or 8 bytes per sample
|
| 621 |
+
(so 24-bit files cannot be memory-mapped, but 32-bit can).
|
| 622 |
+
|
| 623 |
+
IEEE float PCM in 32- or 64-bit format is supported, with or without mmap.
|
| 624 |
+
Values exceeding [-1, +1] are not clipped.
|
| 625 |
+
|
| 626 |
+
Non-linear PCM (mu-law, A-law) is not supported.
|
| 627 |
+
|
| 628 |
+
References
|
| 629 |
+
----------
|
| 630 |
+
.. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
|
| 631 |
+
Interface and Data Specifications 1.0", section "Data Format of the
|
| 632 |
+
Samples", August 1991
|
| 633 |
+
http://www.tactilemedia.com/info/MCI_Control_Info.html
|
| 634 |
+
.. [2] Adobe Systems Incorporated, "Adobe Audition 3 User Guide", section
|
| 635 |
+
"Audio file formats: 24-bit Packed Int (type 1, 20-bit)", 2007
|
| 636 |
+
|
| 637 |
+
Examples
|
| 638 |
+
--------
|
| 639 |
+
>>> from os.path import dirname, join as pjoin
|
| 640 |
+
>>> from scipy.io import wavfile
|
| 641 |
+
>>> import scipy.io
|
| 642 |
+
|
| 643 |
+
Get the filename for an example .wav file from the tests/data directory.
|
| 644 |
+
|
| 645 |
+
>>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data')
|
| 646 |
+
>>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
|
| 647 |
+
|
| 648 |
+
Load the .wav file contents.
|
| 649 |
+
|
| 650 |
+
>>> samplerate, data = wavfile.read(wav_fname)
|
| 651 |
+
>>> print(f"number of channels = {data.shape[1]}")
|
| 652 |
+
number of channels = 2
|
| 653 |
+
>>> length = data.shape[0] / samplerate
|
| 654 |
+
>>> print(f"length = {length}s")
|
| 655 |
+
length = 0.01s
|
| 656 |
+
|
| 657 |
+
Plot the waveform.
|
| 658 |
+
|
| 659 |
+
>>> import matplotlib.pyplot as plt
|
| 660 |
+
>>> import numpy as np
|
| 661 |
+
>>> time = np.linspace(0., length, data.shape[0])
|
| 662 |
+
>>> plt.plot(time, data[:, 0], label="Left channel")
|
| 663 |
+
>>> plt.plot(time, data[:, 1], label="Right channel")
|
| 664 |
+
>>> plt.legend()
|
| 665 |
+
>>> plt.xlabel("Time [s]")
|
| 666 |
+
>>> plt.ylabel("Amplitude")
|
| 667 |
+
>>> plt.show()
|
| 668 |
+
|
| 669 |
+
"""
|
| 670 |
+
if hasattr(filename, 'read'):
|
| 671 |
+
fid = filename
|
| 672 |
+
mmap = False
|
| 673 |
+
else:
|
| 674 |
+
fid = open(filename, 'rb')
|
| 675 |
+
|
| 676 |
+
try:
|
| 677 |
+
file_size, is_big_endian, is_rf64 = _read_riff_chunk(fid)
|
| 678 |
+
fmt_chunk_received = False
|
| 679 |
+
data_chunk_received = False
|
| 680 |
+
while fid.tell() < file_size:
|
| 681 |
+
# read the next chunk
|
| 682 |
+
chunk_id = fid.read(4)
|
| 683 |
+
|
| 684 |
+
if not chunk_id:
|
| 685 |
+
if data_chunk_received:
|
| 686 |
+
# End of file but data successfully read
|
| 687 |
+
warnings.warn(
|
| 688 |
+
f"Reached EOF prematurely; finished at {fid.tell():d} bytes, "
|
| 689 |
+
f"expected {file_size:d} bytes from header.",
|
| 690 |
+
WavFileWarning, stacklevel=2)
|
| 691 |
+
break
|
| 692 |
+
else:
|
| 693 |
+
raise ValueError("Unexpected end of file.")
|
| 694 |
+
elif len(chunk_id) < 4:
|
| 695 |
+
msg = f"Incomplete chunk ID: {repr(chunk_id)}"
|
| 696 |
+
# If we have the data, ignore the broken chunk
|
| 697 |
+
if fmt_chunk_received and data_chunk_received:
|
| 698 |
+
warnings.warn(msg + ", ignoring it.", WavFileWarning,
|
| 699 |
+
stacklevel=2)
|
| 700 |
+
else:
|
| 701 |
+
raise ValueError(msg)
|
| 702 |
+
|
| 703 |
+
if chunk_id == b'fmt ':
|
| 704 |
+
fmt_chunk_received = True
|
| 705 |
+
fmt_chunk = _read_fmt_chunk(fid, is_big_endian)
|
| 706 |
+
format_tag, channels, fs = fmt_chunk[1:4]
|
| 707 |
+
bit_depth = fmt_chunk[6]
|
| 708 |
+
block_align = fmt_chunk[5]
|
| 709 |
+
elif chunk_id == b'fact':
|
| 710 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 711 |
+
elif chunk_id == b'data':
|
| 712 |
+
data_chunk_received = True
|
| 713 |
+
if not fmt_chunk_received:
|
| 714 |
+
raise ValueError("No fmt chunk before data")
|
| 715 |
+
data = _read_data_chunk(fid, format_tag, channels, bit_depth,
|
| 716 |
+
is_big_endian, is_rf64, block_align, mmap)
|
| 717 |
+
elif chunk_id == b'LIST':
|
| 718 |
+
# Someday this could be handled properly but for now skip it
|
| 719 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 720 |
+
elif chunk_id in {b'JUNK', b'Fake'}:
|
| 721 |
+
# Skip alignment chunks without warning
|
| 722 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 723 |
+
else:
|
| 724 |
+
warnings.warn("Chunk (non-data) not understood, skipping it.",
|
| 725 |
+
WavFileWarning, stacklevel=2)
|
| 726 |
+
_skip_unknown_chunk(fid, is_big_endian)
|
| 727 |
+
finally:
|
| 728 |
+
if not hasattr(filename, 'read'):
|
| 729 |
+
fid.close()
|
| 730 |
+
else:
|
| 731 |
+
fid.seek(0)
|
| 732 |
+
|
| 733 |
+
return fs, data
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def write(filename, rate, data):
|
| 737 |
+
"""
|
| 738 |
+
Write a NumPy array as a WAV file.
|
| 739 |
+
|
| 740 |
+
Parameters
|
| 741 |
+
----------
|
| 742 |
+
filename : string or open file handle
|
| 743 |
+
Output wav file.
|
| 744 |
+
rate : int
|
| 745 |
+
The sample rate (in samples/sec).
|
| 746 |
+
data : ndarray
|
| 747 |
+
A 1-D or 2-D NumPy array of either integer or float data-type.
|
| 748 |
+
|
| 749 |
+
Notes
|
| 750 |
+
-----
|
| 751 |
+
* Writes a simple uncompressed WAV file.
|
| 752 |
+
* To write multiple-channels, use a 2-D array of shape
|
| 753 |
+
(Nsamples, Nchannels).
|
| 754 |
+
* The bits-per-sample and PCM/float will be determined by the data-type.
|
| 755 |
+
|
| 756 |
+
Common data types: [1]_
|
| 757 |
+
|
| 758 |
+
===================== =========== =========== =============
|
| 759 |
+
WAV format Min Max NumPy dtype
|
| 760 |
+
===================== =========== =========== =============
|
| 761 |
+
32-bit floating-point -1.0 +1.0 float32
|
| 762 |
+
32-bit PCM -2147483648 +2147483647 int32
|
| 763 |
+
16-bit PCM -32768 +32767 int16
|
| 764 |
+
8-bit PCM 0 255 uint8
|
| 765 |
+
===================== =========== =========== =============
|
| 766 |
+
|
| 767 |
+
Note that 8-bit PCM is unsigned.
|
| 768 |
+
|
| 769 |
+
References
|
| 770 |
+
----------
|
| 771 |
+
.. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
|
| 772 |
+
Interface and Data Specifications 1.0", section "Data Format of the
|
| 773 |
+
Samples", August 1991
|
| 774 |
+
http://www.tactilemedia.com/info/MCI_Control_Info.html
|
| 775 |
+
|
| 776 |
+
Examples
|
| 777 |
+
--------
|
| 778 |
+
Create a 100Hz sine wave, sampled at 44100Hz.
|
| 779 |
+
Write to 16-bit PCM, Mono.
|
| 780 |
+
|
| 781 |
+
>>> from scipy.io.wavfile import write
|
| 782 |
+
>>> import numpy as np
|
| 783 |
+
>>> samplerate = 44100; fs = 100
|
| 784 |
+
>>> t = np.linspace(0., 1., samplerate)
|
| 785 |
+
>>> amplitude = np.iinfo(np.int16).max
|
| 786 |
+
>>> data = amplitude * np.sin(2. * np.pi * fs * t)
|
| 787 |
+
>>> write("example.wav", samplerate, data.astype(np.int16))
|
| 788 |
+
|
| 789 |
+
"""
|
| 790 |
+
if hasattr(filename, 'write'):
|
| 791 |
+
fid = filename
|
| 792 |
+
else:
|
| 793 |
+
fid = open(filename, 'wb')
|
| 794 |
+
|
| 795 |
+
fs = rate
|
| 796 |
+
|
| 797 |
+
try:
|
| 798 |
+
dkind = data.dtype.kind
|
| 799 |
+
allowed_dtypes = ['float32', 'float64',
|
| 800 |
+
'uint8', 'int16', 'int32', 'int64']
|
| 801 |
+
if data.dtype.name not in allowed_dtypes:
|
| 802 |
+
raise ValueError("Unsupported data type '%s'" % data.dtype)
|
| 803 |
+
|
| 804 |
+
header_data = b''
|
| 805 |
+
|
| 806 |
+
header_data += b'RIFF'
|
| 807 |
+
header_data += b'\x00\x00\x00\x00'
|
| 808 |
+
header_data += b'WAVE'
|
| 809 |
+
|
| 810 |
+
# fmt chunk
|
| 811 |
+
header_data += b'fmt '
|
| 812 |
+
if dkind == 'f':
|
| 813 |
+
format_tag = WAVE_FORMAT.IEEE_FLOAT
|
| 814 |
+
else:
|
| 815 |
+
format_tag = WAVE_FORMAT.PCM
|
| 816 |
+
if data.ndim == 1:
|
| 817 |
+
channels = 1
|
| 818 |
+
else:
|
| 819 |
+
channels = data.shape[1]
|
| 820 |
+
bit_depth = data.dtype.itemsize * 8
|
| 821 |
+
bytes_per_second = fs*(bit_depth // 8)*channels
|
| 822 |
+
block_align = channels * (bit_depth // 8)
|
| 823 |
+
|
| 824 |
+
fmt_chunk_data = struct.pack('<HHIIHH', format_tag, channels, fs,
|
| 825 |
+
bytes_per_second, block_align, bit_depth)
|
| 826 |
+
if not (dkind == 'i' or dkind == 'u'):
|
| 827 |
+
# add cbSize field for non-PCM files
|
| 828 |
+
fmt_chunk_data += b'\x00\x00'
|
| 829 |
+
|
| 830 |
+
header_data += struct.pack('<I', len(fmt_chunk_data))
|
| 831 |
+
header_data += fmt_chunk_data
|
| 832 |
+
|
| 833 |
+
# check data size (needs to be immediately before the data chunk)
|
| 834 |
+
# if too large for standard RIFF, use RF64 instead
|
| 835 |
+
resulting_file_size = len(header_data) + 4 + 4 + data.nbytes
|
| 836 |
+
is_rf64 = (resulting_file_size - 8) > 0xFFFFFFFF
|
| 837 |
+
if is_rf64:
|
| 838 |
+
header_data = b''
|
| 839 |
+
header_data += b'RF64'
|
| 840 |
+
header_data += b'\xFF\xFF\xFF\xFF'
|
| 841 |
+
header_data += b'WAVE'
|
| 842 |
+
header_data += b'ds64'
|
| 843 |
+
# size of ds64 chunk
|
| 844 |
+
header_data += struct.pack('<I', 28)
|
| 845 |
+
# will be filled later with real file size
|
| 846 |
+
header_data += struct.pack('<Q', 0)
|
| 847 |
+
header_data += struct.pack('<Q', data.nbytes)
|
| 848 |
+
header_data += struct.pack('<Q', data.shape[0])
|
| 849 |
+
# ignore 'table' field for now
|
| 850 |
+
header_data += struct.pack('<I', 0)
|
| 851 |
+
header_data += b'fmt '
|
| 852 |
+
header_data += struct.pack('<I', len(fmt_chunk_data))
|
| 853 |
+
header_data += fmt_chunk_data
|
| 854 |
+
|
| 855 |
+
# fact chunk (non-PCM files)
|
| 856 |
+
if not (dkind == 'i' or dkind == 'u'):
|
| 857 |
+
header_data += b'fact'
|
| 858 |
+
header_data += struct.pack('<II', 4, data.shape[0])
|
| 859 |
+
|
| 860 |
+
fid.write(header_data)
|
| 861 |
+
|
| 862 |
+
# data chunk
|
| 863 |
+
fid.write(b'data')
|
| 864 |
+
# write data chunk size, unless its too big in which case 0xFFFFFFFF is written
|
| 865 |
+
fid.write(struct.pack('<I', min(data.nbytes, 4294967295)))
|
| 866 |
+
|
| 867 |
+
if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and
|
| 868 |
+
sys.byteorder == 'big'):
|
| 869 |
+
data = data.byteswap()
|
| 870 |
+
_array_tofile(fid, data)
|
| 871 |
+
|
| 872 |
+
# Determine file size and place it in correct
|
| 873 |
+
# position at start of the file or the data chunk.
|
| 874 |
+
size = fid.tell()
|
| 875 |
+
if not is_rf64:
|
| 876 |
+
fid.seek(4)
|
| 877 |
+
fid.write(struct.pack('<I', size-8))
|
| 878 |
+
else:
|
| 879 |
+
fid.seek(20)
|
| 880 |
+
fid.write(struct.pack('<Q', size-8))
|
| 881 |
+
|
| 882 |
+
finally:
|
| 883 |
+
if not hasattr(filename, 'write'):
|
| 884 |
+
fid.close()
|
| 885 |
+
else:
|
| 886 |
+
fid.seek(0)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def _array_tofile(fid, data):
|
| 890 |
+
# ravel gives a c-contiguous buffer
|
| 891 |
+
fid.write(data.ravel().view('b').data)
|
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc
ADDED
|
Binary file (6.69 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|