diff --git a/ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg.pt b/ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..21d7802c9bcea61b2a09424e1b5e019138934bd5 --- /dev/null +++ b/ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f07b309d3553ae9fd5e99c2f44a80c2640179e14a747a7268f3a5df00621cdf2 +size 9372 diff --git a/ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg_sq.pt b/ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..8a7824f5eaf74d1fb2b282e655aa08c10e3ffd50 --- /dev/null +++ b/ckpts/universal/global_step40/zero/13.post_attention_layernorm.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ff625f47bced33b98757679996399de33e2c91d05c1feeaf13de810ff2232de +size 9387 diff --git a/ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg.pt b/ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..f068a890492cf3b1aa72592d247e2db05e3316be --- /dev/null +++ b/ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:646552e221ebc7421a53ada64f1d1505daabaf2b22ca4ef2d3a12d1e7c7e189c +size 16778396 diff --git a/ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg_sq.pt b/ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..655d66b1cecc788d147a7ae6cc400155c1dd4c69 --- /dev/null +++ b/ckpts/universal/global_step40/zero/15.attention.dense.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f7af86e6739da6582dedcf651017239eaaa364ea9c2ed6578ba8004dcc17ae7 +size 16778411 diff --git a/ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg.pt b/ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..4e10f54b443e3384de431228dd456e98aa1051df --- /dev/null +++ b/ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:686bbc5205bf3d92f059bc47acebe4bbe9050cb9fbea263b30603159e56445c6 +size 9372 diff --git a/ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt b/ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..11f99d28c9394797efd1ee97fcc11fe253a91e91 --- /dev/null +++ b/ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a142cc7046accc32efdc0ceb6409dca534088b765ff3d184c71620f5bd4874b9 +size 9387 diff --git a/ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt b/ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..822d4ef2112f946375ff4dd56e7954d555acfd13 --- /dev/null +++ b/ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc09d9e918c81a8be10dd753e767177d5fdb658fe034c01c3205569aae720ad6 +size 33555612 diff --git a/venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac771e75d2ce563629075d94b6b76f4e934e4f77 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c1b64f515fb2f467cc55533f330835fd6f9ef8d Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_helper.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/__init__.py b/venv/lib/python3.10/site-packages/scipy/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1417abe144142078b38c45794f73178cec486b8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/__init__.py @@ -0,0 +1,116 @@ +""" +================================== +Input and output (:mod:`scipy.io`) +================================== + +.. currentmodule:: scipy.io + +SciPy has many modules, classes, and functions available to read data +from and write data to a variety of file formats. + +.. seealso:: `NumPy IO routines `__ + +MATLAB® files +============= + +.. autosummary:: + :toctree: generated/ + + loadmat - Read a MATLAB style mat file (version 4 through 7.1) + savemat - Write a MATLAB style mat file (version 4 through 7.1) + whosmat - List contents of a MATLAB style mat file (version 4 through 7.1) + +For low-level MATLAB reading and writing utilities, see `scipy.io.matlab`. + +IDL® files +========== + +.. autosummary:: + :toctree: generated/ + + readsav - Read an IDL 'save' file + +Matrix Market files +=================== + +.. autosummary:: + :toctree: generated/ + + mminfo - Query matrix info from Matrix Market formatted file + mmread - Read matrix from Matrix Market formatted file + mmwrite - Write matrix to Matrix Market formatted file + +Unformatted Fortran files +=============================== + +.. autosummary:: + :toctree: generated/ + + FortranFile - A file object for unformatted sequential Fortran files + FortranEOFError - Exception indicating the end of a well-formed file + FortranFormattingError - Exception indicating an inappropriate end + +Netcdf +====== + +.. autosummary:: + :toctree: generated/ + + netcdf_file - A file object for NetCDF data + netcdf_variable - A data object for the netcdf module + +Harwell-Boeing files +==================== + +.. autosummary:: + :toctree: generated/ + + hb_read -- read H-B file + hb_write -- write H-B file + +Wav sound files (:mod:`scipy.io.wavfile`) +========================================= + +.. module:: scipy.io.wavfile + +.. autosummary:: + :toctree: generated/ + + read + write + WavFileWarning + +Arff files (:mod:`scipy.io.arff`) +================================= + +.. module:: scipy.io.arff + +.. autosummary:: + :toctree: generated/ + + loadarff + MetaData + ArffError + ParseArffError +""" +# matfile read and write +from .matlab import loadmat, savemat, whosmat + +# netCDF file support +from ._netcdf import netcdf_file, netcdf_variable + +# Fortran file support +from ._fortran import FortranFile, FortranEOFError, FortranFormattingError + +from ._fast_matrix_market import mminfo, mmread, mmwrite +from ._idl import readsav +from ._harwell_boeing import hb_read, hb_write + +# Deprecated namespaces, to be removed in v2.0.0 +from . import arff, harwell_boeing, idl, mmio, netcdf, wavfile + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/venv/lib/python3.10/site-packages/scipy/io/_fortran.py b/venv/lib/python3.10/site-packages/scipy/io/_fortran.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c93c57bcdab3b5a40437a147a384167772c306 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/_fortran.py @@ -0,0 +1,354 @@ +""" +Module to read / write Fortran unformatted sequential files. + +This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz. + +""" +import warnings +import numpy as np + +__all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError'] + + +class FortranEOFError(TypeError, OSError): + """Indicates that the file ended properly. + + This error descends from TypeError because the code used to raise + TypeError (and this was the only way to know that the file had + ended) so users might have ``except TypeError:``. + + """ + pass + + +class FortranFormattingError(TypeError, OSError): + """Indicates that the file ended mid-record. + + Descends from TypeError for backward compatibility. + + """ + pass + + +class FortranFile: + """ + A file object for unformatted sequential files from Fortran code. + + Parameters + ---------- + filename : file or str + Open file object or filename. + mode : {'r', 'w'}, optional + Read-write mode, default is 'r'. + header_dtype : dtype, optional + Data type of the header. Size and endianness must match the input/output file. + + Notes + ----- + These files are broken up into records of unspecified types. The size of + each record is given at the start (although the size of this header is not + standard) and the data is written onto disk without any formatting. Fortran + compilers supporting the BACKSPACE statement will write a second copy of + the size to facilitate backwards seeking. + + This class only supports files written with both sizes for the record. + It also does not support the subrecords used in Intel and gfortran compilers + for records which are greater than 2GB with a 4-byte header. + + An example of an unformatted sequential file in Fortran would be written as:: + + OPEN(1, FILE=myfilename, FORM='unformatted') + + WRITE(1) myvariable + + Since this is a non-standard file format, whose contents depend on the + compiler and the endianness of the machine, caution is advised. Files from + gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work. + + Consider using Fortran direct-access files or files from the newer Stream + I/O, which can be easily read by `numpy.fromfile`. + + Examples + -------- + To create an unformatted sequential Fortran file: + + >>> from scipy.io import FortranFile + >>> import numpy as np + >>> f = FortranFile('test.unf', 'w') + >>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32)) + >>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T) + >>> f.close() + + To read this file: + + >>> f = FortranFile('test.unf', 'r') + >>> print(f.read_ints(np.int32)) + [1 2 3 4 5] + >>> print(f.read_reals(float).reshape((5,4), order="F")) + [[0. 0.05263158 0.10526316 0.15789474] + [0.21052632 0.26315789 0.31578947 0.36842105] + [0.42105263 0.47368421 0.52631579 0.57894737] + [0.63157895 0.68421053 0.73684211 0.78947368] + [0.84210526 0.89473684 0.94736842 1. ]] + >>> f.close() + + Or, in Fortran:: + + integer :: a(5), i + double precision :: b(5,4) + open(1, file='test.unf', form='unformatted') + read(1) a + read(1) b + close(1) + write(*,*) a + do i = 1, 5 + write(*,*) b(i,:) + end do + + """ + def __init__(self, filename, mode='r', header_dtype=np.uint32): + if header_dtype is None: + raise ValueError('Must specify dtype') + + header_dtype = np.dtype(header_dtype) + if header_dtype.kind != 'u': + warnings.warn("Given a dtype which is not unsigned.", stacklevel=2) + + if mode not in 'rw' or len(mode) != 1: + raise ValueError('mode must be either r or w') + + if hasattr(filename, 'seek'): + self._fp = filename + else: + self._fp = open(filename, '%sb' % mode) + + self._header_dtype = header_dtype + + def _read_size(self, eof_ok=False): + n = self._header_dtype.itemsize + b = self._fp.read(n) + if (not b) and eof_ok: + raise FortranEOFError("End of file occurred at end of record") + elif len(b) < n: + raise FortranFormattingError( + "End of file in the middle of the record size") + return int(np.frombuffer(b, dtype=self._header_dtype, count=1)[0]) + + def write_record(self, *items): + """ + Write a record (including sizes) to the file. + + Parameters + ---------- + *items : array_like + The data arrays to write. + + Notes + ----- + Writes data items to a file:: + + write_record(a.T, b.T, c.T, ...) + + write(1) a, b, c, ... + + Note that data in multidimensional arrays is written in + row-major order --- to make them read correctly by Fortran + programs, you need to transpose the arrays yourself when + writing them. + + """ + items = tuple(np.asarray(item) for item in items) + total_size = sum(item.nbytes for item in items) + + nb = np.array([total_size], dtype=self._header_dtype) + + nb.tofile(self._fp) + for item in items: + item.tofile(self._fp) + nb.tofile(self._fp) + + def read_record(self, *dtypes, **kwargs): + """ + Reads a record of a given type from the file. + + Parameters + ---------- + *dtypes : dtypes, optional + Data type(s) specifying the size and endianness of the data. + + Returns + ------- + data : ndarray + A 1-D array object. + + Raises + ------ + FortranEOFError + To signal that no further records are available + FortranFormattingError + To signal that the end of the file was encountered + part-way through a record + + Notes + ----- + If the record contains a multidimensional array, you can specify + the size in the dtype. For example:: + + INTEGER var(5,4) + + can be read with:: + + read_record('(4,5)i4').T + + Note that this function does **not** assume the file data is in Fortran + column major order, so you need to (i) swap the order of dimensions + when reading and (ii) transpose the resulting array. + + Alternatively, you can read the data as a 1-D array and handle the + ordering yourself. For example:: + + read_record('i4').reshape(5, 4, order='F') + + For records that contain several variables or mixed types (as opposed + to single scalar or array types), give them as separate arguments:: + + double precision :: a + integer :: b + write(1) a, b + + record = f.read_record('u1', + 2: '>i2', + 3: '>i4', + 4: '>f4', + 5: '>f8', + 6: '>c8', + 7: '|O', + 8: '|O', + 9: '>c16', + 10: '|O', + 11: '|O', + 12: '>u2', + 13: '>u4', + 14: '>i8', + 15: '>u8'} + +# Define the different record types that can be found in an IDL save file +RECTYPE_DICT = {0: "START_MARKER", + 1: "COMMON_VARIABLE", + 2: "VARIABLE", + 3: "SYSTEM_VARIABLE", + 6: "END_MARKER", + 10: "TIMESTAMP", + 12: "COMPILED", + 13: "IDENTIFICATION", + 14: "VERSION", + 15: "HEAP_HEADER", + 16: "HEAP_DATA", + 17: "PROMOTE64", + 19: "NOTICE", + 20: "DESCRIPTION"} + +# Define a dictionary to contain structure definitions +STRUCT_DICT = {} + + +def _align_32(f): + '''Align to the next 32-bit position in a file''' + + pos = f.tell() + if pos % 4 != 0: + f.seek(pos + 4 - pos % 4) + return + + +def _skip_bytes(f, n): + '''Skip `n` bytes''' + f.read(n) + return + + +def _read_bytes(f, n): + '''Read the next `n` bytes''' + return f.read(n) + + +def _read_byte(f): + '''Read a single byte''' + return np.uint8(struct.unpack('>B', f.read(4)[:1])[0]) + + +def _read_long(f): + '''Read a signed 32-bit integer''' + return np.int32(struct.unpack('>l', f.read(4))[0]) + + +def _read_int16(f): + '''Read a signed 16-bit integer''' + return np.int16(struct.unpack('>h', f.read(4)[2:4])[0]) + + +def _read_int32(f): + '''Read a signed 32-bit integer''' + return np.int32(struct.unpack('>i', f.read(4))[0]) + + +def _read_int64(f): + '''Read a signed 64-bit integer''' + return np.int64(struct.unpack('>q', f.read(8))[0]) + + +def _read_uint16(f): + '''Read an unsigned 16-bit integer''' + return np.uint16(struct.unpack('>H', f.read(4)[2:4])[0]) + + +def _read_uint32(f): + '''Read an unsigned 32-bit integer''' + return np.uint32(struct.unpack('>I', f.read(4))[0]) + + +def _read_uint64(f): + '''Read an unsigned 64-bit integer''' + return np.uint64(struct.unpack('>Q', f.read(8))[0]) + + +def _read_float32(f): + '''Read a 32-bit float''' + return np.float32(struct.unpack('>f', f.read(4))[0]) + + +def _read_float64(f): + '''Read a 64-bit float''' + return np.float64(struct.unpack('>d', f.read(8))[0]) + + +class Pointer: + '''Class used to define pointers''' + + def __init__(self, index): + self.index = index + return + + +class ObjectPointer(Pointer): + '''Class used to define object pointers''' + pass + + +def _read_string(f): + '''Read a string''' + length = _read_long(f) + if length > 0: + chars = _read_bytes(f, length).decode('latin1') + _align_32(f) + else: + chars = '' + return chars + + +def _read_string_data(f): + '''Read a data string (length is specified twice)''' + length = _read_long(f) + if length > 0: + length = _read_long(f) + string_data = _read_bytes(f, length) + _align_32(f) + else: + string_data = '' + return string_data + + +def _read_data(f, dtype): + '''Read a variable with a specified data type''' + if dtype == 1: + if _read_int32(f) != 1: + raise Exception("Error occurred while reading byte variable") + return _read_byte(f) + elif dtype == 2: + return _read_int16(f) + elif dtype == 3: + return _read_int32(f) + elif dtype == 4: + return _read_float32(f) + elif dtype == 5: + return _read_float64(f) + elif dtype == 6: + real = _read_float32(f) + imag = _read_float32(f) + return np.complex64(real + imag * 1j) + elif dtype == 7: + return _read_string_data(f) + elif dtype == 8: + raise Exception("Should not be here - please report this") + elif dtype == 9: + real = _read_float64(f) + imag = _read_float64(f) + return np.complex128(real + imag * 1j) + elif dtype == 10: + return Pointer(_read_int32(f)) + elif dtype == 11: + return ObjectPointer(_read_int32(f)) + elif dtype == 12: + return _read_uint16(f) + elif dtype == 13: + return _read_uint32(f) + elif dtype == 14: + return _read_int64(f) + elif dtype == 15: + return _read_uint64(f) + else: + raise Exception("Unknown IDL type: %i - please report this" % dtype) + + +def _read_structure(f, array_desc, struct_desc): + ''' + Read a structure, with the array and structure descriptors given as + `array_desc` and `structure_desc` respectively. + ''' + + nrows = array_desc['nelements'] + columns = struct_desc['tagtable'] + + dtype = [] + for col in columns: + if col['structure'] or col['array']: + dtype.append(((col['name'].lower(), col['name']), np.object_)) + else: + if col['typecode'] in DTYPE_DICT: + dtype.append(((col['name'].lower(), col['name']), + DTYPE_DICT[col['typecode']])) + else: + raise Exception("Variable type %i not implemented" % + col['typecode']) + + structure = np.rec.recarray((nrows, ), dtype=dtype) + + for i in range(nrows): + for col in columns: + dtype = col['typecode'] + if col['structure']: + structure[col['name']][i] = _read_structure(f, + struct_desc['arrtable'][col['name']], + struct_desc['structtable'][col['name']]) + elif col['array']: + structure[col['name']][i] = _read_array(f, dtype, + struct_desc['arrtable'][col['name']]) + else: + structure[col['name']][i] = _read_data(f, dtype) + + # Reshape structure if needed + if array_desc['ndims'] > 1: + dims = array_desc['dims'][:int(array_desc['ndims'])] + dims.reverse() + structure = structure.reshape(dims) + + return structure + + +def _read_array(f, typecode, array_desc): + ''' + Read an array of type `typecode`, with the array descriptor given as + `array_desc`. + ''' + + if typecode in [1, 3, 4, 5, 6, 9, 13, 14, 15]: + + if typecode == 1: + nbytes = _read_int32(f) + if nbytes != array_desc['nbytes']: + warnings.warn("Not able to verify number of bytes from header", + stacklevel=3) + + # Read bytes as numpy array + array = np.frombuffer(f.read(array_desc['nbytes']), + dtype=DTYPE_DICT[typecode]) + + elif typecode in [2, 12]: + + # These are 2 byte types, need to skip every two as they are not packed + + array = np.frombuffer(f.read(array_desc['nbytes']*2), + dtype=DTYPE_DICT[typecode])[1::2] + + else: + + # Read bytes into list + array = [] + for i in range(array_desc['nelements']): + dtype = typecode + data = _read_data(f, dtype) + array.append(data) + + array = np.array(array, dtype=np.object_) + + # Reshape array if needed + if array_desc['ndims'] > 1: + dims = array_desc['dims'][:int(array_desc['ndims'])] + dims.reverse() + array = array.reshape(dims) + + # Go to next alignment position + _align_32(f) + + return array + + +def _read_record(f): + '''Function to read in a full record''' + + record = {'rectype': _read_long(f)} + + nextrec = _read_uint32(f) + nextrec += _read_uint32(f).astype(np.int64) * 2**32 + + _skip_bytes(f, 4) + + if record['rectype'] not in RECTYPE_DICT: + raise Exception("Unknown RECTYPE: %i" % record['rectype']) + + record['rectype'] = RECTYPE_DICT[record['rectype']] + + if record['rectype'] in ["VARIABLE", "HEAP_DATA"]: + + if record['rectype'] == "VARIABLE": + record['varname'] = _read_string(f) + else: + record['heap_index'] = _read_long(f) + _skip_bytes(f, 4) + + rectypedesc = _read_typedesc(f) + + if rectypedesc['typecode'] == 0: + + if nextrec == f.tell(): + record['data'] = None # Indicates NULL value + else: + raise ValueError("Unexpected type code: 0") + + else: + + varstart = _read_long(f) + if varstart != 7: + raise Exception("VARSTART is not 7") + + if rectypedesc['structure']: + record['data'] = _read_structure(f, rectypedesc['array_desc'], + rectypedesc['struct_desc']) + elif rectypedesc['array']: + record['data'] = _read_array(f, rectypedesc['typecode'], + rectypedesc['array_desc']) + else: + dtype = rectypedesc['typecode'] + record['data'] = _read_data(f, dtype) + + elif record['rectype'] == "TIMESTAMP": + + _skip_bytes(f, 4*256) + record['date'] = _read_string(f) + record['user'] = _read_string(f) + record['host'] = _read_string(f) + + elif record['rectype'] == "VERSION": + + record['format'] = _read_long(f) + record['arch'] = _read_string(f) + record['os'] = _read_string(f) + record['release'] = _read_string(f) + + elif record['rectype'] == "IDENTIFICATON": + + record['author'] = _read_string(f) + record['title'] = _read_string(f) + record['idcode'] = _read_string(f) + + elif record['rectype'] == "NOTICE": + + record['notice'] = _read_string(f) + + elif record['rectype'] == "DESCRIPTION": + + record['description'] = _read_string_data(f) + + elif record['rectype'] == "HEAP_HEADER": + + record['nvalues'] = _read_long(f) + record['indices'] = [_read_long(f) for _ in range(record['nvalues'])] + + elif record['rectype'] == "COMMONBLOCK": + + record['nvars'] = _read_long(f) + record['name'] = _read_string(f) + record['varnames'] = [_read_string(f) for _ in range(record['nvars'])] + + elif record['rectype'] == "END_MARKER": + + record['end'] = True + + elif record['rectype'] == "UNKNOWN": + + warnings.warn("Skipping UNKNOWN record", stacklevel=3) + + elif record['rectype'] == "SYSTEM_VARIABLE": + + warnings.warn("Skipping SYSTEM_VARIABLE record", stacklevel=3) + + else: + + raise Exception(f"record['rectype']={record['rectype']} not implemented") + + f.seek(nextrec) + + return record + + +def _read_typedesc(f): + '''Function to read in a type descriptor''' + + typedesc = {'typecode': _read_long(f), 'varflags': _read_long(f)} + + if typedesc['varflags'] & 2 == 2: + raise Exception("System variables not implemented") + + typedesc['array'] = typedesc['varflags'] & 4 == 4 + typedesc['structure'] = typedesc['varflags'] & 32 == 32 + + if typedesc['structure']: + typedesc['array_desc'] = _read_arraydesc(f) + typedesc['struct_desc'] = _read_structdesc(f) + elif typedesc['array']: + typedesc['array_desc'] = _read_arraydesc(f) + + return typedesc + + +def _read_arraydesc(f): + '''Function to read in an array descriptor''' + + arraydesc = {'arrstart': _read_long(f)} + + if arraydesc['arrstart'] == 8: + + _skip_bytes(f, 4) + + arraydesc['nbytes'] = _read_long(f) + arraydesc['nelements'] = _read_long(f) + arraydesc['ndims'] = _read_long(f) + + _skip_bytes(f, 8) + + arraydesc['nmax'] = _read_long(f) + + arraydesc['dims'] = [_read_long(f) for _ in range(arraydesc['nmax'])] + + elif arraydesc['arrstart'] == 18: + + warnings.warn("Using experimental 64-bit array read", stacklevel=3) + + _skip_bytes(f, 8) + + arraydesc['nbytes'] = _read_uint64(f) + arraydesc['nelements'] = _read_uint64(f) + arraydesc['ndims'] = _read_long(f) + + _skip_bytes(f, 8) + + arraydesc['nmax'] = 8 + + arraydesc['dims'] = [] + for d in range(arraydesc['nmax']): + v = _read_long(f) + if v != 0: + raise Exception("Expected a zero in ARRAY_DESC") + arraydesc['dims'].append(_read_long(f)) + + else: + + raise Exception("Unknown ARRSTART: %i" % arraydesc['arrstart']) + + return arraydesc + + +def _read_structdesc(f): + '''Function to read in a structure descriptor''' + + structdesc = {} + + structstart = _read_long(f) + if structstart != 9: + raise Exception("STRUCTSTART should be 9") + + structdesc['name'] = _read_string(f) + predef = _read_long(f) + structdesc['ntags'] = _read_long(f) + structdesc['nbytes'] = _read_long(f) + + structdesc['predef'] = predef & 1 + structdesc['inherits'] = predef & 2 + structdesc['is_super'] = predef & 4 + + if not structdesc['predef']: + + structdesc['tagtable'] = [_read_tagdesc(f) + for _ in range(structdesc['ntags'])] + + for tag in structdesc['tagtable']: + tag['name'] = _read_string(f) + + structdesc['arrtable'] = {tag['name']: _read_arraydesc(f) + for tag in structdesc['tagtable'] + if tag['array']} + + structdesc['structtable'] = {tag['name']: _read_structdesc(f) + for tag in structdesc['tagtable'] + if tag['structure']} + + if structdesc['inherits'] or structdesc['is_super']: + structdesc['classname'] = _read_string(f) + structdesc['nsupclasses'] = _read_long(f) + structdesc['supclassnames'] = [ + _read_string(f) for _ in range(structdesc['nsupclasses'])] + structdesc['supclasstable'] = [ + _read_structdesc(f) for _ in range(structdesc['nsupclasses'])] + + STRUCT_DICT[structdesc['name']] = structdesc + + else: + + if structdesc['name'] not in STRUCT_DICT: + raise Exception("PREDEF=1 but can't find definition") + + structdesc = STRUCT_DICT[structdesc['name']] + + return structdesc + + +def _read_tagdesc(f): + '''Function to read in a tag descriptor''' + + tagdesc = {'offset': _read_long(f)} + + if tagdesc['offset'] == -1: + tagdesc['offset'] = _read_uint64(f) + + tagdesc['typecode'] = _read_long(f) + tagflags = _read_long(f) + + tagdesc['array'] = tagflags & 4 == 4 + tagdesc['structure'] = tagflags & 32 == 32 + tagdesc['scalar'] = tagdesc['typecode'] in DTYPE_DICT + # Assume '10'x is scalar + + return tagdesc + + +def _replace_heap(variable, heap): + + if isinstance(variable, Pointer): + + while isinstance(variable, Pointer): + + if variable.index == 0: + variable = None + else: + if variable.index in heap: + variable = heap[variable.index] + else: + warnings.warn("Variable referenced by pointer not found " + "in heap: variable will be set to None", + stacklevel=3) + variable = None + + replace, new = _replace_heap(variable, heap) + + if replace: + variable = new + + return True, variable + + elif isinstance(variable, np.rec.recarray): + + # Loop over records + for ir, record in enumerate(variable): + + replace, new = _replace_heap(record, heap) + + if replace: + variable[ir] = new + + return False, variable + + elif isinstance(variable, np.record): + + # Loop over values + for iv, value in enumerate(variable): + + replace, new = _replace_heap(value, heap) + + if replace: + variable[iv] = new + + return False, variable + + elif isinstance(variable, np.ndarray): + + # Loop over values if type is np.object_ + if variable.dtype.type is np.object_: + + for iv in range(variable.size): + + replace, new = _replace_heap(variable.item(iv), heap) + + if replace: + variable.reshape(-1)[iv] = new + + return False, variable + + else: + + return False, variable + + +class AttrDict(dict): + ''' + A case-insensitive dictionary with access via item, attribute, and call + notations: + + >>> from scipy.io._idl import AttrDict + >>> d = AttrDict() + >>> d['Variable'] = 123 + >>> d['Variable'] + 123 + >>> d.Variable + 123 + >>> d.variable + 123 + >>> d('VARIABLE') + 123 + >>> d['missing'] + Traceback (most recent error last): + ... + KeyError: 'missing' + >>> d.missing + Traceback (most recent error last): + ... + AttributeError: 'AttrDict' object has no attribute 'missing' + ''' + + def __init__(self, init={}): + dict.__init__(self, init) + + def __getitem__(self, name): + return super().__getitem__(name.lower()) + + def __setitem__(self, key, value): + return super().__setitem__(key.lower(), value) + + def __getattr__(self, name): + try: + return self.__getitem__(name) + except KeyError: + raise AttributeError( + f"'{type(self)}' object has no attribute '{name}'") from None + + __setattr__ = __setitem__ + __call__ = __getitem__ + + +def readsav(file_name, idict=None, python_dict=False, + uncompressed_file_name=None, verbose=False): + """ + Read an IDL .sav file. + + Parameters + ---------- + file_name : str + Name of the IDL save file. + idict : dict, optional + Dictionary in which to insert .sav file variables. + python_dict : bool, optional + By default, the object return is not a Python dictionary, but a + case-insensitive dictionary with item, attribute, and call access + to variables. To get a standard Python dictionary, set this option + to True. + uncompressed_file_name : str, optional + This option only has an effect for .sav files written with the + /compress option. If a file name is specified, compressed .sav + files are uncompressed to this file. Otherwise, readsav will use + the `tempfile` module to determine a temporary filename + automatically, and will remove the temporary file upon successfully + reading it in. + verbose : bool, optional + Whether to print out information about the save file, including + the records read, and available variables. + + Returns + ------- + idl_dict : AttrDict or dict + If `python_dict` is set to False (default), this function returns a + case-insensitive dictionary with item, attribute, and call access + to variables. If `python_dict` is set to True, this function + returns a Python dictionary with all variable names in lowercase. + If `idict` was specified, then variables are written to the + dictionary specified, and the updated dictionary is returned. + + Examples + -------- + >>> from os.path import dirname, join as pjoin + >>> import scipy.io as sio + >>> from scipy.io import readsav + + Get the filename for an example .sav file from the tests/data directory. + + >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data') + >>> sav_fname = pjoin(data_dir, 'array_float32_1d.sav') + + Load the .sav file contents. + + >>> sav_data = readsav(sav_fname) + + Get keys of the .sav file contents. + + >>> print(sav_data.keys()) + dict_keys(['array1d']) + + Access a content with a key. + + >>> print(sav_data['array1d']) + [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. + 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. + 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. + 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. + 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. + 0. 0. 0.] + + """ + + # Initialize record and variable holders + records = [] + if python_dict or idict: + variables = {} + else: + variables = AttrDict() + + # Open the IDL file + f = open(file_name, 'rb') + + # Read the signature, which should be 'SR' + signature = _read_bytes(f, 2) + if signature != b'SR': + raise Exception("Invalid SIGNATURE: %s" % signature) + + # Next, the record format, which is '\x00\x04' for normal .sav + # files, and '\x00\x06' for compressed .sav files. + recfmt = _read_bytes(f, 2) + + if recfmt == b'\x00\x04': + pass + + elif recfmt == b'\x00\x06': + + if verbose: + print("IDL Save file is compressed") + + if uncompressed_file_name: + fout = open(uncompressed_file_name, 'w+b') + else: + fout = tempfile.NamedTemporaryFile(suffix='.sav') + + if verbose: + print(" -> expanding to %s" % fout.name) + + # Write header + fout.write(b'SR\x00\x04') + + # Cycle through records + while True: + + # Read record type + rectype = _read_long(f) + fout.write(struct.pack('>l', int(rectype))) + + # Read position of next record and return as int + nextrec = _read_uint32(f) + nextrec += _read_uint32(f).astype(np.int64) * 2**32 + + # Read the unknown 4 bytes + unknown = f.read(4) + + # Check if the end of the file has been reached + if RECTYPE_DICT[rectype] == 'END_MARKER': + modval = np.int64(2**32) + fout.write(struct.pack('>I', int(nextrec) % modval)) + fout.write( + struct.pack('>I', int((nextrec - (nextrec % modval)) / modval)) + ) + fout.write(unknown) + break + + # Find current position + pos = f.tell() + + # Decompress record + rec_string = zlib.decompress(f.read(nextrec-pos)) + + # Find new position of next record + nextrec = fout.tell() + len(rec_string) + 12 + + # Write out record + fout.write(struct.pack('>I', int(nextrec % 2**32))) + fout.write(struct.pack('>I', int((nextrec - (nextrec % 2**32)) / 2**32))) + fout.write(unknown) + fout.write(rec_string) + + # Close the original compressed file + f.close() + + # Set f to be the decompressed file, and skip the first four bytes + f = fout + f.seek(4) + + else: + raise Exception("Invalid RECFMT: %s" % recfmt) + + # Loop through records, and add them to the list + while True: + r = _read_record(f) + records.append(r) + if 'end' in r: + if r['end']: + break + + # Close the file + f.close() + + # Find heap data variables + heap = {} + for r in records: + if r['rectype'] == "HEAP_DATA": + heap[r['heap_index']] = r['data'] + + # Find all variables + for r in records: + if r['rectype'] == "VARIABLE": + replace, new = _replace_heap(r['data'], heap) + if replace: + r['data'] = new + variables[r['varname'].lower()] = r['data'] + + if verbose: + + # Print out timestamp info about the file + for record in records: + if record['rectype'] == "TIMESTAMP": + print("-"*50) + print("Date: %s" % record['date']) + print("User: %s" % record['user']) + print("Host: %s" % record['host']) + break + + # Print out version info about the file + for record in records: + if record['rectype'] == "VERSION": + print("-"*50) + print("Format: %s" % record['format']) + print("Architecture: %s" % record['arch']) + print("Operating System: %s" % record['os']) + print("IDL Version: %s" % record['release']) + break + + # Print out identification info about the file + for record in records: + if record['rectype'] == "IDENTIFICATON": + print("-"*50) + print("Author: %s" % record['author']) + print("Title: %s" % record['title']) + print("ID Code: %s" % record['idcode']) + break + + # Print out descriptions saved with the file + for record in records: + if record['rectype'] == "DESCRIPTION": + print("-"*50) + print("Description: %s" % record['description']) + break + + print("-"*50) + print("Successfully read %i records of which:" % + (len(records))) + + # Create convenience list of record types + rectypes = [r['rectype'] for r in records] + + for rt in set(rectypes): + if rt != 'END_MARKER': + print(" - %i are of type %s" % (rectypes.count(rt), rt)) + print("-"*50) + + if 'VARIABLE' in rectypes: + print("Available variables:") + for var in variables: + print(f" - {var} [{type(variables[var])}]") + print("-"*50) + + if idict: + for var in variables: + idict[var] = variables[var] + return idict + else: + return variables diff --git a/venv/lib/python3.10/site-packages/scipy/io/_mmio.py b/venv/lib/python3.10/site-packages/scipy/io/_mmio.py new file mode 100644 index 0000000000000000000000000000000000000000..d39e03551b14cd22aa850846890fc313a8be7795 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/_mmio.py @@ -0,0 +1,961 @@ +""" + Matrix Market I/O in Python. + See http://math.nist.gov/MatrixMarket/formats.html + for information about the Matrix Market format. +""" +# +# Author: Pearu Peterson +# Created: October, 2004 +# +# References: +# http://math.nist.gov/MatrixMarket/ +# +import os + +import numpy as np +from numpy import (asarray, real, imag, conj, zeros, ndarray, concatenate, + ones, can_cast) + +from scipy.sparse import coo_matrix, issparse + +__all__ = ['mminfo', 'mmread', 'mmwrite', 'MMFile'] + + +# ----------------------------------------------------------------------------- +def asstr(s): + if isinstance(s, bytes): + return s.decode('latin1') + return str(s) + + +def mminfo(source): + """ + Return size and storage parameters from Matrix Market file-like 'source'. + + Parameters + ---------- + source : str or file-like + Matrix Market filename (extension .mtx) or open file-like object + + Returns + ------- + rows : int + Number of matrix rows. + cols : int + Number of matrix columns. + entries : int + Number of non-zero entries of a sparse matrix + or rows*cols for a dense matrix. + format : str + Either 'coordinate' or 'array'. + field : str + Either 'real', 'complex', 'pattern', or 'integer'. + symmetry : str + Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'. + + Examples + -------- + >>> from io import StringIO + >>> from scipy.io import mminfo + + >>> text = '''%%MatrixMarket matrix coordinate real general + ... 5 5 7 + ... 2 3 1.0 + ... 3 4 2.0 + ... 3 5 3.0 + ... 4 1 4.0 + ... 4 2 5.0 + ... 4 3 6.0 + ... 4 4 7.0 + ... ''' + + + ``mminfo(source)`` returns the number of rows, number of columns, + format, field type and symmetry attribute of the source file. + + >>> mminfo(StringIO(text)) + (5, 5, 7, 'coordinate', 'real', 'general') + """ + return MMFile.info(source) + +# ----------------------------------------------------------------------------- + + +def mmread(source): + """ + Reads the contents of a Matrix Market file-like 'source' into a matrix. + + Parameters + ---------- + source : str or file-like + Matrix Market filename (extensions .mtx, .mtz.gz) + or open file-like object. + + Returns + ------- + a : ndarray or coo_matrix + Dense or sparse matrix depending on the matrix format in the + Matrix Market file. + + Examples + -------- + >>> from io import StringIO + >>> from scipy.io import mmread + + >>> text = '''%%MatrixMarket matrix coordinate real general + ... 5 5 7 + ... 2 3 1.0 + ... 3 4 2.0 + ... 3 5 3.0 + ... 4 1 4.0 + ... 4 2 5.0 + ... 4 3 6.0 + ... 4 4 7.0 + ... ''' + + ``mmread(source)`` returns the data as sparse matrix in COO format. + + >>> m = mmread(StringIO(text)) + >>> m + <5x5 sparse matrix of type '' + with 7 stored elements in COOrdinate format> + >>> m.A + array([[0., 0., 0., 0., 0.], + [0., 0., 1., 0., 0.], + [0., 0., 0., 2., 3.], + [4., 5., 6., 7., 0.], + [0., 0., 0., 0., 0.]]) + """ + return MMFile().read(source) + +# ----------------------------------------------------------------------------- + + +def mmwrite(target, a, comment='', field=None, precision=None, symmetry=None): + r""" + Writes the sparse or dense array `a` to Matrix Market file-like `target`. + + Parameters + ---------- + target : str or file-like + Matrix Market filename (extension .mtx) or open file-like object. + a : array like + Sparse or dense 2-D array. + comment : str, optional + Comments to be prepended to the Matrix Market file. + field : None or str, optional + Either 'real', 'complex', 'pattern', or 'integer'. + precision : None or int, optional + Number of digits to display for real or complex values. + symmetry : None or str, optional + Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'. + If symmetry is None the symmetry type of 'a' is determined by its + values. + + Returns + ------- + None + + Examples + -------- + >>> from io import BytesIO + >>> import numpy as np + >>> from scipy.sparse import coo_matrix + >>> from scipy.io import mmwrite + + Write a small NumPy array to a matrix market file. The file will be + written in the ``'array'`` format. + + >>> a = np.array([[1.0, 0, 0, 0], [0, 2.5, 0, 6.25]]) + >>> target = BytesIO() + >>> mmwrite(target, a) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix array real general + % + 2 4 + 1.0000000000000000e+00 + 0.0000000000000000e+00 + 0.0000000000000000e+00 + 2.5000000000000000e+00 + 0.0000000000000000e+00 + 0.0000000000000000e+00 + 0.0000000000000000e+00 + 6.2500000000000000e+00 + + Add a comment to the output file, and set the precision to 3. + + >>> target = BytesIO() + >>> mmwrite(target, a, comment='\n Some test data.\n', precision=3) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix array real general + % + % Some test data. + % + 2 4 + 1.000e+00 + 0.000e+00 + 0.000e+00 + 2.500e+00 + 0.000e+00 + 0.000e+00 + 0.000e+00 + 6.250e+00 + + Convert to a sparse matrix before calling ``mmwrite``. This will + result in the output format being ``'coordinate'`` rather than + ``'array'``. + + >>> target = BytesIO() + >>> mmwrite(target, coo_matrix(a), precision=3) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix coordinate real general + % + 2 4 3 + 1 1 1.00e+00 + 2 2 2.50e+00 + 2 4 6.25e+00 + + Write a complex Hermitian array to a matrix market file. Note that + only six values are actually written to the file; the other values + are implied by the symmetry. + + >>> z = np.array([[3, 1+2j, 4-3j], [1-2j, 1, -5j], [4+3j, 5j, 2.5]]) + >>> z + array([[ 3. +0.j, 1. +2.j, 4. -3.j], + [ 1. -2.j, 1. +0.j, -0. -5.j], + [ 4. +3.j, 0. +5.j, 2.5+0.j]]) + + >>> target = BytesIO() + >>> mmwrite(target, z, precision=2) + >>> print(target.getvalue().decode('latin1')) + %%MatrixMarket matrix array complex hermitian + % + 3 3 + 3.00e+00 0.00e+00 + 1.00e+00 -2.00e+00 + 4.00e+00 3.00e+00 + 1.00e+00 0.00e+00 + 0.00e+00 5.00e+00 + 2.50e+00 0.00e+00 + + """ + MMFile().write(target, a, comment, field, precision, symmetry) + + +############################################################################### +class MMFile: + __slots__ = ('_rows', + '_cols', + '_entries', + '_format', + '_field', + '_symmetry') + + @property + def rows(self): + return self._rows + + @property + def cols(self): + return self._cols + + @property + def entries(self): + return self._entries + + @property + def format(self): + return self._format + + @property + def field(self): + return self._field + + @property + def symmetry(self): + return self._symmetry + + @property + def has_symmetry(self): + return self._symmetry in (self.SYMMETRY_SYMMETRIC, + self.SYMMETRY_SKEW_SYMMETRIC, + self.SYMMETRY_HERMITIAN) + + # format values + FORMAT_COORDINATE = 'coordinate' + FORMAT_ARRAY = 'array' + FORMAT_VALUES = (FORMAT_COORDINATE, FORMAT_ARRAY) + + @classmethod + def _validate_format(self, format): + if format not in self.FORMAT_VALUES: + msg = f'unknown format type {format}, must be one of {self.FORMAT_VALUES}' + raise ValueError(msg) + + # field values + FIELD_INTEGER = 'integer' + FIELD_UNSIGNED = 'unsigned-integer' + FIELD_REAL = 'real' + FIELD_COMPLEX = 'complex' + FIELD_PATTERN = 'pattern' + FIELD_VALUES = (FIELD_INTEGER, FIELD_UNSIGNED, FIELD_REAL, FIELD_COMPLEX, + FIELD_PATTERN) + + @classmethod + def _validate_field(self, field): + if field not in self.FIELD_VALUES: + msg = f'unknown field type {field}, must be one of {self.FIELD_VALUES}' + raise ValueError(msg) + + # symmetry values + SYMMETRY_GENERAL = 'general' + SYMMETRY_SYMMETRIC = 'symmetric' + SYMMETRY_SKEW_SYMMETRIC = 'skew-symmetric' + SYMMETRY_HERMITIAN = 'hermitian' + SYMMETRY_VALUES = (SYMMETRY_GENERAL, SYMMETRY_SYMMETRIC, + SYMMETRY_SKEW_SYMMETRIC, SYMMETRY_HERMITIAN) + + @classmethod + def _validate_symmetry(self, symmetry): + if symmetry not in self.SYMMETRY_VALUES: + raise ValueError(f'unknown symmetry type {symmetry}, ' + f'must be one of {self.SYMMETRY_VALUES}') + + DTYPES_BY_FIELD = {FIELD_INTEGER: 'intp', + FIELD_UNSIGNED: 'uint64', + FIELD_REAL: 'd', + FIELD_COMPLEX: 'D', + FIELD_PATTERN: 'd'} + + # ------------------------------------------------------------------------- + @staticmethod + def reader(): + pass + + # ------------------------------------------------------------------------- + @staticmethod + def writer(): + pass + + # ------------------------------------------------------------------------- + @classmethod + def info(self, source): + """ + Return size, storage parameters from Matrix Market file-like 'source'. + + Parameters + ---------- + source : str or file-like + Matrix Market filename (extension .mtx) or open file-like object + + Returns + ------- + rows : int + Number of matrix rows. + cols : int + Number of matrix columns. + entries : int + Number of non-zero entries of a sparse matrix + or rows*cols for a dense matrix. + format : str + Either 'coordinate' or 'array'. + field : str + Either 'real', 'complex', 'pattern', or 'integer'. + symmetry : str + Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'. + """ + + stream, close_it = self._open(source) + + try: + + # read and validate header line + line = stream.readline() + mmid, matrix, format, field, symmetry = \ + (asstr(part.strip()) for part in line.split()) + if not mmid.startswith('%%MatrixMarket'): + raise ValueError('source is not in Matrix Market format') + if not matrix.lower() == 'matrix': + raise ValueError("Problem reading file header: " + line) + + # http://math.nist.gov/MatrixMarket/formats.html + if format.lower() == 'array': + format = self.FORMAT_ARRAY + elif format.lower() == 'coordinate': + format = self.FORMAT_COORDINATE + + # skip comments + # line.startswith('%') + while line: + if line.lstrip() and line.lstrip()[0] in ['%', 37]: + line = stream.readline() + else: + break + + # skip empty lines + while not line.strip(): + line = stream.readline() + + split_line = line.split() + if format == self.FORMAT_ARRAY: + if not len(split_line) == 2: + raise ValueError("Header line not of length 2: " + + line.decode('ascii')) + rows, cols = map(int, split_line) + entries = rows * cols + else: + if not len(split_line) == 3: + raise ValueError("Header line not of length 3: " + + line.decode('ascii')) + rows, cols, entries = map(int, split_line) + + return (rows, cols, entries, format, field.lower(), + symmetry.lower()) + + finally: + if close_it: + stream.close() + + # ------------------------------------------------------------------------- + @staticmethod + def _open(filespec, mode='rb'): + """ Return an open file stream for reading based on source. + + If source is a file name, open it (after trying to find it with mtx and + gzipped mtx extensions). Otherwise, just return source. + + Parameters + ---------- + filespec : str or file-like + String giving file name or file-like object + mode : str, optional + Mode with which to open file, if `filespec` is a file name. + + Returns + ------- + fobj : file-like + Open file-like object. + close_it : bool + True if the calling function should close this file when done, + false otherwise. + """ + # If 'filespec' is path-like (str, pathlib.Path, os.DirEntry, other class + # implementing a '__fspath__' method), try to convert it to str. If this + # fails by throwing a 'TypeError', assume it's an open file handle and + # return it as-is. + try: + filespec = os.fspath(filespec) + except TypeError: + return filespec, False + + # 'filespec' is definitely a str now + + # open for reading + if mode[0] == 'r': + + # determine filename plus extension + if not os.path.isfile(filespec): + if os.path.isfile(filespec+'.mtx'): + filespec = filespec + '.mtx' + elif os.path.isfile(filespec+'.mtx.gz'): + filespec = filespec + '.mtx.gz' + elif os.path.isfile(filespec+'.mtx.bz2'): + filespec = filespec + '.mtx.bz2' + # open filename + if filespec.endswith('.gz'): + import gzip + stream = gzip.open(filespec, mode) + elif filespec.endswith('.bz2'): + import bz2 + stream = bz2.BZ2File(filespec, 'rb') + else: + stream = open(filespec, mode) + + # open for writing + else: + if filespec[-4:] != '.mtx': + filespec = filespec + '.mtx' + stream = open(filespec, mode) + + return stream, True + + # ------------------------------------------------------------------------- + @staticmethod + def _get_symmetry(a): + m, n = a.shape + if m != n: + return MMFile.SYMMETRY_GENERAL + issymm = True + isskew = True + isherm = a.dtype.char in 'FD' + + # sparse input + if issparse(a): + # check if number of nonzero entries of lower and upper triangle + # matrix are equal + a = a.tocoo() + (row, col) = a.nonzero() + if (row < col).sum() != (row > col).sum(): + return MMFile.SYMMETRY_GENERAL + + # define iterator over symmetric pair entries + a = a.todok() + + def symm_iterator(): + for ((i, j), aij) in a.items(): + if i > j: + aji = a[j, i] + yield (aij, aji, False) + elif i == j: + yield (aij, aij, True) + + # non-sparse input + else: + # define iterator over symmetric pair entries + def symm_iterator(): + for j in range(n): + for i in range(j, n): + aij, aji = a[i][j], a[j][i] + yield (aij, aji, i == j) + + # check for symmetry + # yields aij, aji, is_diagonal + for (aij, aji, is_diagonal) in symm_iterator(): + if isskew and is_diagonal and aij != 0: + isskew = False + else: + if issymm and aij != aji: + issymm = False + with np.errstate(over="ignore"): + # This can give a warning for uint dtypes, so silence that + if isskew and aij != -aji: + isskew = False + if isherm and aij != conj(aji): + isherm = False + if not (issymm or isskew or isherm): + break + + # return symmetry value + if issymm: + return MMFile.SYMMETRY_SYMMETRIC + if isskew: + return MMFile.SYMMETRY_SKEW_SYMMETRIC + if isherm: + return MMFile.SYMMETRY_HERMITIAN + return MMFile.SYMMETRY_GENERAL + + # ------------------------------------------------------------------------- + @staticmethod + def _field_template(field, precision): + return {MMFile.FIELD_REAL: '%%.%ie\n' % precision, + MMFile.FIELD_INTEGER: '%i\n', + MMFile.FIELD_UNSIGNED: '%u\n', + MMFile.FIELD_COMPLEX: '%%.%ie %%.%ie\n' % + (precision, precision) + }.get(field, None) + + # ------------------------------------------------------------------------- + def __init__(self, **kwargs): + self._init_attrs(**kwargs) + + # ------------------------------------------------------------------------- + def read(self, source): + """ + Reads the contents of a Matrix Market file-like 'source' into a matrix. + + Parameters + ---------- + source : str or file-like + Matrix Market filename (extensions .mtx, .mtz.gz) + or open file object. + + Returns + ------- + a : ndarray or coo_matrix + Dense or sparse matrix depending on the matrix format in the + Matrix Market file. + """ + stream, close_it = self._open(source) + + try: + self._parse_header(stream) + return self._parse_body(stream) + + finally: + if close_it: + stream.close() + + # ------------------------------------------------------------------------- + def write(self, target, a, comment='', field=None, precision=None, + symmetry=None): + """ + Writes sparse or dense array `a` to Matrix Market file-like `target`. + + Parameters + ---------- + target : str or file-like + Matrix Market filename (extension .mtx) or open file-like object. + a : array like + Sparse or dense 2-D array. + comment : str, optional + Comments to be prepended to the Matrix Market file. + field : None or str, optional + Either 'real', 'complex', 'pattern', or 'integer'. + precision : None or int, optional + Number of digits to display for real or complex values. + symmetry : None or str, optional + Either 'general', 'symmetric', 'skew-symmetric', or 'hermitian'. + If symmetry is None the symmetry type of 'a' is determined by its + values. + """ + + stream, close_it = self._open(target, 'wb') + + try: + self._write(stream, a, comment, field, precision, symmetry) + + finally: + if close_it: + stream.close() + else: + stream.flush() + + # ------------------------------------------------------------------------- + def _init_attrs(self, **kwargs): + """ + Initialize each attributes with the corresponding keyword arg value + or a default of None + """ + + attrs = self.__class__.__slots__ + public_attrs = [attr[1:] for attr in attrs] + invalid_keys = set(kwargs.keys()) - set(public_attrs) + + if invalid_keys: + raise ValueError('''found {} invalid keyword arguments, please only + use {}'''.format(tuple(invalid_keys), + public_attrs)) + + for attr in attrs: + setattr(self, attr, kwargs.get(attr[1:], None)) + + # ------------------------------------------------------------------------- + def _parse_header(self, stream): + rows, cols, entries, format, field, symmetry = \ + self.__class__.info(stream) + self._init_attrs(rows=rows, cols=cols, entries=entries, format=format, + field=field, symmetry=symmetry) + + # ------------------------------------------------------------------------- + def _parse_body(self, stream): + rows, cols, entries, format, field, symm = (self.rows, self.cols, + self.entries, self.format, + self.field, self.symmetry) + + dtype = self.DTYPES_BY_FIELD.get(field, None) + + has_symmetry = self.has_symmetry + is_integer = field == self.FIELD_INTEGER + is_unsigned_integer = field == self.FIELD_UNSIGNED + is_complex = field == self.FIELD_COMPLEX + is_skew = symm == self.SYMMETRY_SKEW_SYMMETRIC + is_herm = symm == self.SYMMETRY_HERMITIAN + is_pattern = field == self.FIELD_PATTERN + + if format == self.FORMAT_ARRAY: + a = zeros((rows, cols), dtype=dtype) + line = 1 + i, j = 0, 0 + if is_skew: + a[i, j] = 0 + if i < rows - 1: + i += 1 + while line: + line = stream.readline() + # line.startswith('%') + if not line or line[0] in ['%', 37] or not line.strip(): + continue + if is_integer: + aij = int(line) + elif is_unsigned_integer: + aij = int(line) + elif is_complex: + aij = complex(*map(float, line.split())) + else: + aij = float(line) + a[i, j] = aij + if has_symmetry and i != j: + if is_skew: + a[j, i] = -aij + elif is_herm: + a[j, i] = conj(aij) + else: + a[j, i] = aij + if i < rows-1: + i = i + 1 + else: + j = j + 1 + if not has_symmetry: + i = 0 + else: + i = j + if is_skew: + a[i, j] = 0 + if i < rows-1: + i += 1 + + if is_skew: + if not (i in [0, j] and j == cols - 1): + raise ValueError("Parse error, did not read all lines.") + else: + if not (i in [0, j] and j == cols): + raise ValueError("Parse error, did not read all lines.") + + elif format == self.FORMAT_COORDINATE: + # Read sparse COOrdinate format + + if entries == 0: + # empty matrix + return coo_matrix((rows, cols), dtype=dtype) + + I = zeros(entries, dtype='intc') + J = zeros(entries, dtype='intc') + if is_pattern: + V = ones(entries, dtype='int8') + elif is_integer: + V = zeros(entries, dtype='intp') + elif is_unsigned_integer: + V = zeros(entries, dtype='uint64') + elif is_complex: + V = zeros(entries, dtype='complex') + else: + V = zeros(entries, dtype='float') + + entry_number = 0 + for line in stream: + # line.startswith('%') + if not line or line[0] in ['%', 37] or not line.strip(): + continue + + if entry_number+1 > entries: + raise ValueError("'entries' in header is smaller than " + "number of entries") + l = line.split() + I[entry_number], J[entry_number] = map(int, l[:2]) + + if not is_pattern: + if is_integer: + V[entry_number] = int(l[2]) + elif is_unsigned_integer: + V[entry_number] = int(l[2]) + elif is_complex: + V[entry_number] = complex(*map(float, l[2:])) + else: + V[entry_number] = float(l[2]) + entry_number += 1 + if entry_number < entries: + raise ValueError("'entries' in header is larger than " + "number of entries") + + I -= 1 # adjust indices (base 1 -> base 0) + J -= 1 + + if has_symmetry: + mask = (I != J) # off diagonal mask + od_I = I[mask] + od_J = J[mask] + od_V = V[mask] + + I = concatenate((I, od_J)) + J = concatenate((J, od_I)) + + if is_skew: + od_V *= -1 + elif is_herm: + od_V = od_V.conjugate() + + V = concatenate((V, od_V)) + + a = coo_matrix((V, (I, J)), shape=(rows, cols), dtype=dtype) + else: + raise NotImplementedError(format) + + return a + + # ------------------------------------------------------------------------ + def _write(self, stream, a, comment='', field=None, precision=None, + symmetry=None): + if isinstance(a, list) or isinstance(a, ndarray) or \ + isinstance(a, tuple) or hasattr(a, '__array__'): + rep = self.FORMAT_ARRAY + a = asarray(a) + if len(a.shape) != 2: + raise ValueError('Expected 2 dimensional array') + rows, cols = a.shape + + if field is not None: + + if field == self.FIELD_INTEGER: + if not can_cast(a.dtype, 'intp'): + raise OverflowError("mmwrite does not support integer " + "dtypes larger than native 'intp'.") + a = a.astype('intp') + elif field == self.FIELD_REAL: + if a.dtype.char not in 'fd': + a = a.astype('d') + elif field == self.FIELD_COMPLEX: + if a.dtype.char not in 'FD': + a = a.astype('D') + + else: + if not issparse(a): + raise ValueError('unknown matrix type: %s' % type(a)) + + rep = 'coordinate' + rows, cols = a.shape + + typecode = a.dtype.char + + if precision is None: + if typecode in 'fF': + precision = 8 + else: + precision = 16 + if field is None: + kind = a.dtype.kind + if kind == 'i': + if not can_cast(a.dtype, 'intp'): + raise OverflowError("mmwrite does not support integer " + "dtypes larger than native 'intp'.") + field = 'integer' + elif kind == 'f': + field = 'real' + elif kind == 'c': + field = 'complex' + elif kind == 'u': + field = 'unsigned-integer' + else: + raise TypeError('unexpected dtype kind ' + kind) + + if symmetry is None: + symmetry = self._get_symmetry(a) + + # validate rep, field, and symmetry + self.__class__._validate_format(rep) + self.__class__._validate_field(field) + self.__class__._validate_symmetry(symmetry) + + # write initial header line + data = f'%%MatrixMarket matrix {rep} {field} {symmetry}\n' + stream.write(data.encode('latin1')) + + # write comments + for line in comment.split('\n'): + data = '%%%s\n' % (line) + stream.write(data.encode('latin1')) + + template = self._field_template(field, precision) + # write dense format + if rep == self.FORMAT_ARRAY: + # write shape spec + data = '%i %i\n' % (rows, cols) + stream.write(data.encode('latin1')) + + if field in (self.FIELD_INTEGER, self.FIELD_REAL, + self.FIELD_UNSIGNED): + if symmetry == self.SYMMETRY_GENERAL: + for j in range(cols): + for i in range(rows): + data = template % a[i, j] + stream.write(data.encode('latin1')) + + elif symmetry == self.SYMMETRY_SKEW_SYMMETRIC: + for j in range(cols): + for i in range(j + 1, rows): + data = template % a[i, j] + stream.write(data.encode('latin1')) + + else: + for j in range(cols): + for i in range(j, rows): + data = template % a[i, j] + stream.write(data.encode('latin1')) + + elif field == self.FIELD_COMPLEX: + + if symmetry == self.SYMMETRY_GENERAL: + for j in range(cols): + for i in range(rows): + aij = a[i, j] + data = template % (real(aij), imag(aij)) + stream.write(data.encode('latin1')) + else: + for j in range(cols): + for i in range(j, rows): + aij = a[i, j] + data = template % (real(aij), imag(aij)) + stream.write(data.encode('latin1')) + + elif field == self.FIELD_PATTERN: + raise ValueError('pattern type inconsisted with dense format') + + else: + raise TypeError('Unknown field type %s' % field) + + # write sparse format + else: + coo = a.tocoo() # convert to COOrdinate format + + # if symmetry format used, remove values above main diagonal + if symmetry != self.SYMMETRY_GENERAL: + lower_triangle_mask = coo.row >= coo.col + coo = coo_matrix((coo.data[lower_triangle_mask], + (coo.row[lower_triangle_mask], + coo.col[lower_triangle_mask])), + shape=coo.shape) + + # write shape spec + data = '%i %i %i\n' % (rows, cols, coo.nnz) + stream.write(data.encode('latin1')) + + template = self._field_template(field, precision-1) + + if field == self.FIELD_PATTERN: + for r, c in zip(coo.row+1, coo.col+1): + data = "%i %i\n" % (r, c) + stream.write(data.encode('latin1')) + elif field in (self.FIELD_INTEGER, self.FIELD_REAL, + self.FIELD_UNSIGNED): + for r, c, d in zip(coo.row+1, coo.col+1, coo.data): + data = ("%i %i " % (r, c)) + (template % d) + stream.write(data.encode('latin1')) + elif field == self.FIELD_COMPLEX: + for r, c, d in zip(coo.row+1, coo.col+1, coo.data): + data = ("%i %i " % (r, c)) + (template % (d.real, d.imag)) + stream.write(data.encode('latin1')) + else: + raise TypeError('Unknown field type %s' % field) + + +def _is_fromfile_compatible(stream): + """ + Check whether `stream` is compatible with numpy.fromfile. + + Passing a gzipped file object to ``fromfile/fromstring`` doesn't work with + Python 3. + """ + + bad_cls = [] + try: + import gzip + bad_cls.append(gzip.GzipFile) + except ImportError: + pass + try: + import bz2 + bad_cls.append(bz2.BZ2File) + except ImportError: + pass + + bad_cls = tuple(bad_cls) + return not isinstance(stream, bad_cls) diff --git a/venv/lib/python3.10/site-packages/scipy/io/harwell_boeing.py b/venv/lib/python3.10/site-packages/scipy/io/harwell_boeing.py new file mode 100644 index 0000000000000000000000000000000000000000..d4d17fe7d522a4a6ad41cbfb0ef5f05a221d06da --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/harwell_boeing.py @@ -0,0 +1,21 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'MalformedHeader', 'hb_read', 'hb_write', 'HBInfo', + 'HBFile', 'HBMatrixType', 'FortranFormatParser', 'IntFormat', + 'ExpFormat', 'BadFortranFormat', 'hb' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io", module="harwell_boeing", + private_modules=["_harwell_boeing"], all=__all__, + attribute=name) diff --git a/venv/lib/python3.10/site-packages/scipy/io/idl.py b/venv/lib/python3.10/site-packages/scipy/io/idl.py new file mode 100644 index 0000000000000000000000000000000000000000..1168022eeaa03a21c59d13f84469b7e24b95b785 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/idl.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'readsav', 'DTYPE_DICT', 'RECTYPE_DICT', 'STRUCT_DICT', + 'Pointer', 'ObjectPointer', 'AttrDict' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io", module="idl", + private_modules=["_idl"], all=__all__, + attribute=name) diff --git a/venv/lib/python3.10/site-packages/scipy/io/mmio.py b/venv/lib/python3.10/site-packages/scipy/io/mmio.py new file mode 100644 index 0000000000000000000000000000000000000000..e03c62376c52de4824086624eb0fb072e07057aa --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/mmio.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'mminfo', 'mmread', 'mmwrite', 'MMFile', + 'coo_matrix', 'asstr' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io", module="mmio", + private_modules=["_mmio"], all=__all__, + attribute=name) diff --git a/venv/lib/python3.10/site-packages/scipy/io/netcdf.py b/venv/lib/python3.10/site-packages/scipy/io/netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..f469c5a3472417b0c97e848a74672e1d119d3eb4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/netcdf.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.io` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'netcdf_file', 'netcdf_variable', + 'array', 'LITTLE_ENDIAN', 'IS_PYPY', 'ABSENT', 'ZERO', + 'NC_BYTE', 'NC_CHAR', 'NC_SHORT', 'NC_INT', 'NC_FLOAT', + 'NC_DOUBLE', 'NC_DIMENSION', 'NC_VARIABLE', 'NC_ATTRIBUTE', + 'FILL_BYTE', 'FILL_CHAR', 'FILL_SHORT', 'FILL_INT', 'FILL_FLOAT', + 'FILL_DOUBLE', 'TYPEMAP', 'FILLMAP', 'REVERSE', 'NetCDFFile', + 'NetCDFVariable' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="io", module="netcdf", + private_modules=["_netcdf"], all=__all__, + attribute=name) diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/io/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/Transparent Busy.ani b/venv/lib/python3.10/site-packages/scipy/io/tests/data/Transparent Busy.ani new file mode 100644 index 0000000000000000000000000000000000000000..3be500032786398c3efdbd9f873f705b6c1636bd Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/Transparent Busy.ani differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav new file mode 100644 index 0000000000000000000000000000000000000000..619a1259670a361ac76ffa86c481a813dbaec07a Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_2d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_2d.sav new file mode 100644 index 0000000000000000000000000000000000000000..804d8b1a8a90636c880e974b6f85bd385033306b Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_2d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..3fa56c450eaa916d9c91b492ba17e7e843df2d53 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_4d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_4d.sav new file mode 100644 index 0000000000000000000000000000000000000000..4bb951e274a399f091ff70b639d6e3b55ee1e122 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_4d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav new file mode 100644 index 0000000000000000000000000000000000000000..2854dbc8b1e53f298ac3b135eac1f06e73940152 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_5d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_6d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_6d.sav new file mode 100644 index 0000000000000000000000000000000000000000..91588d348d5f89af354209840062202d5b28c1df Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_6d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_7d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_7d.sav new file mode 100644 index 0000000000000000000000000000000000000000..3e978fad540a8979435d4561de151573696affd8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_7d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_8d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_8d.sav new file mode 100644 index 0000000000000000000000000000000000000000..f699fe2427dfe876283de0fcade2c2325a262061 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_8d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav new file mode 100644 index 0000000000000000000000000000000000000000..8e3a402c60a515149811e2ca21628e97180c4956 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_1d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav new file mode 100644 index 0000000000000000000000000000000000000000..dd3504f0ecfaed178ace02e1a8a84650111c3936 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_2d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav new file mode 100644 index 0000000000000000000000000000000000000000..d99fa48f0a43ec06c3101560f9cade829c8b1940 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav new file mode 100644 index 0000000000000000000000000000000000000000..de5e984e49f507ae550b1ae2fd54b799e742a195 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_5d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav new file mode 100644 index 0000000000000000000000000000000000000000..bb76671a65be41fd2a426146c6c366f1e7fb07c3 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_6d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav new file mode 100644 index 0000000000000000000000000000000000000000..995d23c6ed05b095442b6247b09191126f797f23 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav new file mode 100644 index 0000000000000000000000000000000000000000..4249ec62119e264d55a81d3faf9c87dcaed1c7c8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_8d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_1.nc b/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_1.nc new file mode 100644 index 0000000000000000000000000000000000000000..5775622d0ef85828b436dffcd21366f7538fc55c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_1.nc differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_2.nc b/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_2.nc new file mode 100644 index 0000000000000000000000000000000000000000..07db1cd986a4c3b9929c01c1f22bcc3f562b1c16 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_2.nc differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc b/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc new file mode 100644 index 0000000000000000000000000000000000000000..57f8bf9da3bca295c15508963c77a870222af0bc Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat new file mode 100644 index 0000000000000000000000000000000000000000..87731eb9d4b1f2ac827a212436fe6de175431e11 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-3x3d-2i.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat new file mode 100644 index 0000000000000000000000000000000000000000..a165a7a30424b20af9a3a0636c5e655239ea6fa5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat new file mode 100644 index 0000000000000000000000000000000000000000..c3bb9dcbe50ef784ce3282b28e53f4c40beb48ce Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-11x1x10.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..351801fd47a2e3e48d9b63034fbae28f8318c9f9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-15x10x22.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat new file mode 100644 index 0000000000000000000000000000000000000000..64bf92f74a457d2f4bc42798493db15cc3ab1008 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..3d3f27f88eef4e02451d18204cdcfd51f96f6d15 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x5.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat new file mode 100644 index 0000000000000000000000000000000000000000..0bd683096f18eadceb7168f811c75bf072baecfe Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x7.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..25269ff9ea4f6dd3f8a9ca0c8ad27d399e4248f5 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat new file mode 100644 index 0000000000000000000000000000000000000000..9850de37cf86af622b759625c15e6b1a9477ce47 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-11x1x10.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat new file mode 100644 index 0000000000000000000000000000000000000000..98c09c2dff6e1ef605e25ed1d00afe94597abddc Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-15x10x22.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat new file mode 100644 index 0000000000000000000000000000000000000000..959098d2a9cdd6140758843e059d4ca529b14279 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x1.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..49c0ec1d18d9f08111fe2d2a269ed407da71b158 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x5.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat new file mode 100644 index 0000000000000000000000000000000000000000..bb936b8789920ce18281fa754a5c048b31e59ba8 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat new file mode 100644 index 0000000000000000000000000000000000000000..cb3e9e4876249f42924a43232b74f05b91123815 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x3x5.dat differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..d53893c6c734e6c7771e08042c16874623dc6f0e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..8cee5ebecc3bef248ed37c438e0731160b31a310 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/null_pointer.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav new file mode 100644 index 0000000000000000000000000000000000000000..e4027b3cf302b8610b87d9ef8b0aac39d5a40ef9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav new file mode 100644 index 0000000000000000000000000000000000000000..182e29bc57dc05154388553a71876820025bca8d Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_byte_descr.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav new file mode 100644 index 0000000000000000000000000000000000000000..593e8c6208ab0bf3aa869de89e213b8aa9f8c071 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav new file mode 100644 index 0000000000000000000000000000000000000000..be9e3877ea845da76d9466c14d70c4cce882368c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float32.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav new file mode 100644 index 0000000000000000000000000000000000000000..9680b2878c6008a27c8fc9ae6966903ff936cc4a Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_float64.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav new file mode 100644 index 0000000000000000000000000000000000000000..d02b1756ac043a4ba6119acb28ef34c40359a4dd Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_heap_pointer.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav new file mode 100644 index 0000000000000000000000000000000000000000..603525694cc307d47412717c4c2f85ddc960897b Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int16.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav new file mode 100644 index 0000000000000000000000000000000000000000..40210b889402c0f27562296ab39ce1a714f0d0ef Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav new file mode 100644 index 0000000000000000000000000000000000000000..c91cd0a561e011a2f18c86119e45392fbc0be825 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav new file mode 100644 index 0000000000000000000000000000000000000000..759c2e64fa034c6ddbdbe6181efae1e699a0c314 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint16.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav new file mode 100644 index 0000000000000000000000000000000000000000..74dec7b8933418d30d17c83d617443a73ceef0c6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav new file mode 100644 index 0000000000000000000000000000000000000000..fc9da5796eab6ce9fb59488b836ba2f567de7b25 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint64.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..40c9cd330e0c731968d71dbbfeae9bd8c4a745a2 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav new file mode 100644 index 0000000000000000000000000000000000000000..f1aa416f8e661893be282a490005536953d4b7af Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_byte_idl80.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..bac9b207488eb9712ec27fb3567155f0dd773f34 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated_3d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav new file mode 100644 index 0000000000000000000000000000000000000000..8babd56306f09fa612f731ce593ae13c75f84f4c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_inherit.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav new file mode 100644 index 0000000000000000000000000000000000000000..a3c678162911426702a9a6e932761385a01f247e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..38b812261125e6aabef8618955b234f6c7b04955 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..db1c256c85a707f0a0d78c28241b78d1eddcab1e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav new file mode 100644 index 0000000000000000000000000000000000000000..acbb058a307090f6c9e2d8402c7badf6bb48144c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..d16f4655cc20318db2b0d629cd5ed6d7be01b518 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..732dd2cbfa9c7fd029bb59b4cfcb630cc1077f54 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers_replicated_3d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav new file mode 100644 index 0000000000000000000000000000000000000000..69d7eaf4ecf8747c21d07e14edcf65b4e394974c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..2222391ae5b93ba34c1fdb982c02eb97d9658b58 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..a35f1acfb4cb93ecb637310bbfa7fc1a2151d483 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav b/venv/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav new file mode 100644 index 0000000000000000000000000000000000000000..dcdb0b0d433939d6a240c86e5060214cd8875732 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav differ diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/test_mmio.py b/venv/lib/python3.10/site-packages/scipy/io/tests/test_mmio.py new file mode 100644 index 0000000000000000000000000000000000000000..77f4224de7c34a214eb7776528b5ae23934cc75e --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/tests/test_mmio.py @@ -0,0 +1,802 @@ +from tempfile import mkdtemp +import os +import io +import shutil +import textwrap + +import numpy as np +from numpy import array, transpose, pi +from numpy.testing import (assert_equal, assert_allclose, + assert_array_equal, assert_array_almost_equal) +import pytest +from pytest import raises as assert_raises + +import scipy.sparse +import scipy.io._mmio +import scipy.io._fast_matrix_market as fmm + + +parametrize_args = [('integer', 'int'), + ('unsigned-integer', 'uint')] + + +# Run the entire test suite on both _mmio and _fast_matrix_market implementations +@pytest.fixture(scope='module', params=(scipy.io._mmio, fmm), autouse=True) +def implementations(request): + global mminfo + global mmread + global mmwrite + mminfo = request.param.mminfo + mmread = request.param.mmread + mmwrite = request.param.mmwrite + + +class TestMMIOArray: + def setup_method(self): + self.tmpdir = mkdtemp() + self.fn = os.path.join(self.tmpdir, 'testfile.mtx') + + def teardown_method(self): + shutil.rmtree(self.tmpdir) + + def check(self, a, info): + mmwrite(self.fn, a) + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn) + assert_array_almost_equal(a, b) + + def check_exact(self, a, info): + mmwrite(self.fn, a) + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn) + assert_equal(a, b) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_integer(self, typeval, dtype): + self.check_exact(array([[1, 2], [3, 4]], dtype=dtype), + (2, 2, 4, 'array', typeval, 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_32bit_integer(self, typeval, dtype): + a = array([[2**31-1, 2**31-2], [2**31-3, 2**31-4]], dtype=dtype) + self.check_exact(a, (2, 2, 4, 'array', typeval, 'general')) + + def test_64bit_integer(self): + a = array([[2**31, 2**32], [2**63-2, 2**63-1]], dtype=np.int64) + if (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite: + assert_raises(OverflowError, mmwrite, self.fn, a) + else: + self.check_exact(a, (2, 2, 4, 'array', 'integer', 'general')) + + def test_64bit_unsigned_integer(self): + a = array([[2**31, 2**32], [2**64-2, 2**64-1]], dtype=np.uint64) + self.check_exact(a, (2, 2, 4, 'array', 'unsigned-integer', 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_upper_triangle_integer(self, typeval, dtype): + self.check_exact(array([[0, 1], [0, 0]], dtype=dtype), + (2, 2, 4, 'array', typeval, 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_lower_triangle_integer(self, typeval, dtype): + self.check_exact(array([[0, 0], [1, 0]], dtype=dtype), + (2, 2, 4, 'array', typeval, 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_rectangular_integer(self, typeval, dtype): + self.check_exact(array([[1, 2, 3], [4, 5, 6]], dtype=dtype), + (2, 3, 6, 'array', typeval, 'general')) + + def test_simple_rectangular_float(self): + self.check([[1, 2], [3.5, 4], [5, 6]], + (3, 2, 6, 'array', 'real', 'general')) + + def test_simple_float(self): + self.check([[1, 2], [3, 4.0]], + (2, 2, 4, 'array', 'real', 'general')) + + def test_simple_complex(self): + self.check([[1, 2], [3, 4j]], + (2, 2, 4, 'array', 'complex', 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_symmetric_integer(self, typeval, dtype): + self.check_exact(array([[1, 2], [2, 4]], dtype=dtype), + (2, 2, 4, 'array', typeval, 'symmetric')) + + def test_simple_skew_symmetric_integer(self): + self.check_exact([[0, 2], [-2, 0]], + (2, 2, 4, 'array', 'integer', 'skew-symmetric')) + + def test_simple_skew_symmetric_float(self): + self.check(array([[0, 2], [-2.0, 0.0]], 'f'), + (2, 2, 4, 'array', 'real', 'skew-symmetric')) + + def test_simple_hermitian_complex(self): + self.check([[1, 2+3j], [2-3j, 4]], + (2, 2, 4, 'array', 'complex', 'hermitian')) + + def test_random_symmetric_float(self): + sz = (20, 20) + a = np.random.random(sz) + a = a + transpose(a) + self.check(a, (20, 20, 400, 'array', 'real', 'symmetric')) + + def test_random_rectangular_float(self): + sz = (20, 15) + a = np.random.random(sz) + self.check(a, (20, 15, 300, 'array', 'real', 'general')) + + def test_bad_number_of_array_header_fields(self): + s = """\ + %%MatrixMarket matrix array real general + 3 3 999 + 1.0 + 2.0 + 3.0 + 4.0 + 5.0 + 6.0 + 7.0 + 8.0 + 9.0 + """ + text = textwrap.dedent(s).encode('ascii') + with pytest.raises(ValueError, match='not of length 2'): + scipy.io.mmread(io.BytesIO(text)) + + def test_gh13634_non_skew_symmetric_int(self): + self.check_exact(array([[1, 2], [-2, 99]], dtype=np.int32), + (2, 2, 4, 'array', 'integer', 'general')) + + def test_gh13634_non_skew_symmetric_float(self): + self.check(array([[1, 2], [-2, 99.]], dtype=np.float32), + (2, 2, 4, 'array', 'real', 'general')) + + +class TestMMIOSparseCSR(TestMMIOArray): + def setup_method(self): + self.tmpdir = mkdtemp() + self.fn = os.path.join(self.tmpdir, 'testfile.mtx') + + def teardown_method(self): + shutil.rmtree(self.tmpdir) + + def check(self, a, info): + mmwrite(self.fn, a) + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn) + assert_array_almost_equal(a.toarray(), b.toarray()) + + def check_exact(self, a, info): + mmwrite(self.fn, a) + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn) + assert_equal(a.toarray(), b.toarray()) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_integer(self, typeval, dtype): + self.check_exact(scipy.sparse.csr_matrix([[1, 2], [3, 4]], dtype=dtype), + (2, 2, 4, 'coordinate', typeval, 'general')) + + def test_32bit_integer(self): + a = scipy.sparse.csr_matrix(array([[2**31-1, -2**31+2], + [2**31-3, 2**31-4]], + dtype=np.int32)) + self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general')) + + def test_64bit_integer(self): + a = scipy.sparse.csr_matrix(array([[2**32+1, 2**32+1], + [-2**63+2, 2**63-2]], + dtype=np.int64)) + if (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite: + assert_raises(OverflowError, mmwrite, self.fn, a) + else: + self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general')) + + def test_32bit_unsigned_integer(self): + a = scipy.sparse.csr_matrix(array([[2**31-1, 2**31-2], + [2**31-3, 2**31-4]], + dtype=np.uint32)) + self.check_exact(a, (2, 2, 4, 'coordinate', 'unsigned-integer', 'general')) + + def test_64bit_unsigned_integer(self): + a = scipy.sparse.csr_matrix(array([[2**32+1, 2**32+1], + [2**64-2, 2**64-1]], + dtype=np.uint64)) + self.check_exact(a, (2, 2, 4, 'coordinate', 'unsigned-integer', 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_upper_triangle_integer(self, typeval, dtype): + self.check_exact(scipy.sparse.csr_matrix([[0, 1], [0, 0]], dtype=dtype), + (2, 2, 1, 'coordinate', typeval, 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_lower_triangle_integer(self, typeval, dtype): + self.check_exact(scipy.sparse.csr_matrix([[0, 0], [1, 0]], dtype=dtype), + (2, 2, 1, 'coordinate', typeval, 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_rectangular_integer(self, typeval, dtype): + self.check_exact(scipy.sparse.csr_matrix([[1, 2, 3], [4, 5, 6]], dtype=dtype), + (2, 3, 6, 'coordinate', typeval, 'general')) + + def test_simple_rectangular_float(self): + self.check(scipy.sparse.csr_matrix([[1, 2], [3.5, 4], [5, 6]]), + (3, 2, 6, 'coordinate', 'real', 'general')) + + def test_simple_float(self): + self.check(scipy.sparse.csr_matrix([[1, 2], [3, 4.0]]), + (2, 2, 4, 'coordinate', 'real', 'general')) + + def test_simple_complex(self): + self.check(scipy.sparse.csr_matrix([[1, 2], [3, 4j]]), + (2, 2, 4, 'coordinate', 'complex', 'general')) + + @pytest.mark.parametrize('typeval, dtype', parametrize_args) + def test_simple_symmetric_integer(self, typeval, dtype): + self.check_exact(scipy.sparse.csr_matrix([[1, 2], [2, 4]], dtype=dtype), + (2, 2, 3, 'coordinate', typeval, 'symmetric')) + + def test_simple_skew_symmetric_integer(self): + self.check_exact(scipy.sparse.csr_matrix([[0, 2], [-2, 0]]), + (2, 2, 1, 'coordinate', 'integer', 'skew-symmetric')) + + def test_simple_skew_symmetric_float(self): + self.check(scipy.sparse.csr_matrix(array([[0, 2], [-2.0, 0]], 'f')), + (2, 2, 1, 'coordinate', 'real', 'skew-symmetric')) + + def test_simple_hermitian_complex(self): + self.check(scipy.sparse.csr_matrix([[1, 2+3j], [2-3j, 4]]), + (2, 2, 3, 'coordinate', 'complex', 'hermitian')) + + def test_random_symmetric_float(self): + sz = (20, 20) + a = np.random.random(sz) + a = a + transpose(a) + a = scipy.sparse.csr_matrix(a) + self.check(a, (20, 20, 210, 'coordinate', 'real', 'symmetric')) + + def test_random_rectangular_float(self): + sz = (20, 15) + a = np.random.random(sz) + a = scipy.sparse.csr_matrix(a) + self.check(a, (20, 15, 300, 'coordinate', 'real', 'general')) + + def test_simple_pattern(self): + a = scipy.sparse.csr_matrix([[0, 1.5], [3.0, 2.5]]) + p = np.zeros_like(a.toarray()) + p[a.toarray() > 0] = 1 + info = (2, 2, 3, 'coordinate', 'pattern', 'general') + mmwrite(self.fn, a, field='pattern') + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn) + assert_array_almost_equal(p, b.toarray()) + + def test_gh13634_non_skew_symmetric_int(self): + a = scipy.sparse.csr_matrix([[1, 2], [-2, 99]], dtype=np.int32) + self.check_exact(a, (2, 2, 4, 'coordinate', 'integer', 'general')) + + def test_gh13634_non_skew_symmetric_float(self): + a = scipy.sparse.csr_matrix([[1, 2], [-2, 99.]], dtype=np.float32) + self.check(a, (2, 2, 4, 'coordinate', 'real', 'general')) + + +_32bit_integer_dense_example = '''\ +%%MatrixMarket matrix array integer general +2 2 +2147483647 +2147483646 +2147483647 +2147483646 +''' + +_32bit_integer_sparse_example = '''\ +%%MatrixMarket matrix coordinate integer symmetric +2 2 2 +1 1 2147483647 +2 2 2147483646 +''' + +_64bit_integer_dense_example = '''\ +%%MatrixMarket matrix array integer general +2 2 + 2147483648 +-9223372036854775806 + -2147483648 + 9223372036854775807 +''' + +_64bit_integer_sparse_general_example = '''\ +%%MatrixMarket matrix coordinate integer general +2 2 3 +1 1 2147483648 +1 2 9223372036854775807 +2 2 9223372036854775807 +''' + +_64bit_integer_sparse_symmetric_example = '''\ +%%MatrixMarket matrix coordinate integer symmetric +2 2 3 +1 1 2147483648 +1 2 -9223372036854775807 +2 2 9223372036854775807 +''' + +_64bit_integer_sparse_skew_example = '''\ +%%MatrixMarket matrix coordinate integer skew-symmetric +2 2 3 +1 1 2147483648 +1 2 -9223372036854775807 +2 2 9223372036854775807 +''' + +_over64bit_integer_dense_example = '''\ +%%MatrixMarket matrix array integer general +2 2 + 2147483648 +9223372036854775807 + 2147483648 +9223372036854775808 +''' + +_over64bit_integer_sparse_example = '''\ +%%MatrixMarket matrix coordinate integer symmetric +2 2 2 +1 1 2147483648 +2 2 19223372036854775808 +''' + + +class TestMMIOReadLargeIntegers: + def setup_method(self): + self.tmpdir = mkdtemp() + self.fn = os.path.join(self.tmpdir, 'testfile.mtx') + + def teardown_method(self): + shutil.rmtree(self.tmpdir) + + def check_read(self, example, a, info, dense, over32, over64): + with open(self.fn, 'w') as f: + f.write(example) + assert_equal(mminfo(self.fn), info) + if ((over32 and (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite) + or over64): + assert_raises(OverflowError, mmread, self.fn) + else: + b = mmread(self.fn) + if not dense: + b = b.toarray() + assert_equal(a, b) + + def test_read_32bit_integer_dense(self): + a = array([[2**31-1, 2**31-1], + [2**31-2, 2**31-2]], dtype=np.int64) + self.check_read(_32bit_integer_dense_example, + a, + (2, 2, 4, 'array', 'integer', 'general'), + dense=True, + over32=False, + over64=False) + + def test_read_32bit_integer_sparse(self): + a = array([[2**31-1, 0], + [0, 2**31-2]], dtype=np.int64) + self.check_read(_32bit_integer_sparse_example, + a, + (2, 2, 2, 'coordinate', 'integer', 'symmetric'), + dense=False, + over32=False, + over64=False) + + def test_read_64bit_integer_dense(self): + a = array([[2**31, -2**31], + [-2**63+2, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_dense_example, + a, + (2, 2, 4, 'array', 'integer', 'general'), + dense=True, + over32=True, + over64=False) + + def test_read_64bit_integer_sparse_general(self): + a = array([[2**31, 2**63-1], + [0, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_sparse_general_example, + a, + (2, 2, 3, 'coordinate', 'integer', 'general'), + dense=False, + over32=True, + over64=False) + + def test_read_64bit_integer_sparse_symmetric(self): + a = array([[2**31, -2**63+1], + [-2**63+1, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_sparse_symmetric_example, + a, + (2, 2, 3, 'coordinate', 'integer', 'symmetric'), + dense=False, + over32=True, + over64=False) + + def test_read_64bit_integer_sparse_skew(self): + a = array([[2**31, -2**63+1], + [2**63-1, 2**63-1]], dtype=np.int64) + self.check_read(_64bit_integer_sparse_skew_example, + a, + (2, 2, 3, 'coordinate', 'integer', 'skew-symmetric'), + dense=False, + over32=True, + over64=False) + + def test_read_over64bit_integer_dense(self): + self.check_read(_over64bit_integer_dense_example, + None, + (2, 2, 4, 'array', 'integer', 'general'), + dense=True, + over32=True, + over64=True) + + def test_read_over64bit_integer_sparse(self): + self.check_read(_over64bit_integer_sparse_example, + None, + (2, 2, 2, 'coordinate', 'integer', 'symmetric'), + dense=False, + over32=True, + over64=True) + + +_general_example = '''\ +%%MatrixMarket matrix coordinate real general +%================================================================================= +% +% This ASCII file represents a sparse MxN matrix with L +% nonzeros in the following Matrix Market format: +% +% +----------------------------------------------+ +% |%%MatrixMarket matrix coordinate real general | <--- header line +% |% | <--+ +% |% comments | |-- 0 or more comment lines +% |% | <--+ +% | M N L | <--- rows, columns, entries +% | I1 J1 A(I1, J1) | <--+ +% | I2 J2 A(I2, J2) | | +% | I3 J3 A(I3, J3) | |-- L lines +% | . . . | | +% | IL JL A(IL, JL) | <--+ +% +----------------------------------------------+ +% +% Indices are 1-based, i.e. A(1,1) is the first element. +% +%================================================================================= + 5 5 8 + 1 1 1.000e+00 + 2 2 1.050e+01 + 3 3 1.500e-02 + 1 4 6.000e+00 + 4 2 2.505e+02 + 4 4 -2.800e+02 + 4 5 3.332e+01 + 5 5 1.200e+01 +''' + +_hermitian_example = '''\ +%%MatrixMarket matrix coordinate complex hermitian + 5 5 7 + 1 1 1.0 0 + 2 2 10.5 0 + 4 2 250.5 22.22 + 3 3 1.5e-2 0 + 4 4 -2.8e2 0 + 5 5 12. 0 + 5 4 0 33.32 +''' + +_skew_example = '''\ +%%MatrixMarket matrix coordinate real skew-symmetric + 5 5 7 + 1 1 1.0 + 2 2 10.5 + 4 2 250.5 + 3 3 1.5e-2 + 4 4 -2.8e2 + 5 5 12. + 5 4 0 +''' + +_symmetric_example = '''\ +%%MatrixMarket matrix coordinate real symmetric + 5 5 7 + 1 1 1.0 + 2 2 10.5 + 4 2 250.5 + 3 3 1.5e-2 + 4 4 -2.8e2 + 5 5 12. + 5 4 8 +''' + +_symmetric_pattern_example = '''\ +%%MatrixMarket matrix coordinate pattern symmetric + 5 5 7 + 1 1 + 2 2 + 4 2 + 3 3 + 4 4 + 5 5 + 5 4 +''' + +# example (without comment lines) from Figure 1 in +# https://math.nist.gov/MatrixMarket/reports/MMformat.ps +_empty_lines_example = '''\ +%%MatrixMarket MATRIX Coordinate Real General + + 5 5 8 + +1 1 1.0 +2 2 10.5 +3 3 1.5e-2 +4 4 -2.8E2 +5 5 12. + 1 4 6 + 4 2 250.5 + 4 5 33.32 + +''' + + +class TestMMIOCoordinate: + def setup_method(self): + self.tmpdir = mkdtemp() + self.fn = os.path.join(self.tmpdir, 'testfile.mtx') + + def teardown_method(self): + shutil.rmtree(self.tmpdir) + + def check_read(self, example, a, info): + f = open(self.fn, 'w') + f.write(example) + f.close() + assert_equal(mminfo(self.fn), info) + b = mmread(self.fn).toarray() + assert_array_almost_equal(a, b) + + def test_read_general(self): + a = [[1, 0, 0, 6, 0], + [0, 10.5, 0, 0, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 33.32], + [0, 0, 0, 0, 12]] + self.check_read(_general_example, a, + (5, 5, 8, 'coordinate', 'real', 'general')) + + def test_read_hermitian(self): + a = [[1, 0, 0, 0, 0], + [0, 10.5, 0, 250.5 - 22.22j, 0], + [0, 0, .015, 0, 0], + [0, 250.5 + 22.22j, 0, -280, -33.32j], + [0, 0, 0, 33.32j, 12]] + self.check_read(_hermitian_example, a, + (5, 5, 7, 'coordinate', 'complex', 'hermitian')) + + def test_read_skew(self): + a = [[1, 0, 0, 0, 0], + [0, 10.5, 0, -250.5, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 0], + [0, 0, 0, 0, 12]] + self.check_read(_skew_example, a, + (5, 5, 7, 'coordinate', 'real', 'skew-symmetric')) + + def test_read_symmetric(self): + a = [[1, 0, 0, 0, 0], + [0, 10.5, 0, 250.5, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 8], + [0, 0, 0, 8, 12]] + self.check_read(_symmetric_example, a, + (5, 5, 7, 'coordinate', 'real', 'symmetric')) + + def test_read_symmetric_pattern(self): + a = [[1, 0, 0, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 0], + [0, 1, 0, 1, 1], + [0, 0, 0, 1, 1]] + self.check_read(_symmetric_pattern_example, a, + (5, 5, 7, 'coordinate', 'pattern', 'symmetric')) + + def test_read_empty_lines(self): + a = [[1, 0, 0, 6, 0], + [0, 10.5, 0, 0, 0], + [0, 0, .015, 0, 0], + [0, 250.5, 0, -280, 33.32], + [0, 0, 0, 0, 12]] + self.check_read(_empty_lines_example, a, + (5, 5, 8, 'coordinate', 'real', 'general')) + + def test_empty_write_read(self): + # https://github.com/scipy/scipy/issues/1410 (Trac #883) + + b = scipy.sparse.coo_matrix((10, 10)) + mmwrite(self.fn, b) + + assert_equal(mminfo(self.fn), + (10, 10, 0, 'coordinate', 'real', 'symmetric')) + a = b.toarray() + b = mmread(self.fn).toarray() + assert_array_almost_equal(a, b) + + def test_bzip2_py3(self): + # test if fix for #2152 works + try: + # bz2 module isn't always built when building Python. + import bz2 + except ImportError: + return + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + + b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + fn_bzip2 = "%s.bz2" % self.fn + with open(self.fn, 'rb') as f_in: + f_out = bz2.BZ2File(fn_bzip2, 'wb') + f_out.write(f_in.read()) + f_out.close() + + a = mmread(fn_bzip2).toarray() + assert_array_almost_equal(a, b.toarray()) + + def test_gzip_py3(self): + # test if fix for #2152 works + try: + # gzip module can be missing from Python installation + import gzip + except ImportError: + return + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + + b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + fn_gzip = "%s.gz" % self.fn + with open(self.fn, 'rb') as f_in: + f_out = gzip.open(fn_gzip, 'wb') + f_out.write(f_in.read()) + f_out.close() + + a = mmread(fn_gzip).toarray() + assert_array_almost_equal(a, b.toarray()) + + def test_real_write_read(self): + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + + b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + assert_equal(mminfo(self.fn), + (5, 5, 8, 'coordinate', 'real', 'general')) + a = b.toarray() + b = mmread(self.fn).toarray() + assert_array_almost_equal(a, b) + + def test_complex_write_read(self): + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j, + 250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j]) + + b = scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5)) + + mmwrite(self.fn, b) + + assert_equal(mminfo(self.fn), + (5, 5, 8, 'coordinate', 'complex', 'general')) + a = b.toarray() + b = mmread(self.fn).toarray() + assert_array_almost_equal(a, b) + + def test_sparse_formats(self, tmp_path): + # Note: `tmp_path` is a pytest fixture, it handles cleanup + tmpdir = tmp_path / 'sparse_formats' + tmpdir.mkdir() + + mats = [] + I = array([0, 0, 1, 2, 3, 3, 3, 4]) + J = array([0, 3, 1, 2, 1, 3, 4, 4]) + + V = array([1.0, 6.0, 10.5, 0.015, 250.5, -280.0, 33.32, 12.0]) + mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5))) + + V = array([1.0 + 3j, 6.0 + 2j, 10.50 + 0.9j, 0.015 + -4.4j, + 250.5 + 0j, -280.0 + 5j, 33.32 + 6.4j, 12.00 + 0.8j]) + mats.append(scipy.sparse.coo_matrix((V, (I, J)), shape=(5, 5))) + + for mat in mats: + expected = mat.toarray() + for fmt in ['csr', 'csc', 'coo']: + fname = tmpdir / (fmt + '.mtx') + mmwrite(fname, mat.asformat(fmt)) + result = mmread(fname).toarray() + assert_array_almost_equal(result, expected) + + def test_precision(self): + test_values = [pi] + [10**(i) for i in range(0, -10, -1)] + test_precisions = range(1, 10) + for value in test_values: + for precision in test_precisions: + # construct sparse matrix with test value at last main diagonal + n = 10**precision + 1 + A = scipy.sparse.dok_matrix((n, n)) + A[n-1, n-1] = value + # write matrix with test precision and read again + mmwrite(self.fn, A, precision=precision) + A = scipy.io.mmread(self.fn) + # check for right entries in matrix + assert_array_equal(A.row, [n-1]) + assert_array_equal(A.col, [n-1]) + assert_allclose(A.data, [float('%%.%dg' % precision % value)]) + + def test_bad_number_of_coordinate_header_fields(self): + s = """\ + %%MatrixMarket matrix coordinate real general + 5 5 8 999 + 1 1 1.000e+00 + 2 2 1.050e+01 + 3 3 1.500e-02 + 1 4 6.000e+00 + 4 2 2.505e+02 + 4 4 -2.800e+02 + 4 5 3.332e+01 + 5 5 1.200e+01 + """ + text = textwrap.dedent(s).encode('ascii') + with pytest.raises(ValueError, match='not of length 3'): + scipy.io.mmread(io.BytesIO(text)) + + +def test_gh11389(): + mmread(io.StringIO("%%MatrixMarket matrix coordinate complex symmetric\n" + " 1 1 1\n" + "1 1 -2.1846000000000e+02 0.0000000000000e+00")) + + +def test_gh18123(tmp_path): + lines = [" %%MatrixMarket matrix coordinate real general\n", + "5 5 3\n", + "2 3 1.0\n", + "3 4 2.0\n", + "3 5 3.0\n"] + test_file = tmp_path / "test.mtx" + with open(test_file, "w") as f: + f.writelines(lines) + mmread(test_file) + + +def test_threadpoolctl(): + try: + import threadpoolctl + if not hasattr(threadpoolctl, "register"): + pytest.skip("threadpoolctl too old") + return + except ImportError: + pytest.skip("no threadpoolctl") + return + + with threadpoolctl.threadpool_limits(limits=4): + assert_equal(fmm.PARALLELISM, 4) + + with threadpoolctl.threadpool_limits(limits=2, user_api='scipy'): + assert_equal(fmm.PARALLELISM, 2) diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/test_paths.py b/venv/lib/python3.10/site-packages/scipy/io/tests/test_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..84464e469b64579cf389dcea0fece7b0e9d36121 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/tests/test_paths.py @@ -0,0 +1,93 @@ +""" +Ensure that we can use pathlib.Path objects in all relevant IO functions. +""" +from pathlib import Path + +import numpy as np + +import scipy.io +import scipy.io.wavfile +from scipy._lib._tmpdirs import tempdir +import scipy.sparse + + +class TestPaths: + data = np.arange(5).astype(np.int64) + + def test_savemat(self): + with tempdir() as temp_dir: + path = Path(temp_dir) / 'data.mat' + scipy.io.savemat(path, {'data': self.data}) + assert path.is_file() + + def test_loadmat(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + path = Path(temp_dir) / 'data.mat' + scipy.io.savemat(str(path), {'data': self.data}) + + mat_contents = scipy.io.loadmat(path) + assert (mat_contents['data'] == self.data).all() + + def test_whosmat(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + path = Path(temp_dir) / 'data.mat' + scipy.io.savemat(str(path), {'data': self.data}) + + contents = scipy.io.whosmat(path) + assert contents[0] == ('data', (1, 5), 'int64') + + def test_readsav(self): + path = Path(__file__).parent / 'data/scalar_string.sav' + scipy.io.readsav(path) + + def test_hb_read(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + data = scipy.sparse.csr_matrix(scipy.sparse.eye(3)) + path = Path(temp_dir) / 'data.hb' + scipy.io.hb_write(str(path), data) + + data_new = scipy.io.hb_read(path) + assert (data_new != data).nnz == 0 + + def test_hb_write(self): + with tempdir() as temp_dir: + data = scipy.sparse.csr_matrix(scipy.sparse.eye(3)) + path = Path(temp_dir) / 'data.hb' + scipy.io.hb_write(path, data) + assert path.is_file() + + def test_mmio_read(self): + # Save data with string path, load with pathlib.Path + with tempdir() as temp_dir: + data = scipy.sparse.csr_matrix(scipy.sparse.eye(3)) + path = Path(temp_dir) / 'data.mtx' + scipy.io.mmwrite(str(path), data) + + data_new = scipy.io.mmread(path) + assert (data_new != data).nnz == 0 + + def test_mmio_write(self): + with tempdir() as temp_dir: + data = scipy.sparse.csr_matrix(scipy.sparse.eye(3)) + path = Path(temp_dir) / 'data.mtx' + scipy.io.mmwrite(path, data) + + def test_netcdf_file(self): + path = Path(__file__).parent / 'data/example_1.nc' + scipy.io.netcdf_file(path) + + def test_wavfile_read(self): + path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav' + scipy.io.wavfile.read(path) + + def test_wavfile_write(self): + # Read from str path, write to Path + input_path = Path(__file__).parent / 'data/test-8000Hz-le-2ch-1byteu.wav' + rate, data = scipy.io.wavfile.read(str(input_path)) + + with tempdir() as temp_dir: + output_path = Path(temp_dir) / input_path.name + scipy.io.wavfile.write(output_path, rate, data) diff --git a/venv/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py b/venv/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py new file mode 100644 index 0000000000000000000000000000000000000000..0a048fad1f981a5af6651ed2170fed3847749972 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py @@ -0,0 +1,426 @@ +import os +import sys +from io import BytesIO + +import numpy as np +from numpy.testing import (assert_equal, assert_, assert_array_equal, + break_cycles, suppress_warnings, IS_PYPY) +import pytest +from pytest import raises, warns + +from scipy.io import wavfile + + +def datafile(fn): + return os.path.join(os.path.dirname(__file__), 'data', fn) + + +def test_read_1(): + # 32-bit PCM (which uses extensible format) + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 44100) + assert_(np.issubdtype(data.dtype, np.int32)) + assert_equal(data.shape, (4410,)) + + del data + + +def test_read_2(): + # 8-bit unsigned PCM + for mmap in [False, True]: + filename = 'test-8000Hz-le-2ch-1byteu.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.uint8)) + assert_equal(data.shape, (800, 2)) + + del data + + +def test_read_3(): + # Little-endian float + for mmap in [False, True]: + filename = 'test-44100Hz-2ch-32bit-float-le.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 44100) + assert_(np.issubdtype(data.dtype, np.float32)) + assert_equal(data.shape, (441, 2)) + + del data + + +def test_read_4(): + # Contains unsupported 'PEAK' chunk + for mmap in [False, True]: + with suppress_warnings() as sup: + sup.filter(wavfile.WavFileWarning, + "Chunk .non-data. not understood, skipping it") + filename = 'test-48000Hz-2ch-64bit-float-le-wavex.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 48000) + assert_(np.issubdtype(data.dtype, np.float64)) + assert_equal(data.shape, (480, 2)) + + del data + + +def test_read_5(): + # Big-endian float + for mmap in [False, True]: + filename = 'test-44100Hz-2ch-32bit-float-be.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 44100) + assert_(np.issubdtype(data.dtype, np.float32)) + assert_(data.dtype.byteorder == '>' or (sys.byteorder == 'big' and + data.dtype.byteorder == '=')) + assert_equal(data.shape, (441, 2)) + + del data + + +def test_5_bit_odd_size_no_pad(): + # 5-bit, 1 B container, 5 channels, 9 samples, 45 B data chunk + # Generated by LTspice, which incorrectly omits pad byte, but should be + # readable anyway + for mmap in [False, True]: + filename = 'test-8000Hz-le-5ch-9S-5bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.uint8)) + assert_equal(data.shape, (9, 5)) + + # 8-5 = 3 LSBits should be 0 + assert_equal(data & 0b00000111, 0) + + # Unsigned + assert_equal(data.max(), 0b11111000) # Highest possible + assert_equal(data[0, 0], 128) # Midpoint is 128 for <= 8-bit + assert_equal(data.min(), 0) # Lowest possible + + del data + + +def test_12_bit_even_size(): + # 12-bit, 2 B container, 4 channels, 9 samples, 72 B data chunk + # Generated by LTspice from 1 Vpk sine waves + for mmap in [False, True]: + filename = 'test-8000Hz-le-4ch-9S-12bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=mmap) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int16)) + assert_equal(data.shape, (9, 4)) + + # 16-12 = 4 LSBits should be 0 + assert_equal(data & 0b00000000_00001111, 0) + + # Signed + assert_equal(data.max(), 0b01111111_11110000) # Highest possible + assert_equal(data[0, 0], 0) # Midpoint is 0 for >= 9-bit + assert_equal(data.min(), -0b10000000_00000000) # Lowest possible + + del data + + +def test_24_bit_odd_size_with_pad(): + # 24-bit, 3 B container, 3 channels, 5 samples, 45 B data chunk + # Should not raise any warnings about the data chunk pad byte + filename = 'test-8000Hz-le-3ch-5S-24bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int32)) + assert_equal(data.shape, (5, 3)) + + # All LSBytes should be 0 + assert_equal(data & 0xff, 0) + + # Hand-made max/min samples under different conventions: + # 2**(N-1) 2**(N-1)-1 LSB + assert_equal(data, [[-0x8000_0000, -0x7fff_ff00, -0x200], + [-0x4000_0000, -0x3fff_ff00, -0x100], + [+0x0000_0000, +0x0000_0000, +0x000], + [+0x4000_0000, +0x3fff_ff00, +0x100], + [+0x7fff_ff00, +0x7fff_ff00, +0x200]]) + # ^ clipped + + +def test_20_bit_extra_data(): + # 20-bit, 3 B container, 1 channel, 10 samples, 30 B data chunk + # with extra data filling container beyond the bit depth + filename = 'test-8000Hz-le-1ch-10S-20bit-extra.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 1234) + assert_(np.issubdtype(data.dtype, np.int32)) + assert_equal(data.shape, (10,)) + + # All LSBytes should still be 0, because 3 B container in 4 B dtype + assert_equal(data & 0xff, 0) + + # But it should load the data beyond 20 bits + assert_((data & 0xf00).any()) + + # Full-scale positive/negative samples, then being halved each time + assert_equal(data, [+0x7ffff000, # +full-scale 20-bit + -0x7ffff000, # -full-scale 20-bit + +0x7ffff000 >> 1, # +1/2 + -0x7ffff000 >> 1, # -1/2 + +0x7ffff000 >> 2, # +1/4 + -0x7ffff000 >> 2, # -1/4 + +0x7ffff000 >> 3, # +1/8 + -0x7ffff000 >> 3, # -1/8 + +0x7ffff000 >> 4, # +1/16 + -0x7ffff000 >> 4, # -1/16 + ]) + + +def test_36_bit_odd_size(): + # 36-bit, 5 B container, 3 channels, 5 samples, 75 B data chunk + pad + filename = 'test-8000Hz-le-3ch-5S-36bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # 28 LSBits should be 0 + assert_equal(data & 0xfffffff, 0) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_f000_0000, -0x2000_0000], + [-0x4000_0000_0000_0000, -0x3fff_ffff_f000_0000, -0x1000_0000], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000_0000], + [+0x4000_0000_0000_0000, +0x3fff_ffff_f000_0000, +0x1000_0000], + [+0x7fff_ffff_f000_0000, +0x7fff_ffff_f000_0000, +0x2000_0000]] + # ^ clipped + + assert_equal(data, correct) + + +def test_45_bit_even_size(): + # 45-bit, 6 B container, 3 channels, 5 samples, 90 B data chunk + filename = 'test-8000Hz-le-3ch-5S-45bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # 19 LSBits should be 0 + assert_equal(data & 0x7ffff, 0) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_fff8_0000, -0x10_0000], + [-0x4000_0000_0000_0000, -0x3fff_ffff_fff8_0000, -0x08_0000], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x00_0000], + [+0x4000_0000_0000_0000, +0x3fff_ffff_fff8_0000, +0x08_0000], + [+0x7fff_ffff_fff8_0000, +0x7fff_ffff_fff8_0000, +0x10_0000]] + # ^ clipped + + assert_equal(data, correct) + + +def test_53_bit_odd_size(): + # 53-bit, 7 B container, 3 channels, 5 samples, 105 B data chunk + pad + filename = 'test-8000Hz-le-3ch-5S-53bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # 11 LSBits should be 0 + assert_equal(data & 0x7ff, 0) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_f800, -0x1000], + [-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_f800, -0x0800], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0000], + [+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_f800, +0x0800], + [+0x7fff_ffff_ffff_f800, +0x7fff_ffff_ffff_f800, +0x1000]] + # ^ clipped + + assert_equal(data, correct) + + +def test_64_bit_even_size(): + # 64-bit, 8 B container, 3 channels, 5 samples, 120 B data chunk + for mmap in [False, True]: + filename = 'test-8000Hz-le-3ch-5S-64bit.wav' + rate, data = wavfile.read(datafile(filename), mmap=False) + + assert_equal(rate, 8000) + assert_(np.issubdtype(data.dtype, np.int64)) + assert_equal(data.shape, (5, 3)) + + # Hand-made max/min samples under different conventions: + # Fixed-point 2**(N-1) Full-scale 2**(N-1)-1 LSB + correct = [[-0x8000_0000_0000_0000, -0x7fff_ffff_ffff_ffff, -0x2], + [-0x4000_0000_0000_0000, -0x3fff_ffff_ffff_ffff, -0x1], + [+0x0000_0000_0000_0000, +0x0000_0000_0000_0000, +0x0], + [+0x4000_0000_0000_0000, +0x3fff_ffff_ffff_ffff, +0x1], + [+0x7fff_ffff_ffff_ffff, +0x7fff_ffff_ffff_ffff, +0x2]] + # ^ clipped + + assert_equal(data, correct) + + del data + + +def test_unsupported_mmap(): + # Test containers that cannot be mapped to numpy types + for filename in {'test-8000Hz-le-3ch-5S-24bit.wav', + 'test-8000Hz-le-3ch-5S-36bit.wav', + 'test-8000Hz-le-3ch-5S-45bit.wav', + 'test-8000Hz-le-3ch-5S-53bit.wav', + 'test-8000Hz-le-1ch-10S-20bit-extra.wav'}: + with raises(ValueError, match="mmap.*not compatible"): + rate, data = wavfile.read(datafile(filename), mmap=True) + + +def test_rifx(): + # Compare equivalent RIFX and RIFF files + for rifx, riff in {('test-44100Hz-be-1ch-4bytes.wav', + 'test-44100Hz-le-1ch-4bytes.wav'), + ('test-8000Hz-be-3ch-5S-24bit.wav', + 'test-8000Hz-le-3ch-5S-24bit.wav')}: + rate1, data1 = wavfile.read(datafile(rifx), mmap=False) + rate2, data2 = wavfile.read(datafile(riff), mmap=False) + assert_equal(rate1, rate2) + assert_equal(data1, data2) + + +def test_read_unknown_filetype_fail(): + # Not an RIFF + for mmap in [False, True]: + filename = 'example_1.nc' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="CDF.*'RIFF' and 'RIFX' supported"): + wavfile.read(fp, mmap=mmap) + + +def test_read_unknown_riff_form_type(): + # RIFF, but not WAVE form + for mmap in [False, True]: + filename = 'Transparent Busy.ani' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match='Not a WAV file.*ACON'): + wavfile.read(fp, mmap=mmap) + + +def test_read_unknown_wave_format(): + # RIFF and WAVE, but not supported format + for mmap in [False, True]: + filename = 'test-8000Hz-le-1ch-1byte-ulaw.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match='Unknown wave file format.*MULAW.*' + 'Supported formats'): + wavfile.read(fp, mmap=mmap) + + +def test_read_early_eof_with_data(): + # File ends inside 'data' chunk, but we keep incomplete data + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes-early-eof.wav' + with open(datafile(filename), 'rb') as fp: + with warns(wavfile.WavFileWarning, match='Reached EOF'): + rate, data = wavfile.read(fp, mmap=mmap) + assert data.size > 0 + assert rate == 44100 + # also test writing (gh-12176) + data[0] = 0 + + +def test_read_early_eof(): + # File ends after 'fact' chunk at boundary, no data read + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="Unexpected end of file."): + wavfile.read(fp, mmap=mmap) + + +def test_read_incomplete_chunk(): + # File ends inside 'fmt ' chunk ID, no data read + for mmap in [False, True]: + filename = 'test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="Incomplete chunk ID.*b'f'"): + wavfile.read(fp, mmap=mmap) + + +def test_read_inconsistent_header(): + # File header's size fields contradict each other + for mmap in [False, True]: + filename = 'test-8000Hz-le-3ch-5S-24bit-inconsistent.wav' + with open(datafile(filename), 'rb') as fp: + with raises(ValueError, match="header is invalid"): + wavfile.read(fp, mmap=mmap) + + +# signed 8-bit integer PCM is not allowed +# unsigned > 8-bit integer PCM is not allowed +# 8- or 16-bit float PCM is not expected +# g and q are platform-dependent, so not included +@pytest.mark.parametrize("dt_str", ["i2", ">i4", ">i8", ">f4", ">f8", '|u1']) +@pytest.mark.parametrize("channels", [1, 2, 5]) +@pytest.mark.parametrize("rate", [8000, 32000]) +@pytest.mark.parametrize("mmap", [False, True]) +@pytest.mark.parametrize("realfile", [False, True]) +def test_write_roundtrip(realfile, mmap, rate, channels, dt_str, tmpdir): + dtype = np.dtype(dt_str) + if realfile: + tmpfile = str(tmpdir.join('temp.wav')) + else: + tmpfile = BytesIO() + data = np.random.rand(100, channels) + if channels == 1: + data = data[:, 0] + if dtype.kind == 'f': + # The range of the float type should be in [-1, 1] + data = data.astype(dtype) + else: + data = (data*128).astype(dtype) + + wavfile.write(tmpfile, rate, data) + + rate2, data2 = wavfile.read(tmpfile, mmap=mmap) + + assert_equal(rate, rate2) + assert_(data2.dtype.byteorder in ('<', '=', '|'), msg=data2.dtype) + assert_array_equal(data, data2) + # also test writing (gh-12176) + if realfile: + data2[0] = 0 + else: + with pytest.raises(ValueError, match='read-only'): + data2[0] = 0 + + if realfile and mmap and IS_PYPY and sys.platform == 'win32': + # windows cannot remove a dead file held by a mmap but not collected + # in PyPy; since the filename gets reused in this test, clean this up + break_cycles() + break_cycles() + + +@pytest.mark.parametrize("dtype", [np.float16]) +def test_wavfile_dtype_unsupported(tmpdir, dtype): + tmpfile = str(tmpdir.join('temp.wav')) + rng = np.random.default_rng(1234) + data = rng.random((100, 5)).astype(dtype) + rate = 8000 + with pytest.raises(ValueError, match="Unsupported"): + wavfile.write(tmpfile, rate, data)