91 lines
3.1 KiB
Python
91 lines
3.1 KiB
Python
def load_mat(f,var,squeeze=True,cast_string=True,cast_integer=False):
|
|
try:
|
|
return load_matbin(f,var,squeeze=squeeze)
|
|
except NotImplementedError:
|
|
return load_matv73(f,var,squeeze=squeeze,cast_string=cast_string,cast_integer=cast_integer)
|
|
|
|
def load_matbin(f,var,squeeze=True):
|
|
'''Loads variables from a matlab binary mat file (not v7.3).'''
|
|
from scipy.io import loadmat
|
|
import numpy
|
|
data = loadmat(f,variable_names=var,squeeze_me=squeeze,struct_as_record=True)
|
|
def parse(val):
|
|
if not isinstance(val,numpy.ndarray):
|
|
return val
|
|
if val.dtype.names is not None:
|
|
d = {}
|
|
for key in val.dtype.names:
|
|
d[key] = parse(val[key].item())
|
|
return d
|
|
else:
|
|
return val
|
|
if isinstance(var,(tuple,list)):
|
|
return tuple(parse(data[x]) for x in var)
|
|
else:
|
|
return parse(data[var])
|
|
|
|
def load_matv73(f,var,squeeze=True,cast_string=True,cast_integer=False):
|
|
'''Loads variables from a matlab hdf5 mat file (v7.3).'''
|
|
import numpy
|
|
import h5py
|
|
if isinstance(f,str):
|
|
f = h5py.File(f,'r')
|
|
if isinstance(var,(list,tuple)):
|
|
return tuple(load_matv73(f,x,cast_string=cast_string,cast_integer=cast_integer) for x in var)
|
|
def parse(val):
|
|
# String data
|
|
if cast_string and val.dtype==numpy.dtype('uint16'):
|
|
return ''.join([chr(x) for x in val.squeeze()])
|
|
# Numeric data
|
|
val = val.transpose()
|
|
if cast_integer:
|
|
val_int = numpy.rint(val)
|
|
if numpy.all(numpy.abs(val-val_int)<1e-8):
|
|
val = val_int.astype('int')
|
|
if squeeze:
|
|
val = val.squeeze()
|
|
if val.shape==():
|
|
val = val.item()
|
|
return val
|
|
t = f[var]
|
|
if isinstance(t,h5py.Dataset):
|
|
val = t[:]
|
|
if val.dtype==numpy.dtype('object'):
|
|
# Cell arrays are stored as references
|
|
for idx,x in numpy.ndenumerate(val):
|
|
val[idx] = parse(f[val[idx]][:])
|
|
return val
|
|
else:
|
|
return parse(val)
|
|
else:
|
|
d = {}
|
|
for key in t:
|
|
d[key] = load_matv73(t,key,
|
|
squeeze=squeeze,
|
|
cast_string=cast_string,
|
|
cast_integer=cast_integer)
|
|
return d
|
|
|
|
def h5write(file,arr,name='data',truncate=True):
|
|
import h5py
|
|
is_open = isinstance(file,(h5py.File,h5py.Group))
|
|
flag = 'w' if truncate else 'a'
|
|
f = file if is_open else h5py.File(file,flag)
|
|
f.create_dataset(name,data=arr)
|
|
if not is_open: f.close()
|
|
return
|
|
|
|
def h5read(file,name='data'):
|
|
import h5py
|
|
is_open = isinstance(file,(h5py.File,h5py.Group))
|
|
f = file if is_open else h5py.File(file,'r')
|
|
data = f[name][:]
|
|
if not is_open: f.close()
|
|
return data
|
|
|
|
def convert_coordinate_to_absolute(coord,bounds):
|
|
assert len(coord) in (3,6)
|
|
if len(coord)==3:
|
|
return tuple(bounds[2*ii]+(bounds[2*ii+1]-bounds[2*ii])*coord[ii] for ii in range(3))
|
|
else:
|
|
return tuple(bounds[2*(ii//2)]+(bounds[2*(ii//2)+1]-bounds[2*(ii//2)])*coord[ii] for ii in range(6)) |