def test_evoked_proj(): """Test SSP proj operations """ for proj in [True, False]: ave = read_evoked(fname, setno=0, proj=proj) assert_true(all(p['active'] == proj for p in ave.info['projs'])) # test adding / deleting proj if proj: assert_raises(ValueError, ave.add_proj, [], {'remove_existing': True}) assert_raises(ValueError, ave.del_proj, 0) else: projs = deepcopy(ave.info['projs']) n_proj = len(ave.info['projs']) ave.del_proj(0) assert_true(len(ave.info['projs']) == n_proj - 1) ave.add_proj(projs, remove_existing=False) assert_true(len(ave.info['projs']) == 2 * n_proj - 1) ave.add_proj(projs, remove_existing=True) assert_true(len(ave.info['projs']) == n_proj) ave = read_evoked(fname, setno=0, proj=False) data = ave.data.copy() ave.apply_proj() assert_allclose(np.dot(ave._projector, data), ave.data)
def test_evoked_io_from_epochs(): """Test IO of evoked data made from epochs """ # offset our tmin so we don't get exactly a zero value when decimating with warnings.catch_warnings(True) as w: epochs = Epochs(raw, events[:4], event_id, tmin + 0.011, tmax, picks=picks, baseline=(None, 0), decim=5) assert_true(len(w) == 1) evoked = epochs.average() evoked.save(op.join(tempdir, "evoked.fif")) evoked2 = read_evoked(op.join(tempdir, "evoked.fif")) assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20) assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1 / evoked.info["sfreq"]) # now let's do one with negative time with warnings.catch_warnings(True) as w: epochs = Epochs(raw, events[:4], event_id, 0.1, tmax, picks=picks, baseline=(0.1, 0.2), decim=5) evoked = epochs.average() evoked.save(op.join(tempdir, "evoked.fif")) evoked2 = read_evoked(op.join(tempdir, "evoked.fif")) assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20) assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20) # should be equivalent to a cropped original with warnings.catch_warnings(True) as w: epochs = Epochs(raw, events[:4], event_id, -0.2, tmax, picks=picks, baseline=(0.1, 0.2), decim=5) evoked = epochs.average() evoked.crop(0.099, None) assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20) assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
def test_evoked_standard_error(): """Test calculation and read/write of standard error """ epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0)) evoked = [epochs.average(), epochs.standard_error()] fiff.write_evoked(op.join(tempdir, 'evoked.fif'), evoked) evoked2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1]) evoked3 = [ read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown'), read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown', kind='standard_error') ] for evoked_new in [evoked2, evoked3]: assert_true( evoked_new[0]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_AVERAGE) assert_true(evoked_new[0].kind == 'average') assert_true( evoked_new[1]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_STD_ERR) assert_true(evoked_new[1].kind == 'standard_error') for ave, ave2 in zip(evoked, evoked_new): assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_evoked_resample(): """Test for resampling of evoked data """ # upsample, write it out, read it in ave = read_evoked(fname, 0) sfreq_normal = ave.info['sfreq'] ave.resample(2 * sfreq_normal) write_evoked(op.join(tempdir, 'evoked.fif'), ave) ave_up = read_evoked(op.join(tempdir, 'evoked.fif'), 0) # compare it to the original ave_normal = read_evoked(fname, 0) # and compare the original to the downsampled upsampled version ave_new = read_evoked(op.join(tempdir, 'evoked.fif'), 0) ave_new.resample(sfreq_normal) assert_array_almost_equal(ave_normal.data, ave_new.data, 2) assert_array_almost_equal(ave_normal.times, ave_new.times) assert_equal(ave_normal.nave, ave_new.nave) assert_equal(ave_normal._aspect_kind, ave_new._aspect_kind) assert_equal(ave_normal.kind, ave_new.kind) assert_equal(ave_normal.last, ave_new.last) assert_equal(ave_normal.first, ave_new.first) # for the above to work, the upsampling just about had to, but # we'll add a couple extra checks anyway assert_true(len(ave_up.times) == 2 * len(ave_normal.times)) assert_true(ave_up.data.shape[1] == 2 * ave_normal.data.shape[1])
def test_io_evoked(): """Test IO for evoked data (fif + gz) with integer and str args """ ave = read_evoked(fname, 0) write_evoked(op.join(tempdir, 'evoked.fif'), ave) ave2 = read_evoked(op.join(tempdir, 'evoked.fif')) # This not being assert_array_equal due to windows rounding assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3)) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first) # test compressed i/o ave2 = read_evoked(fname_gz, 0) assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8)) # test str access setno = 'Left Auditory' assert_raises(ValueError, read_evoked, fname, setno, kind='stderr') assert_raises(ValueError, read_evoked, fname, setno, kind='standard_error') ave3 = read_evoked(fname, setno) assert_array_almost_equal(ave.data, ave3.data, 19)
def test_evoked_standard_error(): """Test calculation and read/write of standard error """ epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0)) evoked = [epochs.average(), epochs.standard_error()] fiff.write_evoked(op.join(tempdir, 'evoked.fif'), evoked) evoked2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1]) evoked3 = [read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown'), read_evoked(op.join(tempdir, 'evoked.fif'), 'Unknown', kind='standard_error')] for evoked_new in [evoked2, evoked3]: assert_true(evoked_new[0]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_AVERAGE) assert_true(evoked_new[0].kind == 'average') assert_true(evoked_new[1]._aspect_kind == fiff.FIFF.FIFFV_ASPECT_STD_ERR) assert_true(evoked_new[1].kind == 'standard_error') for ave, ave2 in zip(evoked, evoked_new): assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_evoked_io_from_epochs(): """Test IO of evoked data made from epochs """ # offset our tmin so we don't get exactly a zero value when decimating with warnings.catch_warnings(True) as w: epochs = Epochs(raw, events[:4], event_id, tmin + 0.011, tmax, picks=picks, baseline=(None, 0), decim=5) assert_true(len(w) == 1) evoked = epochs.average() evoked.save(op.join(tempdir, 'evoked.fif')) evoked2 = read_evoked(op.join(tempdir, 'evoked.fif')) assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20) assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1 / evoked.info['sfreq']) # now let's do one with negative time with warnings.catch_warnings(True) as w: epochs = Epochs(raw, events[:4], event_id, 0.1, tmax, picks=picks, baseline=(0.1, 0.2), decim=5) evoked = epochs.average() evoked.save(op.join(tempdir, 'evoked.fif')) evoked2 = read_evoked(op.join(tempdir, 'evoked.fif')) assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20) assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20) # should be equivalent to a cropped original with warnings.catch_warnings(True) as w: epochs = Epochs(raw, events[:4], event_id, -0.2, tmax, picks=picks, baseline=(0.1, 0.2), decim=5) evoked = epochs.average() evoked.crop(0.099, None) assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20) assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
def test_evoked_to_nitime(): """ Test to_nitime """ aves = read_evoked(fname, [0, 1, 2, 3]) evoked_ts = aves[0].to_nitime() assert_equal(evoked_ts.data, aves[0].data) picks2 = [1, 2] aves = read_evoked(fname, [0, 1, 2, 3]) evoked_ts = aves[0].to_nitime(picks=picks2) assert_equal(evoked_ts.data, aves[0].data[picks2])
def test_evoked_detrend(): """Test for detrending evoked data """ ave = read_evoked(fname, 0) ave_normal = read_evoked(fname, 0) ave.detrend(0) ave_normal.data -= np.mean(ave_normal.data, axis=1)[:, np.newaxis] picks = pick_types(ave.info, meg=True, eeg=True, exclude='bads') assert_true(np.allclose(ave.data[picks], ave_normal.data[picks], rtol=1e-8, atol=1e-16))
def test_io_multi_evoked(): """Test IO for multiple evoked datasets """ aves = read_evoked(fname, [0, 1, 2, 3]) write_evoked('evoked.fif', aves) aves2 = read_evoked('evoked.fif', [0, 1, 2, 3]) for [ave, ave2] in zip(aves, aves2): assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave.aspect_kind, ave2.aspect_kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_io_evoked(): """Test IO for evoked data """ ave = read_evoked(fname) ave.crop(tmin=0) write_evoked('evoked.fif', ave) ave2 = read_evoked('evoked.fif') assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave.aspect_kind, ave2.aspect_kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_meg_field_interpolation_helmet(): """Test interpolation of MEG field onto helmet """ evoked = read_evoked(evoked_fname, setno='Left Auditory') info = evoked.info surf = get_meg_helmet_surf(info) # let's reduce the number of channels by a bunch to speed it up info['bads'] = info['ch_names'][:200] # bad ch_type assert_raises(ValueError, make_surface_mapping, info, surf, 'foo') # bad mode assert_raises(ValueError, make_surface_mapping, info, surf, 'meg', mode='foo') # no picks evoked_eeg = pick_types_evoked(evoked, meg=False, eeg=True) assert_raises(RuntimeError, make_surface_mapping, evoked_eeg.info, surf, 'meg') # bad surface def nn = surf['nn'] del surf['nn'] assert_raises(KeyError, make_surface_mapping, info, surf, 'meg') surf['nn'] = nn cf = surf['coord_frame'] del surf['coord_frame'] assert_raises(KeyError, make_surface_mapping, info, surf, 'meg') surf['coord_frame'] = cf # now do it data = make_surface_mapping(info, surf, 'meg', mode='fast') assert_array_equal(data.shape, (304, 106)) # data onto surf
def test_io_evoked(): """Test IO for evoked data (fif + gz) with integer and str args """ ave = read_evokeds(fname, 0) write_evokeds(op.join(tempdir, 'evoked.fif'), ave) ave2 = read_evokeds(op.join(tempdir, 'evoked.fif'))[0] # This not being assert_array_equal due to windows rounding assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-3)) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave._aspect_kind, ave2._aspect_kind) assert_equal(ave.kind, ave2.kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first) # test compressed i/o ave2 = read_evokeds(fname_gz, 0) assert_true(np.allclose(ave.data, ave2.data, atol=1e-16, rtol=1e-8)) # test str access condition = 'Left Auditory' assert_raises(ValueError, read_evokeds, fname, condition, kind='stderr') assert_raises(ValueError, read_evokeds, fname, condition, kind='standard_error') ave3 = read_evokeds(fname, condition) assert_array_almost_equal(ave.data, ave3.data, 19) # test deprecation warning for read_evoked and write_evoked # XXX should be deleted for 0.9 release with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ave = read_evoked(fname, setno=0) assert_true(w[0].category == DeprecationWarning) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') write_evoked(op.join(tempdir, 'evoked.fif'), ave) assert_true(w[0].category == DeprecationWarning) # test read_evokeds and write_evokeds types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual'] aves1 = read_evokeds(fname) aves2 = read_evokeds(fname, [0, 1, 2, 3]) aves3 = read_evokeds(fname, types) write_evokeds(op.join(tempdir, 'evoked.fif'), aves1) aves4 = read_evokeds(op.join(tempdir, 'evoked.fif')) for aves in [aves2, aves3, aves4]: for [av1, av2] in zip(aves1, aves): assert_array_almost_equal(av1.data, av2.data) assert_array_almost_equal(av1.times, av2.times) assert_equal(av1.nave, av2.nave) assert_equal(av1.kind, av2.kind) assert_equal(av1._aspect_kind, av2._aspect_kind) assert_equal(av1.last, av2.last) assert_equal(av1.first, av2.first) assert_equal(av1.comment, av2.comment)
def test_plot_topomap(): """Testing topomap plotting """ # evoked evoked = fiff.read_evoked(evoked_fname, 'Left Auditory', baseline=(None, 0)) evoked.plot_topomap(0.1, 'mag', layout=layout) plot_evoked_topomap(evoked, None, ch_type='mag') times = [0.1, 0.2] plot_evoked_topomap(evoked, times, ch_type='eeg') plot_evoked_topomap(evoked, times, ch_type='grad') plot_evoked_topomap(evoked, times, ch_type='planar1') plot_evoked_topomap(evoked, times, ch_type='planar2') with warnings.catch_warnings(True): # delaunay triangulation warning plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto') assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag', proj='interactive') # projs have already been applied evoked.proj = False # let's fake it like they haven't been applied plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive') assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50)) assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6]) # projs projs = read_proj(ecg_fname)[:7] plot_projs_topomap(projs) plt.close('all')
def test_plot_topomap(): """Test topomap plotting """ # evoked warnings.simplefilter('always', UserWarning) with warnings.catch_warnings(record=True): evoked = fiff.read_evoked(evoked_fname, 'Left Auditory', baseline=(None, 0)) evoked.plot_topomap(0.1, 'mag', layout=layout) plot_evoked_topomap(evoked, None, ch_type='mag') times = [0.1, 0.2] plot_evoked_topomap(evoked, times, ch_type='eeg') plot_evoked_topomap(evoked, times, ch_type='grad') plot_evoked_topomap(evoked, times, ch_type='planar1') plot_evoked_topomap(evoked, times, ch_type='planar2') plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True) p = plot_evoked_topomap(evoked, times, ch_type='grad', show_names=lambda x: x.replace('MEG', '')) subplot = [x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)][0] assert_true(all('MEG' not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text))) # Test title def get_texts(p): return [x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text)] p = plot_evoked_topomap(evoked, times, ch_type='eeg') assert_equal(len(get_texts(p)), 0) p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom') texts = get_texts(p) assert_equal(len(texts), 1) assert_equal(texts[0], 'Custom') # delaunay triangulation warning with warnings.catch_warnings(record=True): plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto') assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag', proj='interactive') # projs have already been applied evoked.proj = False # let's fake it like they haven't been applied plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive') assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50)) assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6]) projs = read_proj(ecg_fname) projs = [p for p in projs if p['desc'].lower().find('eeg') < 0] plot_projs_topomap(projs) plt.close('all') for ch in evoked.info['chs']: if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG: if ch['eeg_loc'] is not None: ch['eeg_loc'].fill(0) ch['loc'].fill(0) assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type='eeg')
def compensate_mne(fname, comp): tmp_fname = '%s-%d.fif' % (fname[:-4], comp) cmd = [ 'mne_compensate_data', '--in', fname, '--out', tmp_fname, '--grad', str(comp) ] run_subprocess(cmd) return read_evoked(tmp_fname)
def test_drop_channels_mixin(): """Test channels-dropping functionality """ evoked = read_evoked(fname, setno=0, proj=True) drop_ch = evoked.ch_names[:3] ch_names = evoked.ch_names[3:] evoked.drop_channels(drop_ch) assert_equal(ch_names, evoked.ch_names) assert_equal(len(ch_names), len(evoked.data))
def test_as_data_frame(): """Test evoked Pandas exporter""" ave = read_evoked(fname, [0])[0] assert_raises(ValueError, ave.as_data_frame, picks=np.arange(400)) df = ave.as_data_frame() assert_true((df.columns == ave.ch_names).all()) df = ave.as_data_frame(use_time_index=False) assert_true('time' in df.columns) assert_array_equal(df.values[:, 1], ave.data[0] * 1e13) assert_array_equal(df.values[:, 3], ave.data[2] * 1e15)
def test_io_multi_evoked(): """Test IO for multiple evoked datasets """ aves = read_evoked(fname, [0, 1, 2, 3]) write_evoked(op.join(tempdir, 'evoked.fif'), aves) aves2 = read_evoked(op.join(tempdir, 'evoked.fif'), [0, 1, 2, 3]) types = ['Left Auditory', 'Right Auditory', 'Left visual', 'Right visual'] aves3 = read_evoked(op.join(tempdir, 'evoked.fif'), types) for aves_new in [aves2, aves3]: for [ave, ave_new] in zip(aves, aves_new): assert_array_almost_equal(ave.data, ave_new.data) assert_array_almost_equal(ave.times, ave_new.times) assert_equal(ave.nave, ave_new.nave) assert_equal(ave.kind, ave_new.kind) assert_equal(ave._aspect_kind, ave_new._aspect_kind) assert_equal(ave.last, ave_new.last) assert_equal(ave.first, ave_new.first) # this should throw an error since there are mulitple datasets assert_raises(ValueError, read_evoked, fname)
def test_as_data_frame(): """Test Pandas exporter""" ave = read_evoked(fname, [0])[0] assert_raises(ValueError, ave.as_data_frame, picks=np.arange(400)) df = ave.as_data_frame() assert_true((df.columns == ave.ch_names).all()) df = ave.as_data_frame(use_time_index=False) assert_true('time' in df.columns) assert_array_equal(df.values[:, 1], ave.data[0] * 1e13) assert_array_equal(df.values[:, 3], ave.data[2] * 1e15)
def test_equalize_channels(): """Test equalization of channels """ evoked1 = read_evoked(fname, setno=0, proj=True) evoked2 = evoked1.copy() ch_names = evoked1.ch_names[2:] evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) my_comparison = [evoked1, evoked2] equalize_channels(my_comparison) for e in my_comparison: assert_equal(ch_names, e.ch_names)
def extract_data(s, setno, ch_names): print "hello" data = fiff.read_evoked(s,setno=setno,baseline=(None, 0)) sel = [data['info']['ch_names'].index(c) for c in ch_names] print "hello3" times = data['evoked']['times'] mask = times > 0 print "-------------- " + str(data['info']['bads']) epochs = data['evoked']['epochs'][sel][:, mask] bads = [k for k, _ in enumerate(sel) if ch_names[k] in data['info']['bads']] bads_name = [ch_names[k] for k, _ in enumerate(sel) if ch_names[k] in data['info']['bads']] return epochs, times[mask], bads, bads_name
def test_io_evoked(): """Test IO for evoked data (fif + gz) """ ave = read_evoked(fname) ave.crop(tmin=0) write_evoked('evoked.fif', ave) ave2 = read_evoked('evoked.fif') assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave.aspect_kind, ave2.aspect_kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first) # test compressed i/o ave2 = read_evoked(fname_gz) ave2.crop(tmin=0) assert_array_equal(ave.data, ave2.data)
def test_plot_evoked_field(): trans_fname = op.join(data_dir, 'MEG', 'sample', 'sample_audvis_raw-trans.fif') setno = 'Left Auditory' evoked = fiff.read_evoked(evoked_fname, setno=setno, baseline=(-0.2, 0.0)) evoked = pick_channels_evoked(evoked, evoked.ch_names[::10]) # speed for t in ['meg', None]: maps = make_field_map(evoked, trans_fname=trans_fname, subject='sample', subjects_dir=subjects_dir, n_jobs=1, ch_type=t) evoked.plot_field(maps, time=0.1)
def extract_data(s, setno, ch_names): print "hello" data = fiff.read_evoked(s, setno=setno, baseline=(None, 0)) sel = [data['info']['ch_names'].index(c) for c in ch_names] print "hello3" times = data['evoked']['times'] mask = times > 0 print "-------------- " + str(data['info']['bads']) epochs = data['evoked']['epochs'][sel][:, mask] bads = [ k for k, _ in enumerate(sel) if ch_names[k] in data['info']['bads'] ] bads_name = [ ch_names[k] for k, _ in enumerate(sel) if ch_names[k] in data['info']['bads'] ] return epochs, times[mask], bads, bads_name
def test_evoked_standard_error(): """Test calculation and read/write of standard error """ epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0)) evoked = [epochs.average(), epochs.standard_error()] fiff.write_evoked('evoked.fif', evoked) evoked2 = fiff.read_evoked('evoked.fif', [0, 1]) assert_true(evoked2[0].aspect_kind == fiff.FIFF.FIFFV_ASPECT_AVERAGE) assert_true(evoked2[1].aspect_kind == fiff.FIFF.FIFFV_ASPECT_STD_ERR) for ave, ave2 in zip(evoked, evoked2): assert_array_almost_equal(ave.data, ave2.data) assert_array_almost_equal(ave.times, ave2.times) assert_equal(ave.nave, ave2.nave) assert_equal(ave.aspect_kind, ave2.aspect_kind) assert_equal(ave.last, ave2.last) assert_equal(ave.first, ave2.first)
def test_plot_topomap(): """Testing topomap plotting """ # evoked evoked = fiff.read_evoked(evoked_fname, "Left Auditory", baseline=(None, 0)) evoked.plot_topomap(0.1, "mag", layout=layout) plot_evoked_topomap(evoked, None, ch_type="mag") times = [0.1, 0.2] plot_evoked_topomap(evoked, times, ch_type="grad") plot_evoked_topomap(evoked, times, ch_type="planar1") plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto") plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive") assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50)) assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6]) # projs projs = read_proj(ecg_fname)[:7] plot_projs_topomap(projs)
def test_get_peak(): """Test peak getter """ evoked = read_evoked(fname, setno=0, proj=True) assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=1) assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmax=0.9) assert_raises(ValueError, evoked.get_peak, ch_type='mag', tmin=0.02, tmax=0.01) assert_raises(ValueError, evoked.get_peak, ch_type='mag', mode='foo') assert_raises(RuntimeError, evoked.get_peak, ch_type=None, mode='foo') assert_raises(ValueError, evoked.get_peak, ch_type='misc', mode='foo') ch_idx, time_idx = evoked.get_peak(ch_type='mag') assert_true(ch_idx in evoked.ch_names) assert_true(time_idx in evoked.times) ch_idx, time_idx = evoked.get_peak(ch_type='mag', time_as_index=True) assert_true(time_idx < len(evoked.times)) data = np.array([[0., 1., 2.], [0., -3., 0]]) times = np.array([.1, .2, .3]) ch_idx, time_idx = _get_peak(data, times, mode='abs') assert_equal(ch_idx, 1) assert_equal(time_idx, 1) ch_idx, time_idx = _get_peak(data * -1, times, mode='neg') assert_equal(ch_idx, 0) assert_equal(time_idx, 2) ch_idx, time_idx = _get_peak(data, times, mode='pos') assert_equal(ch_idx, 0) assert_equal(time_idx, 2) assert_raises(ValueError, _get_peak, data + 1e3, times, mode='neg') assert_raises(ValueError, _get_peak, data - 1e3, times, mode='pos')
def test_make_field_map_eeg(): """Test interpolation of EEG field onto head """ trans = read_trans(trans_fname) evoked = read_evoked(evoked_fname, setno='Left Auditory') evoked.info['bads'] = ['MEG 2443', 'EEG 053'] # add some bads surf = get_head_surf('sample', subjects_dir=subjects_dir) # we must have trans if surface is in MRI coords assert_raises(ValueError, _make_surface_mapping, evoked.info, surf, 'eeg') evoked = pick_types_evoked(evoked, meg=False, eeg=True) fmd = make_field_map(evoked, trans_fname=trans_fname, subject='sample', subjects_dir=subjects_dir) # trans is necessary for EEG only assert_raises(RuntimeError, make_field_map, evoked, trans_fname=None, subject='sample', subjects_dir=subjects_dir) fmd = make_field_map(evoked, trans_fname=trans_fname, subject='sample', subjects_dir=subjects_dir) assert_true(len(fmd) == 1) assert_array_equal(fmd[0]['data'].shape, (2562, 59)) # maps data onto surf assert_true(len(fmd[0]['ch_names']), 59)
def test_plot_topomap(): """Test topomap plotting """ # evoked warnings.simplefilter('always', UserWarning) with warnings.catch_warnings(record=True): evoked = fiff.read_evoked(evoked_fname, 'Left Auditory', baseline=(None, 0)) evoked.plot_topomap(0.1, 'mag', layout=layout) plot_evoked_topomap(evoked, None, ch_type='mag') times = [0.1, 0.2] plot_evoked_topomap(evoked, times, ch_type='eeg') plot_evoked_topomap(evoked, times, ch_type='grad') plot_evoked_topomap(evoked, times, ch_type='planar1') plot_evoked_topomap(evoked, times, ch_type='planar2') with warnings.catch_warnings(record=True): # delaunay triangulation warning plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto') assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag', proj='interactive') # projs have already been applied evoked.proj = False # let's fake it like they haven't been applied plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive') assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50)) assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6]) projs = read_proj(ecg_fname) projs = [p for p in projs if p['desc'].lower().find('eeg') < 0] plot_projs_topomap(projs) plt.close('all') for ch in evoked.info['chs']: if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG: if ch['eeg_loc'] is not None: ch['eeg_loc'].fill(0) ch['loc'].fill(0) assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type='eeg')
def test_make_field_map_meg(): """Test interpolation of MEG field onto helmet """ evoked = read_evoked(evoked_fname, setno='Left Auditory') info = evoked.info surf = get_meg_helmet_surf(info) # let's reduce the number of channels by a bunch to speed it up info['bads'] = info['ch_names'][:200] # bad ch_type assert_raises(ValueError, _make_surface_mapping, info, surf, 'foo') # bad mode assert_raises(ValueError, _make_surface_mapping, info, surf, 'meg', mode='foo') # no picks evoked_eeg = pick_types_evoked(evoked, meg=False, eeg=True) assert_raises(RuntimeError, _make_surface_mapping, evoked_eeg.info, surf, 'meg') # bad surface def nn = surf['nn'] del surf['nn'] assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg') surf['nn'] = nn cf = surf['coord_frame'] del surf['coord_frame'] assert_raises(KeyError, _make_surface_mapping, info, surf, 'meg') surf['coord_frame'] = cf # now do it with make_field_map evoked = pick_types_evoked(evoked, meg=True, eeg=False) fmd = make_field_map(evoked, trans_fname=None, subject='sample', subjects_dir=subjects_dir) assert_true(len(fmd) == 1) assert_array_equal(fmd[0]['data'].shape, (304, 106)) # maps data onto surf assert_true(len(fmd[0]['ch_names']), 106) assert_raises(ValueError, make_field_map, evoked, ch_type='foobar')
def test_shift_time_evoked(): """ Test for shifting of time scale """ # Shift backward ave = read_evoked(fname, 0) ave.shift_time(-0.1, relative=True) write_evoked(op.join(tempdir, 'evoked.fif'), ave) # Shift forward twice the amount ave_bshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0) ave_bshift.shift_time(0.2, relative=True) write_evoked(op.join(tempdir, 'evoked.fif'), ave_bshift) # Shift backward again ave_fshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0) ave_fshift.shift_time(-0.1, relative=True) write_evoked(op.join(tempdir, 'evoked.fif'), ave_fshift) ave_normal = read_evoked(fname, 0) ave_relative = read_evoked(op.join(tempdir, 'evoked.fif'), 0) assert_true( np.allclose(ave_normal.data, ave_relative.data, atol=1e-16, rtol=1e-3)) assert_array_almost_equal(ave_normal.times, ave_relative.times, 10) assert_equal(ave_normal.last, ave_relative.last) assert_equal(ave_normal.first, ave_relative.first) # Absolute time shift ave = read_evoked(fname, 0) ave.shift_time(-0.3, relative=False) write_evoked(op.join(tempdir, 'evoked.fif'), ave) ave_absolute = read_evoked(op.join(tempdir, 'evoked.fif'), 0) assert_true( np.allclose(ave_normal.data, ave_absolute.data, atol=1e-16, rtol=1e-3)) assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
def test_shift_time_evoked(): """ Test for shifting of time scale """ # Shift backward ave = read_evoked(fname, 0) ave.shift_time(-0.1, relative=True) write_evoked(op.join(tempdir, 'evoked.fif'), ave) # Shift forward twice the amount ave_bshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0) ave_bshift.shift_time(0.2, relative=True) write_evoked(op.join(tempdir, 'evoked.fif'), ave_bshift) # Shift backward again ave_fshift = read_evoked(op.join(tempdir, 'evoked.fif'), 0) ave_fshift.shift_time(-0.1, relative=True) write_evoked(op.join(tempdir, 'evoked.fif'), ave_fshift) ave_normal = read_evoked(fname, 0) ave_relative = read_evoked(op.join(tempdir, 'evoked.fif'), 0) assert_true(np.allclose(ave_normal.data, ave_relative.data, atol=1e-16, rtol=1e-3)) assert_array_almost_equal(ave_normal.times, ave_relative.times, 10) assert_equal(ave_normal.last, ave_relative.last) assert_equal(ave_normal.first, ave_relative.first) # Absolute time shift ave = read_evoked(fname, 0) ave.shift_time(-0.3, relative=False) write_evoked(op.join(tempdir, 'evoked.fif'), ave) ave_absolute = read_evoked(op.join(tempdir, 'evoked.fif'), 0) assert_true(np.allclose(ave_normal.data, ave_absolute.data, atol=1e-16, rtol=1e-3)) assert_equal(ave_absolute.first, int(-0.3 * ave.info['sfreq']))
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') fname_fwd = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-oct-6-fwd.fif') label = 'Aud-rh' fname_label = op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label) evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file setno = 0 loose = None evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0)) evoked.crop(tmin=0.08, tmax=0.12) # Handling forward solution forward = read_forward_solution(fname_fwd, force_fixed=True) label = read_label(fname_label) def test_MxNE_inverse(): """Test MxNE inverse computation""" alpha = 60 # spatial regularization parameter stc = mixed_norm(evoked, forward, cov, alpha, loose=None, depth=0.9, maxit=500, tol=1e-4, active_set_size=10) assert_array_almost_equal(stc.times, evoked.times, 5) assert_true(stc.vertno[1][0] in label.vertices)
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation""" # Handling forward solution evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file setno = 0 loose = None depth = 0.9 evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0)) evoked.crop(tmin=-0.1, tmax=0.4) evoked_l21 = copy.deepcopy(evoked) evoked_l21.crop(tmin=0.08, tmax=0.1) label = read_label(fname_label) weights_min = 0.5 forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=loose, depth=depth, fixed=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. # MxNE tests alpha = 60 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='prox') stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_prox.data, stc_cd.data, 5) assert_true(stc_prox.vertno[1][0] in label.vertices) assert_true(stc_cd.vertno[1][0] in label.vertices) stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=depth, maxit=500, tol=1e-4, active_set_size=10, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert_true(stc.vertno[1][0] in label.vertices) # Do with TF-MxNE for test memory savings alpha_space = 60. # spatial regularization parameter alpha_time = 1. # temporal regularization parameter stc, _ = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked.times, 5) assert_true(stc.vertno[1][0] in label.vertices)
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') fname_fwd = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-oct-6-fwd.fif') label = 'Aud-rh' fname_label = op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label) evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file setno = 0 loose = None evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0)) evoked.crop(tmin=0.08, tmax=0.12) # Handling forward solution forward = read_forward_solution(fname_fwd, force_fixed=True) label = read_label(fname_label) def test_MxNE_inverse(): """Test MxNE inverse computation""" alpha = 60 # spatial regularization parameter stc = mixed_norm(evoked, forward, cov, alpha, loose=None,
# # License: BSD (3-clause) print __doc__ import os import mne from mne import fiff fname = os.environ['MNE_SAMPLE_DATASET_PATH'] fname += '/MEG/sample/sample_audvis-ave.fif' cov_fname = os.environ['MNE_SAMPLE_DATASET_PATH'] cov_fname += '/MEG/sample/sample_audvis-cov.fif' # Reading ave = fiff.read_evoked(fname, setno=0, baseline=(None, 0)) cov = mne.Covariance() cov.load(cov_fname) ave_whiten, W = cov.whiten_evoked(ave) bads = ave_whiten['info']['bads'] ind_meg_grad = fiff.pick_types(ave['info'], meg='grad', exclude=bads) ind_meg_mag = fiff.pick_types(ave['info'], meg='mag', exclude=bads) ind_eeg = fiff.pick_types(ave['info'], meg=False, eeg=True, exclude=bads) ############################################################################### # Show result import pylab as pl pl.clf() pl.subplot(3, 1, 1)
from mne import fiff from mne.datasets import sample from mne.inverse_sparse import mixed_norm from mne.minimum_norm import make_inverse_operator, apply_inverse from mne.viz import plot_sparse_source_estimates data_path = sample.data_path() fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif' cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif' # Read noise covariance matrix cov = mne.read_cov(cov_fname) # Handling average file setno = 0 evoked = fiff.read_evoked(ave_fname, setno=setno, baseline=(None, 0)) evoked.crop(tmin=0, tmax=0.3) # Handling forward solution forward = mne.read_forward_solution(fwd_fname, surf_ori=True) cov = mne.cov.regularize(cov, evoked.info) import matplotlib.pyplot as plt plt.figure() ylim = dict(eeg=[-10, 10], grad=[-400, 400], mag=[-600, 600]) evoked.plot(ylim=ylim, proj=True) ############################################################################### # Run solver alpha = 70 # regularization parameter between 0 and 100 (100 is high) loose, depth = 0.2, 0.9 # loose orientation & depth weighting
def test_plot_topomap(): """Test topomap plotting """ # evoked warnings.simplefilter('always', UserWarning) with warnings.catch_warnings(record=True): evoked = fiff.read_evoked(evoked_fname, 'Left Auditory', baseline=(None, 0)) evoked.plot_topomap(0.1, 'mag', layout=layout) plot_evoked_topomap(evoked, None, ch_type='mag') times = [0.1, 0.2] plot_evoked_topomap(evoked, times, ch_type='eeg') plot_evoked_topomap(evoked, times, ch_type='grad') plot_evoked_topomap(evoked, times, ch_type='planar1') plot_evoked_topomap(evoked, times, ch_type='planar2') plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True) p = plot_evoked_topomap(evoked, times, ch_type='grad', show_names=lambda x: x.replace('MEG', '')) subplot = [ x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot) ][0] assert_true( all('MEG' not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text))) # Test title def get_texts(p): return [ x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text) ] p = plot_evoked_topomap(evoked, times, ch_type='eeg') assert_equal(len(get_texts(p)), 0) p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom') texts = get_texts(p) assert_equal(len(texts), 1) assert_equal(texts[0], 'Custom') # delaunay triangulation warning with warnings.catch_warnings(record=True): plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto') assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag', proj='interactive') # projs have already been applied evoked.proj = False # let's fake it like they haven't been applied plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive') assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50)) assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6]) projs = read_proj(ecg_fname) projs = [p for p in projs if p['desc'].lower().find('eeg') < 0] plot_projs_topomap(projs) plt.close('all') for ch in evoked.info['chs']: if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG: if ch['eeg_loc'] is not None: ch['eeg_loc'].fill(0) ch['loc'].fill(0) assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type='eeg')
from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse from mne.inverse_sparse import tf_mixed_norm from mne.viz import plot_sparse_source_estimates data_path = sample.data_path() fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif' cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif' # Read noise covariance matrix cov = mne.read_cov(cov_fname) # Handling average file setno = 'Left visual' evoked = fiff.read_evoked(ave_fname, setno=setno, baseline=(None, 0)) evoked = fiff.pick.pick_channels_evoked(evoked) # We make the window slightly larger than what you'll eventually be interested # in ([-0.05, 0.3]) to avoid edge effects. evoked.crop(tmin=-0.1, tmax=0.4) # Handling forward solution forward = mne.read_forward_solution(fwd_fname, force_fixed=False, surf_ori=True) cov = mne.cov.regularize(cov, evoked.info) ############################################################################### # Run solver # alpha_space regularization parameter is between 0 and 100 (100 is high)
""" # Author: Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print __doc__ import pylab as pl from mne import fiff from mne.layouts import Layout from mne.viz import plot_topo from mne.datasets import sample data_path = sample.data_path('.') fname = data_path + '/MEG/sample/sample_audvis-ave.fif' # Reading evoked = fiff.read_evoked(fname, setno=0, baseline=(None, 0)) layout = Layout('Vectorview-all') ############################################################################### # Show topography plot_topo(evoked, layout) title = 'MNE sample data (condition : %s)' % evoked.comment pl.figtext(0.03, 0.93, title, color='w', fontsize=18) pl.show()