
    tKgP                        d Z ddlZddlZddl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$ G d  d!      Z% G d" d#      Z& G d$ d%e	      Z'd+d&Z( G d' d(      Z) G d) d*      Z*y),z1 Classes for read / write of matlab (TM) 4 files
    N   )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                       e Zd ZdZdZd Zy)r   Fc                 J    || _         || _        || _        || _        || _        y N)namedtypemclassdims
is_complex)selfrB   rC   rD   rE   rF   s         Y/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/scipy/io/matlab/_mio4.py__init__zVarHeader4.__init__Z   s'     	
	$    N)__name__
__module____qualname__
is_logical	is_globalrI    rJ   rH   r   r   U   s    JI
%rJ   r   c                   D    e Zd ZdZd Zd ZddZddZd Zd Z	d Z
d	 Zy
)r   z" Class to read matlab 4 variables c                     || _         |j                  | _        |j                  | _        |j                  | _        |j                  | _        y rA   )file_reader
mat_streamdtypeschars_as_strings
squeeze_me)rG   rS   s     rH   rI   zVarReader4.__init__j   s?    &%00!(( + < <%00rJ   c                 "   t        | j                  | j                  d         }| j                  j                  t	        |d               j                  d      }|d   dk  s|d   dkD  rt        d      t        |d   d      \  }}|d	vr&t        j                  d
t        |   z  t        d       t        |d      \  }}|dk7  rt        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   zBWe do not support byte ordering '%s'; returned data may be corruptr$   )
stackleveld   z,O in MOPT integer should be 0, wrong format?
   r/   r0   r1   r   )r   rT   rU   readintstrip
ValueErrordivmodwarningswarnr!   UserWarningr   )rG   datarB   MrestOPTrE   rF   rC   s              rH   read_headerzVarReader4.read_headerq   s'   $//4;;x+@A##CX$78>>wG<!tF|d2MNNft,4F?MM 02=a.A%!5 s#46KLLr"4WtG}-']a'
A 	rJ   c                 >   |j                   }|t        k(  r| j                  |      }n\|t        k(  r+| j	                  |      }|r@| j
                  r4t        |      }n(|t        k(  r| j                  |      S t        d|z        |r| j                  rt        |      S |S )NNo reader for class code %s)rD   r   read_full_arrayr   read_char_arrayrV   r   r   read_sparse_array	TypeErrorrW   r   )rG   hdrprocessrD   arrs        rH   array_from_headerzVarReader4.array_from_header   s    \!&&s+C|#&&s+C400&s+~%))#..9FBCCt"3''
rJ   c                 P   |j                   }|j                  }|j                  }|D ]  }||z  }	 | j                  j	                  t        |            }t        |      |k7  rt        d|j                  z        t        j                  |||d      }|r|j                         }|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``
        zNot enough bytes to read matrix '%s'; is this a badly-formed file? Consider listing matrices with `whosmat` and loading named matrices with `variable_names` kwarg to `loadmat`F)shaperC   bufferorder)rC   rE   itemsizerT   r_   r`   lenrb   rB   npndarraycopy)	rG   rt   r   dtrE   	num_bytesdr{   rv   s	            rH   read_sub_arrayzVarReader4.read_sub_array   s    " YYxxKK	ANI %%c)n5v;)# C FIXXN O O jjt! &"$ ((*C
rJ   c                     |j                   r.| j                  |d      }| j                  |d      }||dz  z   S | j                  |      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              ?)rF   r   )rG   rt   resres_js       rH   rp   zVarReader4.read_full_array   sU     >>%%c%6C''%'8E%"*%%""3''rJ   c                 H   | j                  |      j                  t        j                        }|j	                         j                  d      }t        j                  |j                  t        j                  d      t        j                  |            j                         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   rz   rC   r{   )r   astyper   uint8tobytesdecoder   rE   rC   arrayr   )rG   rt   rv   Ss       rH   rq   zVarReader4.read_char_array   sm     !!#&--bhh7KKM  +zz "!#!..2df	5rJ   c                     | j                  |      }|ddddf   }t        |d         t        |d         f}t        j                  |dddf   d      }t        j                  |dddf   d      }|dz  }|dz  }|j                  d   d	k(  rt        j                  |ddd
f   d      }n,t        j                  |ddd
f   d      }|ddd	f   |_        t        j                  j                  |||ff|      S )a   Read and return sparse matrix type

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

        Returns
        -------
        arr : ``scipy.sparse.coo_matrix``
            with dtype ``float`` and shape read from the sparse matrix 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rC   r   r$   r#   floatcomplex)	r   r`   r   ascontiguousarrayrz   imagscipyr>   
coo_matrix)rG   rt   r   tmprE   IJVs           rH   rr   zVarReader4.read_sparse_array   s    6 !!#&#2#a%jCICI/  QqS7  QqS7	Q	Q99Q<1$$S1XG<A$$S1XI>A1XAF||&&1Q%y$77rJ   c                    |j                   }|t        k(  r%t        t        t        |j
                              }nz|t        k(  r7t        t        t        |j
                              }| j                  rA|dd }n:|t        k(  r"|j                  }|j
                  }t        |      dk(  r|d   dk\  r|d   dk\  sy| j                  j                  |j                  |d   dz
  z  d       t        j                  d|| j                  j!                  |j                              }| j                  j                  |j                  |d   dz
  z  d       t        j                  d|| j                  j!                  |j                              }t	        |      t	        |      f}nt#        d|z        | j$                  rt        |D cg c]
  }|dk7  s	| c}      }|S c c}w )	zwRead the shape of the array described by the header.
        The file position after this call is unspecified.
        Nr   r#   r   r   rP   r   ro   )rD   r   tuplemapr`   rE   r   rV   r   rC   r~   rT   seekr}   r   r   r_   rs   rW   )	rG   rt   rD   rz   r   rE   rowscolsxs	            rH   shape_from_headerzVarReader4.shape_from_header  s    \!#c388,-E|##c388,-E$$cr
~%B88DINtAw!|Q1 OO  Q!!<a@::Bb%)__%9%9"++%FHDOO  Q!!<a@::Bb%)__%9%9"++%FHD YD	*E9FBCC??e6eqAv1e67E 7s   

G"G"NT)rK   rL   rM   __doc__rI   rm   rw   r   rp   rq   rr   r   rP   rJ   rH   r   r   g   s/    ,14""H(,5$(8T rJ   r   c                   T     e Zd ZdZe fd       Zd Zd Zd Zd	dZ	d
dZ
d Z xZS )r   z Reader for Mat4 files c                 :    t        |   |g|i | d| _        y)zR Initialize matlab 4 file reader

    %(matstream_arg)s
    %(load_args)s
        N)superrI   _matrix_reader)rG   rT   argskwargs	__class__s       rH   rI   zMatFile4Reader.__init__7  s$     	5d5f5"rJ   c                    | j                   j                  d       t        | j                   t        j                  d            }| j                   j                  d       |dk(  ry|dk  s|dkD  rt
        xr dxs dS t
        xr dxs dS )Nr   r)   r9   rZ   r:   )rT   r   r   r   rC   r   )rG   r.   s     rH   guess_byte_orderzMatFile4Reader.guess_byte_orderA  su    Q$//288D>:Q19!8td{$,33 (S/C/rJ   c                 b    t        t        | j                        | _        t	        |       | _        y)za Run when beginning read of variables

        Sets up readers from parameters in `self`
        N)r   r   
byte_orderrU   r   r   )rG   s    rH   initialize_readzMatFile4Reader.initialize_readM  s$    
 %%5tG(.rJ   c                 "   | j                   j                         }t        d |j                  d      }|j                  j
                  |z  }|j                  r|j                  t        k(  s|dz  }| j                  j                         |z   }||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
        c                     | |z  S rA   rP   )r   ys     rH   <lambda>z0MatFile4Reader.read_var_header.<locals>.<lambda>e  s    !rJ   r   r#   )r   rm   r   rE   rC   r}   rF   rD   r   rT   tell)rG   rt   nremaining_bytesnext_positions        rH   read_var_headerzMatFile4Reader.read_var_headerU  s}     !!--/#SXXq1)),,q0>>#**">q O,,.@M!!rJ   c                 :    | j                   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   rw   )rG   r-   ru   s      rH   read_var_arrayzMatFile4Reader.read_var_arrayl  s      ""44VWEErJ   c                 F   t        |t              r|g}n|t        |      }| j                  j	                  d       | j                          i }| j                         s| j                         \  }}|j                  dn|j                  j                  d      }| ||vr| j                  j	                  |       n| j                  |      ||<   | j                  j	                  |       |"|j                  |       t        |      dk(  r	 |S | j                         s|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.
        r   Nonelatin1)
isinstancestrlistrT   r   r   end_of_streamr   rB   r   r   remover~   )rG   variable_namesmdictrt   r   rB   s         rH   get_variableszMatFile4Reader.get_variables~  s    nc*,-N'!.1NQ$$&!%!5!5!7C XX-6388??83LD)d..H$$]3--c2E$KOO  /)%%d+~&!+ $$& rJ   c                    | j                   j                  d       | j                          g }| j                         s| j	                         \  }}|j
                  dn|j
                  j                  d      }| j                  j                  |      }t        j                  |j                  d      }|j                  |||f       | j                   j                  |       | j                         s|S )z list variables from stream r   r   r   unknown)rT   r   r   r   r   rB   r   r   r   r   getrD   append)rG   varsrt   r   rB   rz   infos          rH   list_variableszMatFile4Reader.list_variables  s    Q$$&!%!5!5!7C XX-6388??83LD''99#>E??3::y9DKKud+,OO  / $$& rJ   r   rA   )rK   rL   rM   r   r   rI   r   r   r   r   r   r   __classcell__)r   s   @rH   r   r   5  s7    !# #
0/".F$>rJ   r   c                 n    t        | |      }t        |      dkD  rt        d      | j                  |      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~   rb   reshape)rv   oned_asrE   s      rH   r   r     s<    " 3 D
4y1} ( ) 	);;trJ   c                   D    e Zd Zd Zd Zd ZeedfdZd Z	d Z
d Zd	 Zy
)r   c                 H    |j                   | _         |j                  | _        y rA   )file_streamr   )rG   file_writers     rH   rI   zVarWriter4.__init__  s    &22"**rJ   c                 Z    | j                   j                  |j                  d             y )Nry   )r|   )r   writer   )rG   rv   s     rH   write_byteszVarWriter4.write_bytes  s!    s{{{56rJ   c                 :    | j                   j                  |       y rA   )r   r   )rG   ss     rH   write_stringzVarWriter4.write_string  s    q!rJ   r   c                 6   t        j                  dt        d         }t         }d}|dz  |dz  z   |dz  z   |z   |d<   |d   |d<   |d	   |d
<   ||d<   t	        |      d	z   |d<   | j                  |       |dz   }	| j                  |	j                  d             y)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
        rP   r-   r   r[   r]   r^   r.   r/   r   r0   r1   r2    r   N)r   emptyr   r   r~   r   r   encode)
rG   rB   rz   rk   rl   r1   r-   rh   rj   rg   s
             rH   write_headerzVarWriter4.write_header  s    $ ".x89!!d(c'"b&! v  (w(wwt9q=x d{$++h/0rJ   c                    t         j                  j                  |      r| j                  ||       yt	        j
                  |      }|j                  }|j                  s |j                  |j                  d            }|j                  }|t        j                  u rt        d      |t        j                  u rt        d      |t        j                  t        j                  fv r| j!                  ||       y| j#                  ||       y)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_sparser   asarrayrC   isnativer   newbyteordertypeobject_rs   voidstr_bytes_
write_charwrite_numeric)rG   rv   rB   r   dtts        rH   r   zVarWriter4.write  s     <<  %c4(jjoYY{{**R__S12Cgg"**?@@BGG^:;;RWWbii((OOC&3%rJ   c                    t        || j                        }|j                  j                  dk(  }	 t        |j                  j
                  dd     }| j                  ||j                  |t        |       |r7| j                  |j                         | j                  |j                         y | j                  |       y # t        $ r. |r|j                  d      }n|j                  d      }t        }Y w xY w)Ncr   c128r'   )rk   rl   r1   )r   r   rC   kindr    r   KeyErrorr   r   r   rz   r   r   realr   )rG   rv   rB   r1   rk   s        rH   r   zVarWriter4.write_numeric  s    T\\*		#%	SYY]]12./A 	$))( %	 	 	'
 SXX&SXX&S!  	jj(jj&A	s    C   4C76C7c                    |j                   j                  t        j                  k(  rA|j                   j                  t        j                   d      j                  k7  rt        |      }t        || j                        }|j                  }| j                  ||t        t               |j                   j                  dk(  rnt        j                  |      }t        j                  dt!        ||      |      }|j#                         j%                  d      }t        j                  |d|      }| j'                  |       y )Nr3   rk   rl   UrP   r   r   r8   )rC   r   r   r   r}   r	   r   r   rz   r   r   r   r   mathprodr   r
   itemr   r   )rG   rv   rB   rE   n_charsst_arrsts          rH   r   zVarWriter4.write_char%  s    99>>RWW$););rxx~?V?V)Vs#CT\\*yy	 	 	
 99>>S iioGZZb&6sG&D'*,F %%i0B**4tB?CrJ   c                 P   |j                         }|j                  j                  dk(  }t        j                  |j
                  dz   d|z   fd      }|j                  |dddf<   |j                  |dddf<   |dddd	fxx   dz  cc<   |r;|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        
       | j                  |       y)zY Sparse matrices are 2-D

        See docstring for VarReader4.read_sparse_array
        r   r   r$   r'   r   Nr   r   r#   r   )tocoorC   r   r   zerosnnzrowcolrg   r   r   rz   r   r   r   r   )rG   rv   rB   Ar1   ijvs         rH   r   zVarWriter4.write_sparse9  s   
 IIK#hh	1U7+48UUCRCE
UUCRCE
CRC!GCAJCAJCAJggBqsFII	 	 	
 	rJ   N)rK   rL   rM   rI   r   r   r   r   r   r   r   r   r   rP   rJ   rH   r   r     s4    +7" +3l! 1B&:",(rJ   r   c                        e Zd ZdZddZddZy)r   z) Class for writing matlab 4 format files Nc                 6    || _         |d}|| _        d | _        y )Nr  )r   r   _matrix_writer)rG   r   r   s      rH   rI   zMatFile4Writer.__init__T  s#    &?G"rJ   c                     t        |       | _        |j                         D ]!  \  }}| j                  j                  ||       # y)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   )rG   r   r   rB   vars        rH   put_variableszMatFile4Writer.put_variables[  s;    ( ).ID#%%c40 'rJ   rA   )rK   rL   rM   r   rI   r  rP   rJ   rH   r   r   R  s    3#1rJ   r   )r  )+r   sysrd   r   numpyr   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   r   r   r   r   r   r   rP   rJ   rH   <module>r     sM   
    F F F :  MMX- 


 ddTTdT !
 	$   






  
 (&H% %$K K\v] vr0I IX1 1rJ   