test_mio_funcs.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ''' Jottings to work out format for __function_workspace__ matrix at end
  2. of mat file.
  3. '''
  4. from __future__ import division, print_function, absolute_import
  5. import os.path
  6. import sys
  7. import io
  8. from numpy.compat import asstr
  9. from scipy.io.matlab.mio5 import (MatlabObject, MatFile5Writer,
  10. MatFile5Reader, MatlabFunction)
  11. test_data_path = os.path.join(os.path.dirname(__file__), 'data')
  12. def read_minimat_vars(rdr):
  13. rdr.initialize_read()
  14. mdict = {'__globals__': []}
  15. i = 0
  16. while not rdr.end_of_stream():
  17. hdr, next_position = rdr.read_var_header()
  18. name = asstr(hdr.name)
  19. if name == '':
  20. name = 'var_%d' % i
  21. i += 1
  22. res = rdr.read_var_array(hdr, process=False)
  23. rdr.mat_stream.seek(next_position)
  24. mdict[name] = res
  25. if hdr.is_global:
  26. mdict['__globals__'].append(name)
  27. return mdict
  28. def read_workspace_vars(fname):
  29. fp = open(fname, 'rb')
  30. rdr = MatFile5Reader(fp, struct_as_record=True)
  31. vars = rdr.get_variables()
  32. fws = vars['__function_workspace__']
  33. ws_bs = io.BytesIO(fws.tostring())
  34. ws_bs.seek(2)
  35. rdr.mat_stream = ws_bs
  36. # Guess byte order.
  37. mi = rdr.mat_stream.read(2)
  38. rdr.byte_order = mi == b'IM' and '<' or '>'
  39. rdr.mat_stream.read(4) # presumably byte padding
  40. mdict = read_minimat_vars(rdr)
  41. fp.close()
  42. return mdict
  43. def test_jottings():
  44. # example
  45. fname = os.path.join(test_data_path, 'parabola.mat')
  46. ws_vars = read_workspace_vars(fname)