
    >qj-<                         d Z ddlZddlZddlmZ ddlmZmZ ddlm	Z	m
Z
 ddlmZmZ ddlmZ g d	Zedd
       ZddZddZdeddZ	 	 	 	 	 ddZedd       Zy)z7
Module for reading and writing matlab (TM) .mat files
    N)contextmanager   )_get_matfile_version	docfiller)MatFile4ReaderMatFile4Writer)MatFile5ReaderMatFile5Writer)_NoValue)loadmatsavematwhosmatc              #      K   t        | ||      \  }}	 | |r|j                          y y # |r|j                          w w xY ww)N)
_open_fileclose)	file_like	appendmatmodefopeneds        S/opt/rentech/trading_bot/.venv/lib/python3.12/site-packages/scipy/io/matlab/_mio.py_open_file_contextr      sD     9i6IAvGGI 6GGI s   A, AAAc                    t        |      t        d      z  rdhn	t               }t        |      t        d      z  r|j                  d       |j                  t        |             r| dfS 	 t	        | |      dfS # t
        $ rL}t        | t              r+|r| j                  d      s| dz  } t	        | |      dfcY d}~S t        d	      |d}~ww xY w)
a  
    Open `file_like` and return as file-like object. First, check if object is
    already file-like; if so, return it as-is. Otherwise, try to pass it
    to open(). If that fails, and `file_like` is a string, and `appendmat` is true,
    append '.mat' and try again.
    zr+readzwax+writeFTz.matNz/Reader needs file name or open file-like object)	setaddissubsetdiropenOSError
isinstancestrendswith)r   r   r   reqses        r   r   r      s     4y3t9,F8#%D
4y3v;}}S^$%It$d** 	i%!3!3F!;V#		4($..A	s$   ,A: :	C5C
8C>C

Cc                     t        | |      \  }}t        |      \  }}|dk(  rt        |fi ||fS |dk(  rt        |fi ||fS |dk(  rt	        d      t        d|       )a,  
    Create reader for matlab .mat format files.

    Returns
    -------
    matreader : MatFileReader object
       Initialized instance of MatFileReader class matching the mat file
       type detected in `filename`.
    file_opened : bool
       Whether the file was opened by this routine.

    r   r      z6Please use HDF reader for matlab v7.3 files, e.g. h5pyzDid not recognize version )r   r   r   r	   NotImplementedError	TypeError)	file_namer   kwargsbyte_streamfile_openedmjvmnvs          r   mat_reader_factoryr1   8   s      *)Y?K#K0HC
axk4V4kAA	k4V4kAA	! #5 6 	6 4SE:;;    )spmatrixc                J   |j                  dd      }t        | |      5 }t        |fi |\  }}|j                  |      }	ddd       d}
ddlm}m}m}m}m	} t        	j                               D ]  \  }} ||      s|t        u rBt        j                  j                  t               f}t#        j$                  |
t&        |       d}|r|j(                  dk(  r|n|}n|j(                  dk(  r|n|} ||      |	|<    ||j+                  |	       |S |	}|S # 1 sw Y   xY w)	a1  
    Load MATLAB file.

    Parameters
    ----------
    file_name : str
        Name of the mat file (do not need .mat extension if
        appendmat==True). Can also pass open file-like object.
    mdict : dict, optional
        Dictionary in which to insert matfile variables.
    appendmat : bool, optional
        True to append the .mat extension to the end of the given
        filename, if not already present. Default is True.
    spmatrix : bool, optional (default: True)
        If ``True``, return sparse matrix. Otherwise return sparse array.
        Format is `COO` for MatFile 4 and `CSC` for MatFile 5.
        Only relevant for sparse variables.

        .. deprecated:: 1.18.0
            The default value for `spmatrix` is changing to False in v1.20.
            That means the default return value will be a sparse array.
            Unless you use * instead of @, ** for matrix power, or you depend
            on 2D shapes from e.g. ``A.sum(axis=0)``, it may not matter to you.
            See :ref:`Migration from spmatrix to sparray <migration_to_sparray>`.

    **kwargs
        The following aditional keyword arguments can be passed:

        byte_order : str or None, optional
            None by default, implying byte order guessed from mat
            file. Otherwise can be one of ('native', '=', 'little', '<',
            'BIG', '>').
        mat_dtype : bool, optional
            If True, return arrays in same dtype as would be loaded into
            MATLAB (instead of the dtype with which they are saved).
        squeeze_me : bool, optional
            Whether to squeeze unit matrix dimensions or not.
        chars_as_strings : bool, optional
            Whether to convert char arrays to string arrays.
        matlab_compatible : bool, optional
            Returns matrices as would be loaded by MATLAB (implies
            squeeze_me=False, chars_as_strings=False, mat_dtype=True,
            struct_as_record=True).
        struct_as_record : bool, optional
            Whether to load MATLAB structs as NumPy record arrays, or as
            old-style NumPy arrays with dtype=object. Setting this flag to
            False replicates the behavior of scipy version 0.7.x (returning
            NumPy object arrays). The default setting is True, because it
            allows easier round-trip load and save of MATLAB files.
        verify_compressed_data_integrity : bool, optional
            Whether the length of compressed sequences in the MATLAB file
            should be checked, to ensure that they are not longer than we expect.
            It is advisable to enable this (the default) because overlong
            compressed sequences in MATLAB files generally indicate that the
            files have experienced some sort of corruption.
        variable_names : None or sequence
            If None (the default) - read all variables in file. Otherwise,
            `variable_names` should be a sequence of strings, giving names of the
            MATLAB variables to read from the file. The reader will skip any
            variable with a name not in this sequence, possibly saving some read
            processing.
        simplify_cells : False, optional
            If True, return a simplified dict structure (which is useful if the mat
            file contains cell arrays). Note that this only affects the structure
            of the result and not its contents (which is identical for both output
            structures). If True, this automatically sets `struct_as_record` to
            False and `squeeze_me` to True, which is required to simplify cells.
        uint16_codec : str, optional
            The codec to use for decoding characters, which are stored as uint16
            values. The default uses the system encoding, but this can be manually
            set to other values such as 'ascii', 'latin1', and 'utf-8'. This
            parameter is relevant only for files stored as v6 and above, and not
            for files stored as v4.

    Returns
    -------
    mat_dict : dict
       dictionary with variable names as keys, and loaded matrices as values.

    Notes
    -----
    v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.

    You will need an HDF5 Python library to read MATLAB 7.3 format mat
    files. Because SciPy does not supply one, we do not implement the
    HDF5 / 7.3 interface here.

    Examples
    --------
    >>> from os.path import dirname, join as pjoin
    >>> import scipy.io as sio

    Get the filename for an example .mat file from the tests/data directory.

    >>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
    >>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')

    Load the .mat file contents.

    >>> mat_contents = sio.loadmat(mat_fname, spmatrix=False)

    The result is a dictionary, one key/value pair for each variable:

    >>> sorted(mat_contents.keys())
    ['__globals__', '__header__', '__version__', 'testdouble']
    >>> mat_contents['testdouble']
    array([[0.        , 0.78539816, 1.57079633, 2.35619449, 3.14159265,
            3.92699082, 4.71238898, 5.49778714, 6.28318531]])

    By default SciPy reads MATLAB structs as structured NumPy arrays where the
    dtype fields are of type `object` and the names correspond to the MATLAB
    struct field names. This can be disabled by setting the optional argument
    `struct_as_record=False`.

    Get the filename for an example .mat file that contains a MATLAB struct
    called `teststruct` and load the contents.

    >>> matstruct_fname = pjoin(data_dir, 'teststruct_7.4_GLNX86.mat')
    >>> matstruct_contents = sio.loadmat(matstruct_fname)
    >>> teststruct = matstruct_contents['teststruct']
    >>> teststruct.dtype
    dtype([('stringfield', 'O'), ('doublefield', 'O'), ('complexfield', 'O')])

    The size of the structured array is the size of the MATLAB struct, not the
    number of elements in any particular field. The shape defaults to 2-D
    unless the optional argument `squeeze_me=True`, in which case all length 1
    dimensions are removed.

    >>> teststruct.size
    1
    >>> teststruct.shape
    (1, 1)

    Get the 'stringfield' of the first element in the MATLAB struct.

    >>> teststruct[0, 0]['stringfield']
    array(['Rats live on no evil star.'],
      dtype='<U26')

    Get the first element of the 'doublefield'.

    >>> teststruct['doublefield'][0, 0]
    array([[ 1.41421356,  2.71828183,  3.14159265]])

    Load the MATLAB struct, squeezing out length 1 dimensions, and get the item
    from the 'complexfield'.

    >>> matstruct_squeezed = sio.loadmat(matstruct_fname, squeeze_me=True)
    >>> matstruct_squeezed['teststruct'].shape
    ()
    >>> matstruct_squeezed['teststruct']['complexfield'].shape
    ()
    >>> matstruct_squeezed['teststruct']['complexfield'].item()
    array([ 1.41421356+1.41421356j,  2.71828183+2.71828183j,
        3.14159265+3.14159265j])
    variable_namesNa  The default value for `spmatrix` is changing to `False` in v1.20.
        That means the default return type will be a sparse array.
        Unless you use * instead of @, ** for matrix power, or you depend
        on 2D shapes from e.g. `A.sum(axis=0)` it may not matter to you.
        See the spmatrix to sparray migration guide for details.
        https://docs.scipy.org/doc/scipy/reference/sparse.migration_to_sparray.html
        r   )issparse
coo_matrix
csc_matrix	coo_array	csc_array)skip_file_prefixesTcoo)popr   r1   get_variablesscipy.sparser6   r7   r8   r9   r:   listitemsr   ospathdirname__file__warningswarnDeprecationWarningformatupdate)r+   mdictr   r3   r,   r5   r   MR_matfile_dictwarn_msgr6   r7   r8   r9   r:   namevarprefixes
fmt_matrixs                       r   r   r   R   s!   z ZZ 0$7N	Iy	1 8Q"1//A''78H TS,,,./ 
1	cC=8#GGOOH57h(:xX+.::+>ZJ
*-***=Y9
!+CL
1 \" L L=8 8s   !DD"c                     t        | |d      5 }|dk(  r|rd}t        |      t        ||      }	n!|dk(  rt        ||d||      }	nt        d      |	j	                  |       ddd       y# 1 sw Y   yxY w)	aO  
    Save a dictionary of names and arrays into a MATLAB-style .mat file.

    This saves the array objects in the given dictionary to a MATLAB-
    style .mat file.

    Parameters
    ----------
    file_name : str or file-like object
        Name of the .mat file (.mat extension not needed if ``appendmat ==
        True``).
        Can also pass open file_like object.
    mdict : dict
        Dictionary from which to save matfile variables. Note that if this dict
        has a key starting with ``_`` or a sub-dict has a key starting with ``_``
        or a digit, these key's items will not be saved in the mat file and
        `MatWriteWarning` will be issued.
    appendmat : bool, optional
        True (the default) to append the .mat extension to the end of the
        given filename, if not already present.
    format : {'5', '4'}, string, optional
        '5' (the default) for MATLAB 5 and up (to 7.2),
        '4' for MATLAB 4 .mat files.
    long_field_names : bool, optional
        False (the default) - maximum field name length in a structure is
        31 characters which is the documented maximum length.
        True - maximum field name length in a structure is 63 characters
        which works for MATLAB 7.6+.
    do_compression : bool, optional
        Whether or not to compress matrices on write. Default is False.
    oned_as : {'row', 'column'}, optional
        If 'column', write 1-D NumPy arrays as column vectors.
        If 'row', write 1-D NumPy arrays as row vectors.

    Examples
    --------
    >>> from scipy.io import savemat
    >>> import numpy as np
    >>> a = np.arange(20)
    >>> mdic = {"a": a, "label": "experiment"}
    >>> mdic
    {'a': array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
        17, 18, 19]),
    'label': 'experiment'}
    >>> savemat("matlab_matrix.mat", mdic)
    wb4z6Long field names are not available for version 4 files5T)do_compressionunicode_stringslong_field_namesoned_aszFormat should be '4' or '5'N)r   
ValueErrorr   r
   put_variables)
r+   rK   r   rI   rZ   rX   r[   file_streammessageMWs
             r   r   r     s    h 
Iy$	7  ;S=R ))W5Bs]/=041A(/	1B :;;
     s   AA++A4c                     t        | |      5 }t        |fi |\  }}|j                         }ddd       |S # 1 sw Y   S xY w)a  
    List variables inside a MATLAB file.

    Parameters
    ----------
    %(file_arg)s
    %(append_arg)s
    %(load_args)s
    %(struct_arg)s

    Returns
    -------
    variables : list of tuples
        A list of tuples, where each tuple holds the matrix name (a string),
        its shape (tuple of ints), and its data class (a string).
        Possible data classes are: int8, uint8, int16, uint16, int32, uint32,
        int64, uint64, single, double, cell, struct, object, char, sparse,
        function, opaque, logical, unknown.

    Notes
    -----
    v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.

    You will need an HDF5 python library to read matlab 7.3 format mat
    files (e.g. h5py). Because SciPy does not supply one, we do not implement the
    HDF5 / 7.3 interface here.

    .. versionadded:: 0.12.0

    Examples
    --------
    >>> from io import BytesIO
    >>> import numpy as np
    >>> from scipy.io import savemat, whosmat

    Create some arrays, and use `savemat` to write them to a ``BytesIO``
    instance.

    >>> a = np.array([[10, 20, 30], [11, 21, 31]], dtype=np.int32)
    >>> b = np.geomspace(1, 10, 5)
    >>> f = BytesIO()
    >>> savemat(f, {'a': a, 'b': b})

    Use `whosmat` to inspect ``f``.  Each tuple in the output list gives
    the name, shape and data type of the array in ``f``.

    >>> whosmat(f)
    [('a', (2, 3), 'int32'), ('b', (1, 5), 'double')]

    N)r   r1   list_variables)r+   r   r,   r   MLr.   	variabless          r   r   r   V  sR    h 
Iy	1 (Q,Q9&9K%%'	( ( s	    7A)rb)T)NT)TrW   FFrow)__doc__rB   rF   
contextlibr   _miobaser   r   _mio4r   r   _mio5r	   r
   scipy._lib.deprecationr   __all__r   r   r1   r   r   r    r2   r   <module>ro      s   
 
  % 5 1 1 +
+  6<4|x |@ " B J 6 6r2   