L iRdZddlZddlZddlZddlmZddlZddlZ ddl m Z m Z m Z mZmZmZmZddlmZmZddlmZgdZej0d k(ZdZdZd Zd Zd Zd ZededededededdgdddiZ eeeeeeeeeeed Z!dZ"dZ#d Z$ddddddZ%e"de#de$d iZ&ejNejPjRZ*Gd!d"Z+Gd#d$Z,Gd%d&e Z-d,d'Z.Gd(d)Z/Gd*d+Z0y)-z1 Classes for read / write of matlab (TM) 4 files N)mul) MatFileReader docfillermatdims read_dtypeconvert_dtypes arr_to_charsarr_dtype_number)squeeze_elementchars_to_strings)reduce)MatFile4ReaderMatFile4WriterSYS_LITTLE_ENDIAN VarHeader4 VarReader4 VarWriter4 arr_to_2d mclass_infomdtypes_templatemiDOUBLEmiINT16miINT32miSINGLEmiUINT16miUINT8 mxCHAR_CLASS mxFULL_CLASSmxSPARSE_CLASS np_to_mtypes order_codeslittlef8f4i4i2u2u1header))moptr*)mrowsr*)ncolsr*)imagfr*)namlenr*U1) r(c32c24c16r)c8r*r+r,r-S1<>z VAX D-floatz VAX G-floatCray)rrr$r%r&doublecharsparseceZdZdZdZdZy)rFcJ||_||_||_||_||_yN)namedtypemclassdims is_complex)selfrCrDrErFrGs [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/io/matlab/_mio4.py__init__zVarHeader4.__init__^s'     $N)__name__ __module__ __qualname__ is_logical is_globalrJrKrIrrYsJI %rKrcDeZdZdZdZdZd dZd dZdZdZ dZ d Z y ) rz" Class to read matlab 4 variables c||_|j|_|j|_|j|_|j|_yrB) file_reader mat_streamdtypeschars_as_strings squeeze_me)rHrTs rIrJzVarReader4.__init__ns?&%00!(( + < <%00rKc$t|j|jd}|jjt |dj d}|ddks|ddkDr t dt|dd\}}|d vr'tjd t|d td t|d\}}|dk7r t dt|d\}}|}|d|df}|ddk(} |j|} t|| ||| S)z% Read and return header for variable r.r3r/rz.Mat 4 mopt wrong format, byteswapping problem?)rrz!We do not support byte ordering 'z'; returned data may be corruptr%) stackleveldz,O in MOPT integer should be 0, wrong format? r0r1r2r) rrUrVreadintstrip ValueErrordivmodwarningswarnr" UserWarningr) rHdatarCMrestOPTrFrGrDs rI read_headerzVarReader4.read_headerus,$//4;;x+@A##CX$78>>wG |j}|tk(r|j|}n\|tk(r+|j |}|r@|j r4t |}n(|tk(r|j|Std||r|jr t|S|S)NNo reader for class code ) rErread_full_arrayrread_char_arrayrWr r read_sparse_array TypeErrorrXr )rHhdrprocessrEarrs rIarray_from_headerzVarReader4.array_from_headers \ !&&s+C | #&&s+C400&s+ ~ %))#. .7x@A A t"3' ' rKc|j}tt|jt j |j }|tkDr(td|jjdd|jj|}t||k7r(td|jjddt j|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`` 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)shaperDbufferorder)rDrrrFnpint64itemsize _MAX_INTPrcrCdecoderUr`lenndarraycopy)rHrurdt num_bytesr}rws rIread_sub_arrayzVarReader4.read_sub_arrays"YY3"((2;;*?@ y SXX__X678MNO O%%i0 v;) #HHOOH-./DEF F jjsxx! &"$ ((*C rKc|jr.|j|d}|j|d}||dzzS|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)ry?)rGr)rHruresres_js rIrqzVarReader4.read_full_arraysU >>%%c%6C''%'8E%"*% %""3''rKcH|j|jtj}|j j d}tj |jtjdtj|jS)z latin-1 text matrix (char matrix) reader Parameters ---------- hdr : ``VarHeader4`` instance Returns ------- arr : ndarray with dtype 'U1', shape given by `hdr` ``dims`` latin-1r4r|rDr}) rastyperuint8tobytesrrrFrDarrayr)rHrurwSs rIrrzVarReader4.read_char_arraysm!!#&--bhh7 KKM  +zz "!#!..2df 5rKc|j|}|ddddf}t|dt|df}tj|dddfd}tj|dddfd}|dz}|dz}|jdd k(rtj|ddd fd }n,tj|ddd fd }|ddd f|_t jj|||ff|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)rr)rrrintcrDrr%r$floatcomplex) rrarascontiguousarrayr|imagscipyr? coo_array)rHrurtmprFIJVs rIrszVarReader4.read_sparse_arrays6!!#&#2#a%jCICI/  QqS 7  QqS 7 Q Q 99Q<1 $$S1XGA1XAF||%%q!Ai66rKc|j}|tk(r%ttt|j }nz|t k(r7ttt|j }|jrA|dd}n:|tk(r"|j}|j }t|dk(r|ddk\r|ddk\sy|jj|j|ddz zdtjd||jj!|j}|jj|j|ddz zdtjd||jj!|j}t |t |f}nt#d||j$rt|Dcgc] }|dk7s | c}}|Scc}w) zwRead the shape of the array described by the header. The file position after this call is unspecified. Nrr$rrrQrrp)rErtuplemaprarFrrWr rDrrUseekrrrr`rtrX) rHrurEr|rrFrowscolsxs rIshape_from_headerzVarReader4.shape_from_headers \ !#c388,-E | ##c388,-E$$cr  ~ %B88DINtAw!|Q1  OO Q! !s$ 5d5f5"rKc|jjdt|jtjd}|jjd|dk(ry|dks|dkDrt xrdxsdSt xrdxsdS)Nrr*r:r[r;)rUrrrrDr)rHr/s rIguess_byte_orderzMatFile4Reader.guess_byte_orderHsu Q$//288D>: Q 19 !8td{$,3 3 (S/C/rKcbtt|j|_t ||_y)za Run when beginning read of variables Sets up readers from parameters in `self` N)r r byte_orderrVrr)rHs rIinitialize_readzMatFile4Reader.initialize_readTs$ %%5tG (.rKcD|jj}tt|jt j |jj}|jr|jtk(s|dz}|jj|z}||fS)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$)rrnrrrFrrrDrrGrEr rUtell)rHruremaining_bytes next_positions rIread_var_headerzMatFile4Reader.read_var_header\s{!!--/ chh9K9K0LM >>#**"> q O,,.@ M!!rKc:|jj||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`. )rrx)rHr.rvs rIread_var_arrayzMatFile4Reader.read_var_arrayss ""44VWEErKcFt|tr|g}n | t|}|jj d|j i}|j s|j\}}|jdn|jjd}| ||vr|jj |n|j|||<|jj ||"|j|t|dk(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. rNonerz) isinstancestrlistrUrr end_of_streamrrCrrremover)rHvariable_namesmdictrurrCs rI get_variableszMatFile4Reader.get_variabless  nc *,-N  '!.1N Q $$&!%!5!5!7 C XX-6388??83LD)d..H$$]3--c2E$K OO  /)%%d+~&!+ $$& rKc|jjd|jg}|js|j \}}|j dn|j j d}|jj|}tj|jd}|j|||f|jj||js|S)z list variables from stream rrrzunknown) rUrrrrrCrrrrgetrEappend)rHvarsrurrCr|infos rIlist_variableszMatFile4Reader.list_variabless Q $$&!%!5!5!7 C XX-6388??83LD''99#>E??3::y9D KKud+ , OO  /$$& rKrrB) rLrMrNrrrJrrrrrr __classcell__)rs@rIrr<s7!## 0/".F$>rKrcnt||}t|dkDr td|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)rrrcreshape)rwoned_asrFs rIrrs<" 3 D 4y1}() ) ;;t rKcDeZdZdZdZdZeedfdZdZ dZ dZ d Z y ) rcH|j|_|j|_yrB) file_streamr)rH file_writers rIrJzVarWriter4.__init__s&22"** rKcZ|jj|jdy)Nr{)r~)rwriter)rHrws rI write_byteszVarWriter4.write_bytess! s{{{56rKc:|jj|yrB)rr)rHss rI write_stringzVarWriter4.write_strings q!rKrc6tjdtd}t }d}|dz|dzz|dzz|z|d<|d|d<|d |d <||d <t |d z|d <|j ||d z} |j | jdy)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 rQr.rr\r^r_r/r0rr1r2r3rzN)remptyrrrrrencode) rHrCr|rlrmr2r.rirkrhs rI write_headerzVarWriter4.write_headers$".x89! ! d(c'"b&!v (w(wwt9q=x  d{ $++h/0rKctjj|r|j||yt j |}|j }|js |j|jd}|j}|tjur td|tjur td|tjtjfvr|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 Mat4zCannot save void type arrays)rr?issparse write_sparserasarrayrDisnativer newbyteordertypeobject_rtvoidstr_bytes_ write_char write_numeric)rHrwrCrdtts rIrzVarWriter4.writes <<  %   c4 ( jjo YY{{**R__S12Cgg "** ?@ @ BGG^:; ; RWWbii( ( OOC &  3%rKct||j}|jjdk(} t|jj dd}|j||j|t||r7|j|j|j|jy|j|y#t $r.|r|jd}n|jd}t}YwxYw)Ncrc128r()rlrmr2)rrrDkindr!rKeyErrorrrrr|rrrealr)rHrwrCr2rls rIrzVarWriter4.write_numericsT\\* #% SYY]]12./A $))( %  '    SXX &   SXX &   S ! jj(jj&A  s C4C76C7c|jjtjk(rA|jjtjdjk7r t |}t ||j}|j}|j||tt|jjdk(rntj|}tjdt!|||}|j#j%d}tj|d|}|j'|y)Nr4rlrmUrQrrr9)rDrrrrr rrr|rrrrmathprodrr itemrr)rHrwrCrFn_charsst_arrsts rIrzVarWriter4.write_char,s 99>>RWW $););rxx~?V?V)Vs#CT\\*yy      99>>S iioGZZb&6sG&D'*,F%%i0B**4tB?C rKcP|j}|jjdk(}tj|j dzd|zfd}|j |dddf<|j|dddf<|dddd fxxdz cc<|r;|jj|ddd f<|jj|dddf<n|j|ddd f<|j|ddd f<|j||jtt |j|y) zY Sparse matrices are 2-D See docstring for VarReader4.read_sparse_array rrr%r(rNrrr$r)tocoorDrrzerosnnzrowcolrhrrr|rrr r)rHrwrCAr2ijvs rIrzVarWriter4.write_sparse@s IIK #hh 1U7+48UUCRCE UUCRCE  CRC!G  CAJCAJCAJggBqsF    II   rKN) rLrMrNrJrrrrrrrrrrQrKrIrrs4+7"+3l!1B&:",(rKrc eZdZdZddZddZy)rz) Class for writing matlab 4 format files Nc6||_|d}||_d|_y)Nr)rr_matrix_writer)rHrrs rIrJzMatFile4Writer.__init__[s#& ?G "rKct||_|jD]!\}}|jj||#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)rr itemsr)rHrrrCvars rI put_variableszMatFile4Writer.put_variablesbs@(). 1ID#    % %c4 0 1rKrB)rLrMrNrrJrrQrKrIrrYs3#1rKr)r)1rsysreroperatorrnumpyr scipy.sparser_miobaserrrrr r r _mio_utilsr r functoolsr__all__ byteorderrrrrrrrrr!rrr r"riinfointpmaxrrrrrrrrQrKrIrsl  FFF: MMX-       d d T T d T !  $                    (&H  BHHRWW  ! ! %%$NNbv]vr0IIX11rK