o
    Ö­jÌ2  ã                
   @   sþ   U d Z ddlmZ ddlZddlmZ ddlmZ	 g d¢Z
G dd	„ d	eƒZG d
d„ deƒZG dd„ deƒZddddddddddœ	Ze e¡Zeed< 	 dd„ Zdd„ Zddœdd „ZeZd!Zd"d#„ Zd/d%d&„ZG d'd(„ d(ƒZG d)d*„ d*ƒZd+d,„ Zd-d.„ ZdS )0zf
Base classes for MATLAB file stream reading.

MATLAB is a registered trademark of the Mathworks inc.
é    )ÚFinalN)Údocceré   )Ú_byteordercodes)ÚMatReadErrorÚMatReadWarningÚMatWriteErrorc                   @   ó   e Zd ZdZdS )r   z"Exception indicating a read issue.N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   úU/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/io/matlab/_miobase.pyr      ó    r   c                   @   r	   )r   z#Exception indicating a write issue.Nr
   r   r   r   r   r      r   r   c                   @   r	   )r   zWarning class for read issues.Nr
   r   r   r   r   r      r   r   zfile_name : str
   Name of the mat file (do not need .mat extension if
   appendmat==True) Can also pass open file-like object.z�appendmat : bool, optional
   True to append the .mat extension to the end of the given
   filename, if not already present. Default is True.až  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).ab  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.zAmat_stream : file-like
   Object with file API, open for reading.a  long_field_names : bool, optional
   * False - maximum field name length in a structure is 31 characters
     which is the documented maximum length. This is the default.
   * True - maximum field name length in a structure is 63 characters
     which works for MATLAB 7.6z[do_compression : bool, optional
   Whether to compress matrices on write. Default is False.z’oned_as : {'row', 'column'}, optional
   If 'column', write 1-D NumPy arrays as column vectors.
   If 'row', write 1D NumPy arrays as row vectors.zbunicode_strings : bool, optional
   If True, write strings as Unicode, else MATLAB usual encoding.)	Úfile_argÚ
append_argÚ	load_argsÚ
struct_argÚmatstream_argÚlong_fieldsÚdo_compressionÚoned_asÚunicode_stringsÚ	docfillerc                 C   s.   |   ¡ }|D ]}t || ¡ |¡||< q|S )až   Convert dtypes in mapping to given order

    Parameters
    ----------
    dtype_template : mapping
       mapping with values returning numpy dtype from ``np.dtype(val)``
    order_code : str
       an order code suitable for using in ``dtype.newbyteorder()``

    Returns
    -------
    dtypes : mapping
       mapping where values have been replaced by
       ``np.dtype(val).newbyteorder(order_code)``

    )ÚcopyÚnpÚdtypeÚnewbyteorder)Údtype_templateÚ
order_codeÚdtypesÚkr   r   r   Úconvert_dtypesƒ   s   r$   c                 C   s"   |j }tjd||  |¡dd�}|S )af  
    Generic get of byte stream data of known type

    Parameters
    ----------
    mat_stream : file_like object
        MATLAB (tm) mat file stream
    a_dtype : dtype
        dtype of array to read. `a_dtype` is assumed to be correct
        endianness.

    Returns
    -------
    arr : ndarray
        Array of dtype `a_dtype` read from stream.

    r   ÚF)Úshaper   ÚbufferÚorder)Úitemsizer   ÚndarrayÚread)Ú
mat_streamÚa_dtypeÚ	num_bytesÚarrr   r   r   Ú
read_dtypeš   s   ýr0   T©Ú	appendmatc                C   sD   ddl m} || |d��}t|ƒW  d  ƒ S 1 sw   Y  dS )a˜  
    Return major, minor tuple depending on apparent mat file type

    Where:

     #. 0,x -> version 4 format mat files
     #. 1,x -> version 5 format mat files
     #. 2,x -> version 7.3 format mat files (HDF format)

    Parameters
    ----------
    file_name : str
       Name of the mat file (do not need .mat extension if
       appendmat==True). Can also pass open file-like object.
    appendmat : bool, optional
       True to append the .mat extension to the end of the given
       filename, if not already present. Default is True.

    Returns
    -------
    major_version : {0, 1, 2}
        major MATLAB File format version
    minor_version : int
        minor MATLAB file format version

    Raises
    ------
    MatReadError
        If the file is empty.
    ValueError
        The matfile version is unknown.

    Notes
    -----
    Has the side effect of setting the file read pointer to 0
    r   )Ú_open_file_contextr1   N)Ú_mior3   Ú_get_matfile_version)Ú	file_namer2   r3   Úfileobjr   r   r   Úmatfile_version´   s   %$ÿr8   é   c                 C   sâ   |   d¡ |  t¡}t|ƒtk rtdƒ‚| d¡tkr#tdt› d�ƒ‚tjdtj|d d… d�}d|v r;|   d¡ dS |   d	¡ |  d¡}|   d¡ t	|d
 dkƒ}t	|| ƒ}t	|d|  ƒ}||f}|dv rj|S t
dj|Ž ƒ‚)Nr   z Mat file appears to be truncatedz&Mat file appears to be corrupt (first z bytes == 0))é   r:   ©r&   r   r'   ©r   r   é|   é   éI   r   )r   r>   z%Unknown mat file type, version {}, {})Úseekr+   Ú_HDR_N_BYTESÚlenr   Úcountr   r*   Úuint8ÚintÚ
ValueErrorÚformat)r7   Ú	hdr_bytesÚ	mopt_intsÚtst_strÚmaj_indÚmaj_valÚmin_valÚretr   r   r   r5   ä   s,   


ÿ



r5   Úcolumnc                 C   sb   | j }|dkr	dS t|ƒdkr/|d dkrdS |dkr|d S |dkr'd| S td	|› d
�ƒ‚|S )aú  
    Determine equivalent MATLAB dimensions for given array

    Parameters
    ----------
    arr : ndarray
        Input array
    oned_as : {'column', 'row'}, optional
        Whether 1-D arrays are returned as MATLAB row or column matrices.
        Default is 'column'.

    Returns
    -------
    dims : tuple
        Shape tuple, in the form MATLAB expects it.

    Notes
    -----
    We had to decide what shape a 1 dimensional array would be by
    default. ``np.atleast_2d`` thinks it is a row vector. The
    default for a vector in MATLAB (e.g., ``>> 1:12``) is a row vector.

    Versions of scipy up to and including 0.11 resulted (accidentally)
    in 1-D arrays being read as column vectors. For the moment, we
    maintain the same tradition here.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.io.matlab._miobase import matdims
    >>> matdims(np.array(1)) # NumPy scalar
    (1, 1)
    >>> matdims(np.array([1])) # 1-D array, 1 element
    (1, 1)
    >>> matdims(np.array([1,2])) # 1-D array, 2 elements
    (2, 1)
    >>> matdims(np.array([[2],[3]])) # 2-D array, column vector
    (2, 1)
    >>> matdims(np.array([[2,3]])) # 2-D array, row vector
    (1, 2)
    >>> matdims(np.array([[[2,3]]])) # 3-D array, rowish vector
    (1, 1, 2)
    >>> matdims(np.array([])) # empty 1-D array
    (0, 0)
    >>> matdims(np.array([[]])) # empty 2-D array
    (0, 0)
    >>> matdims(np.array([[[]]])) # empty 3-D array
    (0, 0, 0)

    Optional argument flips 1-D shape behavior.

    >>> matdims(np.array([1,2]), 'row') # 1-D array, 2 elements
    (1, 2)

    The argument has to make sense though

    >>> matdims(np.array([1,2]), 'bizarre')
    Traceback (most recent call last):
       ...
    ValueError: 1-D option "bizarre" is strange

    r   )r   r   r   r   r<   rO   )r   Úrowz1-D option "z" is strange)r&   rB   rF   )r/   r   r&   r   r   r   Úmatdims   s   ?rQ   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚMatVarReaderz; Abstract class defining required interface for var readersc                 C   s   d S )Nr   )ÚselfÚfile_readerr   r   r   Ú__init__P  s   zMatVarReader.__init__c                 C   ó   dS )z Returns header Nr   ©rS   r   r   r   Úread_headerS  ó   zMatVarReader.read_headerc                 C   rV   )z Reads array given header Nr   )rS   Úheaderr   r   r   Úarray_from_headerW  rY   zMatVarReader.array_from_headerN)r   r   r   r   rU   rX   r[   r   r   r   r   rR   N  s
    rR   c                   @   sF   e Zd ZdZe								ddd„ƒZdd„ Zd	d
„ Zdd„ ZdS )ÚMatFileReadera   Base object for reading mat files

    To make this class functional, you will need to override the
    following methods:

    matrix_getter_factory   - gives object to fetch next matrix from stream
    guess_byte_order        - guesses file byte order from file
    NFTc
           
      C   st   || _ i | _|s|  ¡ }nt |¡}|| _|| _|r|  ¡  n	|| _|| _	|| _
|| _|	| _|	r8d| _d| _dS dS )z–
        Initializer for mat file reader

        mat_stream : file-like
            object with file API, open for reading
    %(load_args)s
        TFN)r,   r"   Úguess_byte_orderÚbocÚto_numpy_codeÚ
byte_orderÚstruct_as_recordÚset_matlab_compatibleÚ
squeeze_meÚchars_as_stringsÚ	mat_dtypeÚ verify_compressed_data_integrityÚsimplify_cells)
rS   r,   r`   re   rc   rd   Úmatlab_compatiblera   rf   rg   r   r   r   rU   f  s$   



þzMatFileReader.__init__c                 C   s   d| _ d| _d| _dS )z4 Sets options to return arrays as MATLAB loads them TFN)re   rc   rd   rW   r   r   r   rb   Œ  s   
z#MatFileReader.set_matlab_compatiblec                 C   s   t jS )z9 As we do not know what file type we have, assume native )r^   Únative_coderW   r   r   r   r]   ’  s   zMatFileReader.guess_byte_orderc                 C   s2   | j  d¡}| j  ¡ }| j  |d ¡ t|ƒdkS )Nr   r   )r,   r+   Útellr@   rB   )rS   ÚbÚcurposr   r   r   Úend_of_stream–  s   
zMatFileReader.end_of_stream)NFFTFTTF)	r   r   r   r   r   rU   rb   r]   rm   r   r   r   r   r\   \  s    	ø%r\   c                 C   s   t  | jjdd… t|ƒ ¡S )z3 Return dtype for given number of items per elementNr>   )r   r   Ústr)r/   Únumr   r   r   Úarr_dtype_number�  s   rp   c                 C   s€   t | jƒ}|s
dg}| t| jjdd… ƒ¡ tj|t| dƒ| d�} | tj	d| jd�kg}t 
|¡s4| S |  ¡ } d| t|ƒ< | S )z$ Convert string array to char array r   r>   Nr;   Ú )r   ú )Úlistr&   ÚappendrE   r   rn   r   r*   rp   ÚarrayÚanyr   Útuple)r/   ÚdimsÚemptiesr   r   r   Úarr_to_chars¢  s   
þ
rz   )rO   )r   Útypingr   Únumpyr   Ú
scipy._libr   rq   r   r^   Ú__all__Ú	Exceptionr   r   ÚUserWarningr   Údoc_dictÚfilldocr   Ú__annotations__r$   r0   r8   Úget_matfile_versionrA   r5   rQ   rR   r\   rp   rz   r   r   r   r   Ú<module>   sB   Ðÿ4-*
NA