
    _MhR                        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j'        ej(                  j)        Z* G d! d"          Z+ G d# d$          Z, G d% d&e          Z-d-d(Z. G d) d*          Z/ G 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                       e Zd ZdZdZd ZdS )r   Fc                 L    || _         || _        || _        || _        || _        d S N)namedtypemclassdims
is_complex)selfrC   rD   rE   rF   rG   s         U/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/io/matlab/_mio4.py__init__zVarHeader4.__init__^   s+     	
	$    N)__name__
__module____qualname__
is_logical	is_globalrJ    rK   rI   r   r   Y   s-        JI
% 
% 
% 
% 
%rK   r   c                   F    e Zd ZdZd Zd ZddZddZd Zd Z	d	 Z
d
 ZdS )r   z" Class to read matlab 4 variables c                 t    || _         |j        | _        |j        | _        |j        | _        |j        | _        d S rB   )file_reader
mat_streamdtypeschars_as_strings
squeeze_me)rH   rT   s     rI   rJ   zVarReader4.__init__n   s7    &%0!( + <%0rK   c                    t          | j        | j        d                   }| j                            t	          |d                                                 d          }|d         dk     s|d         dk    rt          d          t          |d         d          \  }}|d	vr+t          j	        d
t          |          dt          d           t          |d          \  }}|dk    rt          d          t          |d          \  }}|}|d         |d         f}|d         dk    }	| j        |         }
t          ||
|||	          S )z% Read and return header for variable r.   r3       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?
   r0   r1   r2   r   )r   rU   rV   readintstrip
ValueErrordivmodwarningswarnr"   UserWarningr   )rH   datarC   MrestOPTrF   rG   rD   s              rI   read_headerzVarReader4.read_headeru   s^   $/4;x+@AA##CX$7$788>>wGG<!tF|d22MNNNft,,4F??M :k!n : : :%!5 5 5 5 s##466KLLLr""4WtG}-']a'
A  	rK   Tc                 \   |j         }|t          k    r|                     |          }nk|t          k    r.|                     |          }|r| j        rt          |          }n2|t          k    r|                     |          S t          d|           |r| j
        rt          |          S |S )NNo reader for class code )rE   r   read_full_arrayr   read_char_arrayrW   r   r    read_sparse_array	TypeErrorrX   r   )rH   hdrprocessrE   arrs        rI   array_from_headerzVarReader4.array_from_header   s    \!!&&s++CC|##&&s++C ,40 ,&s++~%%))#...@@@AAA 	(t 	("3'''
rK   c                    |j         }t          t          |j        t	          j        |j                            }|t          k    r+t          d|j	        
                    d           d          | j                            |          }t          |          |k    r+t          d|j	        
                    d           d          t	          j        |j        ||d          }|r|                                }|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)shaperD   bufferorder)rD   r   r   rF   npint64itemsize	_MAX_INTPrc   rC   decoderU   r`   lenndarraycopy)rH   ru   r   dt	num_bytesr}   rw   s          rI   read_sub_arrayzVarReader4.read_sub_array   s   " Y3"(2;*?*?@@	y  NSX__X66 N N NO O O %%i00v;;)##EHOOH--E E EF F F
 jsx! &"$ $ $  	((**C
rK   c                     |j         r6|                     |d          }|                     |d          }||dz  z   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              ?)rG   r   )rH   ru   resres_js       rI   rq   zVarReader4.read_full_array   sa     > 	&%%c%66C''%'88E%"*%%""3'''rK   c                 X   |                      |                              t          j                  }|                                                    d          }t          j        |j        t          j        d          t          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-1r4   r|   rD   r}   )r   astyper   uint8tobytesr   r   rF   rD   arrayr   )rH   ru   rw   Ss       rI   rr   zVarReader4.read_char_array   s~     !!#&&--bh77KKMM  ++z "!#!. . ..2dff	5rK   c                 >   |                      |          }|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          }n1t          j        |ddd
f         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rD   r   r%   r$   floatcomplex)	r   ra   r   ascontiguousarrayr|   imagscipyr?   	coo_array)rH   ru   r   tmprF   IJVs           rI   rs   zVarReader4.read_sparse_array   s&   6 !!#&&#2#aaa%jCICI/ QQQqS777 QQQqS777	Q	Q9Q<1$S1XG<<<AA$S1XI>>>A1XAF|%%q!Ai666rK   c                    |j         }|t          k    r)t          t          t          |j                            }n}|t          k    r:t          t          t          |j                            }| j        r
|dd         }n8|t          k    r|j	        }|j        }t          |          dk    r|d         dk    r|d         dk    sdS | j                            |j        |d         dz
  z  d           t          j        d|| j                            |j                            }| j                            |j        |d         dz
  z  d           t          j        d|| j                            |j                            }t	          |          t	          |          f}nt#          d|           | j        rt          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   rQ   r   rp   c                     g | ]
}|d k    |S )r   rQ   ).0xs     rI   
<listcomp>z0VarReader4.shape_from_header.<locals>.<listcomp>8  s    666qAvv1vvvrK   )rE   r   tuplemapra   rF   r   rW   r    rD   r   rU   seekr   r   r   r`   rt   rX   )rH   ru   rE   r|   r   rF   rowscolss           rI   shape_from_headerzVarReader4.shape_from_header  s    \!!#c38,,--EE|###c38,,--E$ #crc
~%%B8DIINNtAw!||Q1r O  Q!!<a@@@:Bb%)_%9%9"+%F%FH H HDO  Q!!<a@@@:Bb%)_%9%9"+%F%FH H HD YYD		*EE@@@AAA? 	866e66677ErK   NT)rL   rM   rN   __doc__rJ   rn   rx   r   rq   rr   rs   r   rQ   rK   rI   r   r   k   s        ,,1 1 1  4   "% % % %N( ( (,5 5 5$(7 (7 (7T         rK   r   c                   Z     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                 P     t                      j        |g|R i | d| _        dS )zR Initialize matlab 4 file reader

    %(matstream_arg)s
    %(load_args)s
        N)superrJ   _matrix_reader)rH   rU   argskwargs	__class__s       rI   rJ   zMatFile4Reader.__init__>  s:     	5d555f555"rK   c                    | j                             d           t          | j         t          j        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*   r:   r[   r;   )rU   r   r   r   rD   r   )rH   r/   s     rI   guess_byte_orderzMatFile4Reader.guess_byte_orderH  s    Q$/28D>>::Q1993!88td{{$,33 (S/C/rK   c                 l    t          t          | j                  | _        t	          |           | _        dS )za Run when beginning read of variables

        Sets up readers from parameters in `self`
        N)r	   r   
byte_orderrV   r   r   )rH   s    rI   initialize_readzMatFile4Reader.initialize_readT  s.    
 %%5tGG(..rK   c                    | j                                         }t          t          |j        t          j        |j        j                            }|j	        r|j
        t          k    s|dz  }| 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
        r$   )r   rn   r   r   rF   r   r   rD   r   rG   rE   r    rU   tell)rH   ru   remaining_bytesnext_positions       rI   read_var_headerzMatFile4Reader.read_var_header\  s}     !--// ch9K0L0LMM> 	!#*">">q O,,..@M!!rK   Tc                 8    | 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   rx   )rH   r.   rv   s      rI   read_var_arrayzMatFile4Reader.read_var_arrays  s      "44VWEEErK   Nc                 z   t          |t                    r|g}n|t          |          }| j                            d           |                                  i }|                                 s|                                 \  }}|j        dn|j        	                    d          }|||vr| j                            |           o| 
                    |          ||<   | j                            |           |)|                    |           t          |          dk    rn|                                 |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   Nonerz   )
isinstancestrlistrU   r   r   end_of_streamr   rC   r   r   remover   )rH   variable_namesmdictru   r   rC   s         rI   get_variableszMatFile4Reader.get_variables  sK    nc** 	2,-NN'!.11NQ$$&& 	!%!5!5!7!7C X-6638??83L3LD)d..H.H$$]333--c22E$KO  ///)%%d+++~&&!++ $$&& 	 rK   c                    | j                             d           |                                  g }|                                 s|                                 \  }}|j        dn|j                            d          }| j                            |          }t          
                    |j        d          }|                    |||f           | j                             |           |                                 |S )z list variables from stream r   Nr   rz   unknown)rU   r   r   r   r   rC   r   r   r   r   getrE   append)rH   varsru   r   rC   r|   infos          rI   list_variableszMatFile4Reader.list_variables  s    Q$$&& 	0!%!5!5!7!7C X-6638??83L3LD'99#>>E??3:y99DKKud+,,,O  /// $$&& 	0 rK   r   rB   )rL   rM   rN   r   r   rJ   r   r   r   r   r   r   __classcell__)r   s   @rI   r   r   <  s        !!# # # # Y#
0 
0 
0/ / /" " ".F F F F$   >      rK   r   rowc                     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   rc   reshape)rw   oned_asrF   s      rI   r   r     sK    " 3  D
4yy1}} ( ) ) 	);;trK   c                   F    e Zd Zd Zd Zd ZeedfdZd Z	d Z
d Zd	 Zd
S )r   c                 6    |j         | _         |j        | _        d S rB   )file_streamr   )rH   file_writers     rI   rJ   zVarWriter4.__init__  s    &2"*rK   c                 b    | j                             |                    d                     d S )Nr{   )r~   )r   writer   )rH   rw   s     rI   write_byteszVarWriter4.write_bytes  s-    s{{{5566666rK   c                 :    | j                             |           d S rB   )r   r   )rH   ss     rI   write_stringzVarWriter4.write_string  s    q!!!!!rK   r   c                 l   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<   |                     |           |dz   }	|                     |	                    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
        rQ   r.   r   r\   r^   r_   r/   r0   r   r1   r2   r3    rz   N)r   emptyr   r   r   r   r   encode)
rH   rC   r|   rl   rm   r2   r.   ri   rk   rh   s
             rI   write_headerzVarWriter4.write_header  s    $ ".x899!!d(c'"b&! v  (w(wwt99q=x   d{$++h//00000rK   c                    t           j                            |          r|                     ||           dS t	          j        |          }|j        }|j        s(|                    |	                    d                    }|j
        }|t          j        u rt          d          |t          j        u rt          d          |t          j        t          j        fv r|                     ||           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_sparser   asarrayrD   isnativer   newbyteordertypeobject_rt   voidstr_bytes_
write_charwrite_numeric)rH   rw   rC   r   dtts        rI   r   zVarWriter4.write  s     <  %% 	c4(((FjooY{ 	3**R__S1122Cg"*?@@@BG^^:;;;RWbi(((OOC&&&F3%%%%%rK   c                    t          || j                  }|j        j        dk    }	 t          |j        j        dd                   }nD# t          $ r7 |r|                    d          }n|                    d          }t          }Y nw xY w| 	                    ||j
        |t          |           |r6|                     |j                   |                     |j                   d S |                     |           d S )Ncr   c128r(   )rl   rm   r2   )r   r   rD   kindr!   r   KeyErrorr   r   r   r|   r   r   realr   )rH   rw   rC   r2   rl   s        rI   r   zVarWriter4.write_numeric  s   T\**	#%	SY]122./AA 	 	 	 'jj((jj&&AAA	 	$)( %	 	 	' 	' 	'
  	"SX&&&SX&&&&&S!!!!!s   A >BBc                 \   |j         j        t          j        k    r6|j         j        t          j         d          j        k    rt          |          }t          || j                  }|j        }| 	                    ||t          t                     |j         j        dk    rwt          j        |          }t          j        dt!          ||          |          }|                                                    d          }t          j        |d|          }|                     |           d S )Nr4   rl   rm   UrQ   r   r   r9   )rD   r   r   r   r   r
   r   r   r|   r   r   r   r   mathprodr   r   itemr   r   )rH   rw   rC   rF   n_charsst_arrsts          rI   r   zVarWriter4.write_char,  s   9>RW$$);rx~~?V)V)Vs##CT\**y	 	 	 	 	
 9>S  iooGZb&6sG&D&D'*, , ,F %%i00B*4tB???CrK   c                    |                                 }|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        t          t          
           |                     |           dS )zY Sparse matrices are 2-D

        See docstring for VarReader4.read_sparse_array
        r   r   r%   r(   r   Nr   r   r$   r   )tocoorD   r   r   zerosnnzr   colrh   r   r   r|   r   r   r    r   )rH   rw   rC   Ar2   ijvs         rI   r   zVarWriter4.write_sparse@  s+   
 IIKK#h	1U7+4888UCRCE
UCRCE
CRC!G 	 CAJCAJJCAJgBqsFI	 	 	 	 	
 	rK   N)rL   rM   rN   rJ   r   r   r   r   r   r   r   r   r   rQ   rK   rI   r   r     s        + + +7 7 7" " " +3l! 1 1 1 1B& & &:" " ",  (    rK   r   c                   "    e Zd ZdZddZddZdS )r   z) Class for writing matlab 4 format files Nc                 8    || _         |d}|| _        d | _        d S )Nr   )r   r   _matrix_writer)rH   r   r   s      rI   rJ   zMatFile4Writer.__init__[  s)    &?G"rK   c                     t          |           | _        |                                D ] \  }}| j                            ||           !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   )rH   r   r   rC   vars        rI   put_variableszMatFile4Writer.put_variablesb  sU    ( ).. 	1 	1ID#%%c40000	1 	1rK   rB   )rL   rM   rN   r   rJ   r  rQ   rK   rI   r   r   Y  sB        33# # # #1 1 1 1 1 1rK   r   )r   )1r   sysre   r   operatorr   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   iinfointpmaxr   r   r   r   r   r   r   rQ   rK   rI   <module>r      s    



                F F F F F F F F F F F F F F F F F F : 9 9 9 9 9 9 9         MX- 


 ddTTdT ! ! !
 	$   






   
  (&H BHRW!	% % % % % % % %$N N N N N N N Nbv v v v v] v v vr   0I I I I I I I IX1 1 1 1 1 1 1 1 1 1rK   