
    (phe                        S r SSKrSSKrSSKrSSKrSSKrSSKJr  SSKrSSK	r
SSKrSSKJrJr  SSKJrJrJrJrJrJrJrJrJr  SSKJr  SSKJrJrJrJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.  SS	K/J0r0  S
 r1S r2S r3S r4 " S S\5      r5S r6 " S S5      r7S r8\\   S   S   r9\\   S   S   r:\\   S   S   r;\\   S   S   r< " S S5      r= " S S5      r>g)a;  Classes for read / write of matlab (TM) 5 files

The matfile specification last found here:

https://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf

(as of December 5 2008)

=================================
 Note on functions and mat files
=================================

The document above does not give any hints as to the storage of matlab
function handles, or anonymous function handles. I had, therefore, to
guess the format of matlab arrays of ``mxFUNCTION_CLASS`` and
``mxOPAQUE_CLASS`` by looking at example mat files.

``mxFUNCTION_CLASS`` stores all types of matlab functions. It seems to
contain a struct matrix with a set pattern of fields. For anonymous
functions, a sub-fields of one of these fields seems to contain the
well-named ``mxOPAQUE_CLASS``. This seems to contain:

* array flags as for any matlab matrix
* 3 int8 strings
* a matrix

It seems that whenever the mat file contains a ``mxOPAQUE_CLASS``
instance, there is also an un-named matrix (name == '') at the end of
the mat file. I'll call this the ``__function_workspace__`` matrix.

When I saved two anonymous functions in a mat file, or appended another
anonymous function to the mat file, there was still only one
``__function_workspace__`` un-named matrix at the end, but larger than
that for a mat file with a single anonymous function, suggesting that
the workspaces for the two functions had been merged.

The ``__function_workspace__`` matrix appears to be of double class
(``mxCLASS_DOUBLE``), but stored as uint8, the memory for which is in
the format of a mini .mat file, without the first 124 bytes of the file
header (the description and the subsystem_offset), but with the version
U2 bytes, and the S2 endian test bytes. There follow 4 zero bytes,
presumably for 8 byte padding, and then a series of ``miMATRIX``
entries, as in a standard mat file. The ``miMATRIX`` entries appear to
be series of un-named (name == '') matrices, and may also contain arrays
of this same mini-mat format.

I guess that:

* saving an anonymous function back to a mat file will need the
  associated ``__function_workspace__`` matrix saved as well for the
  anonymous function to work correctly.
* appending to a mat file that has a ``__function_workspace__`` would
  involve first pulling off this workspace, appending, checking whether
  there were any more anonymous functions appended, and then somehow
  merging the relevant workspaces, and saving at the end of the mat
  file.

The mat files I was playing with are in ``tests/data``:

* sqr.mat
* parabola.mat
* some_functions.mat

See ``tests/test_mio.py:test_mio_funcs.py`` for the debugging
script I was working with.

Small fragments of current code adapted from matfile.py by Heiko
Henkelmann; parts of the code for simplify_cells=True adapted from
http://blog.nephics.com/2019/08/28/better-loadmat-for-scipy/.
    N)BytesIO   )native_codeswapped_code)	MatFileReader	docfillermatdims
read_dtypearr_to_charsarr_dtype_numberMatWriteErrorMatReadErrorMatReadWarning)
VarReader5)MatlabObjectMatlabFunctionMDTYPESNP_TO_MTYPESNP_TO_MXTYPESmiCOMPRESSEDmiMATRIXmiINT8miUTF8miUINT32mxCELL_CLASSmxSTRUCT_CLASSmxOBJECT_CLASSmxCHAR_CLASSmxSPARSE_CLASSmxDOUBLE_CLASSmclass_info
mat_struct)ZlibInputStreamc                     [        U [        R                  5      =(       a?    U R                  S:  =(       a)    U R                  S:  =(       a    [        U S   [
        5      $ )zBDetermine if elem is an array and if first array item is a struct.r   )
isinstancenpndarraysizendimr"   )elems    H/var/www/html/venv/lib/python3.13/site-packages/scipy/io/matlab/_mio5.py_has_structr,   i   sF    tRZZ( ,dii!m ,$))a- ,tAw
+-    c                     / nU  Hq  n[        U[        5      (       a  UR                  [        U5      5        M4  [	        U5      (       a  UR                  [        U5      5        M`  UR                  U5        Ms     U$ )zuConstruct lists from cell arrays (loaded as numpy ndarrays), recursing
into items if they contain mat_struct objects.)r%   r"   append_matstruct_to_dictr,   _inspect_cell_array)r'   	elem_listsub_elems      r+   r1   r1   o   si     Ih
++/9:""0:;X&  r-   c                     0 nU R                    HY  nU R                  U   n[        U[        5      (       a  [	        U5      X'   M6  [        U5      (       a  [        U5      X'   MU  X1U'   M[     U$ )z/Construct nested dicts from mat_struct objects.)_fieldnames__dict__r%   r"   r0   r,   r1   )matobjdfr*   s       r+   r0   r0   }   sc    
Aq!dJ''%d+AD&t,ADaD   Hr-   c                     U  HN  n[        X   [        5      (       a  [        X   5      X'   M+  [        X   5      (       d  M?  [	        X   5      X'   MP     U $ )z,Convert mat objects in dict to nested dicts.)r%   r"   r0   r,   r1   )r8   keys     r+   _simplify_cellsr<      sK    afj))'/AF  (0AF	 
 Hr-   c                   ~   ^  \ rS rSrSr\         SU 4S jj5       rS rS rS r	S r
SS jrSS	 jrS
 rSrU =r$ )MatFile5Reader   a  Reader for Mat 5 mat files
Adds the following attribute to base class

uint16_codec - char codec to use for uint16 char arrays
    (defaults to system default codec)

Uses variable reader that has the following standard interface (see
abstract class in ``miobase``::

   __init__(self, file_reader)
   read_header(self)
   array_from_header(self)

and added interface::

   set_stream(self, stream)
   read_full_tag(self)

c                    > [         TU ]  UUUUUUUUU
5	        U	(       d  [        R                  " 5       n	Xl        SU l        SU l        g)zInitializer for matlab 5 file format reader

%(matstream_arg)s
%(load_args)s
%(struct_arg)s
uint16_codec : {None, string}
    Set codec to use for uint16 char arrays (e.g., 'utf-8').
    Use system default codec if None
    N)super__init__sysgetdefaultencodinguint16_codec_file_reader_matrix_reader)self
mat_stream
byte_order	mat_dtype
squeeze_mechars_as_stringsmatlab_compatiblestruct_as_record verify_compressed_data_integrityrE   simplify_cells	__class__s              r+   rB   MatFile5Reader.__init__   sV    * 	,		 113L( "r-   c                     U R                   R                  S5        U R                   R                  S5      nU R                   R                  S5        US:H  =(       a    S=(       d    S$ )z*Guess byte order.
Sets stream pointer to 0~      r   s   IM<>)rI   seekread)rH   mis     r+   guess_byte_orderMatFile5Reader.guess_byte_order   sP     	S!__!!!$QU{"s)c)r-   c                     0 n[         U R                     S   S   n[        U R                  U5      nUS   R	                  5       R                  S5      US'   US   S-	  nUS   S-  nS	XE4-  US
'   U$ )zRead in mat 5 file header dtypesfile_headerdescriptions    	
 
__header__version      z%d.%d__version__)r   rJ   r
   rI   itemstrip)rH   hdict	hdr_dtypehdrv_majorv_minors         r+   read_file_headerMatFile5Reader.read_file_header   s    DOO,X6}E	)4!-0557==lKli.A%i.4'&');;mr-   c                 D    [        U 5      U l        [        U 5      U l        g)zPRun when beginning read of variables

Sets up readers from parameters in `self`
N)r   rF   rG   rH   s    r+   initialize_readMatFile5Reader.initialize_read   s     't,(.r-   c                    U R                   R                  5       u  pUS:  d  [        S5      eU R                  R	                  5       U-   nU[
        :X  aZ  [        U R                  U5      nU R                  R                  U5        U R                  nU R                  R                  5       u  pO'SnU R                  R                  U R                  5        U[        :X  d  [        SU-  5      eU R                  R                  U5      nXc4$ )a;  Read header, return header, next position

Header has to define at least .name and .is_global

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   zDid not read any bytesFz$Expecting miMATRIX type here, got %d)rF   read_full_tag
ValueErrorrI   tellr   r#   rG   
set_streamrP   r   	TypeErrorread_header)rH   mdtype
byte_countnext_posstreamcheck_stream_limitheaders          r+   read_var_headerMatFile5Reader.read_var_header   s    " "..<<>A~566??'')J6\!$T__jAF**62!%!F!F!%!4!4!B!B!DFJ!&**4??;!BVKLL$$001CDr-   c                 8    U R                   R                  X5      $ )aL  Read array, given `header`

Parameters
----------
header : header object
   object with fields defining variable header
process : {True, False} bool, optional
   If True, apply recursive post-processing during loading of
   array.

Returns
-------
arr : array
   array with post-processing applied or not according to
   `process`.
)rG   array_from_header)rH   r   processs      r+   read_var_arrayMatFile5Reader.read_var_array  s    " ""44VEEr-   c                    [        U[        5      (       a  U/nOUb  [        U5      nU R                  R	                  S5        U R                  5         U R                  5       n/ US'   U R                  5       (       Gd%  U R                  5       u  p4UR                  c  SOUR                  R                  S5      nXR;   a   SU S3n[        R                  " U[        SS	9  US
:X  a  SnSnOSnUb"  XQ;  a  U R                  R	                  U5        M   U R                  X75      nU R                  R	                  U5        XU'   UR"                  (       a  US   R%                  U5        Ub!  UR'                  U5        [)        U5      S:X  a  OU R                  5       (       d  GM%  U R*                  (       a  [-        U5      $ U$ ! [         a0  n	[        R                  " SU SU	 S3[         SS	9  SU	 3n Sn	A	NSn	A	ff = f)zget variables from stream as dictionary

variable_names   - optional list of variable names to get

If variable_names is None, then get all variables in file
Nr   __globals__Nonelatin1zDuplicate variable name "z{" in stream - replacing previous with new
Considerscipy.io.matlab.varmats_from_mat to split file into single variable filesrV   )
stacklevel __function_workspace__FTzUnreadable variable "z", because ""zRead error: )r%   strlistrI   rY   rr   rn   end_of_streamr   namedecodewarningswarnr   r   r   Warning	is_globalr/   removelenrQ   r<   )
rH   variable_namesmdictrk   next_positionr   msgr   reserrs
             r+   get_variablesMatFile5Reader.get_variables%  s    nc**,-N'!.1NQ%%'!m$$&&!%!5!5!7C XX-6388??83LD}/v 66 6  c>a@rz/  )d.H$$]3+))#7 OO  /$K}}m$++D1)%%d+~&!+I $$&&J "5))L!   ++D6cU!D+ %SE*	+s   G 
G;&G66G;c                 \   U R                   R                  S5        U R                  5         U R                  5         / nU R	                  5       (       d  U R                  5       u  p#UR                  c  SOUR                  R                  S5      nUS:X  a  SnU R                  R                  U5      nUR                  (       a  SnO![        R                  " UR                  S5      nUR                  XEU45        U R                   R                  U5        U R	                  5       (       d  M  U$ )zlist variables from stream r   r   r   r   r   logicalunknown)rI   rY   rr   rn   r   r   r   r   rG   shape_from_header
is_logicalr!   getmclassr/   )rH   varsrk   r   r   shapeinfos          r+   list_variablesMatFile5Reader.list_variables`  s    Q$$&&!%!5!5!7C XX-6388??83LDrz/''99#>E~~ "szz9=KKd+,OO  / $$&& r-   )rF   rG   rE   )	NFFTFTTNF)TN)__name__
__module____qualname____firstlineno____doc__r   rB   r\   rn   rr   r   r   r   r   __static_attributes____classcell__)rR   s   @r+   r>   r>      se    &  ! !"&#("&26" %$# $#L*	
/! FF&9v r-   r>   c                    [        U 5      nU R                  S5        [        [           S   S   R                  nU R                  U5      nU R                  S5        UR                  5         UR                  5         U R                  5       n/ nUR                  5       (       d  UnUR                  5       u  ptUR                  c  SOUR                  R                  S5      nU R                  U5        XF-
  n	U R                  U	5      n
[        5       nUR                  U5        UR                  U
5        UR                  S5        UR                  X45        UR                  5       (       d  M  U$ )a  Pull variables out of mat 5 file as a sequence of mat file objects

This can be useful with a difficult mat file, containing unreadable
variables. This routine pulls the variables out in raw form and puts them,
unread, back into a file stream for saving or reading. Another use is the
pathological case where there is more than one variable of the same name in
the file; this routine returns the duplicates, whereas the standard reader
will overwrite duplicates in the returned dictionary.

The file pointer in `file_obj` will be undefined. File pointers for the
returned file-like objects are set at 0.

Parameters
----------
file_obj : file-like
    file object containing mat file

Returns
-------
named_mats : list
    list contains tuples of (name, BytesIO) where BytesIO is a file-like
    object containing mat file contents as for a single variable. The
    BytesIO contains a string with the original header and a single var. If
    ``var_file_obj`` is an individual BytesIO instance, then save as a mat
    file with something like ``open('test.mat',
    'wb').write(var_file_obj.read())``

Examples
--------
>>> import scipy.io
>>> import numpy as np
>>> from io import BytesIO
>>> from scipy.io.matlab._mio5 import varmats_from_mat
>>> mat_fileobj = BytesIO()
>>> scipy.io.savemat(mat_fileobj, {'b': np.arange(10), 'a': 'a string'})
>>> varmats = varmats_from_mat(mat_fileobj)
>>> sorted([name for name, str_obj in varmats])
['a', 'b']
r   r_   r`   r   r   )r>   rY   r   r   itemsizerZ   rr   rn   rw   r   r   r   r   r   writer/   )file_objrdrhdr_lenraw_hdrr   
named_matsstart_positionrk   r   r|   var_strout_objs               r+   varmats_from_matr   y  s.   P 
"CMM!k"8,];DDGmmG$GMM!MMOMJ!!& 002)vsxxx/Hn%"3
--
+)ggQ4/* !! r-   c                       \ rS rSrSrSrg)EmptyStructMarkeri  z<Class to indicate presence of empty matlab struct on output  N)r   r   r   r   r   r   r   r-   r+   r   r     s    Gr-   r   c                 `   [        U [        R                  5      (       a  U $ U c  g[        U S5      (       a  [        R                  " U 5      $ [        U S5      =(       a    [        U S5      =(       a    [        U S5      n[        U [        R
                  5      (       a  O`U(       dY  [        U S5      (       aH  U R                  R                  5        VVs0 s H  u  p#UR                  S5      (       a  M  X#_M!     n nnSnU(       a  / n/ nU R                  5        HX  u  pc[        U[        5      (       d  M  US	   S
;  d  M'  UR                  [        U5      [        45        UR                  U5        MZ     U(       a!  [        R                  " [        U5      /U5      $ [        $  [        R                  " U 5      nUR"                  R$                  [        [        R&                  4;   a  UR(                  S:X  a  Xp:X  a  gU$ s  snnf ! [          a    [        R                  " U [        S9n Nqf = f)a  Convert input object ``source`` to something we can write

Parameters
----------
source : object

Returns
-------
arr : None or ndarray or EmptyStructMarker
    If `source` cannot be converted to something we can write to a matfile,
    return None.  If `source` is equivalent to an empty dictionary, return
    ``EmptyStructMarker``.  Otherwise return `source` converted to an
    ndarray with contents for writing to matfile.
N	__array__keysvaluesitemsr6   _Tr   _0123456789dtyper   )r%   r&   r'   hasattrasarraygenericr6   r   
startswithr   r/   objectarraytupler   
asanyarrayrv   r   typeobject_r   )source
is_mappingr;   valuer   r   fieldnarrs           r+   to_writeabler     s    &"**%%~v{##zz&!!&&) +gfh.G +&'*  &"**%%GFJ77/5/D/D/F 2/F ^^C0 #*/F 2
"LLNLE5#&&!HM1c%j&12e$	 +
 88U6]OU33$$3}}V$ zz62::..zzRDNK12$  3}}V623s   H4H%H #H-,H-r_   r`   tag_fulltag_smalldataarray_flagsc                       \ rS rSrSr\R                  " S\5      r\	\S'   S r
S rS rSS	 jrS
 rS r   SS jrS rS rS rS rSS jrS rS rS rS rS rS rSrg)
VarWriter5i   z$Generic matlab matrix writing class r   r{   c                     UR                   U l         UR                  U l        UR                  U l        UR                  U l        S U l        SU l        g )NF)file_streamunicode_stringslong_field_namesoned_as	_var_name_var_is_global)rH   file_writers     r+   rB   VarWriter5.__init__  sH    &22*:: + < <"**#r-   c                 T    U R                   R                  UR                  SS95        g )NForder)r   r   tobytesrH   arrs     r+   write_bytesVarWriter5.write_bytes  s!    s{{{56r-   c                 :    U R                   R                  U5        g r   )r   r   )rH   ss     r+   write_stringVarWriter5.write_string  s    q!r-   Nc                 |   Uc   [         UR                  R                  SS    nUR                  R                  [        :X  a7  UR                  5       R                  UR                  R                  5       5      nUR                  UR                  -  nUS::  a  U R                  XU5        gU R                  XU5        g)zwrite tag and data Nr      )r   r   r   	byteorderr   byteswapviewnewbyteorderr(   r   write_smalldata_elementwrite_regular_element)rH   r   r{   r|   s       r+   write_elementVarWriter5.write_element  s    >!#))--"34F99,.,,.%%cii&<&<&>?CXXcll*
?((jA&&sJ?r-   c                     [         R                  " S[        5      nUS-  U-   US'   UR                  SS9US'   U R	                  U5        g )Nr      byte_count_mdtyper   r   data)r&   zerosNDT_TAG_SMALLr   r   )rH   r   r{   r|   tags        r+   r   "VarWriter5.write_smalldata_element!  sI    hhr=)$."$4#> kkk,Fr-   c                     [         R                  " S[        5      nX$S'   X4S'   U R                  U5        U R                  U5        US-  nU(       a"  U R                  R                  SSU-
  -  5        g g )Nr   r{   r|   rd       )r&   r  NDT_TAG_FULLr   r   r   )rH   r   r{   r|   r
  bc_mod_8s         r+   r   VarWriter5.write_regular_element)  sk    hhr<(H&L>""7aj#9: r-   c                 R   U R                   nU R                  nU R                  R                  5       U l        U R                  U R                  5        [        R                  " S[        5      n[        US'   SUS'   US-  US-  -  US-  -  n	X)S-  -  US'   XXS	'   U R                  U5        U R                  [        R                  " US
S95        [        R                  " U5      nUS:X  a  U R                  U[        S5        OU R                  U[        5        SU l         SU l        g)aR  Write header for given data options
shape : sequence
   array shape
mclass      - mat5 matrix class
is_complex  - True if matrix is complex
is_logical  - True if matrix is logical
nzmax        - max non zero elements for sparse arrays

We get the name and the global flag from the object, and reset
them to defaults after we've used them
r   	data_typerd   r|      rV   r   flags_classnzmaxi4r   r   r   FN)r   r   r   rw   _mat_tag_posr   mat_tagr&   r  NDT_ARRAY_FLAGSr   r  r   r   r   r   )
rH   r   r   
is_complexr   r  r   r   afflagss
             r+   write_headerVarWriter5.write_header5  s   $ ~~''	 ,,113&XXb/*";<a)q.0:?B"aZ/=7288E67zz$2:((vq9tV,#r-   c                 &   U R                   R                  5       nU R                   R                  U5        X!-
  S-
  nUS:  a  [        S5      eX0R                  S'   U R                  U R                  5        U R                   R                  U5        g )Nrd   l        z-Matrix too large to save with Matlab 5 formatr|   )r   rw   rY   r   r  r   )rH   	start_poscurr_posr|   s       r+   update_matrix_tagVarWriter5.update_matrix_tag`  s    ##((*i()A-
 !+ , ,%/\"&h'r-   c                 >    X0l         X l        U R                  U5        g)a7  Write variable at top level of mat file

Parameters
----------
arr : array_like
    array-like object to create writer for
name : str, optional
    name as it will appear in matlab workspace
    default is empty string
is_global : {False, True}, optional
    whether variable will be global on load into matlab
N)r   r   r   )rH   r   r   r   s       r+   	write_topVarWriter5.write_topk  s     (

3r-   c                 V   U R                   R                  5       n[        R                  R	                  U5      (       a#  U R                  U5        U R                  U5        g[        U5      nUc  [        SU S[        U5       S35      e[        U[        5      (       a  U R                  U5        O[        U[        5      (       a  [        S5      eU[        L a  U R!                  5         OUR"                  R$                  (       a  U R'                  U5        OUR"                  R(                  (       a  U R+                  U5        OSUR"                  R,                  S;   a(  U R.                  (       a  SnOSnU R1                  X45        OU R3                  U5        U R                  U5        g)	zWrite `arr` to stream at top and sub levels

Parameters
----------
arr : array_like
    array-like object to create writer for
NzCould not convert z (type z
) to arrayzCannot write matlab functions)USUTF8ascii)r   rw   scipysparseissparsewrite_sparser"  r   ry   r   r%   r   write_objectr   r   r   write_empty_structr   fieldswrite_struct	hasobjectwrite_cellskindr   
write_charwrite_numeric)rH   r   mat_tag_posr   codecs        r+   r   VarWriter5.write  sD    &&++-<<  %%c""";/C <0WT#YKzRSSdL))d#n-- ?@@&&##%ZZd#ZZ!!T"ZZ__
*##OOD(t${+r-   c                 D   UR                   R                  S:H  nUR                   R                  S:H  n [        UR                   R                  SS     nU R                  [        XR                  5      UUUS9  U(       a7  U R                  UR                  5        U R                  UR                  5        g U R                  U5        g ! [         aL    U(       a  UR                  S5      nO*U(       a  UR                  S5      nOUR                  S5      n[        n Nf = f)Ncbr   c128i1f8)r  r   )r   r6  r   r   KeyErrorastyper    r  r	   r   r  realimag)rH   r   imagflogifr   s        r+   r8  VarWriter5.write_numeric  s    		#%		#%	$"399==#45F 	'#||4 %*%* 	 	, sxx(sxx(s#%  		$ jj(jj&jj&#F		$s    C	 	ADDc                    UR                   S:X  d  [        R                  " US:H  5      (       aS  S[        R                  " UR                  S/5      -  nU R                  U[        5        U R                  U[        S5        g[        U5      nUR                  nU R                  U[        5        UR                  R                  S:X  a  UR                   (       a  [        R                  " U5      n[        R                  " S[!        X5      UR"                  R%                  5       S9nUR'                  5       R)                  U5      n[        R                  " [+        U5      4S	US9nU R-                  U[        S
9  g)z4Write string array `arr` with given `codec`
        r   r   )r   rV   Nr(  r   r   r   bufferS1r{   )r(   r&   allmaxr)   r  r   r   r   r   r   r   r6  mathprodr'   r   Tcopyrg   encoder   r  )rH   r   r:  r   n_charsst_arrsts          r+   r7  VarWriter5.write_char  s    88q=BFF3"9-- 266388Q-00Ee\2((fa8 3 		%.99>>S SXX
 ii&GZZb&6s&D'*uuzz|5F %%e,B**CG:#'$&(C 	3v.r-   c                 p   UR                  5       nUR                  5         UR                  R                  S:H  nUR                  R                  S:H  nUR                  nU R                  [        XR                  5      [        UUUS:X  a  SOUS9  U R                  UR                  R                  S5      5        U R                  UR                  R                  S5      5        U R                  UR                  R                  5        U(       a&  U R                  UR                  R                  5        gg)zSparse matrices are 2D
        r=  r>  r   r   )r  r   r  r  N)tocscsort_indicesr   r6  nnzr  r	   r   r   r  indicesrC  indptrr  rD  rE  )rH   r   Ar  r   nzs         r+   r/  VarWriter5.write_sparse  s     IIK	ggllc)
ggllc)
UU'#||4(%/%/%'1W" 	 	6 	199++D12188??401166;;'qvv{{+ r-   c                     U R                  [        XR                  5      [        5        [        R
                  " U5      R                  S5      nU H  nU R                  U5        M     g )Nr   )r  r	   r   r   r&   
atleast_2dflattenr   )rH   r   r_  els       r+   r5  VarWriter5.write_cells  sN    '#||4&	( MM#&&s+BJJrN r-   c                     U R                  S[        5        U R                  [        R                  " S[        R
                  S95        U R                  [        R                  " / [        R                  S95        g )N)r   r   r   r   )r  r   r  r&   r   int32int8rq   s    r+   r1  VarWriter5.write_empty_struct  sL    &.1288ARXX67288Bbgg67r-   c                 x    U R                  [        XR                  5      [        5        U R	                  U5        g r   )r  r	   r   r   _write_itemsr   s     r+   r3  VarWriter5.write_struct  s,    '#||4(	*#r-   c                 R   UR                   R                   Vs/ s H  o"S   PM	     nn[        U Vs/ s H  n[        U5      PM     sn5      S-   nU R                  =(       a    S=(       d    SnXV:  a  [        SUS-
  -  5      eU R                  [        R                  " U/SS95        U R                  [        R                  " USU-  S9[        S	9  [        R                  " U5      R                  S
5      nU H  nU H  nU R                  X   5        M     M!     g s  snf s  snf )Nr   r   @       z+Field names are restricted to %d charactersr  r   zS%drM  r   )r   descrrO  r   r   rv   r  r&   r   r   rc  rd  r   )	rH   r   r9   
fieldnames	fieldnamelength
max_lengthr_  re  s	            r+   rl  VarWriter5._write_items  s   $'IIOO4OqdO
4jAjc)njAB1D++29r
J(l, - -288VHD9:HHZu'78 	 	 MM#&&s+B

25!    5As
   DD$c                     U R                  [        XR                  5      [        5        U R	                  [
        R                  " UR                  SS9[        S9  U R                  U5        g)z]Same as writing structs, except different mx class, and extra
classname element after header
r)  r   rM  N)
r  r	   r   r   r  r&   r   	classnamer   rl  r   s     r+   r0  VarWriter5.write_object#  sU     	'#||4(	*288CMM="( 	 	*#r-   )r  r   r   r   r   r   r   r   )FFr   )r+  )r   r   r   r   r   r&   r  r  r  r   rB   r   r   r  r   r  r  r"  r%  r   r8  r7  r/  r5  r1  r3  rl  r0  r   r   r-   r+   r   r      s    /hhr<(G GH$7"@
; !& %)$V	((%,N$2)/V,(8
""r-   r   c                   F    \ rS rSrSr\     SS j5       rS rS	S jrSr	g)
MatFile5Writeri.  zClass for writing mat5 files Nc                 x    Xl         X l        X0l        U(       a  X@l        O/ U l        XPl        X`l        SU l        g)zInitialize writer for matlab 5 format files

Parameters
----------
%(do_compression)s
%(unicode_strings)s
global_vars : None or sequence of strings, optional
    Names of variables to be marked as global for matlab
%(long_fields)s
%(oned_as)s
N)r   do_compressionr   global_varsr   r   _matrix_writer)rH   r   r}  r   r~  r   r   s          r+   rB   MatFile5Writer.__init__1  s:    $ ',.*!D 0"r-   c                 H   [         R                  " S[        5      nS[        R                   S[
        R                  " 5        3US'   SUS'   [         R                  " SS[         R                  " S5      S	9US
'   U R                  R                  UR                  5       5        g )Nr   zMATLAB 5.0 MAT-file Platform: z, Created on: ra      rc   S2iIM  rJ  endian_test)r&   r  NDT_FILE_HDRosr   timeasctimer'   uint16r   r   r   )rH   rk   s     r+   write_file_header MatFile5Writer.write_file_headerN  s    hhr<( >rwwi H--1\\^,<>MIZZb,0-/YYv->@M 	s{{}-r-   c                 6   Uc  U R                   R                  5       S:H  nU(       a  U R                  5         [        U 5      U l        UR                  5        GH=  u  p4US   S:X  a  M  X0R                  ;   nU R                  (       a  [        5       nX`R                  l         U R                  R                  XCR                  S5      U5        [        R                  " UR                  5       5      n[        R                  " S[         5      n["        US'   [%        U5      US'   U R                   R'                  UR)                  5       5        U R                   R'                  U5        GM  U R                  R                  XCR                  S5      U5        GM@     g)a  Write variables in `mdict` to stream

Parameters
----------
mdict : mapping
   mapping with method ``items`` returns name, contents pairs where
   ``name`` which will appear 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}, optional
   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
Nr   r   r   r   r{   r|   )r   rw   r  r   r  r   r~  r}  r   r%  rT  zlibcompressgetvaluer&   emptyr  r   r   r   r   )	rH   r   r  r   varr   r~   out_strr
  s	            r+   put_variablesMatFile5Writer.put_variablesY  s1   $ ++002a7L""$(.IDAw#~ 0 00I"" 28##/##--c;;x3H)T--(9:hhr<0 ,H$'LL!  &&s{{}5  &&w/##--c;;x3H)T 'r-   )r  r}  r   r~  r   r   r   )FFNFrowr   )
r   r   r   r   r   r   rB   r  r  r   r   r-   r+   r{  r{  .  s1    ( %!&!"'# #8	.&Ur-   r{  )?r   rP  r  r  rC   r  ior   r   numpyr&   scipy.sparser,  _byteordercodesr   r   _miobaser   r   r	   r
   r   r   r   r   r   _mio5_utilsr   _mio5_paramsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   _streamsr#   r,   r1   r0   r<   r>   r   r   r   r  r  r	  r  r   r{  r   r-   r+   <module>r     s  EN  	  
      64 4 4
 $C C C C C &-a] aHAHH H5r {#H-m<{#H-j9$X.?+&x0?k k\	QU QUr-   