diff --git a/.gitattributes b/.gitattributes index 5931a953edc18af106d4bfcf0562f80cab82c7b9..4b445b8328847f63e80a81a889330344a6099cf1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1313,3 +1313,19 @@ videochat2/lib/python3.10/site-packages/av/container/streams.cpython-310-x86_64- videochat2/lib/python3.10/site-packages/av/error.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videochat2/lib/python3.10/site-packages/av/audio/frame.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videochat2/lib/python3.10/site-packages/av/container/pyio.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_rcont/rcont.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/ncx2_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/beta_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/ncf_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/skewnorm_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/__pycache__/_distn_infrastructure.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/nbinom_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/nct_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/hypergeom_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/invgauss_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videochat2/lib/python3.10/site-packages/scipy/stats/_boost/binom_ufunc.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/videochat2/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618b281ca86e6823f831df21f8e22e3e2903b32c --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30da37d7bcb69e837a546d4023e15680393266f49120253f3c4138fc1adb527c +size 153730 diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/__init__.py b/videochat2/lib/python3.10/site-packages/scipy/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a1417abe144142078b38c45794f73178cec486b8 --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/_fortran.py b/videochat2/lib/python3.10/site-packages/scipy/io/_fortran.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c93c57bcdab3b5a40437a147a384167772c306 --- /dev/null +++ b/videochat2/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(' 0, -n and n if n < 0 + + Parameters + ---------- + n : int + max number one wants to be able to represent + min : int + minimum number of characters to use for the format + + Returns + ------- + res : IntFormat + IntFormat instance with reasonable (see Notes) computed width + + Notes + ----- + Reasonable should be understood as the minimal string length necessary + without losing precision. For example, IntFormat.from_number(1) will + return an IntFormat instance of width 2, so that any 0 and 1 may be + represented as 1-character strings without loss of information. + """ + width = number_digits(n) + 1 + if n < 0: + width += 1 + repeat = 80 // width + return cls(width, min, repeat=repeat) + + def __init__(self, width, min=None, repeat=None): + self.width = width + self.repeat = repeat + self.min = min + + def __repr__(self): + r = "IntFormat(" + if self.repeat: + r += "%d" % self.repeat + r += "I%d" % self.width + if self.min: + r += ".%d" % self.min + return r + ")" + + @property + def fortran_format(self): + r = "(" + if self.repeat: + r += "%d" % self.repeat + r += "I%d" % self.width + if self.min: + r += ".%d" % self.min + return r + ")" + + @property + def python_format(self): + return "%" + str(self.width) + "d" + + +class ExpFormat: + @classmethod + def from_number(cls, n, min=None): + """Given a float number, returns a "reasonable" ExpFormat instance to + represent any number between -n and n. + + Parameters + ---------- + n : float + max number one wants to be able to represent + min : int + minimum number of characters to use for the format + + Returns + ------- + res : ExpFormat + ExpFormat instance with reasonable (see Notes) computed width + + Notes + ----- + Reasonable should be understood as the minimal string length necessary + to avoid losing precision. + """ + # len of one number in exp format: sign + 1|0 + "." + + # number of digit for fractional part + 'E' + sign of exponent + + # len of exponent + finfo = np.finfo(n.dtype) + # Number of digits for fractional part + n_prec = finfo.precision + 1 + # Number of digits for exponential part + n_exp = number_digits(np.max(np.abs([finfo.maxexp, finfo.minexp]))) + width = 1 + 1 + n_prec + 1 + n_exp + 1 + if n < 0: + width += 1 + repeat = int(np.floor(80 / width)) + return cls(width, n_prec, min, repeat=repeat) + + def __init__(self, width, significand, min=None, repeat=None): + """\ + Parameters + ---------- + width : int + number of characters taken by the string (includes space). + """ + self.width = width + self.significand = significand + self.repeat = repeat + self.min = min + + def __repr__(self): + r = "ExpFormat(" + if self.repeat: + r += "%d" % self.repeat + r += "E%d.%d" % (self.width, self.significand) + if self.min: + r += "E%d" % self.min + return r + ")" + + @property + def fortran_format(self): + r = "(" + if self.repeat: + r += "%d" % self.repeat + r += "E%d.%d" % (self.width, self.significand) + if self.min: + r += "E%d" % self.min + return r + ")" + + @property + def python_format(self): + return "%" + str(self.width-1) + "." + str(self.significand) + "E" + + +class Token: + def __init__(self, type, value, pos): + self.type = type + self.value = value + self.pos = pos + + def __str__(self): + return f"""Token('{self.type}', "{self.value}")""" + + def __repr__(self): + return self.__str__() + + +class Tokenizer: + def __init__(self): + self.tokens = list(TOKENS.keys()) + self.res = [re.compile(TOKENS[i]) for i in self.tokens] + + def input(self, s): + self.data = s + self.curpos = 0 + self.len = len(s) + + def next_token(self): + curpos = self.curpos + + while curpos < self.len: + for i, r in enumerate(self.res): + m = r.match(self.data, curpos) + if m is None: + continue + else: + self.curpos = m.end() + return Token(self.tokens[i], m.group(), self.curpos) + raise SyntaxError("Unknown character at position %d (%s)" + % (self.curpos, self.data[curpos])) + + +# Grammar for fortran format: +# format : LPAR format_string RPAR +# format_string : repeated | simple +# repeated : repeat simple +# simple : int_fmt | exp_fmt +# int_fmt : INT_ID width +# exp_fmt : simple_exp_fmt +# simple_exp_fmt : EXP_ID width DOT significand +# extended_exp_fmt : EXP_ID width DOT significand EXP_ID ndigits +# repeat : INT +# width : INT +# significand : INT +# ndigits : INT + +# Naive fortran formatter - parser is hand-made +class FortranFormatParser: + """Parser for Fortran format strings. The parse method returns a *Format + instance. + + Notes + ----- + Only ExpFormat (exponential format for floating values) and IntFormat + (integer format) for now. + """ + def __init__(self): + self.tokenizer = Tokenizer() + + def parse(self, s): + self.tokenizer.input(s) + + tokens = [] + + try: + while True: + t = self.tokenizer.next_token() + if t is None: + break + else: + tokens.append(t) + return self._parse_format(tokens) + except SyntaxError as e: + raise BadFortranFormat(str(e)) from e + + def _get_min(self, tokens): + next = tokens.pop(0) + if not next.type == "DOT": + raise SyntaxError() + next = tokens.pop(0) + return next.value + + def _expect(self, token, tp): + if not token.type == tp: + raise SyntaxError() + + def _parse_format(self, tokens): + if not tokens[0].type == "LPAR": + raise SyntaxError("Expected left parenthesis at position " + "%d (got '%s')" % (0, tokens[0].value)) + elif not tokens[-1].type == "RPAR": + raise SyntaxError("Expected right parenthesis at position " + "%d (got '%s')" % (len(tokens), tokens[-1].value)) + + tokens = tokens[1:-1] + types = [t.type for t in tokens] + if types[0] == "INT": + repeat = int(tokens.pop(0).value) + else: + repeat = None + + next = tokens.pop(0) + if next.type == "INT_ID": + next = self._next(tokens, "INT") + width = int(next.value) + if tokens: + min = int(self._get_min(tokens)) + else: + min = None + return IntFormat(width, min, repeat) + elif next.type == "EXP_ID": + next = self._next(tokens, "INT") + width = int(next.value) + + next = self._next(tokens, "DOT") + + next = self._next(tokens, "INT") + significand = int(next.value) + + if tokens: + next = self._next(tokens, "EXP_ID") + + next = self._next(tokens, "INT") + min = int(next.value) + else: + min = None + return ExpFormat(width, significand, min, repeat) + else: + raise SyntaxError("Invalid formatter type %s" % next.value) + + def _next(self, tokens, tp): + if not len(tokens) > 0: + raise SyntaxError() + next = tokens.pop(0) + self._expect(next, tp) + return next diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py new file mode 100644 index 0000000000000000000000000000000000000000..210982bee2ffa3f84816d6660e8fa9ee933eb6e5 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py @@ -0,0 +1,571 @@ +""" +Implementation of Harwell-Boeing read/write. + +At the moment not the full Harwell-Boeing format is supported. Supported +features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + +""" +# TODO: +# - Add more support (symmetric/complex matrices, non-assembled matrices ?) + +# XXX: reading is reasonably efficient (>= 85 % is in numpy.fromstring), but +# takes a lot of memory. Being faster would require compiled code. +# write is not efficient. Although not a terribly exciting task, +# having reusable facilities to efficiently read/write fortran-formatted files +# would be useful outside this module. + +import warnings + +import numpy as np +from scipy.sparse import csc_matrix +from ._fortran_format_parser import FortranFormatParser, IntFormat, ExpFormat + +__all__ = ["MalformedHeader", "hb_read", "hb_write", "HBInfo", "HBFile", + "HBMatrixType"] + + +class MalformedHeader(Exception): + pass + + +class LineOverflow(Warning): + pass + + +def _nbytes_full(fmt, nlines): + """Return the number of bytes to read to get every full lines for the + given parsed fortran format.""" + return (fmt.repeat * fmt.width + 1) * (nlines - 1) + + +class HBInfo: + @classmethod + def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None): + """Create a HBInfo instance from an existing sparse matrix. + + Parameters + ---------- + m : sparse matrix + the HBInfo instance will derive its parameters from m + title : str + Title to put in the HB header + key : str + Key + mxtype : HBMatrixType + type of the input matrix + fmt : dict + not implemented + + Returns + ------- + hb_info : HBInfo instance + """ + m = m.tocsc(copy=False) + + pointer = m.indptr + indices = m.indices + values = m.data + + nrows, ncols = m.shape + nnon_zeros = m.nnz + + if fmt is None: + # +1 because HB use one-based indexing (Fortran), and we will write + # the indices /pointer as such + pointer_fmt = IntFormat.from_number(np.max(pointer+1)) + indices_fmt = IntFormat.from_number(np.max(indices+1)) + + if values.dtype.kind in np.typecodes["AllFloat"]: + values_fmt = ExpFormat.from_number(-np.max(np.abs(values))) + elif values.dtype.kind in np.typecodes["AllInteger"]: + values_fmt = IntFormat.from_number(-np.max(np.abs(values))) + else: + message = f"type {values.dtype.kind} not implemented yet" + raise NotImplementedError(message) + else: + raise NotImplementedError("fmt argument not supported yet.") + + if mxtype is None: + if not np.isrealobj(values): + raise ValueError("Complex values not supported yet") + if values.dtype.kind in np.typecodes["AllInteger"]: + tp = "integer" + elif values.dtype.kind in np.typecodes["AllFloat"]: + tp = "real" + else: + raise NotImplementedError("type %s for values not implemented" + % values.dtype) + mxtype = HBMatrixType(tp, "unsymmetric", "assembled") + else: + raise ValueError("mxtype argument not handled yet.") + + def _nlines(fmt, size): + nlines = size // fmt.repeat + if nlines * fmt.repeat != size: + nlines += 1 + return nlines + + pointer_nlines = _nlines(pointer_fmt, pointer.size) + indices_nlines = _nlines(indices_fmt, indices.size) + values_nlines = _nlines(values_fmt, values.size) + + total_nlines = pointer_nlines + indices_nlines + values_nlines + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_fmt.fortran_format, indices_fmt.fortran_format, + values_fmt.fortran_format) + + @classmethod + def from_file(cls, fid): + """Create a HBInfo instance from a file object containing a matrix in the + HB format. + + Parameters + ---------- + fid : file-like matrix + File or file-like object containing a matrix in the HB format. + + Returns + ------- + hb_info : HBInfo instance + """ + # First line + line = fid.readline().strip("\n") + if not len(line) > 72: + raise ValueError("Expected at least 72 characters for first line, " + "got: \n%s" % line) + title = line[:72] + key = line[72:] + + # Second line + line = fid.readline().strip("\n") + if not len(line.rstrip()) >= 56: + raise ValueError("Expected at least 56 characters for second line, " + "got: \n%s" % line) + total_nlines = _expect_int(line[:14]) + pointer_nlines = _expect_int(line[14:28]) + indices_nlines = _expect_int(line[28:42]) + values_nlines = _expect_int(line[42:56]) + + rhs_nlines = line[56:72].strip() + if rhs_nlines == '': + rhs_nlines = 0 + else: + rhs_nlines = _expect_int(rhs_nlines) + if not rhs_nlines == 0: + raise ValueError("Only files without right hand side supported for " + "now.") + + # Third line + line = fid.readline().strip("\n") + if not len(line) >= 70: + raise ValueError("Expected at least 72 character for third line, got:\n" + "%s" % line) + + mxtype_s = line[:3].upper() + if not len(mxtype_s) == 3: + raise ValueError("mxtype expected to be 3 characters long") + + mxtype = HBMatrixType.from_fortran(mxtype_s) + if mxtype.value_type not in ["real", "integer"]: + raise ValueError("Only real or integer matrices supported for " + "now (detected %s)" % mxtype) + if not mxtype.structure == "unsymmetric": + raise ValueError("Only unsymmetric matrices supported for " + "now (detected %s)" % mxtype) + if not mxtype.storage == "assembled": + raise ValueError("Only assembled matrices supported for now") + + if not line[3:14] == " " * 11: + raise ValueError("Malformed data for third line: %s" % line) + + nrows = _expect_int(line[14:28]) + ncols = _expect_int(line[28:42]) + nnon_zeros = _expect_int(line[42:56]) + nelementals = _expect_int(line[56:70]) + if not nelementals == 0: + raise ValueError("Unexpected value %d for nltvl (last entry of line 3)" + % nelementals) + + # Fourth line + line = fid.readline().strip("\n") + + ct = line.split() + if not len(ct) == 3: + raise ValueError("Expected 3 formats, got %s" % ct) + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + ct[0], ct[1], ct[2], + rhs_nlines, nelementals) + + def __init__(self, title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_format_str, indices_format_str, values_format_str, + right_hand_sides_nlines=0, nelementals=0): + """Do not use this directly, but the class ctrs (from_* functions).""" + self.title = title + self.key = key + if title is None: + title = "No Title" + if len(title) > 72: + raise ValueError("title cannot be > 72 characters") + + if key is None: + key = "|No Key" + if len(key) > 8: + warnings.warn("key is > 8 characters (key is %s)" % key, + LineOverflow, stacklevel=3) + + self.total_nlines = total_nlines + self.pointer_nlines = pointer_nlines + self.indices_nlines = indices_nlines + self.values_nlines = values_nlines + + parser = FortranFormatParser() + pointer_format = parser.parse(pointer_format_str) + if not isinstance(pointer_format, IntFormat): + raise ValueError("Expected int format for pointer format, got %s" + % pointer_format) + + indices_format = parser.parse(indices_format_str) + if not isinstance(indices_format, IntFormat): + raise ValueError("Expected int format for indices format, got %s" % + indices_format) + + values_format = parser.parse(values_format_str) + if isinstance(values_format, ExpFormat): + if mxtype.value_type not in ["real", "complex"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + values_dtype = np.float64 + elif isinstance(values_format, IntFormat): + if mxtype.value_type not in ["integer"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + # XXX: fortran int -> dtype association ? + values_dtype = int + else: + raise ValueError(f"Unsupported format for values {values_format!r}") + + self.pointer_format = pointer_format + self.indices_format = indices_format + self.values_format = values_format + + self.pointer_dtype = np.int32 + self.indices_dtype = np.int32 + self.values_dtype = values_dtype + + self.pointer_nlines = pointer_nlines + self.pointer_nbytes_full = _nbytes_full(pointer_format, pointer_nlines) + + self.indices_nlines = indices_nlines + self.indices_nbytes_full = _nbytes_full(indices_format, indices_nlines) + + self.values_nlines = values_nlines + self.values_nbytes_full = _nbytes_full(values_format, values_nlines) + + self.nrows = nrows + self.ncols = ncols + self.nnon_zeros = nnon_zeros + self.nelementals = nelementals + self.mxtype = mxtype + + def dump(self): + """Gives the header corresponding to this instance as a string.""" + header = [self.title.ljust(72) + self.key.ljust(8)] + + header.append("%14d%14d%14d%14d" % + (self.total_nlines, self.pointer_nlines, + self.indices_nlines, self.values_nlines)) + header.append("%14s%14d%14d%14d%14d" % + (self.mxtype.fortran_format.ljust(14), self.nrows, + self.ncols, self.nnon_zeros, 0)) + + pffmt = self.pointer_format.fortran_format + iffmt = self.indices_format.fortran_format + vffmt = self.values_format.fortran_format + header.append("%16s%16s%20s" % + (pffmt.ljust(16), iffmt.ljust(16), vffmt.ljust(20))) + return "\n".join(header) + + +def _expect_int(value, msg=None): + try: + return int(value) + except ValueError as e: + if msg is None: + msg = "Expected an int, got %s" + raise ValueError(msg % value) from e + + +def _read_hb_data(content, header): + # XXX: look at a way to reduce memory here (big string creation) + ptr_string = "".join([content.read(header.pointer_nbytes_full), + content.readline()]) + ptr = np.fromstring(ptr_string, + dtype=int, sep=' ') + + ind_string = "".join([content.read(header.indices_nbytes_full), + content.readline()]) + ind = np.fromstring(ind_string, + dtype=int, sep=' ') + + val_string = "".join([content.read(header.values_nbytes_full), + content.readline()]) + val = np.fromstring(val_string, + dtype=header.values_dtype, sep=' ') + + try: + return csc_matrix((val, ind-1, ptr-1), + shape=(header.nrows, header.ncols)) + except ValueError as e: + raise e + + +def _write_data(m, fid, header): + m = m.tocsc(copy=False) + + def write_array(f, ar, nlines, fmt): + # ar_nlines is the number of full lines, n is the number of items per + # line, ffmt the fortran format + pyfmt = fmt.python_format + pyfmt_full = pyfmt * fmt.repeat + + # for each array to write, we first write the full lines, and special + # case for partial line + full = ar[:(nlines - 1) * fmt.repeat] + for row in full.reshape((nlines-1, fmt.repeat)): + f.write(pyfmt_full % tuple(row) + "\n") + nremain = ar.size - full.size + if nremain > 0: + f.write((pyfmt * nremain) % tuple(ar[ar.size - nremain:]) + "\n") + + fid.write(header.dump()) + fid.write("\n") + # +1 is for Fortran one-based indexing + write_array(fid, m.indptr+1, header.pointer_nlines, + header.pointer_format) + write_array(fid, m.indices+1, header.indices_nlines, + header.indices_format) + write_array(fid, m.data, header.values_nlines, + header.values_format) + + +class HBMatrixType: + """Class to hold the matrix type.""" + # q2f* translates qualified names to Fortran character + _q2f_type = { + "real": "R", + "complex": "C", + "pattern": "P", + "integer": "I", + } + _q2f_structure = { + "symmetric": "S", + "unsymmetric": "U", + "hermitian": "H", + "skewsymmetric": "Z", + "rectangular": "R" + } + _q2f_storage = { + "assembled": "A", + "elemental": "E", + } + + _f2q_type = {j: i for i, j in _q2f_type.items()} + _f2q_structure = {j: i for i, j in _q2f_structure.items()} + _f2q_storage = {j: i for i, j in _q2f_storage.items()} + + @classmethod + def from_fortran(cls, fmt): + if not len(fmt) == 3: + raise ValueError("Fortran format for matrix type should be 3 " + "characters long") + try: + value_type = cls._f2q_type[fmt[0]] + structure = cls._f2q_structure[fmt[1]] + storage = cls._f2q_storage[fmt[2]] + return cls(value_type, structure, storage) + except KeyError as e: + raise ValueError("Unrecognized format %s" % fmt) from e + + def __init__(self, value_type, structure, storage="assembled"): + self.value_type = value_type + self.structure = structure + self.storage = storage + + if value_type not in self._q2f_type: + raise ValueError("Unrecognized type %s" % value_type) + if structure not in self._q2f_structure: + raise ValueError("Unrecognized structure %s" % structure) + if storage not in self._q2f_storage: + raise ValueError("Unrecognized storage %s" % storage) + + @property + def fortran_format(self): + return self._q2f_type[self.value_type] + \ + self._q2f_structure[self.structure] + \ + self._q2f_storage[self.storage] + + def __repr__(self): + return f"HBMatrixType({self.value_type}, {self.structure}, {self.storage})" + + +class HBFile: + def __init__(self, file, hb_info=None): + """Create a HBFile instance. + + Parameters + ---------- + file : file-object + StringIO work as well + hb_info : HBInfo, optional + Should be given as an argument for writing, in which case the file + should be writable. + """ + self._fid = file + if hb_info is None: + self._hb_info = HBInfo.from_file(file) + else: + #raise OSError("file %s is not writable, and hb_info " + # "was given." % file) + self._hb_info = hb_info + + @property + def title(self): + return self._hb_info.title + + @property + def key(self): + return self._hb_info.key + + @property + def type(self): + return self._hb_info.mxtype.value_type + + @property + def structure(self): + return self._hb_info.mxtype.structure + + @property + def storage(self): + return self._hb_info.mxtype.storage + + def read_matrix(self): + return _read_hb_data(self._fid, self._hb_info) + + def write_matrix(self, m): + return _write_data(m, self._fid, self._hb_info) + + +def hb_read(path_or_open_file): + """Read HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before reading. + + Returns + ------- + data : scipy.sparse.csc_matrix instance + The data read from the HB file as a sparse matrix. + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_matrix, eye + >>> data = csr_matrix(eye(3)) # create a sparse matrix + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb")) # read a hb file + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + + """ + def _get_matrix(fid): + hb = HBFile(fid) + return hb.read_matrix() + + if hasattr(path_or_open_file, 'read'): + return _get_matrix(path_or_open_file) + else: + with open(path_or_open_file) as f: + return _get_matrix(f) + + +def hb_write(path_or_open_file, m, hb_info=None): + """Write HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before writing. + m : sparse-matrix + the sparse matrix to write + hb_info : HBInfo + contains the meta-data for write + + Returns + ------- + None + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_matrix, eye + >>> data = csr_matrix(eye(3)) # create a sparse matrix + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb")) # read a hb file + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + + """ + m = m.tocsc(copy=False) + + if hb_info is None: + hb_info = HBInfo.from_data(m) + + def _set_matrix(fid): + hb = HBFile(fid, hb_info) + return hb.write_matrix(m) + + if hasattr(path_or_open_file, 'write'): + return _set_matrix(path_or_open_file) + else: + with open(path_or_open_file, 'w') as f: + return _set_matrix(f) diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__init__.py b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b32e9d3ba97ff7f29665c14c9535a66c11ae63b5 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b25d0f5edd2c473565038bf82026b9bd53a42fe9 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96ed337f20f8b23477cbda149d3358af04d6fda4 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py new file mode 100644 index 0000000000000000000000000000000000000000..53384ca06d16c2b4ef2d6b19d985d8402439207b --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py @@ -0,0 +1,74 @@ +import numpy as np + +from numpy.testing import assert_equal +from pytest import raises as assert_raises + +from scipy.io._harwell_boeing import ( + FortranFormatParser, IntFormat, ExpFormat, BadFortranFormat) + + +class TestFortranFormatParser: + def setup_method(self): + self.parser = FortranFormatParser() + + def _test_equal(self, format, ref): + ret = self.parser.parse(format) + assert_equal(ret.__dict__, ref.__dict__) + + def test_simple_int(self): + self._test_equal("(I4)", IntFormat(4)) + + def test_simple_repeated_int(self): + self._test_equal("(3I4)", IntFormat(4, repeat=3)) + + def test_simple_exp(self): + self._test_equal("(E4.3)", ExpFormat(4, 3)) + + def test_exp_exp(self): + self._test_equal("(E8.3E3)", ExpFormat(8, 3, 3)) + + def test_repeat_exp(self): + self._test_equal("(2E4.3)", ExpFormat(4, 3, repeat=2)) + + def test_repeat_exp_exp(self): + self._test_equal("(2E8.3E3)", ExpFormat(8, 3, 3, repeat=2)) + + def test_wrong_formats(self): + def _test_invalid(bad_format): + assert_raises(BadFortranFormat, lambda: self.parser.parse(bad_format)) + _test_invalid("I4") + _test_invalid("(E4)") + _test_invalid("(E4.)") + _test_invalid("(E4.E3)") + + +class TestIntFormat: + def test_to_fortran(self): + f = [IntFormat(10), IntFormat(12, 10), IntFormat(12, 10, 3)] + res = ["(I10)", "(I12.10)", "(3I12.10)"] + + for i, j in zip(f, res): + assert_equal(i.fortran_format, j) + + def test_from_number(self): + f = [10, -12, 123456789] + r_f = [IntFormat(3, repeat=26), IntFormat(4, repeat=20), + IntFormat(10, repeat=8)] + for i, j in zip(f, r_f): + assert_equal(IntFormat.from_number(i).__dict__, j.__dict__) + + +class TestExpFormat: + def test_to_fortran(self): + f = [ExpFormat(10, 5), ExpFormat(12, 10), ExpFormat(12, 10, min=3), + ExpFormat(10, 5, repeat=3)] + res = ["(E10.5)", "(E12.10)", "(E12.10E3)", "(3E10.5)"] + + for i, j in zip(f, res): + assert_equal(i.fortran_format, j) + + def test_from_number(self): + f = np.array([1.0, -1.2]) + r_f = [ExpFormat(24, 16, repeat=3), ExpFormat(25, 16, repeat=3)] + for i, j in zip(f, r_f): + assert_equal(ExpFormat.from_number(i).__dict__, j.__dict__) diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py new file mode 100644 index 0000000000000000000000000000000000000000..a4cf88230a09d8ae01a66427bc4f6f860737e80a --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py @@ -0,0 +1,65 @@ +from io import StringIO +import tempfile + +import numpy as np + +from numpy.testing import assert_equal, \ + assert_array_almost_equal_nulp + +from scipy.sparse import coo_matrix, csc_matrix, rand + +from scipy.io import hb_read, hb_write + + +SIMPLE = """\ +No Title |No Key + 9 4 1 4 +RUA 100 100 10 0 +(26I3) (26I3) (3E23.15) +1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9 +9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11 +37 71 89 18 30 45 70 19 25 52 +2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01 +6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01 +4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01 +6.912334991524289e-01 +""" + +SIMPLE_MATRIX = coo_matrix( + ((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799, + 0.0661749042483, 0.887037034319, 0.419647859016, + 0.564960307211, 0.993442388709, 0.691233499152,), + (np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51], + [0, 4, 58, 61, 61, 72, 72, 73, 99, 99]])))) + + +def assert_csc_almost_equal(r, l): + r = csc_matrix(r) + l = csc_matrix(l) + assert_equal(r.indptr, l.indptr) + assert_equal(r.indices, l.indices) + assert_array_almost_equal_nulp(r.data, l.data, 10000) + + +class TestHBReader: + def test_simple(self): + m = hb_read(StringIO(SIMPLE)) + assert_csc_almost_equal(m, SIMPLE_MATRIX) + + +class TestHBReadWrite: + + def check_save_load(self, value): + with tempfile.NamedTemporaryFile(mode='w+t') as file: + hb_write(file, value) + file.file.seek(0) + value_loaded = hb_read(file) + assert_csc_almost_equal(value, value_loaded) + + def test_simple(self): + random_matrix = rand(10, 100, 0.1) + for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'): + matrix = random_matrix.asformat(matrix_format, copy=False) + self.check_save_load(matrix) diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_idl.py b/videochat2/lib/python3.10/site-packages/scipy/io/_idl.py new file mode 100644 index 0000000000000000000000000000000000000000..6d4e95718788a9e3105fe06a5fab3312a0877fcf --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/_idl.py @@ -0,0 +1,918 @@ +# IDLSave - a python module to read IDL 'save' files +# Copyright (c) 2010 Thomas P. Robitaille + +# Many thanks to Craig Markwardt for publishing the Unofficial Format +# Specification for IDL .sav files, without which this Python module would not +# exist (http://cow.physics.wisc.edu/~craigm/idl/savefmt). + +# This code was developed by with permission from ITT Visual Information +# Systems. IDL(r) is a registered trademark of ITT Visual Information Systems, +# Inc. for their Interactive Data Language software. + +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +__all__ = ['readsav'] + +import struct +import numpy as np +import tempfile +import zlib +import warnings + +# Define the different data types that can be found in an IDL save file +DTYPE_DICT = {1: '>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/videochat2/lib/python3.10/site-packages/scipy/io/_mmio.py b/videochat2/lib/python3.10/site-packages/scipy/io/_mmio.py new file mode 100644 index 0000000000000000000000000000000000000000..d39e03551b14cd22aa850846890fc313a8be7795 --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/_netcdf.py b/videochat2/lib/python3.10/site-packages/scipy/io/_netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8b576b8612334169834f58ec2ae7e068f653cd --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/_netcdf.py @@ -0,0 +1,1095 @@ +""" +NetCDF reader/writer module. + +This module is used to read and create NetCDF files. NetCDF files are +accessed through the `netcdf_file` object. Data written to and from NetCDF +files are contained in `netcdf_variable` objects. Attributes are given +as member variables of the `netcdf_file` and `netcdf_variable` objects. + +This module implements the Scientific.IO.NetCDF API to read and create +NetCDF files. The same API is also used in the PyNIO and pynetcdf +modules, allowing these modules to be used interchangeably when working +with NetCDF files. + +Only NetCDF3 is supported here; for NetCDF4 see +`netCDF4-python `__, +which has a similar API. + +""" + +# TODO: +# * properly implement ``_FillValue``. +# * fix character variables. +# * implement PAGESIZE for Python 2.6? + +# The Scientific.IO.NetCDF API allows attributes to be added directly to +# instances of ``netcdf_file`` and ``netcdf_variable``. To differentiate +# between user-set attributes and instance attributes, user-set attributes +# are automatically stored in the ``_attributes`` attribute by overloading +#``__setattr__``. This is the reason why the code sometimes uses +#``obj.__dict__['key'] = value``, instead of simply ``obj.key = value``; +# otherwise the key would be inserted into userspace attributes. + + +__all__ = ['netcdf_file', 'netcdf_variable'] + + +import warnings +import weakref +from operator import mul +from platform import python_implementation + +import mmap as mm + +import numpy as np +from numpy import frombuffer, dtype, empty, array, asarray +from numpy import little_endian as LITTLE_ENDIAN +from functools import reduce + + +IS_PYPY = python_implementation() == 'PyPy' + +ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00' +ZERO = b'\x00\x00\x00\x00' +NC_BYTE = b'\x00\x00\x00\x01' +NC_CHAR = b'\x00\x00\x00\x02' +NC_SHORT = b'\x00\x00\x00\x03' +NC_INT = b'\x00\x00\x00\x04' +NC_FLOAT = b'\x00\x00\x00\x05' +NC_DOUBLE = b'\x00\x00\x00\x06' +NC_DIMENSION = b'\x00\x00\x00\n' +NC_VARIABLE = b'\x00\x00\x00\x0b' +NC_ATTRIBUTE = b'\x00\x00\x00\x0c' +FILL_BYTE = b'\x81' +FILL_CHAR = b'\x00' +FILL_SHORT = b'\x80\x01' +FILL_INT = b'\x80\x00\x00\x01' +FILL_FLOAT = b'\x7C\xF0\x00\x00' +FILL_DOUBLE = b'\x47\x9E\x00\x00\x00\x00\x00\x00' + +TYPEMAP = {NC_BYTE: ('b', 1), + NC_CHAR: ('c', 1), + NC_SHORT: ('h', 2), + NC_INT: ('i', 4), + NC_FLOAT: ('f', 4), + NC_DOUBLE: ('d', 8)} + +FILLMAP = {NC_BYTE: FILL_BYTE, + NC_CHAR: FILL_CHAR, + NC_SHORT: FILL_SHORT, + NC_INT: FILL_INT, + NC_FLOAT: FILL_FLOAT, + NC_DOUBLE: FILL_DOUBLE} + +REVERSE = {('b', 1): NC_BYTE, + ('B', 1): NC_CHAR, + ('c', 1): NC_CHAR, + ('h', 2): NC_SHORT, + ('i', 4): NC_INT, + ('f', 4): NC_FLOAT, + ('d', 8): NC_DOUBLE, + + # these come from asarray(1).dtype.char and asarray('foo').dtype.char, + # used when getting the types from generic attributes. + ('l', 4): NC_INT, + ('S', 1): NC_CHAR} + + +class netcdf_file: + """ + A file object for NetCDF data. + + A `netcdf_file` object has two standard attributes: `dimensions` and + `variables`. The values of both are dictionaries, mapping dimension + names to their associated lengths and variable names to variables, + respectively. Application programs should never modify these + dictionaries. + + All other attributes correspond to global attributes defined in the + NetCDF file. Global file attributes are created by assigning to an + attribute of the `netcdf_file` object. + + Parameters + ---------- + filename : string or file-like + string -> filename + mode : {'r', 'w', 'a'}, optional + read-write-append mode, default is 'r' + mmap : None or bool, optional + Whether to mmap `filename` when reading. Default is True + when `filename` is a file name, False when `filename` is a + file-like object. Note that when mmap is in use, data arrays + returned refer directly to the mmapped data on disk, and the + file cannot be closed as long as references to it exist. + version : {1, 2}, optional + version of netcdf to read / write, where 1 means *Classic + format* and 2 means *64-bit offset format*. Default is 1. See + `here `__ + for more info. + maskandscale : bool, optional + Whether to automatically scale and/or mask data based on attributes. + Default is False. + + Notes + ----- + The major advantage of this module over other modules is that it doesn't + require the code to be linked to the NetCDF libraries. This module is + derived from `pupynere `_. + + NetCDF files are a self-describing binary data format. The file contains + metadata that describes the dimensions and variables in the file. More + details about NetCDF files can be found `here + `__. There + are three main sections to a NetCDF data structure: + + 1. Dimensions + 2. Variables + 3. Attributes + + The dimensions section records the name and length of each dimension used + by the variables. The variables would then indicate which dimensions it + uses and any attributes such as data units, along with containing the data + values for the variable. It is good practice to include a + variable that is the same name as a dimension to provide the values for + that axes. Lastly, the attributes section would contain additional + information such as the name of the file creator or the instrument used to + collect the data. + + When writing data to a NetCDF file, there is often the need to indicate the + 'record dimension'. A record dimension is the unbounded dimension for a + variable. For example, a temperature variable may have dimensions of + latitude, longitude and time. If one wants to add more temperature data to + the NetCDF file as time progresses, then the temperature variable should + have the time dimension flagged as the record dimension. + + In addition, the NetCDF file header contains the position of the data in + the file, so access can be done in an efficient manner without loading + unnecessary data into memory. It uses the ``mmap`` module to create + Numpy arrays mapped to the data on disk, for the same purpose. + + Note that when `netcdf_file` is used to open a file with mmap=True + (default for read-only), arrays returned by it refer to data + directly on the disk. The file should not be closed, and cannot be cleanly + closed when asked, if such arrays are alive. You may want to copy data arrays + obtained from mmapped Netcdf file if they are to be processed after the file + is closed, see the example below. + + Examples + -------- + To create a NetCDF file: + + >>> from scipy.io import netcdf_file + >>> import numpy as np + >>> f = netcdf_file('simple.nc', 'w') + >>> f.history = 'Created for a test' + >>> f.createDimension('time', 10) + >>> time = f.createVariable('time', 'i', ('time',)) + >>> time[:] = np.arange(10) + >>> time.units = 'days since 2008-01-01' + >>> f.close() + + Note the assignment of ``arange(10)`` to ``time[:]``. Exposing the slice + of the time variable allows for the data to be set in the object, rather + than letting ``arange(10)`` overwrite the ``time`` variable. + + To read the NetCDF file we just created: + + >>> from scipy.io import netcdf_file + >>> f = netcdf_file('simple.nc', 'r') + >>> print(f.history) + b'Created for a test' + >>> time = f.variables['time'] + >>> print(time.units) + b'days since 2008-01-01' + >>> print(time.shape) + (10,) + >>> print(time[-1]) + 9 + + NetCDF files, when opened read-only, return arrays that refer + directly to memory-mapped data on disk: + + >>> data = time[:] + + If the data is to be processed after the file is closed, it needs + to be copied to main memory: + + >>> data = time[:].copy() + >>> del time + >>> f.close() + >>> data.mean() + 4.5 + + A NetCDF file can also be used as context manager: + + >>> from scipy.io import netcdf_file + >>> with netcdf_file('simple.nc', 'r') as f: + ... print(f.history) + b'Created for a test' + + """ + def __init__(self, filename, mode='r', mmap=None, version=1, + maskandscale=False): + """Initialize netcdf_file from fileobj (str or file-like).""" + if mode not in 'rwa': + raise ValueError("Mode must be either 'r', 'w' or 'a'.") + + if hasattr(filename, 'seek'): # file-like + self.fp = filename + self.filename = 'None' + if mmap is None: + mmap = False + elif mmap and not hasattr(filename, 'fileno'): + raise ValueError('Cannot use file object for mmap') + else: # maybe it's a string + self.filename = filename + omode = 'r+' if mode == 'a' else mode + self.fp = open(self.filename, '%sb' % omode) + if mmap is None: + # Mmapped files on PyPy cannot be usually closed + # before the GC runs, so it's better to use mmap=False + # as the default. + mmap = (not IS_PYPY) + + if mode != 'r': + # Cannot read write-only files + mmap = False + + self.use_mmap = mmap + self.mode = mode + self.version_byte = version + self.maskandscale = maskandscale + + self.dimensions = {} + self.variables = {} + + self._dims = [] + self._recs = 0 + self._recsize = 0 + + self._mm = None + self._mm_buf = None + if self.use_mmap: + self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ) + self._mm_buf = np.frombuffer(self._mm, dtype=np.int8) + + self._attributes = {} + + if mode in 'ra': + self._read() + + def __setattr__(self, attr, value): + # Store user defined attributes in a separate dict, + # so we can save them to file later. + try: + self._attributes[attr] = value + except AttributeError: + pass + self.__dict__[attr] = value + + def close(self): + """Closes the NetCDF file.""" + if hasattr(self, 'fp') and not self.fp.closed: + try: + self.flush() + finally: + self.variables = {} + if self._mm_buf is not None: + ref = weakref.ref(self._mm_buf) + self._mm_buf = None + if ref() is None: + # self._mm_buf is gc'd, and we can close the mmap + self._mm.close() + else: + # we cannot close self._mm, since self._mm_buf is + # alive and there may still be arrays referring to it + warnings.warn( + "Cannot close a netcdf_file opened with mmap=True, when " + "netcdf_variables or arrays referring to its data still " + "exist. All data arrays obtained from such files refer " + "directly to data on disk, and must be copied before the " + "file can be cleanly closed. " + "(See netcdf_file docstring for more information on mmap.)", + category=RuntimeWarning, stacklevel=2, + ) + self._mm = None + self.fp.close() + __del__ = close + + def __enter__(self): + return self + + def __exit__(self, type, value, traceback): + self.close() + + def createDimension(self, name, length): + """ + Adds a dimension to the Dimension section of the NetCDF data structure. + + Note that this function merely adds a new dimension that the variables can + reference. The values for the dimension, if desired, should be added as + a variable using `createVariable`, referring to this dimension. + + Parameters + ---------- + name : str + Name of the dimension (Eg, 'lat' or 'time'). + length : int + Length of the dimension. + + See Also + -------- + createVariable + + """ + if length is None and self._dims: + raise ValueError("Only first dimension may be unlimited!") + + self.dimensions[name] = length + self._dims.append(name) + + def createVariable(self, name, type, dimensions): + """ + Create an empty variable for the `netcdf_file` object, specifying its data + type and the dimensions it uses. + + Parameters + ---------- + name : str + Name of the new variable. + type : dtype or str + Data type of the variable. + dimensions : sequence of str + List of the dimension names used by the variable, in the desired order. + + Returns + ------- + variable : netcdf_variable + The newly created ``netcdf_variable`` object. + This object has also been added to the `netcdf_file` object as well. + + See Also + -------- + createDimension + + Notes + ----- + Any dimensions to be used by the variable should already exist in the + NetCDF data structure or should be created by `createDimension` prior to + creating the NetCDF variable. + + """ + shape = tuple([self.dimensions[dim] for dim in dimensions]) + shape_ = tuple([dim or 0 for dim in shape]) # replace None with 0 for NumPy + + type = dtype(type) + typecode, size = type.char, type.itemsize + if (typecode, size) not in REVERSE: + raise ValueError("NetCDF 3 does not support type %s" % type) + + # convert to big endian always for NetCDF 3 + data = empty(shape_, dtype=type.newbyteorder("B")) + self.variables[name] = netcdf_variable( + data, typecode, size, shape, dimensions, + maskandscale=self.maskandscale) + return self.variables[name] + + def flush(self): + """ + Perform a sync-to-disk flush if the `netcdf_file` object is in write mode. + + See Also + -------- + sync : Identical function + + """ + if hasattr(self, 'mode') and self.mode in 'wa': + self._write() + sync = flush + + def _write(self): + self.fp.seek(0) + self.fp.write(b'CDF') + self.fp.write(array(self.version_byte, '>b').tobytes()) + + # Write headers and data. + self._write_numrecs() + self._write_dim_array() + self._write_gatt_array() + self._write_var_array() + + def _write_numrecs(self): + # Get highest record count from all record variables. + for var in self.variables.values(): + if var.isrec and len(var.data) > self._recs: + self.__dict__['_recs'] = len(var.data) + self._pack_int(self._recs) + + def _write_dim_array(self): + if self.dimensions: + self.fp.write(NC_DIMENSION) + self._pack_int(len(self.dimensions)) + for name in self._dims: + self._pack_string(name) + length = self.dimensions[name] + self._pack_int(length or 0) # replace None with 0 for record dimension + else: + self.fp.write(ABSENT) + + def _write_gatt_array(self): + self._write_att_array(self._attributes) + + def _write_att_array(self, attributes): + if attributes: + self.fp.write(NC_ATTRIBUTE) + self._pack_int(len(attributes)) + for name, values in attributes.items(): + self._pack_string(name) + self._write_att_values(values) + else: + self.fp.write(ABSENT) + + def _write_var_array(self): + if self.variables: + self.fp.write(NC_VARIABLE) + self._pack_int(len(self.variables)) + + # Sort variable names non-recs first, then recs. + def sortkey(n): + v = self.variables[n] + if v.isrec: + return (-1,) + return v._shape + variables = sorted(self.variables, key=sortkey, reverse=True) + + # Set the metadata for all variables. + for name in variables: + self._write_var_metadata(name) + # Now that we have the metadata, we know the vsize of + # each record variable, so we can calculate recsize. + self.__dict__['_recsize'] = sum([ + var._vsize for var in self.variables.values() + if var.isrec]) + # Set the data for all variables. + for name in variables: + self._write_var_data(name) + else: + self.fp.write(ABSENT) + + def _write_var_metadata(self, name): + var = self.variables[name] + + self._pack_string(name) + self._pack_int(len(var.dimensions)) + for dimname in var.dimensions: + dimid = self._dims.index(dimname) + self._pack_int(dimid) + + self._write_att_array(var._attributes) + + nc_type = REVERSE[var.typecode(), var.itemsize()] + self.fp.write(nc_type) + + if not var.isrec: + vsize = var.data.size * var.data.itemsize + vsize += -vsize % 4 + else: # record variable + try: + vsize = var.data[0].size * var.data.itemsize + except IndexError: + vsize = 0 + rec_vars = len([v for v in self.variables.values() + if v.isrec]) + if rec_vars > 1: + vsize += -vsize % 4 + self.variables[name].__dict__['_vsize'] = vsize + self._pack_int(vsize) + + # Pack a bogus begin, and set the real value later. + self.variables[name].__dict__['_begin'] = self.fp.tell() + self._pack_begin(0) + + def _write_var_data(self, name): + var = self.variables[name] + + # Set begin in file header. + the_beguine = self.fp.tell() + self.fp.seek(var._begin) + self._pack_begin(the_beguine) + self.fp.seek(the_beguine) + + # Write data. + if not var.isrec: + self.fp.write(var.data.tobytes()) + count = var.data.size * var.data.itemsize + self._write_var_padding(var, var._vsize - count) + else: # record variable + # Handle rec vars with shape[0] < nrecs. + if self._recs > len(var.data): + shape = (self._recs,) + var.data.shape[1:] + # Resize in-place does not always work since + # the array might not be single-segment + try: + var.data.resize(shape) + except ValueError: + dtype = var.data.dtype + var.__dict__['data'] = np.resize(var.data, shape).astype(dtype) + + pos0 = pos = self.fp.tell() + for rec in var.data: + # Apparently scalars cannot be converted to big endian. If we + # try to convert a ``=i4`` scalar to, say, '>i4' the dtype + # will remain as ``=i4``. + if not rec.shape and (rec.dtype.byteorder == '<' or + (rec.dtype.byteorder == '=' and LITTLE_ENDIAN)): + rec = rec.byteswap() + self.fp.write(rec.tobytes()) + # Padding + count = rec.size * rec.itemsize + self._write_var_padding(var, var._vsize - count) + pos += self._recsize + self.fp.seek(pos) + self.fp.seek(pos0 + var._vsize) + + def _write_var_padding(self, var, size): + encoded_fill_value = var._get_encoded_fill_value() + num_fills = size // len(encoded_fill_value) + self.fp.write(encoded_fill_value * num_fills) + + def _write_att_values(self, values): + if hasattr(values, 'dtype'): + nc_type = REVERSE[values.dtype.char, values.dtype.itemsize] + else: + types = [(int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR)] + + # bytes index into scalars in py3k. Check for "string" types + if isinstance(values, (str, bytes)): + sample = values + else: + try: + sample = values[0] # subscriptable? + except TypeError: + sample = values # scalar + + for class_, nc_type in types: + if isinstance(sample, class_): + break + + typecode, size = TYPEMAP[nc_type] + dtype_ = '>%s' % typecode + # asarray() dies with bytes and '>c' in py3k. Change to 'S' + dtype_ = 'S' if dtype_ == '>c' else dtype_ + + values = asarray(values, dtype=dtype_) + + self.fp.write(nc_type) + + if values.dtype.char == 'S': + nelems = values.itemsize + else: + nelems = values.size + self._pack_int(nelems) + + if not values.shape and (values.dtype.byteorder == '<' or + (values.dtype.byteorder == '=' and LITTLE_ENDIAN)): + values = values.byteswap() + self.fp.write(values.tobytes()) + count = values.size * values.itemsize + self.fp.write(b'\x00' * (-count % 4)) # pad + + def _read(self): + # Check magic bytes and version + magic = self.fp.read(3) + if not magic == b'CDF': + raise TypeError("Error: %s is not a valid NetCDF 3 file" % + self.filename) + self.__dict__['version_byte'] = frombuffer(self.fp.read(1), '>b')[0] + + # Read file headers and set data. + self._read_numrecs() + self._read_dim_array() + self._read_gatt_array() + self._read_var_array() + + def _read_numrecs(self): + self.__dict__['_recs'] = self._unpack_int() + + def _read_dim_array(self): + header = self.fp.read(4) + if header not in [ZERO, NC_DIMENSION]: + raise ValueError("Unexpected header.") + count = self._unpack_int() + + for dim in range(count): + name = self._unpack_string().decode('latin1') + length = self._unpack_int() or None # None for record dimension + self.dimensions[name] = length + self._dims.append(name) # preserve order + + def _read_gatt_array(self): + for k, v in self._read_att_array().items(): + self.__setattr__(k, v) + + def _read_att_array(self): + header = self.fp.read(4) + if header not in [ZERO, NC_ATTRIBUTE]: + raise ValueError("Unexpected header.") + count = self._unpack_int() + + attributes = {} + for attr in range(count): + name = self._unpack_string().decode('latin1') + attributes[name] = self._read_att_values() + return attributes + + def _read_var_array(self): + header = self.fp.read(4) + if header not in [ZERO, NC_VARIABLE]: + raise ValueError("Unexpected header.") + + begin = 0 + dtypes = {'names': [], 'formats': []} + rec_vars = [] + count = self._unpack_int() + for var in range(count): + (name, dimensions, shape, attributes, + typecode, size, dtype_, begin_, vsize) = self._read_var() + # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html + # Note that vsize is the product of the dimension lengths + # (omitting the record dimension) and the number of bytes + # per value (determined from the type), increased to the + # next multiple of 4, for each variable. If a record + # variable, this is the amount of space per record. The + # netCDF "record size" is calculated as the sum of the + # vsize's of all the record variables. + # + # The vsize field is actually redundant, because its value + # may be computed from other information in the header. The + # 32-bit vsize field is not large enough to contain the size + # of variables that require more than 2^32 - 4 bytes, so + # 2^32 - 1 is used in the vsize field for such variables. + if shape and shape[0] is None: # record variable + rec_vars.append(name) + # The netCDF "record size" is calculated as the sum of + # the vsize's of all the record variables. + self.__dict__['_recsize'] += vsize + if begin == 0: + begin = begin_ + dtypes['names'].append(name) + dtypes['formats'].append(str(shape[1:]) + dtype_) + + # Handle padding with a virtual variable. + if typecode in 'bch': + actual_size = reduce(mul, (1,) + shape[1:]) * size + padding = -actual_size % 4 + if padding: + dtypes['names'].append('_padding_%d' % var) + dtypes['formats'].append('(%d,)>b' % padding) + + # Data will be set later. + data = None + else: # not a record variable + # Calculate size to avoid problems with vsize (above) + a_size = reduce(mul, shape, 1) * size + if self.use_mmap: + data = self._mm_buf[begin_:begin_+a_size].view(dtype=dtype_) + data.shape = shape + else: + pos = self.fp.tell() + self.fp.seek(begin_) + data = frombuffer(self.fp.read(a_size), dtype=dtype_ + ).copy() + data.shape = shape + self.fp.seek(pos) + + # Add variable. + self.variables[name] = netcdf_variable( + data, typecode, size, shape, dimensions, attributes, + maskandscale=self.maskandscale) + + if rec_vars: + # Remove padding when only one record variable. + if len(rec_vars) == 1: + dtypes['names'] = dtypes['names'][:1] + dtypes['formats'] = dtypes['formats'][:1] + + # Build rec array. + if self.use_mmap: + buf = self._mm_buf[begin:begin+self._recs*self._recsize] + rec_array = buf.view(dtype=dtypes) + rec_array.shape = (self._recs,) + else: + pos = self.fp.tell() + self.fp.seek(begin) + rec_array = frombuffer(self.fp.read(self._recs*self._recsize), + dtype=dtypes).copy() + rec_array.shape = (self._recs,) + self.fp.seek(pos) + + for var in rec_vars: + self.variables[var].__dict__['data'] = rec_array[var] + + def _read_var(self): + name = self._unpack_string().decode('latin1') + dimensions = [] + shape = [] + dims = self._unpack_int() + + for i in range(dims): + dimid = self._unpack_int() + dimname = self._dims[dimid] + dimensions.append(dimname) + dim = self.dimensions[dimname] + shape.append(dim) + dimensions = tuple(dimensions) + shape = tuple(shape) + + attributes = self._read_att_array() + nc_type = self.fp.read(4) + vsize = self._unpack_int() + begin = [self._unpack_int, self._unpack_int64][self.version_byte-1]() + + typecode, size = TYPEMAP[nc_type] + dtype_ = '>%s' % typecode + + return name, dimensions, shape, attributes, typecode, size, dtype_, begin, vsize + + def _read_att_values(self): + nc_type = self.fp.read(4) + n = self._unpack_int() + + typecode, size = TYPEMAP[nc_type] + + count = n*size + values = self.fp.read(int(count)) + self.fp.read(-count % 4) # read padding + + if typecode != 'c': + values = frombuffer(values, dtype='>%s' % typecode).copy() + if values.shape == (1,): + values = values[0] + else: + values = values.rstrip(b'\x00') + return values + + def _pack_begin(self, begin): + if self.version_byte == 1: + self._pack_int(begin) + elif self.version_byte == 2: + self._pack_int64(begin) + + def _pack_int(self, value): + self.fp.write(array(value, '>i').tobytes()) + _pack_int32 = _pack_int + + def _unpack_int(self): + return int(frombuffer(self.fp.read(4), '>i')[0]) + _unpack_int32 = _unpack_int + + def _pack_int64(self, value): + self.fp.write(array(value, '>q').tobytes()) + + def _unpack_int64(self): + return frombuffer(self.fp.read(8), '>q')[0] + + def _pack_string(self, s): + count = len(s) + self._pack_int(count) + self.fp.write(s.encode('latin1')) + self.fp.write(b'\x00' * (-count % 4)) # pad + + def _unpack_string(self): + count = self._unpack_int() + s = self.fp.read(count).rstrip(b'\x00') + self.fp.read(-count % 4) # read padding + return s + + +class netcdf_variable: + """ + A data object for netcdf files. + + `netcdf_variable` objects are constructed by calling the method + `netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable` + objects behave much like array objects defined in numpy, except that their + data resides in a file. Data is read by indexing and written by assigning + to an indexed subset; the entire array can be accessed by the index ``[:]`` + or (for scalars) by using the methods `getValue` and `assignValue`. + `netcdf_variable` objects also have attribute `shape` with the same meaning + as for arrays, but the shape cannot be modified. There is another read-only + attribute `dimensions`, whose value is the tuple of dimension names. + + All other attributes correspond to variable attributes defined in + the NetCDF file. Variable attributes are created by assigning to an + attribute of the `netcdf_variable` object. + + Parameters + ---------- + data : array_like + The data array that holds the values for the variable. + Typically, this is initialized as empty, but with the proper shape. + typecode : dtype character code + Desired data-type for the data array. + size : int + Desired element size for the data array. + shape : sequence of ints + The shape of the array. This should match the lengths of the + variable's dimensions. + dimensions : sequence of strings + The names of the dimensions used by the variable. Must be in the + same order of the dimension lengths given by `shape`. + attributes : dict, optional + Attribute values (any type) keyed by string names. These attributes + become attributes for the netcdf_variable object. + maskandscale : bool, optional + Whether to automatically scale and/or mask data based on attributes. + Default is False. + + + Attributes + ---------- + dimensions : list of str + List of names of dimensions used by the variable object. + isrec, shape + Properties + + See also + -------- + isrec, shape + + """ + def __init__(self, data, typecode, size, shape, dimensions, + attributes=None, + maskandscale=False): + self.data = data + self._typecode = typecode + self._size = size + self._shape = shape + self.dimensions = dimensions + self.maskandscale = maskandscale + + self._attributes = attributes or {} + for k, v in self._attributes.items(): + self.__dict__[k] = v + + def __setattr__(self, attr, value): + # Store user defined attributes in a separate dict, + # so we can save them to file later. + try: + self._attributes[attr] = value + except AttributeError: + pass + self.__dict__[attr] = value + + def isrec(self): + """Returns whether the variable has a record dimension or not. + + A record dimension is a dimension along which additional data could be + easily appended in the netcdf data structure without much rewriting of + the data file. This attribute is a read-only property of the + `netcdf_variable`. + + """ + return bool(self.data.shape) and not self._shape[0] + isrec = property(isrec) + + def shape(self): + """Returns the shape tuple of the data variable. + + This is a read-only attribute and can not be modified in the + same manner of other numpy arrays. + """ + return self.data.shape + shape = property(shape) + + def getValue(self): + """ + Retrieve a scalar value from a `netcdf_variable` of length one. + + Raises + ------ + ValueError + If the netcdf variable is an array of length greater than one, + this exception will be raised. + + """ + return self.data.item() + + def assignValue(self, value): + """ + Assign a scalar value to a `netcdf_variable` of length one. + + Parameters + ---------- + value : scalar + Scalar value (of compatible type) to assign to a length-one netcdf + variable. This value will be written to file. + + Raises + ------ + ValueError + If the input is not a scalar, or if the destination is not a length-one + netcdf variable. + + """ + if not self.data.flags.writeable: + # Work-around for a bug in NumPy. Calling itemset() on a read-only + # memory-mapped array causes a seg. fault. + # See NumPy ticket #1622, and SciPy ticket #1202. + # This check for `writeable` can be removed when the oldest version + # of NumPy still supported by scipy contains the fix for #1622. + raise RuntimeError("variable is not writeable") + + self.data[:] = value + + def typecode(self): + """ + Return the typecode of the variable. + + Returns + ------- + typecode : char + The character typecode of the variable (e.g., 'i' for int). + + """ + return self._typecode + + def itemsize(self): + """ + Return the itemsize of the variable. + + Returns + ------- + itemsize : int + The element size of the variable (e.g., 8 for float64). + + """ + return self._size + + def __getitem__(self, index): + if not self.maskandscale: + return self.data[index] + + data = self.data[index].copy() + missing_value = self._get_missing_value() + data = self._apply_missing_value(data, missing_value) + scale_factor = self._attributes.get('scale_factor') + add_offset = self._attributes.get('add_offset') + if add_offset is not None or scale_factor is not None: + data = data.astype(np.float64) + if scale_factor is not None: + data = data * scale_factor + if add_offset is not None: + data += add_offset + + return data + + def __setitem__(self, index, data): + if self.maskandscale: + missing_value = ( + self._get_missing_value() or + getattr(data, 'fill_value', 999999)) + self._attributes.setdefault('missing_value', missing_value) + self._attributes.setdefault('_FillValue', missing_value) + data = ((data - self._attributes.get('add_offset', 0.0)) / + self._attributes.get('scale_factor', 1.0)) + data = np.ma.asarray(data).filled(missing_value) + if self._typecode not in 'fd' and data.dtype.kind == 'f': + data = np.round(data) + + # Expand data for record vars? + if self.isrec: + if isinstance(index, tuple): + rec_index = index[0] + else: + rec_index = index + if isinstance(rec_index, slice): + recs = (rec_index.start or 0) + len(data) + else: + recs = rec_index + 1 + if recs > len(self.data): + shape = (recs,) + self._shape[1:] + # Resize in-place does not always work since + # the array might not be single-segment + try: + self.data.resize(shape) + except ValueError: + dtype = self.data.dtype + self.__dict__['data'] = np.resize(self.data, shape).astype(dtype) + self.data[index] = data + + def _default_encoded_fill_value(self): + """ + The default encoded fill-value for this Variable's data type. + """ + nc_type = REVERSE[self.typecode(), self.itemsize()] + return FILLMAP[nc_type] + + def _get_encoded_fill_value(self): + """ + Returns the encoded fill value for this variable as bytes. + + This is taken from either the _FillValue attribute, or the default fill + value for this variable's data type. + """ + if '_FillValue' in self._attributes: + fill_value = np.array(self._attributes['_FillValue'], + dtype=self.data.dtype).tobytes() + if len(fill_value) == self.itemsize(): + return fill_value + else: + return self._default_encoded_fill_value() + else: + return self._default_encoded_fill_value() + + def _get_missing_value(self): + """ + Returns the value denoting "no data" for this variable. + + If this variable does not have a missing/fill value, returns None. + + If both _FillValue and missing_value are given, give precedence to + _FillValue. The netCDF standard gives special meaning to _FillValue; + missing_value is just used for compatibility with old datasets. + """ + + if '_FillValue' in self._attributes: + missing_value = self._attributes['_FillValue'] + elif 'missing_value' in self._attributes: + missing_value = self._attributes['missing_value'] + else: + missing_value = None + + return missing_value + + @staticmethod + def _apply_missing_value(data, missing_value): + """ + Applies the given missing value to the data array. + + Returns a numpy.ma array, with any value equal to missing_value masked + out (unless missing_value is None, in which case the original array is + returned). + """ + + if missing_value is None: + newdata = data + else: + try: + missing_value_isnan = np.isnan(missing_value) + except (TypeError, NotImplementedError): + # some data types (e.g., characters) cannot be tested for NaN + missing_value_isnan = False + + if missing_value_isnan: + mymask = np.isnan(data) + else: + mymask = (data == missing_value) + + newdata = np.ma.masked_where(mymask, data) + + return newdata + + +NetCDFFile = netcdf_file +NetCDFVariable = netcdf_variable diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/_test_fortran.cpython-310-x86_64-linux-gnu.so b/videochat2/lib/python3.10/site-packages/scipy/io/_test_fortran.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..34fc29c089d790546d6d3932752543dcc9cb95c0 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/_test_fortran.cpython-310-x86_64-linux-gnu.so differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/harwell_boeing.py b/videochat2/lib/python3.10/site-packages/scipy/io/harwell_boeing.py new file mode 100644 index 0000000000000000000000000000000000000000..d4d17fe7d522a4a6ad41cbfb0ef5f05a221d06da --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/idl.py b/videochat2/lib/python3.10/site-packages/scipy/io/idl.py new file mode 100644 index 0000000000000000000000000000000000000000..1168022eeaa03a21c59d13f84469b7e24b95b785 --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/mmio.py b/videochat2/lib/python3.10/site-packages/scipy/io/mmio.py new file mode 100644 index 0000000000000000000000000000000000000000..e03c62376c52de4824086624eb0fb072e07057aa --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/netcdf.py b/videochat2/lib/python3.10/site-packages/scipy/io/netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..f469c5a3472417b0c97e848a74672e1d119d3eb4 --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/__init__.py b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/__init__.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e44f852b05c313e36c7baf4afb7d292a72532fae Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de57154ee12da1f519ca979ed2df9c785c2e5e31 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_fortran.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..466a07a09160c692c2f0bd942642eed907a72cb6 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_idl.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_mmio.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_mmio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6059c0400d50a842a874a88dbffe2d4e8c45307a Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_mmio.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_netcdf.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_netcdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b48ebdf5caaf9137bbb77a1ec73f727f87383a1 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_netcdf.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1757559db2501feab883e90062514654ed3f7e66 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_paths.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_wavfile.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_wavfile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76b693cdd46b0c81a0d90b6cda99938fc74110ef Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/__pycache__/test_wavfile.cpython-310.pyc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_1d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_3d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav b/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav new file mode 100644 index 0000000000000000000000000000000000000000..285da7f78ffbbf2155fd2e4e648f19a1d3a42ac3 Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_3d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_4d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/array_float32_pointer_7d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/example_3_maskedvals.nc differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-mixed.dat differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x1x1.dat differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-sf8-1x3x5.dat differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/fortran-si4-1x1x7.dat differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/invalid_pointer.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_complex32.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int32.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_int64.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/scalar_uint32.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav b/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav new file mode 100644 index 0000000000000000000000000000000000000000..6f01fbfd109e76c94b6e6e9bfd9eb388f39d99ee Binary files /dev/null and b/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_arrays_replicated.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointer_arrays_replicated_3d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_pointers.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/struct_scalars_replicated_3d.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav b/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav new file mode 100644 index 0000000000000000000000000000000000000000..6fa1d82cc466464f0378654a0a1dfb6772e1384c --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28acfd497bff477817fc055e103dafca16278f806f0f5bb20e22a9093dee959d +size 17720 diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/data/various_compressed.sav differ diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_fortran.py b/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_fortran.py new file mode 100644 index 0000000000000000000000000000000000000000..905140764411ea0fabf760f2288c546f636f232a --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_fortran.py @@ -0,0 +1,236 @@ +''' Tests for fortran sequential files ''' + +import tempfile +import shutil +from os import path +from glob import iglob +import re + +from numpy.testing import assert_equal, assert_allclose +import numpy as np +import pytest + +from scipy.io import (FortranFile, + _test_fortran, + FortranEOFError, + FortranFormattingError) + + +DATA_PATH = path.join(path.dirname(__file__), 'data') + + +def test_fortranfiles_read(): + for filename in iglob(path.join(DATA_PATH, "fortran-*-*x*x*.dat")): + m = re.search(r'fortran-([^-]+)-(\d+)x(\d+)x(\d+).dat', filename, re.I) + if not m: + raise RuntimeError("Couldn't match %s filename to regex" % filename) + + dims = (int(m.group(2)), int(m.group(3)), int(m.group(4))) + + dtype = m.group(1).replace('s', '<') + + f = FortranFile(filename, 'r', ' 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/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_netcdf.py b/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_netcdf.py new file mode 100644 index 0000000000000000000000000000000000000000..0dcf7a71ebd296b9d1114b53091837eee3499db2 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_netcdf.py @@ -0,0 +1,546 @@ +''' Tests for netcdf ''' +import os +from os.path import join as pjoin, dirname +import shutil +import tempfile +import warnings +from io import BytesIO +from glob import glob +from contextlib import contextmanager + +import numpy as np +from numpy.testing import (assert_, assert_allclose, assert_equal, + break_cycles, suppress_warnings, IS_PYPY) +from pytest import raises as assert_raises + +from scipy.io import netcdf_file +from scipy._lib._tmpdirs import in_tempdir + +TEST_DATA_PATH = pjoin(dirname(__file__), 'data') + +N_EG_ELS = 11 # number of elements for example variable +VARTYPE_EG = 'b' # var type for example variable + + +@contextmanager +def make_simple(*args, **kwargs): + f = netcdf_file(*args, **kwargs) + f.history = 'Created for a test' + f.createDimension('time', N_EG_ELS) + time = f.createVariable('time', VARTYPE_EG, ('time',)) + time[:] = np.arange(N_EG_ELS) + time.units = 'days since 2008-01-01' + f.flush() + yield f + f.close() + + +def check_simple(ncfileobj): + '''Example fileobj tests ''' + assert_equal(ncfileobj.history, b'Created for a test') + time = ncfileobj.variables['time'] + assert_equal(time.units, b'days since 2008-01-01') + assert_equal(time.shape, (N_EG_ELS,)) + assert_equal(time[-1], N_EG_ELS-1) + +def assert_mask_matches(arr, expected_mask): + ''' + Asserts that the mask of arr is effectively the same as expected_mask. + + In contrast to numpy.ma.testutils.assert_mask_equal, this function allows + testing the 'mask' of a standard numpy array (the mask in this case is treated + as all False). + + Parameters + ---------- + arr : ndarray or MaskedArray + Array to test. + expected_mask : array_like of booleans + A list giving the expected mask. + ''' + + mask = np.ma.getmaskarray(arr) + assert_equal(mask, expected_mask) + + +def test_read_write_files(): + # test round trip for example file + cwd = os.getcwd() + try: + tmpdir = tempfile.mkdtemp() + os.chdir(tmpdir) + with make_simple('simple.nc', 'w') as f: + pass + # read the file we just created in 'a' mode + with netcdf_file('simple.nc', 'a') as f: + check_simple(f) + # add something + f._attributes['appendRan'] = 1 + + # To read the NetCDF file we just created:: + with netcdf_file('simple.nc') as f: + # Using mmap is the default (but not on pypy) + assert_equal(f.use_mmap, not IS_PYPY) + check_simple(f) + assert_equal(f._attributes['appendRan'], 1) + + # Read it in append (and check mmap is off) + with netcdf_file('simple.nc', 'a') as f: + assert_(not f.use_mmap) + check_simple(f) + assert_equal(f._attributes['appendRan'], 1) + + # Now without mmap + with netcdf_file('simple.nc', mmap=False) as f: + # Using mmap is the default + assert_(not f.use_mmap) + check_simple(f) + + # To read the NetCDF file we just created, as file object, no + # mmap. When n * n_bytes(var_type) is not divisible by 4, this + # raised an error in pupynere 1.0.12 and scipy rev 5893, because + # calculated vsize was rounding up in units of 4 - see + # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html + with open('simple.nc', 'rb') as fobj: + with netcdf_file(fobj) as f: + # by default, don't use mmap for file-like + assert_(not f.use_mmap) + check_simple(f) + + # Read file from fileobj, with mmap + with suppress_warnings() as sup: + if IS_PYPY: + sup.filter(RuntimeWarning, + "Cannot close a netcdf_file opened with mmap=True.*") + with open('simple.nc', 'rb') as fobj: + with netcdf_file(fobj, mmap=True) as f: + assert_(f.use_mmap) + check_simple(f) + + # Again read it in append mode (adding another att) + with open('simple.nc', 'r+b') as fobj: + with netcdf_file(fobj, 'a') as f: + assert_(not f.use_mmap) + check_simple(f) + f.createDimension('app_dim', 1) + var = f.createVariable('app_var', 'i', ('app_dim',)) + var[:] = 42 + + # And... check that app_var made it in... + with netcdf_file('simple.nc') as f: + check_simple(f) + assert_equal(f.variables['app_var'][:], 42) + + finally: + if IS_PYPY: + # windows cannot remove a dead file held by a mmap + # that has not been collected in PyPy + break_cycles() + break_cycles() + os.chdir(cwd) + shutil.rmtree(tmpdir) + + +def test_read_write_sio(): + eg_sio1 = BytesIO() + with make_simple(eg_sio1, 'w'): + str_val = eg_sio1.getvalue() + + eg_sio2 = BytesIO(str_val) + with netcdf_file(eg_sio2) as f2: + check_simple(f2) + + # Test that error is raised if attempting mmap for sio + eg_sio3 = BytesIO(str_val) + assert_raises(ValueError, netcdf_file, eg_sio3, 'r', True) + # Test 64-bit offset write / read + eg_sio_64 = BytesIO() + with make_simple(eg_sio_64, 'w', version=2) as f_64: + str_val = eg_sio_64.getvalue() + + eg_sio_64 = BytesIO(str_val) + with netcdf_file(eg_sio_64) as f_64: + check_simple(f_64) + assert_equal(f_64.version_byte, 2) + # also when version 2 explicitly specified + eg_sio_64 = BytesIO(str_val) + with netcdf_file(eg_sio_64, version=2) as f_64: + check_simple(f_64) + assert_equal(f_64.version_byte, 2) + + +def test_bytes(): + raw_file = BytesIO() + f = netcdf_file(raw_file, mode='w') + # Dataset only has a single variable, dimension and attribute to avoid + # any ambiguity related to order. + f.a = 'b' + f.createDimension('dim', 1) + var = f.createVariable('var', np.int16, ('dim',)) + var[0] = -9999 + var.c = 'd' + f.sync() + + actual = raw_file.getvalue() + + expected = (b'CDF\x01' + b'\x00\x00\x00\x00' + b'\x00\x00\x00\x0a' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x03' + b'dim\x00' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x0c' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x01' + b'a\x00\x00\x00' + b'\x00\x00\x00\x02' + b'\x00\x00\x00\x01' + b'b\x00\x00\x00' + b'\x00\x00\x00\x0b' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x03' + b'var\x00' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x00' + b'\x00\x00\x00\x0c' + b'\x00\x00\x00\x01' + b'\x00\x00\x00\x01' + b'c\x00\x00\x00' + b'\x00\x00\x00\x02' + b'\x00\x00\x00\x01' + b'd\x00\x00\x00' + b'\x00\x00\x00\x03' + b'\x00\x00\x00\x04' + b'\x00\x00\x00\x78' + b'\xd8\xf1\x80\x01') + + assert_equal(actual, expected) + + +def test_encoded_fill_value(): + with netcdf_file(BytesIO(), mode='w') as f: + f.createDimension('x', 1) + var = f.createVariable('var', 'S1', ('x',)) + assert_equal(var._get_encoded_fill_value(), b'\x00') + var._FillValue = b'\x01' + assert_equal(var._get_encoded_fill_value(), b'\x01') + var._FillValue = b'\x00\x00' # invalid, wrong size + assert_equal(var._get_encoded_fill_value(), b'\x00') + + +def test_read_example_data(): + # read any example data files + for fname in glob(pjoin(TEST_DATA_PATH, '*.nc')): + with netcdf_file(fname, 'r'): + pass + with netcdf_file(fname, 'r', mmap=False): + pass + + +def test_itemset_no_segfault_on_readonly(): + # Regression test for ticket #1202. + # Open the test file in read-only mode. + + filename = pjoin(TEST_DATA_PATH, 'example_1.nc') + with suppress_warnings() as sup: + message = ("Cannot close a netcdf_file opened with mmap=True, when " + "netcdf_variables or arrays referring to its data still exist") + sup.filter(RuntimeWarning, message) + with netcdf_file(filename, 'r', mmap=True) as f: + time_var = f.variables['time'] + + # time_var.assignValue(42) should raise a RuntimeError--not seg. fault! + assert_raises(RuntimeError, time_var.assignValue, 42) + + +def test_appending_issue_gh_8625(): + stream = BytesIO() + + with make_simple(stream, mode='w') as f: + f.createDimension('x', 2) + f.createVariable('x', float, ('x',)) + f.variables['x'][...] = 1 + f.flush() + contents = stream.getvalue() + + stream = BytesIO(contents) + with netcdf_file(stream, mode='a') as f: + f.variables['x'][...] = 2 + + +def test_write_invalid_dtype(): + dtypes = ['int64', 'uint64'] + if np.dtype('int').itemsize == 8: # 64-bit machines + dtypes.append('int') + if np.dtype('uint').itemsize == 8: # 64-bit machines + dtypes.append('uint') + + with netcdf_file(BytesIO(), 'w') as f: + f.createDimension('time', N_EG_ELS) + for dt in dtypes: + assert_raises(ValueError, f.createVariable, 'time', dt, ('time',)) + + +def test_flush_rewind(): + stream = BytesIO() + with make_simple(stream, mode='w') as f: + f.createDimension('x',4) # x is used in createVariable + v = f.createVariable('v', 'i2', ['x']) + v[:] = 1 + f.flush() + len_single = len(stream.getvalue()) + f.flush() + len_double = len(stream.getvalue()) + + assert_(len_single == len_double) + + +def test_dtype_specifiers(): + # Numpy 1.7.0-dev had a bug where 'i2' wouldn't work. + # Specifying np.int16 or similar only works from the same commit as this + # comment was made. + with make_simple(BytesIO(), mode='w') as f: + f.createDimension('x',4) + f.createVariable('v1', 'i2', ['x']) + f.createVariable('v2', np.int16, ['x']) + f.createVariable('v3', np.dtype(np.int16), ['x']) + + +def test_ticket_1720(): + io = BytesIO() + + items = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] + + with netcdf_file(io, 'w') as f: + f.history = 'Created for a test' + f.createDimension('float_var', 10) + float_var = f.createVariable('float_var', 'f', ('float_var',)) + float_var[:] = items + float_var.units = 'metres' + f.flush() + contents = io.getvalue() + + io = BytesIO(contents) + with netcdf_file(io, 'r') as f: + assert_equal(f.history, b'Created for a test') + float_var = f.variables['float_var'] + assert_equal(float_var.units, b'metres') + assert_equal(float_var.shape, (10,)) + assert_allclose(float_var[:], items) + + +def test_mmaps_segfault(): + filename = pjoin(TEST_DATA_PATH, 'example_1.nc') + + if not IS_PYPY: + with warnings.catch_warnings(): + warnings.simplefilter("error") + with netcdf_file(filename, mmap=True) as f: + x = f.variables['lat'][:] + # should not raise warnings + del x + + def doit(): + with netcdf_file(filename, mmap=True) as f: + return f.variables['lat'][:] + + # should not crash + with suppress_warnings() as sup: + message = ("Cannot close a netcdf_file opened with mmap=True, when " + "netcdf_variables or arrays referring to its data still exist") + sup.filter(RuntimeWarning, message) + x = doit() + x.sum() + + +def test_zero_dimensional_var(): + io = BytesIO() + with make_simple(io, 'w') as f: + v = f.createVariable('zerodim', 'i2', []) + # This is checking that .isrec returns a boolean - don't simplify it + # to 'assert not ...' + assert v.isrec is False, v.isrec + f.flush() + + +def test_byte_gatts(): + # Check that global "string" atts work like they did before py3k + # unicode and general bytes confusion + with in_tempdir(): + filename = 'g_byte_atts.nc' + f = netcdf_file(filename, 'w') + f._attributes['holy'] = b'grail' + f._attributes['witch'] = 'floats' + f.close() + f = netcdf_file(filename, 'r') + assert_equal(f._attributes['holy'], b'grail') + assert_equal(f._attributes['witch'], b'floats') + f.close() + + +def test_open_append(): + # open 'w' put one attr + with in_tempdir(): + filename = 'append_dat.nc' + f = netcdf_file(filename, 'w') + f._attributes['Kilroy'] = 'was here' + f.close() + + # open again in 'a', read the att and a new one + f = netcdf_file(filename, 'a') + assert_equal(f._attributes['Kilroy'], b'was here') + f._attributes['naughty'] = b'Zoot' + f.close() + + # open yet again in 'r' and check both atts + f = netcdf_file(filename, 'r') + assert_equal(f._attributes['Kilroy'], b'was here') + assert_equal(f._attributes['naughty'], b'Zoot') + f.close() + + +def test_append_recordDimension(): + dataSize = 100 + + with in_tempdir(): + # Create file with record time dimension + with netcdf_file('withRecordDimension.nc', 'w') as f: + f.createDimension('time', None) + f.createVariable('time', 'd', ('time',)) + f.createDimension('x', dataSize) + x = f.createVariable('x', 'd', ('x',)) + x[:] = np.array(range(dataSize)) + f.createDimension('y', dataSize) + y = f.createVariable('y', 'd', ('y',)) + y[:] = np.array(range(dataSize)) + f.createVariable('testData', 'i', ('time', 'x', 'y')) + f.flush() + f.close() + + for i in range(2): + # Open the file in append mode and add data + with netcdf_file('withRecordDimension.nc', 'a') as f: + f.variables['time'].data = np.append(f.variables["time"].data, i) + f.variables['testData'][i, :, :] = np.full((dataSize, dataSize), i) + f.flush() + + # Read the file and check that append worked + with netcdf_file('withRecordDimension.nc') as f: + assert_equal(f.variables['time'][-1], i) + assert_equal(f.variables['testData'][-1, :, :].copy(), + np.full((dataSize, dataSize), i)) + assert_equal(f.variables['time'].data.shape[0], i+1) + assert_equal(f.variables['testData'].data.shape[0], i+1) + + # Read the file and check that 'data' was not saved as user defined + # attribute of testData variable during append operation + with netcdf_file('withRecordDimension.nc') as f: + with assert_raises(KeyError) as ar: + f.variables['testData']._attributes['data'] + ex = ar.value + assert_equal(ex.args[0], 'data') + +def test_maskandscale(): + t = np.linspace(20, 30, 15) + t[3] = 100 + tm = np.ma.masked_greater(t, 99) + fname = pjoin(TEST_DATA_PATH, 'example_2.nc') + with netcdf_file(fname, maskandscale=True) as f: + Temp = f.variables['Temperature'] + assert_equal(Temp.missing_value, 9999) + assert_equal(Temp.add_offset, 20) + assert_equal(Temp.scale_factor, np.float32(0.01)) + found = Temp[:].compressed() + del Temp # Remove ref to mmap, so file can be closed. + expected = np.round(tm.compressed(), 2) + assert_allclose(found, expected) + + with in_tempdir(): + newfname = 'ms.nc' + f = netcdf_file(newfname, 'w', maskandscale=True) + f.createDimension('Temperature', len(tm)) + temp = f.createVariable('Temperature', 'i', ('Temperature',)) + temp.missing_value = 9999 + temp.scale_factor = 0.01 + temp.add_offset = 20 + temp[:] = tm + f.close() + + with netcdf_file(newfname, maskandscale=True) as f: + Temp = f.variables['Temperature'] + assert_equal(Temp.missing_value, 9999) + assert_equal(Temp.add_offset, 20) + assert_equal(Temp.scale_factor, np.float32(0.01)) + expected = np.round(tm.compressed(), 2) + found = Temp[:].compressed() + del Temp + assert_allclose(found, expected) + + +# ------------------------------------------------------------------------ +# Test reading with masked values (_FillValue / missing_value) +# ------------------------------------------------------------------------ + +def test_read_withValuesNearFillValue(): + # Regression test for ticket #5626 + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var1_fillval0'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_withNoFillValue(): + # For a variable with no fill value, reading data with maskandscale=True + # should return unmasked data + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var2_noFillval'][:] + assert_mask_matches(vardata, [False, False, False]) + assert_equal(vardata, [1,2,3]) + +def test_read_withFillValueAndMissingValue(): + # For a variable with both _FillValue and missing_value, the _FillValue + # should be used + IRRELEVANT_VALUE = 9999 + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var3_fillvalAndMissingValue'][:] + assert_mask_matches(vardata, [True, False, False]) + assert_equal(vardata, [IRRELEVANT_VALUE, 2, 3]) + +def test_read_withMissingValue(): + # For a variable with missing_value but not _FillValue, the missing_value + # should be used + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var4_missingValue'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_withFillValNaN(): + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var5_fillvalNaN'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_withChar(): + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var6_char'][:] + assert_mask_matches(vardata, [False, True, False]) + +def test_read_with2dVar(): + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + with netcdf_file(fname, maskandscale=True) as f: + vardata = f.variables['var7_2d'][:] + assert_mask_matches(vardata, [[True, False], [False, False], [False, True]]) + +def test_read_withMaskAndScaleFalse(): + # If a variable has a _FillValue (or missing_value) attribute, but is read + # with maskandscale set to False, the result should be unmasked + fname = pjoin(TEST_DATA_PATH, 'example_3_maskedvals.nc') + # Open file with mmap=False to avoid problems with closing a mmap'ed file + # when arrays referring to its data still exist: + with netcdf_file(fname, maskandscale=False, mmap=False) as f: + vardata = f.variables['var3_fillvalAndMissingValue'][:] + assert_mask_matches(vardata, [False, False, False]) + assert_equal(vardata, [1, 2, 3]) diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_paths.py b/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..84464e469b64579cf389dcea0fece7b0e9d36121 --- /dev/null +++ b/videochat2/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/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py b/videochat2/lib/python3.10/site-packages/scipy/io/tests/test_wavfile.py new file mode 100644 index 0000000000000000000000000000000000000000..0a048fad1f981a5af6651ed2170fed3847749972 --- /dev/null +++ b/videochat2/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) diff --git a/videochat2/lib/python3.10/site-packages/scipy/io/wavfile.py b/videochat2/lib/python3.10/site-packages/scipy/io/wavfile.py new file mode 100644 index 0000000000000000000000000000000000000000..ad56a811789b1a8181f792814174faf61608ff5e --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/io/wavfile.py @@ -0,0 +1,840 @@ +""" +Module to read / write wav files using NumPy arrays + +Functions +--------- +`read`: Return the sample rate (in samples/sec) and data from a WAV file. + +`write`: Write a NumPy array as a WAV file. + +""" +import io +import sys +import numpy +import struct +import warnings +from enum import IntEnum + + +__all__ = [ + 'WavFileWarning', + 'read', + 'write' +] + + +class WavFileWarning(UserWarning): + pass + + +class WAVE_FORMAT(IntEnum): + """ + WAVE form wFormatTag IDs + + Complete list is in mmreg.h in Windows 10 SDK. ALAC and OPUS are the + newest additions, in v10.0.14393 2016-07 + """ + UNKNOWN = 0x0000 + PCM = 0x0001 + ADPCM = 0x0002 + IEEE_FLOAT = 0x0003 + VSELP = 0x0004 + IBM_CVSD = 0x0005 + ALAW = 0x0006 + MULAW = 0x0007 + DTS = 0x0008 + DRM = 0x0009 + WMAVOICE9 = 0x000A + WMAVOICE10 = 0x000B + OKI_ADPCM = 0x0010 + DVI_ADPCM = 0x0011 + IMA_ADPCM = 0x0011 # Duplicate + MEDIASPACE_ADPCM = 0x0012 + SIERRA_ADPCM = 0x0013 + G723_ADPCM = 0x0014 + DIGISTD = 0x0015 + DIGIFIX = 0x0016 + DIALOGIC_OKI_ADPCM = 0x0017 + MEDIAVISION_ADPCM = 0x0018 + CU_CODEC = 0x0019 + HP_DYN_VOICE = 0x001A + YAMAHA_ADPCM = 0x0020 + SONARC = 0x0021 + DSPGROUP_TRUESPEECH = 0x0022 + ECHOSC1 = 0x0023 + AUDIOFILE_AF36 = 0x0024 + APTX = 0x0025 + AUDIOFILE_AF10 = 0x0026 + PROSODY_1612 = 0x0027 + LRC = 0x0028 + DOLBY_AC2 = 0x0030 + GSM610 = 0x0031 + MSNAUDIO = 0x0032 + ANTEX_ADPCME = 0x0033 + CONTROL_RES_VQLPC = 0x0034 + DIGIREAL = 0x0035 + DIGIADPCM = 0x0036 + CONTROL_RES_CR10 = 0x0037 + NMS_VBXADPCM = 0x0038 + CS_IMAADPCM = 0x0039 + ECHOSC3 = 0x003A + ROCKWELL_ADPCM = 0x003B + ROCKWELL_DIGITALK = 0x003C + XEBEC = 0x003D + G721_ADPCM = 0x0040 + G728_CELP = 0x0041 + MSG723 = 0x0042 + INTEL_G723_1 = 0x0043 + INTEL_G729 = 0x0044 + SHARP_G726 = 0x0045 + MPEG = 0x0050 + RT24 = 0x0052 + PAC = 0x0053 + MPEGLAYER3 = 0x0055 + LUCENT_G723 = 0x0059 + CIRRUS = 0x0060 + ESPCM = 0x0061 + VOXWARE = 0x0062 + CANOPUS_ATRAC = 0x0063 + G726_ADPCM = 0x0064 + G722_ADPCM = 0x0065 + DSAT = 0x0066 + DSAT_DISPLAY = 0x0067 + VOXWARE_BYTE_ALIGNED = 0x0069 + VOXWARE_AC8 = 0x0070 + VOXWARE_AC10 = 0x0071 + VOXWARE_AC16 = 0x0072 + VOXWARE_AC20 = 0x0073 + VOXWARE_RT24 = 0x0074 + VOXWARE_RT29 = 0x0075 + VOXWARE_RT29HW = 0x0076 + VOXWARE_VR12 = 0x0077 + VOXWARE_VR18 = 0x0078 + VOXWARE_TQ40 = 0x0079 + VOXWARE_SC3 = 0x007A + VOXWARE_SC3_1 = 0x007B + SOFTSOUND = 0x0080 + VOXWARE_TQ60 = 0x0081 + MSRT24 = 0x0082 + G729A = 0x0083 + MVI_MVI2 = 0x0084 + DF_G726 = 0x0085 + DF_GSM610 = 0x0086 + ISIAUDIO = 0x0088 + ONLIVE = 0x0089 + MULTITUDE_FT_SX20 = 0x008A + INFOCOM_ITS_G721_ADPCM = 0x008B + CONVEDIA_G729 = 0x008C + CONGRUENCY = 0x008D + SBC24 = 0x0091 + DOLBY_AC3_SPDIF = 0x0092 + MEDIASONIC_G723 = 0x0093 + PROSODY_8KBPS = 0x0094 + ZYXEL_ADPCM = 0x0097 + PHILIPS_LPCBB = 0x0098 + PACKED = 0x0099 + MALDEN_PHONYTALK = 0x00A0 + RACAL_RECORDER_GSM = 0x00A1 + RACAL_RECORDER_G720_A = 0x00A2 + RACAL_RECORDER_G723_1 = 0x00A3 + RACAL_RECORDER_TETRA_ACELP = 0x00A4 + NEC_AAC = 0x00B0 + RAW_AAC1 = 0x00FF + RHETOREX_ADPCM = 0x0100 + IRAT = 0x0101 + VIVO_G723 = 0x0111 + VIVO_SIREN = 0x0112 + PHILIPS_CELP = 0x0120 + PHILIPS_GRUNDIG = 0x0121 + DIGITAL_G723 = 0x0123 + SANYO_LD_ADPCM = 0x0125 + SIPROLAB_ACEPLNET = 0x0130 + SIPROLAB_ACELP4800 = 0x0131 + SIPROLAB_ACELP8V3 = 0x0132 + SIPROLAB_G729 = 0x0133 + SIPROLAB_G729A = 0x0134 + SIPROLAB_KELVIN = 0x0135 + VOICEAGE_AMR = 0x0136 + G726ADPCM = 0x0140 + DICTAPHONE_CELP68 = 0x0141 + DICTAPHONE_CELP54 = 0x0142 + QUALCOMM_PUREVOICE = 0x0150 + QUALCOMM_HALFRATE = 0x0151 + TUBGSM = 0x0155 + MSAUDIO1 = 0x0160 + WMAUDIO2 = 0x0161 + WMAUDIO3 = 0x0162 + WMAUDIO_LOSSLESS = 0x0163 + WMASPDIF = 0x0164 + UNISYS_NAP_ADPCM = 0x0170 + UNISYS_NAP_ULAW = 0x0171 + UNISYS_NAP_ALAW = 0x0172 + UNISYS_NAP_16K = 0x0173 + SYCOM_ACM_SYC008 = 0x0174 + SYCOM_ACM_SYC701_G726L = 0x0175 + SYCOM_ACM_SYC701_CELP54 = 0x0176 + SYCOM_ACM_SYC701_CELP68 = 0x0177 + KNOWLEDGE_ADVENTURE_ADPCM = 0x0178 + FRAUNHOFER_IIS_MPEG2_AAC = 0x0180 + DTS_DS = 0x0190 + CREATIVE_ADPCM = 0x0200 + CREATIVE_FASTSPEECH8 = 0x0202 + CREATIVE_FASTSPEECH10 = 0x0203 + UHER_ADPCM = 0x0210 + ULEAD_DV_AUDIO = 0x0215 + ULEAD_DV_AUDIO_1 = 0x0216 + QUARTERDECK = 0x0220 + ILINK_VC = 0x0230 + RAW_SPORT = 0x0240 + ESST_AC3 = 0x0241 + GENERIC_PASSTHRU = 0x0249 + IPI_HSX = 0x0250 + IPI_RPELP = 0x0251 + CS2 = 0x0260 + SONY_SCX = 0x0270 + SONY_SCY = 0x0271 + SONY_ATRAC3 = 0x0272 + SONY_SPC = 0x0273 + TELUM_AUDIO = 0x0280 + TELUM_IA_AUDIO = 0x0281 + NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285 + FM_TOWNS_SND = 0x0300 + MICRONAS = 0x0350 + MICRONAS_CELP833 = 0x0351 + BTV_DIGITAL = 0x0400 + INTEL_MUSIC_CODER = 0x0401 + INDEO_AUDIO = 0x0402 + QDESIGN_MUSIC = 0x0450 + ON2_VP7_AUDIO = 0x0500 + ON2_VP6_AUDIO = 0x0501 + VME_VMPCM = 0x0680 + TPC = 0x0681 + LIGHTWAVE_LOSSLESS = 0x08AE + OLIGSM = 0x1000 + OLIADPCM = 0x1001 + OLICELP = 0x1002 + OLISBC = 0x1003 + OLIOPR = 0x1004 + LH_CODEC = 0x1100 + LH_CODEC_CELP = 0x1101 + LH_CODEC_SBC8 = 0x1102 + LH_CODEC_SBC12 = 0x1103 + LH_CODEC_SBC16 = 0x1104 + NORRIS = 0x1400 + ISIAUDIO_2 = 0x1401 + SOUNDSPACE_MUSICOMPRESS = 0x1500 + MPEG_ADTS_AAC = 0x1600 + MPEG_RAW_AAC = 0x1601 + MPEG_LOAS = 0x1602 + NOKIA_MPEG_ADTS_AAC = 0x1608 + NOKIA_MPEG_RAW_AAC = 0x1609 + VODAFONE_MPEG_ADTS_AAC = 0x160A + VODAFONE_MPEG_RAW_AAC = 0x160B + MPEG_HEAAC = 0x1610 + VOXWARE_RT24_SPEECH = 0x181C + SONICFOUNDRY_LOSSLESS = 0x1971 + INNINGS_TELECOM_ADPCM = 0x1979 + LUCENT_SX8300P = 0x1C07 + LUCENT_SX5363S = 0x1C0C + CUSEEME = 0x1F03 + NTCSOFT_ALF2CM_ACM = 0x1FC4 + DVM = 0x2000 + DTS2 = 0x2001 + MAKEAVIS = 0x3313 + DIVIO_MPEG4_AAC = 0x4143 + NOKIA_ADAPTIVE_MULTIRATE = 0x4201 + DIVIO_G726 = 0x4243 + LEAD_SPEECH = 0x434C + LEAD_VORBIS = 0x564C + WAVPACK_AUDIO = 0x5756 + OGG_VORBIS_MODE_1 = 0x674F + OGG_VORBIS_MODE_2 = 0x6750 + OGG_VORBIS_MODE_3 = 0x6751 + OGG_VORBIS_MODE_1_PLUS = 0x676F + OGG_VORBIS_MODE_2_PLUS = 0x6770 + OGG_VORBIS_MODE_3_PLUS = 0x6771 + ALAC = 0x6C61 + _3COM_NBX = 0x7000 # Can't have leading digit + OPUS = 0x704F + FAAD_AAC = 0x706D + AMR_NB = 0x7361 + AMR_WB = 0x7362 + AMR_WP = 0x7363 + GSM_AMR_CBR = 0x7A21 + GSM_AMR_VBR_SID = 0x7A22 + COMVERSE_INFOSYS_G723_1 = 0xA100 + COMVERSE_INFOSYS_AVQSBC = 0xA101 + COMVERSE_INFOSYS_SBC = 0xA102 + SYMBOL_G729_A = 0xA103 + VOICEAGE_AMR_WB = 0xA104 + INGENIENT_G726 = 0xA105 + MPEG4_AAC = 0xA106 + ENCORE_G726 = 0xA107 + ZOLL_ASAO = 0xA108 + SPEEX_VOICE = 0xA109 + VIANIX_MASC = 0xA10A + WM9_SPECTRUM_ANALYZER = 0xA10B + WMF_SPECTRUM_ANAYZER = 0xA10C + GSM_610 = 0xA10D + GSM_620 = 0xA10E + GSM_660 = 0xA10F + GSM_690 = 0xA110 + GSM_ADAPTIVE_MULTIRATE_WB = 0xA111 + POLYCOM_G722 = 0xA112 + POLYCOM_G728 = 0xA113 + POLYCOM_G729_A = 0xA114 + POLYCOM_SIREN = 0xA115 + GLOBAL_IP_ILBC = 0xA116 + RADIOTIME_TIME_SHIFT_RADIO = 0xA117 + NICE_ACA = 0xA118 + NICE_ADPCM = 0xA119 + VOCORD_G721 = 0xA11A + VOCORD_G726 = 0xA11B + VOCORD_G722_1 = 0xA11C + VOCORD_G728 = 0xA11D + VOCORD_G729 = 0xA11E + VOCORD_G729_A = 0xA11F + VOCORD_G723_1 = 0xA120 + VOCORD_LBC = 0xA121 + NICE_G728 = 0xA122 + FRACE_TELECOM_G729 = 0xA123 + CODIAN = 0xA124 + FLAC = 0xF1AC + EXTENSIBLE = 0xFFFE + DEVELOPMENT = 0xFFFF + + +KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT} + + +def _raise_bad_format(format_tag): + try: + format_name = WAVE_FORMAT(format_tag).name + except ValueError: + format_name = f'{format_tag:#06x}' + raise ValueError(f"Unknown wave file format: {format_name}. Supported " + "formats: " + + ', '.join(x.name for x in KNOWN_WAVE_FORMATS)) + + +def _read_fmt_chunk(fid, is_big_endian): + """ + Returns + ------- + size : int + size of format subchunk in bytes (minus 8 for "fmt " and itself) + format_tag : int + PCM, float, or compressed format + channels : int + number of channels + fs : int + sampling frequency in samples per second + bytes_per_second : int + overall byte rate for the file + block_align : int + bytes per sample, including all channels + bit_depth : int + bits per sample + + Notes + ----- + Assumes file pointer is immediately after the 'fmt ' id + """ + if is_big_endian: + fmt = '>' + else: + fmt = '<' + + size = struct.unpack(fmt+'I', fid.read(4))[0] + + if size < 16: + raise ValueError("Binary structure of wave file is not compliant") + + res = struct.unpack(fmt+'HHIIHH', fid.read(16)) + bytes_read = 16 + + format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res + + if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2): + ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0] + bytes_read += 2 + if ext_chunk_size >= 22: + extensible_chunk_data = fid.read(22) + bytes_read += 22 + raw_guid = extensible_chunk_data[2+4:2+4+16] + # GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361) + # MS GUID byte order: first three groups are native byte order, + # rest is Big Endian + if is_big_endian: + tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71' + else: + tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71' + if raw_guid.endswith(tail): + format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0] + else: + raise ValueError("Binary structure of wave file is not compliant") + + if format_tag not in KNOWN_WAVE_FORMATS: + _raise_bad_format(format_tag) + + # move file pointer to next chunk + if size > bytes_read: + fid.read(size - bytes_read) + + # fmt should always be 16, 18 or 40, but handle it just in case + _handle_pad_byte(fid, size) + + if format_tag == WAVE_FORMAT.PCM: + if bytes_per_second != fs * block_align: + raise ValueError("WAV header is invalid: nAvgBytesPerSec must" + " equal product of nSamplesPerSec and" + " nBlockAlign, but file has nSamplesPerSec =" + f" {fs}, nBlockAlign = {block_align}, and" + f" nAvgBytesPerSec = {bytes_per_second}") + + return (size, format_tag, channels, fs, bytes_per_second, block_align, + bit_depth) + + +def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian, + block_align, mmap=False): + """ + Notes + ----- + Assumes file pointer is immediately after the 'data' id + + It's possible to not use all available bits in a container, or to store + samples in a container bigger than necessary, so bytes_per_sample uses + the actual reported container size (nBlockAlign / nChannels). Real-world + examples: + + Adobe Audition's "24-bit packed int (type 1, 20-bit)" + + nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20 + + http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav + is: + + nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12 + + http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf + gives an example of: + + nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20 + """ + if is_big_endian: + fmt = '>' + else: + fmt = '<' + + # Size of the data subchunk in bytes + size = struct.unpack(fmt+'I', fid.read(4))[0] + + # Number of bytes per sample (sample container size) + bytes_per_sample = block_align // channels + n_samples = size // bytes_per_sample + + if format_tag == WAVE_FORMAT.PCM: + if 1 <= bit_depth <= 8: + dtype = 'u1' # WAV of 8-bit integer or less are unsigned + elif bytes_per_sample in {3, 5, 6, 7}: + # No compatible dtype. Load as raw bytes for reshaping later. + dtype = 'V1' + elif bit_depth <= 64: + # Remaining bit depths can map directly to signed numpy dtypes + dtype = f'{fmt}i{bytes_per_sample}' + else: + raise ValueError("Unsupported bit depth: the WAV file " + f"has {bit_depth}-bit integer data.") + elif format_tag == WAVE_FORMAT.IEEE_FLOAT: + if bit_depth in {32, 64}: + dtype = f'{fmt}f{bytes_per_sample}' + else: + raise ValueError("Unsupported bit depth: the WAV file " + f"has {bit_depth}-bit floating-point data.") + else: + _raise_bad_format(format_tag) + + start = fid.tell() + if not mmap: + try: + count = size if dtype == 'V1' else n_samples + data = numpy.fromfile(fid, dtype=dtype, count=count) + except io.UnsupportedOperation: # not a C-like file + fid.seek(start, 0) # just in case it seeked, though it shouldn't + data = numpy.frombuffer(fid.read(size), dtype=dtype) + + if dtype == 'V1': + # Rearrange raw bytes into smallest compatible numpy dtype + dt = f'{fmt}i4' if bytes_per_sample == 3 else f'{fmt}i8' + a = numpy.zeros((len(data) // bytes_per_sample, numpy.dtype(dt).itemsize), + dtype='V1') + if is_big_endian: + a[:, :bytes_per_sample] = data.reshape((-1, bytes_per_sample)) + else: + a[:, -bytes_per_sample:] = data.reshape((-1, bytes_per_sample)) + data = a.view(dt).reshape(a.shape[:-1]) + else: + if bytes_per_sample in {1, 2, 4, 8}: + start = fid.tell() + data = numpy.memmap(fid, dtype=dtype, mode='c', offset=start, + shape=(n_samples,)) + fid.seek(start + size) + else: + raise ValueError("mmap=True not compatible with " + f"{bytes_per_sample}-byte container size.") + + _handle_pad_byte(fid, size) + + if channels > 1: + data = data.reshape(-1, channels) + return data + + +def _skip_unknown_chunk(fid, is_big_endian): + if is_big_endian: + fmt = '>I' + else: + fmt = '>> from os.path import dirname, join as pjoin + >>> from scipy.io import wavfile + >>> import scipy.io + + Get the filename for an example .wav file from the tests/data directory. + + >>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data') + >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav') + + Load the .wav file contents. + + >>> samplerate, data = wavfile.read(wav_fname) + >>> print(f"number of channels = {data.shape[1]}") + number of channels = 2 + >>> length = data.shape[0] / samplerate + >>> print(f"length = {length}s") + length = 0.01s + + Plot the waveform. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> time = np.linspace(0., length, data.shape[0]) + >>> plt.plot(time, data[:, 0], label="Left channel") + >>> plt.plot(time, data[:, 1], label="Right channel") + >>> plt.legend() + >>> plt.xlabel("Time [s]") + >>> plt.ylabel("Amplitude") + >>> plt.show() + + """ + if hasattr(filename, 'read'): + fid = filename + mmap = False + else: + fid = open(filename, 'rb') + + try: + file_size, is_big_endian = _read_riff_chunk(fid) + fmt_chunk_received = False + data_chunk_received = False + while fid.tell() < file_size: + # read the next chunk + chunk_id = fid.read(4) + + if not chunk_id: + if data_chunk_received: + # End of file but data successfully read + warnings.warn( + f"Reached EOF prematurely; finished at {fid.tell():d} bytes, " + f"expected {file_size:d} bytes from header.", + WavFileWarning, stacklevel=2) + break + else: + raise ValueError("Unexpected end of file.") + elif len(chunk_id) < 4: + msg = f"Incomplete chunk ID: {repr(chunk_id)}" + # If we have the data, ignore the broken chunk + if fmt_chunk_received and data_chunk_received: + warnings.warn(msg + ", ignoring it.", WavFileWarning, + stacklevel=2) + else: + raise ValueError(msg) + + if chunk_id == b'fmt ': + fmt_chunk_received = True + fmt_chunk = _read_fmt_chunk(fid, is_big_endian) + format_tag, channels, fs = fmt_chunk[1:4] + bit_depth = fmt_chunk[6] + block_align = fmt_chunk[5] + elif chunk_id == b'fact': + _skip_unknown_chunk(fid, is_big_endian) + elif chunk_id == b'data': + data_chunk_received = True + if not fmt_chunk_received: + raise ValueError("No fmt chunk before data") + data = _read_data_chunk(fid, format_tag, channels, bit_depth, + is_big_endian, block_align, mmap) + elif chunk_id == b'LIST': + # Someday this could be handled properly but for now skip it + _skip_unknown_chunk(fid, is_big_endian) + elif chunk_id in {b'JUNK', b'Fake'}: + # Skip alignment chunks without warning + _skip_unknown_chunk(fid, is_big_endian) + else: + warnings.warn("Chunk (non-data) not understood, skipping it.", + WavFileWarning, stacklevel=2) + _skip_unknown_chunk(fid, is_big_endian) + finally: + if not hasattr(filename, 'read'): + fid.close() + else: + fid.seek(0) + + return fs, data + + +def write(filename, rate, data): + """ + Write a NumPy array as a WAV file. + + Parameters + ---------- + filename : string or open file handle + Output wav file. + rate : int + The sample rate (in samples/sec). + data : ndarray + A 1-D or 2-D NumPy array of either integer or float data-type. + + Notes + ----- + * Writes a simple uncompressed WAV file. + * To write multiple-channels, use a 2-D array of shape + (Nsamples, Nchannels). + * The bits-per-sample and PCM/float will be determined by the data-type. + + Common data types: [1]_ + + ===================== =========== =========== ============= + WAV format Min Max NumPy dtype + ===================== =========== =========== ============= + 32-bit floating-point -1.0 +1.0 float32 + 32-bit PCM -2147483648 +2147483647 int32 + 16-bit PCM -32768 +32767 int16 + 8-bit PCM 0 255 uint8 + ===================== =========== =========== ============= + + Note that 8-bit PCM is unsigned. + + References + ---------- + .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming + Interface and Data Specifications 1.0", section "Data Format of the + Samples", August 1991 + http://www.tactilemedia.com/info/MCI_Control_Info.html + + Examples + -------- + Create a 100Hz sine wave, sampled at 44100Hz. + Write to 16-bit PCM, Mono. + + >>> from scipy.io.wavfile import write + >>> import numpy as np + >>> samplerate = 44100; fs = 100 + >>> t = np.linspace(0., 1., samplerate) + >>> amplitude = np.iinfo(np.int16).max + >>> data = amplitude * np.sin(2. * np.pi * fs * t) + >>> write("example.wav", samplerate, data.astype(np.int16)) + + """ + if hasattr(filename, 'write'): + fid = filename + else: + fid = open(filename, 'wb') + + fs = rate + + try: + dkind = data.dtype.kind + allowed_dtypes = ['float32', 'float64', + 'uint8', 'int16', 'int32', 'int64'] + if data.dtype.name not in allowed_dtypes: + raise ValueError("Unsupported data type '%s'" % data.dtype) + + header_data = b'' + + header_data += b'RIFF' + header_data += b'\x00\x00\x00\x00' + header_data += b'WAVE' + + # fmt chunk + header_data += b'fmt ' + if dkind == 'f': + format_tag = WAVE_FORMAT.IEEE_FLOAT + else: + format_tag = WAVE_FORMAT.PCM + if data.ndim == 1: + channels = 1 + else: + channels = data.shape[1] + bit_depth = data.dtype.itemsize * 8 + bytes_per_second = fs*(bit_depth // 8)*channels + block_align = channels * (bit_depth // 8) + + fmt_chunk_data = struct.pack(' 0xFFFFFFFF: + raise ValueError("Data exceeds wave file size limit") + + fid.write(header_data) + + # data chunk + fid.write(b'data') + fid.write(struct.pack('' or (data.dtype.byteorder == '=' and + sys.byteorder == 'big'): + data = data.byteswap() + _array_tofile(fid, data) + + # Determine file size and place it in correct + # position at start of the file. + size = fid.tell() + fid.seek(4) + fid.write(struct.pack(' float | int: ... # type: ignore[misc] + @overload + def rvs(self, size: int | tuple[int, ...] = ...) -> np.ndarray: ... + def set_random_state(self, random_state: SeedType) -> None: ... + + +class TDRDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def dpdf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + + +class TransformedDensityRejection(Method): + def __init__(self, + dist: TDRDist, + *, + mode: None | float = ..., + center: None | float = ..., + domain: None | tuple[float, float] = ..., + c: float = ..., + construction_points: int | npt.ArrayLike = ..., + use_dars: bool = ..., + max_squeeze_hat_ratio: float = ..., + random_state: SeedType = ...) -> None: ... + @property + def squeeze_hat_ratio(self) -> float: ... + @property + def squeeze_area(self) -> float: ... + @overload + def ppf_hat(self, u: ArrayLike0D) -> float: ... # type: ignore[misc] + @overload + def ppf_hat(self, u: npt.ArrayLike) -> np.ndarray: ... + + +class SROUDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + + +class SimpleRatioUniforms(Method): + def __init__(self, + dist: SROUDist, + *, + mode: None | float = ..., + pdf_area: float = ..., + domain: None | tuple[float, float] = ..., + cdf_at_mode: float = ..., + random_state: SeedType = ...) -> None: ... + + +class UError(NamedTuple): + max_error: float + mean_absolute_error: float + +class PINVDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def cdf(self) -> Callable[..., float]: ... + @property + def logpdf(self) -> Callable[..., float]: ... + + +class NumericalInversePolynomial(Method): + def __init__(self, + dist: PINVDist, + *, + mode: None | float = ..., + center: None | float = ..., + domain: None | tuple[float, float] = ..., + order: int = ..., + u_resolution: float = ..., + random_state: SeedType = ...) -> None: ... + @property + def intervals(self) -> int: ... + @overload + def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[misc] + @overload + def ppf(self, u: npt.ArrayLike) -> np.ndarray: ... + @overload + def cdf(self, x: ArrayLike0D) -> float: ... # type: ignore[misc] + @overload + def cdf(self, x: npt.ArrayLike) -> np.ndarray: ... + def u_error(self, sample_size: int = ...) -> UError: ... + def qrvs(self, + size: None | int | tuple[int, ...] = ..., + d: None | int = ..., + qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ... + + +class HINVDist(Protocol): + @property + def pdf(self) -> Callable[..., float]: ... + @property + def cdf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + + +class NumericalInverseHermite(Method): + def __init__(self, + dist: HINVDist, + *, + domain: None | tuple[float, float] = ..., + order: int= ..., + u_resolution: float = ..., + construction_points: None | npt.ArrayLike = ..., + max_intervals: int = ..., + random_state: SeedType = ...) -> None: ... + @property + def intervals(self) -> int: ... + @overload + def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[misc] + @overload + def ppf(self, u: npt.ArrayLike) -> np.ndarray: ... + def qrvs(self, + size: None | int | tuple[int, ...] = ..., + d: None | int = ..., + qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ... + def u_error(self, sample_size: int = ...) -> UError: ... + + +class DAUDist(Protocol): + @property + def pmf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + +class DiscreteAliasUrn(Method): + def __init__(self, + dist: npt.ArrayLike | DAUDist, + *, + domain: None | tuple[float, float] = ..., + urn_factor: float = ..., + random_state: SeedType = ...) -> None: ... + + +class DGTDist(Protocol): + @property + def pmf(self) -> Callable[..., float]: ... + @property + def support(self) -> tuple[float, float]: ... + +class DiscreteGuideTable(Method): + def __init__(self, + dist: npt.ArrayLike | DGTDist, + *, + domain: None | tuple[float, float] = ..., + guide_factor: float = ..., + random_state: SeedType = ...) -> None: ... + @overload + def ppf(self, u: ArrayLike0D) -> float: ... # type: ignore[misc] + @overload + def ppf(self, u: npt.ArrayLike) -> np.ndarray: ... diff --git a/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7018488d6796d43d82009857bbff4616ad1687b5 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01fcdd9ff6bef1c158bfbfdccabb57edaa911daac2ed91b3d347ef36e277e657 +size 277568 diff --git a/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97e4c4f8afe193ee0401c550f9f1c5f2b9cf17fa --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:25fcf0084533c3c0d561234bc2c7e3a13014fd13ebff888cd9c7015914f9a6b3 +size 112274 diff --git a/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-310.pyc b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0a942e608cd686bfd9c3b1243ac7f982b9419ce --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b97c07e90c51b91825d82d6145e17c36683d4304b07cfec5b922d3616919839 +size 265189 diff --git a/videochat2/lib/python3.10/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy new file mode 100644 index 0000000000000000000000000000000000000000..adda664a7b5442fc0977ddbaa572c864ddd31f08 --- /dev/null +++ b/videochat2/lib/python3.10/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf18c1f2d65a232bf2c7121282df31bf2a8be827afafc4ed810ed37457ee898a +size 183728