
    UgP                        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*dS )-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dS )r   Fc                 L    || _         || _        || _        || _        || _        d S N)namedtypemclassdims
is_complex)selfrB   rC   rD   rE   rF   s         T/var/www/surfInsights/venv3-11/lib/python3.11/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                   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 rA   )file_reader
mat_streamdtypeschars_as_strings
squeeze_me)rG   rS   s     rH   rI   zVarReader4.__init__j   s7    &%0!( + <%0rJ   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          |         z  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-   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   sV   $/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 02=a.A%!5 5 5 5 s##466KLLLr""4WtG}-']a'
A  	rJ   Tc                 \   |j         }|t          k    r|                     |          }nk|t          k    r.|                     |          }|r| j        rt          |          }n2|t          k    r|                     |          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++CC|##&&s++C ,40 ,&s++~%%))#...9FBCCC 	(t 	("3'''
rJ   c                 B   |j         }|j        }|j        }|D ]}||z  }| j                            t          |                    }t          |          |k    rt          d|j        z            t          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``
        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    " YxK	 	 	ANII%%c)nn55v;;)## C FIXN O O O jt! &"$ $ $  	((**C
rJ   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              ?)rF   r   )rG   rt   resres_js       rH   rp   zVarReader4.read_full_array   sa     > 	&%%c%66C''%'88E%"*%%""3'''rJ   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-1r3   rz   rC   r{   )r   astyper   uint8tobytesdecoder   rE   rC   arrayr   )rG   rt   rv   Ss       rH   rq   zVarReader4.read_char_array   s~     !!#&&--bh77KKMM  ++z "!#!. . ..2dff	5rJ   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 : ``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#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|&&1Q%y$777rJ   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|z            | 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   rP   r   ro   c                     g | ]
}|d k    |S )r   rP   ).0xs     rH   
<listcomp>z0VarReader4.shape_from_header.<locals>.<listcomp>1  s    666qAvv1vvvrJ   )rD   r   tuplemapr`   rE   r   rV   r   rC   r~   rT   seekr}   r   r   r_   rs   rW   )rG   rt   rD   rz   r   rE   rowscolss           rH   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9FBCCC? 	866e66677ErJ   NT)rK   rL   rM   __doc__rI   rm   rw   r   rp   rq   rr   r   rP   rJ   rH   r   r   g   s        ,,1 1 1  4   "" " " "H( ( (,5 5 5$(8 (8 (8T         rJ   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)superrI   _matrix_reader)rG   rT   argskwargs	__class__s       rH   rI   zMatFile4Reader.__init__7  s:     	5d555f555"rJ   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)   r9   rZ   r:   )rT   r   r   r   rC   r   )rG   r.   s     rH   guess_byte_orderzMatFile4Reader.guess_byte_orderA  s    Q$/28D>>::Q1993!88td{{$,33 (S/C/rJ   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_orderrU   r   r   )rG   s    rH   initialize_readzMatFile4Reader.initialize_readM  s.    
 %%5tGG(..rJ   c                     | j                                         }t          d |j        d          }|j        j        |z  }|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
        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     !--//##SXq11),q0> 	!#*">">q O,,..@M!!rJ   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   rw   )rG   r-   ru   s      rH   read_var_arrayzMatFile4Reader.read_var_arrayl  s      "44VWEEErJ   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   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~  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+++~&&!++ $$&& 	 rJ   c                    | j                             d           |                                  g }|                                 s|                                 \  }}|j        dn|j                            d          }| j                            |          }t          
                    |j        d          }|                    |||f           | j                             |           |                                 |S )z list variables from stream r   Nr   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$$&& 	0!%!5!5!7!7C X-6638??83L3LD'99#>>E??3:y99DKKud+,,,O  /// $$&& 	0 rJ   r   rA   )rK   rL   rM   r   r   rI   r   r   r   r   r   r   __classcell__)r   s   @rH   r   r   5  s        !!# # # # Y#
0 
0 
0/ / /" " ".F F F F$   >      rJ   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~   rb   reshape)rv   oned_asrE   s      rH   r   r     sK    " 3  D
4yy1}} ( ) ) 	);;trJ   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 rA   )file_streamr   )rG   file_writers     rH   rI   zVarWriter4.__init__  s    &2"*rJ   c                 b    | j                             |                    d                     d S )Nry   )r|   )r   writer   )rG   rv   s     rH   write_byteszVarWriter4.write_bytes  s-    s{{{5566666rJ   c                 :    | j                             |           d S rA   )r   r   )rG   ss     rH   write_stringzVarWriter4.write_string  s    q!!!!!rJ   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
        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9!!d(c'"b&! v  (w(wwt99q=x   d{$++h//00000rJ   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   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(((FjooY{ 	3**R__S1122Cg"*?@@@BG^^:;;;RWbi(((OOC&&&F3%%%%%rJ   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'   )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\**	#%	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 )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   9>RW$$);rx~~?V)V)Vs##CT\**y	 	 	 	 	
 9>S  iooGZb&6sG&D&D'*, , ,F %%i00B*4tB???CrJ   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   )tocoorC   r   r   zerosnnzr   colrg   r   r   rz   r   r   r   r   )rG   rv   rB   Ar1   ijvs         rH   r   zVarWriter4.write_sparse9  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	 	 	 	 	
 	rJ   N)rK   rL   rM   rI   r   r   r   r   r   r   r   r   r   rP   rJ   rH   r   r     s        + + +7 7 7" " " +3l! 1 1 1 1B& & &:" " ",  (    rJ   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)rG   r   r   s      rH   rI   zMatFile4Writer.__init__T  s)    &?G"rJ   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   )rG   r   r   rB   vars        rH   put_variableszMatFile4Writer.put_variables[  sU    ( ).. 	1 	1ID#%%c40000	1 	1rJ   rA   )rK   rL   rM   r   rI   r  rP   rJ   rH   r   r   R  sB        33# # # #1 1 1 1 1 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     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% % % % % % % %$K K K K K K K K\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 1rJ   