U
    »mœd„P  ã                   @   s~  d 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 ddd	d
ddddddddddddddddg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&d'd(d)d*d+g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/d0d1d2d3œZ"ed4e d5e!d6iZ#G d7d
„ d
ƒZ$G d8d„ dƒZ%G d9d„ deƒZ&d>d;d„Z'G d<d„ dƒZ(G d=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&   Zc32Zc24Zc16r'   Zc8r(   r)   r*   r+   ÚS1ú<ú>zVAX D-floatzVAX G-floatZ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:   r;   r<   r=   r>   © r@   úN/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scipy/io/matlab/_mio4.pyÚ__init__Y   s
    zVarHeader4.__init__N)Ú__name__Ú
__module__Ú__qualname__Z
is_logicalÚ	is_globalrB   r@   r@   r@   rA   r   T   s   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 r9   )Úfile_readerÚ
mat_streamÚdtypesÚchars_as_stringsÚ
squeeze_me)r?   rG   r@   r@   rA   rB   i   s
    zVarReader4.__init__c                 C   sà   t | j| jd ƒ}| j t|d ƒ¡ d¡}|d dk sD|d dkrLtdƒ‚t|d dƒ\}}|d	krzt 	d
t
|  t¡ 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,   r1   ó    r-   r   éˆ  z.Mat 4 mopt wrong format, byteswapping problem?éè  )r   r   zBWe do not support byte ordering '%s'; returned data may be corruptéd   z,O in MOPT integer should be 0, wrong format?é
   r.   r/   r0   r   )r   rH   rI   ÚreadÚintÚstripÚ
ValueErrorÚdivmodÚwarningsÚwarnr    ÚUserWarningr   )r?   Údatar:   ÚMÚrestÚOÚPÚTr=   r>   r;   r@   r@   rA   Úread_headerp   s4    ÿþ
ûzVarReader4.read_headerTc                 C   st   |j }|tkr|  |¡}nD|tkr@|  |¡}|r^| jr^t|ƒ}n|tkrR|  |¡S t	d| ƒ‚|rp| j
rpt|ƒS |S )NúNo reader for class code %s)r<   r   Úread_full_arrayr   Úread_char_arrayrJ   r   r   Úread_sparse_arrayÚ	TypeErrorrK   r
   )r?   ÚhdrÚprocessr<   Úarrr@   r@   rA   Úarray_from_headerŠ   s    




zVarReader4.array_from_headerc           	      C   sp   |j }|j}|j}|D ]}||9 }q| j t|ƒ¡}t|ƒ|krNtd|j ƒ‚t	j
|||dd�}|rl| ¡ }|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¯Not 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)Úshaper;   ÚbufferÚorder)r;   r=   ÚitemsizerH   rQ   rR   ÚlenrT   r:   ÚnpÚndarrayÚcopy)	r?   re   rq   Údtr=   Ú	num_bytesÚdrk   rg   r@   r@   rA   Ú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)rq   y              ð?)r>   ru   )r?   re   ÚresZres_jr@   r@   rA   ra   ¿   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-1r2   ©rj   r;   rk   )ru   Úastypero   Zuint8ÚtobytesÚdecoderp   r=   r;   Úarrayrq   )r?   re   rg   ÚSr@   r@   rA   rb   Õ   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r¤t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 : ``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   Zintc©r;   r   r#   r"   ÚfloatÚcomplex)	ru   rR   ro   Zascontiguousarrayrj   ÚimagÚscipyr8   Z
coo_matrix)r?   re   rv   Útmpr=   ÚIÚJÚVr@   r@   rA   rc   ç   s    
zVarReader4.read_sparse_arrayc                 C   s2  |j }|tkr ttt|jƒƒ}nô|tkrLttt|jƒƒ}| jrJ|dd… }nÈ|tk�r|j	}|j}t
|ƒdkr†|d dkr†|d dksŠdS | j |j|d d  d¡ tjd|| j |j¡d�}| j |j|d d  d¡ tjd|| j |j¡d�}t|ƒt|ƒf}ntd| ƒ‚| j�r.td	d
„ |D ƒƒ}|S )zwRead the shape of the array described by the header.
        The file position after this call is unspecified.
        Nr~   r"   r   r   r@   rx   r`   c                 S   s   g | ]}|d kr|‘qS )r   r@   )Ú.0Úxr@   r@   rA   Ú
<listcomp>0  s      z0VarReader4.shape_from_header.<locals>.<listcomp>)r<   r   ÚtupleÚmaprR   r=   r   rJ   r   r;   rn   rH   Úseekrm   ro   rp   rQ   rd   rK   )r?   re   r<   rj   rr   r=   ÚrowsÚcolsr@   r@   rA   Úshape_from_header  s2    
$ÿÿzVarReader4.shape_from_headerN)T)T)rC   rD   rE   Ú__doc__rB   r_   rh   ru   ra   rb   rc   r�   r@   r@   r@   rA   r   f   s   

$*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|f|ž|Ž d| _dS )zR Initialize matlab 4 file reader

    %(matstream_arg)s
    %(load_args)s
        N)ÚsuperrB   Ú_matrix_reader)r?   rH   ÚargsÚkwargs©Ú	__class__r@   rA   rB   6  s    zMatFile4Reader.__init__c                 C   s^   | j  d¡ t| j t d¡ƒ}| j  d¡ |dkr6dS |dk sF|dkrRtrNdpPdS trZdp\dS )Nr   r(   r4   rM   r5   )rH   r�   r   ro   r;   r   )r?   r-   r@   r@   rA   Úguess_byte_order@  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   Z
byte_orderrI   r   r“   )r?   r@   r@   rA   Úinitialize_readL  s    zMatFile4Reader.initialize_readc                 C   sV   | j  ¡ }tdd„ |jdƒ}|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
        c                 S   s   | | S r9   r@   )r‰   Úyr@   r@   rA   Ú<lambda>d  ó    z0MatFile4Reader.read_var_header.<locals>.<lambda>r   r"   )r“   r_   r   r=   r;   rm   r>   r<   r   rH   Útell)r?   re   ÚnZremaining_bytesÚnext_positionr@   r@   rA   Úread_var_headerT  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“   rh   )r?   r,   rf   r@   r@   rA   Úread_var_arrayk  s    zMatFile4Reader.read_var_arrayNc                 C   sÆ   t |tƒr|g}n|dk	r"t|ƒ}| j d¡ |  ¡  i }|  ¡ sÂ|  ¡ \}}|jdkr\dn
|j 	d¡}|dk	r†||kr†| j |¡ q:|  
|¡||< | j |¡ |dk	r:| |¡ t|ƒdkr:qÂq:|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ÚlistrH   r�   r™   Úend_of_streamr    r:   r{   r¡   Úremovern   )r?   Zvariable_namesÚmdictre   rŸ   r:   r@   r@   rA   Úget_variables}  s(    	

zMatFile4Reader.get_variablesc                 C   s‚   | j  d¡ |  ¡  g }|  ¡ s~|  ¡ \}}|jdkr:dn
|j d¡}| j |¡}t	 
|jd¡}| |||f¡ | j  |¡ q|S )z list variables from stream r   Nr¢   r£   Úunknown)rH   r�   r™   r§   r    r:   r{   r“   r�   r   Úgetr<   Úappend)r?   Úvarsre   rŸ   r:   rj   Úinfor@   r@   rA   Úlist_variablesœ  s    zMatFile4Reader.list_variables)T)N)rC   rD   rE   r‘   r   rB   r˜   r™   r    r¡   rª   r°   Ú__classcell__r@   r@   r–   rA   r   4  s   	

Ú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   rn   rT   Zreshape)rg   Úoned_asr=   r@   r@   rA   r   ­  s    
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 r9   )Úfile_streamr³   )r?   Zfile_writerr@   r@   rA   rB   Æ  s    zVarWriter4.__init__c                 C   s   | j  |jdd�¡ d S )Nri   )rl   )r´   Úwriterz   )r?   rg   r@   r@   rA   Úwrite_bytesÊ  s    zVarWriter4.write_bytesc                 C   s   | j  |¡ d S r9   )r´   rµ   )r?   Úsr@   r@   rA   Ú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
        r@   r,   r   rN   rO   rP   r-   r.   r   r/   r0   r1   ú r£   N)ro   Úemptyr   r   rn   r¶   r¸   Úencode)
r?   r:   rj   r]   r^   r0   r,   rZ   r\   rY   r@   r@   rA   Úwrite_headerÐ  s"    ÿþý
zVarWriter4.write_headerc                 C   s    t j |¡r|  ||¡ dS t |¡}|j}|jsB| | 	d¡¡}|j
}|tjkr\tdƒ‚n4|tjkrptdƒ‚n |tjtjfk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ƒ   r8   ÚissparseÚwrite_sparsero   Zasarrayr;   Zisnativery   ZnewbyteorderÚtypeZobject_rd   ÚvoidZunicode_Zstring_Ú
write_charÚwrite_numeric)r?   rg   r:   rr   Zdttr@   r@   rA   rµ   ñ  s     




zVarWriter4.writec                 C   s¦   t || jƒ}|jjdk}zt|jjdd …  }W n2 tk
rb   |rP| d¡}n
| d¡}t}Y nX | j	||j
|t|d� |r˜|  |j¡ |  |j¡ n
|  |¡ d S )NÚcr   Zc128r&   )r]   r^   r0   )r   r³   r;   Úkindr   r¥   ÚKeyErrorry   r   r¼   rj   r   r¶   Úrealr‚   )r?   rg   r:   r0   r]   r@   r@   rA   rÃ     s&    

üzVarWriter4.write_numericc                 C   s„   t |ƒ}t|| jƒ}|j}| j||ttd� |jjdkrvt	 
|¡}t	jdt||ƒ|d�}| ¡  d¡}t	j|d|d�}|  |¡ d S )N©r]   r^   ÚUr@   rx   rw   r3   )r   r   r³   rj   r¼   r   r   r;   rÅ   ro   Úprodrp   r	   Úitemr»   r¶   )r?   rg   r:   r=   Zn_charsZst_arrÚstr@   r@   rA   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  < |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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È   )Ztocoor;   rÅ   ro   ZzerosZnnzr²   ÚcolrY   rÇ   r‚   rj   r¼   r   r   r¶   )r?   rg   r:   ÚAr0   Zijvr@   r@   rA   r¿   7  s$    üzVarWriter4.write_sparseN)rC   rD   rE   rB   r¶   r¸   r   r   r¼   rµ   rÃ   rÂ   r¿   r@   r@   r@   rA   r   Å  s   !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 krd}|| _d | _d S )Nr²   )r´   r³   Ú_matrix_writer)r?   r´   r³   r@   r@   rA   rB   R  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µ   )r?   r©   r¼   r:   Úvarr@   r@   rA   Úput_variablesY  s    
zMatFile4Writer.put_variables)N)N)rC   rD   rE   r‘   rB   rÒ   r@   r@   r@   rA   r   P  s   
)r²   )*r‘   ÚsysrV   Únumpyro   Zscipy.sparserƒ   Z_miobaser   r   r   r   r   r   r	   Z
_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   r@   r@   r@   rA   Ú<module>   sº   $               û	
       ü ôõû	   ý Oy
 