o
    Ö­jR  ã                   @   sv  d Z ddlZddlZddlZddlmZ ddlZddlZ	ddl
mZmZmZmZmZmZmZ ddlmZmZ ddlmZ g d¢Zejd	kZdZdZd
ZdZdZdZededededededdg d¢ddiZ eeeeeeeeeeedœZ!dZ"dZ#d
Z$ddddddœZ%e"de#de$d iZ&e 'ej(¡j)Z*G d!d"„ d"ƒZ+G d#d$„ d$ƒZ,G d%d&„ d&eƒZ-d.d(d)„Z.G d*d+„ d+ƒZ/G d,d-„ d-ƒZ0dS )/z1 Classes for read / write of matlab (TM) 4 files
é    N)Úmulé   )ÚMatFileReaderÚ	docfillerÚmatdimsÚ
read_dtypeÚconvert_dtypesÚarr_to_charsÚarr_dtype_number)Úsqueeze_elementÚchars_to_strings)Úreduce)ÚMatFile4ReaderÚMatFile4WriterÚSYS_LITTLE_ENDIANÚ
VarHeader4Ú
VarReader4Ú
VarWriter4Ú	arr_to_2dÚmclass_infoÚmdtypes_templateÚmiDOUBLEÚmiINT16ÚmiINT32ÚmiSINGLEÚmiUINT16ÚmiUINT8ÚmxCHAR_CLASSÚmxFULL_CLASSÚmxSPARSE_CLASSÚnp_to_mtypesÚorder_codesÚlittleé   é   é   é   Úf8Úf4Úi4Úi2Úu2Úu1Úheader))Úmoptr)   )Úmrowsr)   )Úncolsr)   )Úimagfr)   )Únamlenr)   ÚU1)r'   Úc32Úc24Úc16r(   Úc8r)   r*   r+   r,   ÚS1ú<ú>zVAX D-floatzVAX G-floatÚCray)r   r   r#   r$   r%   ÚdoubleÚcharÚsparsec                   @   s   e Zd ZdZdZdd„ ZdS )r   Fc                 C   s"   || _ || _|| _|| _|| _d S ©N)ÚnameÚdtypeÚmclassÚdimsÚ
is_complex)Úselfr@   rA   rB   rC   rD   © rF   úR/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/io/matlab/_mio4.pyÚ__init__^   s
   
zVarHeader4.__init__N)Ú__name__Ú
__module__Ú__qualname__Ú
is_logicalÚ	is_globalrH   rF   rF   rF   rG   r   Y   s    r   c                   @   sT   e Zd ZdZdd„ Zdd„ Zddd„Zdd	d
„Zdd„ Zdd„ Z	dd„ Z
dd„ ZdS )r   z" Class to read matlab 4 variables c                 C   s*   || _ |j| _|j| _|j| _|j| _d S r?   )Úfile_readerÚ
mat_streamÚdtypesÚchars_as_stringsÚ
squeeze_me)rE   rN   rF   rF   rG   rH   n   s
   zVarReader4.__init__c                 C   sè   t | j| jd ƒ}| j t|d ƒ¡ d¡}|d dk s"|d dkr&tdƒ‚t|d dƒ\}}|d	vrAtj	d
t
| › d�tdd� t|dƒ\}}|dkrPtdƒ‚t|dƒ\}}|}|d |d f}|d dk}	| j| }
t||
|||	ƒS )z% Read and return header for variable r-   r2   ó    r.   r   éˆ  z.Mat 4 mopt wrong format, byteswapping problem?éè  )r   r   z!We do not support byte ordering 'z'; returned data may be corruptr$   )Ú
stackleveléd   z,O in MOPT integer should be 0, wrong format?é
   r/   r0   r1   r   )r   rO   rP   ÚreadÚintÚstripÚ
ValueErrorÚdivmodÚwarningsÚwarnr!   ÚUserWarningr   )rE   Údatar@   ÚMÚrestÚOÚPÚTrC   rD   rA   rF   rF   rG   Úread_headeru   s0   þ
ûzVarReader4.read_headerTc                 C   sv   |j }|tkr|  |¡}n#|tkr |  |¡}|r| jrt|ƒ}n|tkr)|  |¡S t	d|› �ƒ‚|r9| j
r9t|ƒS |S )NúNo reader for class code )rB   r   Úread_full_arrayr   Úread_char_arrayrQ   r   r   Úread_sparse_arrayÚ	TypeErrorrR   r   )rE   ÚhdrÚprocessrB   ÚarrrF   rF   rG   Úarray_from_header�   s   

€

zVarReader4.array_from_headerc                 C   s�   |j }tt|jt |j¡ƒ}|tkrtd|j	 
d¡› d�ƒ‚| j |¡}t|ƒ|kr6td|j	 
d¡› d�ƒ‚tj|j||dd�}|rF| ¡ }|S )aì   Mat4 read using header `hdr` dtype and dims

        Parameters
        ----------
        hdr : object
           object with attributes ``dtype``, ``dims``. dtype is assumed to be
           the correct endianness
        copy : bool, optional
           copies array before return if True (default True)
           (buffer is usually read only)

        Returns
        -------
        arr : ndarray
            of dtype given by `hdr` ``dtype`` and shape given by `hdr` ``dims``
        z
Variable 'Úlatin1zL' has byte length longer than largest possible NumPy array on this platform.z!Not enough bytes to read matrix 'zŒ'; is this a badly-formed file? Consider listing matrices with `whosmat` and loading named matrices with `variable_names` kwarg to `loadmat`ÚF)ÚshaperA   ÚbufferÚorder)rA   r   r   rC   ÚnpÚint64ÚitemsizeÚ	_MAX_INTPr\   r@   ÚdecoderO   rY   ÚlenÚndarrayÚcopy)rE   rm   r}   ÚdtÚ	num_bytesrt   ro   rF   rF   rG   Úread_sub_array    s*   ÿ
ÿÿýzVarReader4.read_sub_arrayc                 C   s8   |j r| j|dd�}| j|dd�}||d  S |  |¡S )aM   Full (rather than sparse) matrix getter

        Read matrix (array) can be real or complex

        Parameters
        ----------
        hdr : ``VarHeader4`` instance

        Returns
        -------
        arr : ndarray
            complex array if ``hdr.is_complex`` is True, otherwise a real
            numeric array
        F)r}   y              ð?)rD   r€   )rE   rm   ÚresÚres_jrF   rF   rG   ri   Ç   s
   
zVarReader4.read_full_arrayc                 C   sB   |   |¡ tj¡}| ¡  d¡}tj|jt d¡t 	|¡d� 
¡ S )zñ latin-1 text matrix (char matrix) reader

        Parameters
        ----------
        hdr : ``VarHeader4`` instance

        Returns
        -------
        arr : ndarray
            with dtype 'U1', shape given by `hdr` ``dims``
        úlatin-1r3   ©rs   rA   rt   )r€   Úastyperv   Úuint8Útobytesrz   r|   rC   rA   Úarrayr}   )rE   rm   ro   ÚSrF   rF   rG   rj   Ý   s   þþzVarReader4.read_char_arrayc                 C   sæ   |   |¡}|dd…dd…f }t|d ƒt|d ƒf}tj|dd…df dd�}tj|dd…df dd�}|d8 }|d8 }|jd d	krRtj|dd…d
f dd�}ntj|dd…d
f dd�}|dd…d	f |_tj |||ff|¡S )a¬   Read and return sparse matrix type

        Parameters
        ----------
        hdr : ``VarHeader4`` instance

        Returns
        -------
        arr : coo_array
            with dtype ``float`` and shape read from the sparse array data

        Notes
        -----
        MATLAB 4 real sparse arrays are saved in a N+1 by 3 array format, where
        N is the number of non-zero values. Column 1 values [0:N] are the
        (1-based) row indices of the each non-zero value, column 2 [0:N] are the
        column indices, column 3 [0:N] are the (real) values. The last values
        [-1,0:2] of the rows, column indices are shape[0] and shape[1]
        respectively of the output matrix. The last value for the values column
        is a padding 0. mrows and ncols values from the header give the shape of
        the stored matrix, here [N+1, 3]. Complex data are saved as a 4 column
        matrix, where the fourth column contains the imaginary component; the
        last value is again 0. Complex sparse data do *not* have the header
        ``imagf`` field set to True; the fact that the data are complex is only
        detectable because there are 4 storage columns.
        Néÿÿÿÿ)rŠ   r   )rŠ   r   r   Úintc©rA   r   r$   r#   ÚfloatÚcomplex)	r€   rZ   rv   Úascontiguousarrayrs   ÚimagÚscipyr>   Ú	coo_array)rE   rm   r�   ÚtmprC   ÚIÚJÚVrF   rF   rG   rk   ï   s   
zVarReader4.read_sparse_arrayc                 C   s0  |j }|tkrttt|jƒƒ}nz|tkr&ttt|jƒƒ}| jr%|dd… }nd|tkrƒ|j	}|j}t
|ƒdkrB|d dkrB|d dksDdS | j |j|d d  d¡ tjd|| j |j¡d�}| j |j|d d  d¡ tjd|| j |j¡d�}t|ƒt|ƒf}ntd|› �ƒ‚| jr–td	d
„ |D ƒƒ}|S )zwRead the shape of the array described by the header.
        The file position after this call is unspecified.
        NrŠ   r#   r   r   rF   r„   rh   c                 S   s   g | ]}|d kr|‘qS )r   rF   )Ú.0ÚxrF   rF   rG   Ú
<listcomp>8  s    z0VarReader4.shape_from_header.<locals>.<listcomp>)rB   r   ÚtupleÚmaprZ   rC   r   rQ   r   rA   r{   rO   Úseekrx   rv   r|   rY   rl   rR   )rE   rm   rB   rs   r~   rC   ÚrowsÚcolsrF   rF   rG   Úshape_from_header  s4   €$ÿÿzVarReader4.shape_from_headerN©T)rI   rJ   rK   Ú__doc__rH   rg   rp   r€   ri   rj   rk   rŸ   rF   rF   rF   rG   r   k   s    

'*r   c                       sX   e Zd ZdZe‡ fdd„ƒZdd„ Zdd„ Zdd	„ Zddd„Z	ddd„Z
dd„ Z‡  ZS )r   z Reader for Mat4 files c                    s$   t ƒ j|g|¢R i |¤Ž d| _dS )zR Initialize matlab 4 file reader

    %(matstream_arg)s
    %(load_args)s
        N)ÚsuperrH   Ú_matrix_reader)rE   rO   ÚargsÚkwargs©Ú	__class__rF   rG   rH   >  s   
zMatFile4Reader.__init__c                 C   s^   | j  d¡ t| j t d¡ƒ}| j  d¡ |dkrdS |dk s#|dkr)tr'dp(dS tr-dp.dS )Nr   r)   r9   rT   r:   )rO   rœ   r   rv   rA   r   )rE   r.   rF   rF   rG   Úguess_byte_orderH  s   zMatFile4Reader.guess_byte_orderc                 C   s   t t| jƒ| _t| ƒ| _dS )za Run when beginning read of variables

        Sets up readers from parameters in `self`
        N)r   r   Ú
byte_orderrP   r   r£   )rE   rF   rF   rG   Úinitialize_readT  s   zMatFile4Reader.initialize_readc                 C   sP   | j  ¡ }tt|jt |jj¡ƒ}|j	r|j
tks|d9 }| j ¡ | }||fS )ab   Read and return header, next position

        Parameters
        ----------
        None

        Returns
        -------
        header : object
           object that can be passed to self.read_var_array, and that
           has attributes ``name`` and ``is_global``
        next_position : int
           position in stream of next variable
        r#   )r£   rg   r   r   rC   rv   rw   rA   rx   rD   rB   r   rO   Útell)rE   rm   Úremaining_bytesÚnext_positionrF   rF   rG   Úread_var_header\  s   
zMatFile4Reader.read_var_headerTc                 C   s   | j  ||¡S )a¥   Read array, given `header`

        Parameters
        ----------
        header : header object
           object with fields defining variable header
        process : {True, False}, optional
           If True, apply recursive post-processing during loading of array.

        Returns
        -------
        arr : array
           array with post-processing applied or not according to
           `process`.
        )r£   rp   )rE   r-   rn   rF   rF   rG   Úread_var_arrays  s   zMatFile4Reader.read_var_arrayNc                 C   sÐ   t |tƒr	|g}n|durt|ƒ}| j d¡ |  ¡  i }|  ¡ sf|  ¡ \}}|jdu r.dn|j 	d¡}|durC||vrC| j |¡ q|  
|¡||< | j |¡ |durb| |¡ t|ƒdkrb	 |S |  ¡ r!|S )a,   get variables from stream as dictionary

        Parameters
        ----------
        variable_names : None or str or sequence of str, optional
            variable name, or sequence of variable names to get from Mat file /
            file stream. If None, then get all variables in file.
        Nr   ÚNonerq   )Ú
isinstanceÚstrÚlistrO   rœ   rª   Úend_of_streamr®   r@   rz   r¯   Úremover{   )rE   Úvariable_namesÚmdictrm   r­   r@   rF   rF   rG   Úget_variables…  s,   
	
ôzMatFile4Reader.get_variablesc                 C   sˆ   | j  d¡ |  ¡  g }|  ¡ sB|  ¡ \}}|jdu rdn|j d¡}| j |¡}t	 
|jd¡}| |||f¡ | j  |¡ |  ¡ r|S )z list variables from stream r   Nr°   rq   Úunknown)rO   rœ   rª   r´   r®   r@   rz   r£   rŸ   r   ÚgetrB   Úappend)rE   Úvarsrm   r­   r@   rs   ÚinforF   rF   rG   Úlist_variables¤  s   ùzMatFile4Reader.list_variablesr    r?   )rI   rJ   rK   r¡   r   rH   r¨   rª   r®   r¯   r¸   r¾   Ú__classcell__rF   rF   r¦   rG   r   <  s    	

r   Úrowc                 C   s(   t | |ƒ}t|ƒdkrtdƒ‚|  |¡S )aŒ   Make ``arr`` exactly two dimensional

    If `arr` has more than 2 dimensions, raise a ValueError

    Parameters
    ----------
    arr : array
    oned_as : {'row', 'column'}, optional
       Whether to reshape 1-D vectors as row vectors or column vectors.
       See documentation for ``matdims`` for more detail

    Returns
    -------
    arr2d : array
       2-D version of the array
    r#   z=Matlab 4 files cannot save arrays with more than 2 dimensions)r   r{   r\   Úreshape)ro   Úoned_asrC   rF   rF   rG   r   µ  s   

r   c                   @   sT   e Zd Zdd„ Zdd„ Zdd„ Zeedfdd	„Zd
d„ Z	dd„ Z
dd„ Zdd„ ZdS )r   c                 C   s   |j | _ |j| _d S r?   )Úfile_streamrÂ   )rE   Úfile_writerrF   rF   rG   rH   Î  s   zVarWriter4.__init__c                 C   s   | j  |jdd�¡ d S )Nrr   )ru   )rÃ   Úwriter‡   )rE   ro   rF   rF   rG   Úwrite_bytesÒ  s   zVarWriter4.write_bytesc                 C   s   | j  |¡ d S r?   )rÃ   rÅ   )rE   ÚsrF   rF   rG   Úwrite_stringÕ  s   zVarWriter4.write_stringr   c           
      C   s�   t  dtd ¡}t }d}|d |d  |d  | |d< |d |d< |d	 |d
< ||d< t|ƒd	 |d< |  |¡ |d }	|  |	 d¡¡ dS )a)   Write header for given data options

        Parameters
        ----------
        name : str
            name of variable
        shape : sequence
            Shape of array as it will be read in matlab
        P : int, optional
            code for mat4 data type, one of ``miDOUBLE, miSINGLE, miINT32,
            miINT16, miUINT16, miUINT8``
        T : int, optional
            code for mat4 matrix class, one of ``mxFULL_CLASS, mxCHAR_CLASS,
            mxSPARSE_CLASS``
        imagf : int, optional
            flag indicating complex
        rF   r-   r   rU   rW   rX   r.   r/   r   r0   r1   r2   ú rq   N)rv   Úemptyr   r   r{   rÆ   rÈ   Úencode)
rE   r@   rs   re   rf   r1   r-   rb   rd   ra   rF   rF   rG   Úwrite_headerØ  s"   ÿþý
zVarWriter4.write_headerc                 C   sœ   t j |¡r|  ||¡ dS t |¡}|j}|js!| | 	d¡¡}|j
}|tju r-tdƒ‚|tju r6tdƒ‚|tjtjfv rF|  ||¡ dS |  ||¡ dS )z¿ Write matrix `arr`, with name `name`

        Parameters
        ----------
        arr : array_like
           array to write
        name : str
           name in matlab workspace
        Nú=z!Cannot save object arrays in Mat4zCannot save void type arrays)r‘   r>   ÚissparseÚwrite_sparserv   ÚasarrayrA   Úisnativer…   ÚnewbyteorderÚtypeÚobject_rl   ÚvoidÚstr_Úbytes_Ú
write_charÚwrite_numeric)rE   ro   r@   r~   ÚdttrF   rF   rG   rÅ   ù  s    


zVarWriter4.writec                 C   s¦   t || jƒ}|jjdk}zt|jjdd …  }W n ty0   |r'| d¡}n| d¡}t}Y nw | j	||j
|t|d� |rL|  |j¡ |  |j¡ d S |  |¡ d S )NÚcr   Úc128r'   )re   rf   r1   )r   rÂ   rA   Úkindr    r²   ÚKeyErrorr…   r   rÌ   rs   r   rÆ   Úrealr�   )rE   ro   r@   r1   re   rF   rF   rG   rÙ     s(   
ûüzVarWriter4.write_numericc                 C   s¦   |j jtjkr|j jt  d¡jkrt|ƒ}t|| jƒ}|j}| j	||t
td� |j jdkrLt |¡}tjdt||ƒ|d�}| ¡  d¡}tj|d|d�}|  |¡ d S )Nr3   ©re   rf   ÚUrF   r„   rƒ   r8   )rA   rÓ   rv   rÖ   rx   r	   r   rÂ   rs   rÌ   r   r   rÝ   ÚmathÚprodr|   r
   ÚitemrË   rÆ   )rE   ro   r@   rC   Ún_charsÚst_arrÚstrF   rF   rG   rØ   ,  s&   "ü
þzVarWriter4.write_charc                 C   sä   |  ¡ }|jjdk}tj|jd d| fdd�}|j|dd…df< |j|dd…df< |dd…dd	…f  d7  < |rO|jj	|dd…d	f< |jj
|dd…df< n	|j|dd…d	f< |j|ddd	…f< | j||jttd
� |  |¡ dS )zY Sparse matrices are 2-D

        See docstring for VarReader4.read_sparse_array
        rÛ   r   r$   r'   rŒ   NrŠ   r   r#   rà   )ÚtocoorA   rÝ   rv   ÚzerosÚnnzrÀ   Úcolra   rß   r�   rs   rÌ   r   r   rÆ   )rE   ro   r@   ÚAr1   ÚijvrF   rF   rG   rÏ   @  s$   üzVarWriter4.write_sparseN)rI   rJ   rK   rH   rÆ   rÈ   r   r   rÌ   rÅ   rÙ   rØ   rÏ   rF   rF   rF   rG   r   Í  s    !r   c                   @   s$   e Zd ZdZddd„Zddd„ZdS )r   z) Class for writing matlab 4 format files Nc                 C   s"   || _ |d u r	d}|| _d | _d S )NrÀ   )rÃ   rÂ   Ú_matrix_writer)rE   rÃ   rÂ   rF   rF   rG   rH   [  s
   
zMatFile4Writer.__init__c                 C   s.   t | ƒ| _| ¡ D ]\}}| j ||¡ q	dS )aç   Write variables in `mdict` to stream

        Parameters
        ----------
        mdict : mapping
           mapping with method ``items`` return name, contents pairs
           where ``name`` which will appeak in the matlab workspace in
           file load, and ``contents`` is something writeable to a
           matlab file, such as a NumPy array.
        write_header : {None, True, False}
           If True, then write the matlab file header before writing the
           variables. If None (the default) then write the file header
           if we are at position 0 in the stream. By setting False
           here, and setting the stream position to the end of the file,
           you can append variables to a matlab file
        N)r   rî   ÚitemsrÅ   )rE   r·   rÌ   r@   ÚvarrF   rF   rG   Úput_variablesb  s   
ÿzMatFile4Writer.put_variablesr?   )rI   rJ   rK   r¡   rH   rñ   rF   rF   rF   rG   r   Y  s    
r   )rÀ   )1r¡   Úsysr^   râ   Úoperatorr   Únumpyrv   Úscipy.sparser‘   Ú_miobaser   r   r   r   r   r	   r
   Ú
_mio_utilsr   r   Ú	functoolsr   Ú__all__Ú	byteorderr   r   r   r   r   r   r   r   r    r   r   r   r!   r   ÚiinfoÚintpÚmaxry   r   r   r   r   r   r   rF   rF   rF   rG   Ú<module>   sz    $
	ôõû	ý R
y 