L i.3 @UdZddlmZddlZddlmZddlmZ gdZ Gdd e Z Gd d e Z Gd d eZGddeZdddddddddd Zej$eZeed< dZdZdddZeZd Zd!Zd)d"ZGd#d$ZGd%d&Zd'Zd(Zy)*zf Base classes for MATLAB file stream reading. MATLAB is a registered trademark of the Mathworks inc. )FinalN)doccer)_byteordercodes) MatReadErrorMatReadWarning MatWriteErrorMatWriteWarningceZdZdZy)rz"Exception indicating a read issue.N__name__ __module__ __qualname____doc__^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/io/matlab/_miobase.pyrrs,rrceZdZdZy)r z#Exception indicating a write issue.Nr rrrr r s-rr ceZdZdZy)rzWarning class for read issues.Nr rrrrrs(rrceZdZdZy)r zWarning class for write issues.Nr rrrr r s)rr zfile_name : str Name of the mat file (do not need .mat extension if appendmat==True) Can also pass open file-like object.zappendmat : bool, optional True to append the .mat extension to the end of the given filename, if not already present. Default is True.abyte_order : str or None, optional None by default, implying byte order guessed from mat file. Otherwise can be one of ('native', '=', 'little', '<', 'BIG', '>'). mat_dtype : bool, optional If True, return arrays in same dtype as would be loaded into MATLAB (instead of the dtype with which they are saved). squeeze_me : bool, optional Whether to squeeze unit matrix dimensions or not. chars_as_strings : bool, optional Whether to convert char arrays to string arrays. matlab_compatible : bool, optional Returns matrices as would be loaded by MATLAB (implies squeeze_me=False, chars_as_strings=False, mat_dtype=True, struct_as_record=True).abstruct_as_record : bool, optional Whether to load MATLAB structs as NumPy record arrays, or as old-style NumPy arrays with dtype=object. Setting this flag to False replicates the behavior of SciPy version 0.7.x (returning numpy object arrays). The default setting is True, because it allows easier round-trip load and save of MATLAB files.zAmat_stream : file-like Object with file API, open for reading.along_field_names : bool, optional * False - maximum field name length in a structure is 31 characters which is the documented maximum length. This is the default. * True - maximum field name length in a structure is 63 characters which works for MATLAB 7.6z[do_compression : bool, optional Whether to compress matrices on write. Default is False.zoned_as : {'row', 'column'}, optional If 'column', write 1-D NumPy arrays as column vectors. If 'row', write 1D NumPy arrays as row vectors.zbunicode_strings : bool, optional If True, write strings as Unicode, else MATLAB usual encoding.) file_arg append_arg load_args struct_arg matstream_arg long_fieldsdo_compressiononed_asunicode_strings docfillerc|j}|D],}tj||j|||<.|S)a Convert dtypes in mapping to given order Parameters ---------- dtype_template : mapping mapping with values returning numpy dtype from ``np.dtype(val)`` order_code : str an order code suitable for using in ``dtype.newbyteorder()`` Returns ------- dtypes : mapping mapping where values have been replaced by ``np.dtype(val).newbyteorder(order_code)`` )copynpdtype newbyteorder)dtype_template order_codedtypesks rconvert_dtypesr*sI" "F AHHVAY'44Z@q A Mrcn|j}tjd||j|d}|S)af Generic get of byte stream data of known type Parameters ---------- mat_stream : file_like object MATLAB (tm) mat file stream a_dtype : dtype dtype of array to read. `a_dtype` is assumed to be correct endianness. Returns ------- arr : ndarray Array of dtype `a_dtype` read from stream. rF)shaper$bufferorder)itemsizer#ndarrayread) mat_streama_dtype num_bytesarrs r read_dtyper7s8$  I **2"&OOI6 C JrT appendmatcdddlm}|||5}t|cdddS#1swYyxYw)a Return major, minor tuple depending on apparent mat file type Where: #. 0,x -> version 4 format mat files #. 1,x -> version 5 format mat files #. 2,x -> version 7.3 format mat files (HDF format) Parameters ---------- file_name : str Name of the mat file (do not need .mat extension if appendmat==True). Can also pass open file-like object. appendmat : bool, optional True to append the .mat extension to the end of the given filename, if not already present. Default is True. Returns ------- major_version : {0, 1, 2} major MATLAB File format version minor_version : int minor MATLAB file format version Raises ------ MatReadError If the file is empty. ValueError The matfile version is unknown. Notes ----- Has the side effect of setting the file read pointer to 0 r)_open_file_contextr8N)_mior;_get_matfile_version) file_namer9r;fileobjs rmatfile_versionr@s1J) I ;-w#G,---s &/cf|jd|jt}t|tkr t d|j dtk(rt dtdt jdt j|dd}d|vr|jdy|jd |jd}|jdt|d d k(}t||}t|d |z }||f}|d vr|Stdj|)Nrz Mat file appears to be truncatedz&Mat file appears to be corrupt (first z bytes == 0))rCr-r$r.rr|Ir)rrGz%Unknown mat file type, version {}, {}) seekr2 _HDR_N_BYTESlenrcountr#r1uint8int ValueErrorformat)r? hdr_bytes mopt_intstst_strmaj_indmaj_valmin_valrets rr=r=s" LLO \*I 9~ $=>>q\)%%1N,@A A RXXimLII~ Q LLll1oG LLO'!*'(G''"#G'!g+&'G G C& C<CCSI JJrc|j}|dk(ryt|dk(r,|ddk(ry|dk(r|dzS|dk(rd|zStd |d |S) a Determine equivalent MATLAB dimensions for given array Parameters ---------- arr : ndarray Input array oned_as : {'column', 'row'}, optional Whether 1-D arrays are returned as MATLAB row or column matrices. Default is 'column'. Returns ------- dims : tuple Shape tuple, in the form MATLAB expects it. Notes ----- We had to decide what shape a 1 dimensional array would be by default. ``np.atleast_2d`` thinks it is a row vector. The default for a vector in MATLAB (e.g., ``>> 1:12``) is a row vector. Versions of scipy up to and including 0.11 resulted (accidentally) in 1-D arrays being read as column vectors. For the moment, we maintain the same tradition here. Examples -------- >>> import numpy as np >>> from scipy.io.matlab._miobase import matdims >>> matdims(np.array(1)) # NumPy scalar (1, 1) >>> matdims(np.array([1])) # 1-D array, 1 element (1, 1) >>> matdims(np.array([1,2])) # 1-D array, 2 elements (2, 1) >>> matdims(np.array([[2],[3]])) # 2-D array, column vector (2, 1) >>> matdims(np.array([[2,3]])) # 2-D array, row vector (1, 2) >>> matdims(np.array([[[2,3]]])) # 3-D array, rowish vector (1, 1, 2) >>> matdims(np.array([])) # empty 1-D array (0, 0) >>> matdims(np.array([[]])) # empty 2-D array (0, 0) >>> matdims(np.array([[[]]])) # empty 3-D array (0, 0, 0) Optional argument flips 1-D shape behavior. >>> matdims(np.array([1,2]), 'row') # 1-D array, 2 elements (1, 2) The argument has to make sense though >>> matdims(np.array([1,2]), 'bizarre') Traceback (most recent call last): ... ValueError: 1-D option "bizarre" is strange r)rrrrrEcolumn)rrowz 1-D option "z " is strange)r-rKrO)r6rr-s rmatdimsr[sn~ IIE { 5zQ 8q=  4<   %< |G9LAB B Lrc"eZdZdZdZdZdZy) MatVarReaderz; Abstract class defining required interface for var readerscy)Nr)self file_readers r__init__zMatVarReader.__init__Ss rcy)z Returns header Nrr_s r read_headerzMatVarReader.read_headerV rcy)z Reads array given header Nr)r_headers rarray_from_headerzMatVarReader.array_from_headerZrerN)r rrrrardrhrrrr]r]QsE   rr]cDeZdZdZe ddZdZdZdZy) MatFileReadera  Base object for reading mat files To make this class functional, you will need to override the following methods: matrix_getter_factory - gives object to fetch next matrix from stream guess_byte_order - guesses file byte order from file Nc ||_i|_|s|j}ntj|}||_||_|r|jn||_||_ ||_ ||_ | |_ | rd|_d|_yy)z Initializer for mat file reader mat_stream : file-like object with file API, open for reading %(load_args)s TFN) r3r(guess_byte_orderboc to_numpy_code byte_orderstruct_as_recordset_matlab_compatible squeeze_mechars_as_strings mat_dtype verify_compressed_data_integritysimplify_cells) r_r3rortrrrsmatlab_compatiblerprurvs rrazMatFileReader.__init__is$% ..0J**:6J$ 0   & & ((DO$4D !&DN0P-, "DO$)D ! rc.d|_d|_d|_y)z4 Sets options to return arrays as MATLAB loads them TFN)rtrrrsrcs rrqz#MatFileReader.set_matlab_compatibles %rc"tjS)z9 As we do not know what file type we have, assume native )rm native_codercs rrlzMatFileReader.guess_byte_orders rc|jjd}|jj}|jj|dz t |dk(S)Nrr)r3r2tellrIrK)r_bcurposs r end_of_streamzMatFileReader.end_of_streamsL OO  #%%' VAX&1v{r)NFFTFTTF) r rrrr rarqrlrrrrrjrj_sC  !"&#("&26 %#*#*J& rrjcrtj|jjddt|zS)z3 Return dtype for given number of items per elementNrG)r#r$str)r6nums rarr_dtype_numberrs) 88CIIMM"1%C0 11rct|j}|sdg}|jt|jj ddt j|t|d|}|t jd|jk(g}t j|s|S|j}d|t|<|S)z$ Convert string array to char array rrGNrD)r$ ) listr-appendrNr$rr#r1rarrayanyr"tuple)r6dimsemptiess r arr_to_charsrs  ?D sKKCIIMM!"%&' **4+C3 !Cbhhr334G 66'? ((*CCg Jr)rY) rtypingrnumpyr# scipy._librrrrm__all__ Exceptionrr UserWarningrr doc_dictfilldocr __annotations__r*r7r@get_matfile_versionrJr=r[r]rjrrrrrrs $ -9-.I.)[)*k*  < 9   > . #  ? 6 Ea1F h"6>>(+ 5+*Z.4-1'-T& K8K\   >>B2 r