o
    ?Hh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   U/home/air/sanwanet/gpt-api/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$   )
stackleveld   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rt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 