Skip to content

Commit

Permalink
FIX: Ensure H5-writeable
Browse files Browse the repository at this point in the history
  • Loading branch information
larsoner committed Jun 10, 2020
1 parent 3fdd502 commit 780eede
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 13 deletions.
2 changes: 2 additions & 0 deletions doc/changes/latest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ Bug
- Fix default to be ``foreground=None`` in :func:`mne.viz.plot_source_estimates` to use white or black text based on the background color by `Eric Larson`_
- Fix bug with writing EGI and CTF `mne.Info` to H5 format, e.g., with `mne.time_frequency.AverageTFR.save` by `Eric Larson`_
- Fix bug with :func:`mne.io.Raw.plot` where toggling all projectors did not actually take effect by `Eric Larson`_
- Fix bug with :func:`mne.read_epochs` when loading data in complex format with ``preload=False`` by `Eric Larson`_
Expand Down
2 changes: 1 addition & 1 deletion mne/io/ctf/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def _conv_comp(comp, first, last, chs):
col_names = comp[first]['sensors'][:n_col]
row_names = [comp[p]['sensor_name'] for p in range(first, last + 1)]
mask = np.in1d(col_names, ch_names) # missing channels excluded
col_names = np.array(col_names)[mask]
col_names = np.array(col_names)[mask].tolist()
n_col = len(col_names)
n_row = len(row_names)
ccomp = dict(ctfkind=np.array([comp[first]['coeff_type']]),
Expand Down
1 change: 0 additions & 1 deletion mne/io/egi/egi.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ def my_fread(*x, **y):
for event in range(info['n_events']):
event_codes = ''.join(np.fromfile(fid, 'S1', 4).astype('U1'))
info['event_codes'].append(event_codes)
info['event_codes'] = np.array(info['event_codes'])
else:
raise NotImplementedError('Only continuous files are supported')
info['unsegmented'] = unsegmented
Expand Down
2 changes: 1 addition & 1 deletion mne/io/egi/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _read_events(input_fname, info):
n_samples = info['last_samps'][-1]
mff_events, event_codes = _read_mff_events(input_fname, info['sfreq'])
info['n_events'] = len(event_codes)
info['event_codes'] = np.asarray(event_codes).astype('<U4')
info['event_codes'] = event_codes
events = np.zeros([info['n_events'], info['n_segments'] * n_samples])
for n, event in enumerate(event_codes):
for i in mff_events[event]:
Expand Down
31 changes: 23 additions & 8 deletions mne/io/meas_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
from .open import fiff_open
from .tree import dir_tree_find
from .tag import read_tag, find_tag, _coord_dict
from .proj import _read_proj, _write_proj, _uniquify_projs, _normalize_proj
from .proj import (_read_proj, _write_proj, _uniquify_projs, _normalize_proj,
Projection)
from .ctf_comp import read_ctf_comp, write_ctf_comp
from .write import (start_file, end_file, start_block, end_block,
write_string, write_dig_points, write_float, write_int,
Expand All @@ -31,7 +32,7 @@
from ..transforms import invert_transform, Transform, _coord_frame_name
from ..utils import (logger, verbose, warn, object_diff, _validate_type,
_stamp_to_dt, _dt_to_stamp, _pl, _is_numeric)
from ._digitization import (_format_dig_points, _dig_kind_proper,
from ._digitization import (_format_dig_points, _dig_kind_proper, DigPoint,
_dig_kind_rev, _dig_kind_ints, _read_dig_fif)
from ._digitization import write_dig as _dig_write_dig
from .compensator import get_current_comp
Expand Down Expand Up @@ -179,6 +180,16 @@ def set_montage(self, montage, match_case=True,
return self


def _format_trans(obj, key):
try:
t = obj[key]
except KeyError:
pass
else:
if t is not None:
obj[key] = Transform(t['from'], t['to'], t['trans'])


# XXX Eventually this should be de-duplicated with the MNE-MATLAB stuff...
class Info(dict, MontageMixin):
"""Measurement information.
Expand Down Expand Up @@ -523,12 +534,16 @@ class Info(dict, MontageMixin):
def __init__(self, *args, **kwargs):
super(Info, self).__init__(*args, **kwargs)
# Deal with h5io writing things as dict
try:
t = self['dev_head_t']
except KeyError:
pass
else:
self['dev_head_t'] = Transform(t['from'], t['to'], t['trans'])
for key in ('dev_head_t', 'ctf_head_t', 'dev_ctf_t'):
_format_trans(self, key)
for res in self.get('hpi_results', []):
_format_trans(res, 'coord_trans')
if self.get('dig', None) is not None and len(self['dig']) and \
not isinstance(self['dig'][0], DigPoint):
self['dig'] = _format_dig_points(self['dig'])
for pi, proj in enumerate(self.get('projs', [])):
if not isinstance(proj, Projection):
self['projs'][pi] = Projection(proj)
# Old files could have meas_date as tuple instead of datetime
try:
meas_date = self['meas_date']
Expand Down
12 changes: 10 additions & 2 deletions mne/io/tests/test_raw.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@

from mne import concatenate_raws, create_info, Annotations
from mne.datasets import testing
from mne.io import read_raw_fif, RawArray, BaseRaw
from mne.utils import _TempDir, catch_logging, _raw_annot, _stamp_to_dt
from mne.externals.h5io import read_hdf5, write_hdf5
from mne.io import read_raw_fif, RawArray, BaseRaw, Info
from mne.utils import (_TempDir, catch_logging, _raw_annot, _stamp_to_dt,
object_diff)
from mne.io.meas_info import _get_valid_units
from mne.io._digitization import DigPoint

Expand Down Expand Up @@ -201,6 +203,12 @@ def _test_raw_reader(reader, test_preloading=True, test_kwargs=True,
assert_array_equal(times, times_2,)
assert_array_equal(data[picks_2], data_2)

# Make sure that writing info to h5 format
# (all fields should be compatible)
fname_h5 = op.join(tempdir, 'info.h5')
write_hdf5(fname_h5, raw.info)
new_info = Info(read_hdf5(fname_h5))
assert object_diff(new_info, raw.info) == ''
return raw


Expand Down

0 comments on commit 780eede

Please sign in to comment.