def test_render_report(): """Test rendering -*.fif files for mne report. """ report = Report(info_fname=raw_fname) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') report.parse_folder(data_path=base_dir) assert_true(len(w) == 1) # Check correct paths and filenames assert_true(raw_fname in report.fnames) assert_true(event_name in report.fnames) assert_true(report.data_path == base_dir) # Check if all files were rendered in the report fnames = glob.glob(op.join(base_dir, '*.fif')) bad_name = 'test_ctf_comp_raw-eve.fif' decrement = any(fname.endswith(bad_name) for fname in fnames) fnames = [fname for fname in fnames if fname.endswith(('-eve.fif', '-ave.fif', '-cov.fif', '-sol.fif', '-fwd.fif', '-inv.fif', '-src.fif', '-trans.fif', 'raw.fif', 'sss.fif', '-epo.fif')) and not fname.endswith(bad_name)] # last file above gets created by another test, and it shouldn't be there for fname in fnames: assert_true(''.join(report.html).find(op.basename(fname)) != -1) assert_equal(len(report.fnames), len(fnames)) assert_equal(len(report.html), len(report.fnames)) evoked1 = read_evokeds(evoked1_fname) evoked2 = read_evokeds(evoked2_fname) assert_equal(len(report.fnames) + len(evoked1) + len(evoked2) - 2, report.initial_id - decrement) # Check saving functionality report.data_path = tempdir report.save(fname=op.join(tempdir, 'report.html'), open_browser=False) assert_true(op.isfile(op.join(tempdir, 'report.html'))) # Check add_section functionality fig = evoked1[0].plot(show=False) report.add_section(figs=fig, # test non-list input captions=['evoked response']) assert_equal(len(report.html), len(fnames) + 1) assert_equal(len(report.html), len(report.fnames)) assert_raises(ValueError, report.add_section, figs=[fig, fig], captions='H') # Check saving same report to new filename report.save(fname=op.join(tempdir, 'report2.html'), open_browser=False) assert_true(op.isfile(op.join(tempdir, 'report2.html'))) # Check overwriting file report.save(fname=op.join(tempdir, 'report.html'), open_browser=False, overwrite=True) assert_true(op.isfile(op.join(tempdir, 'report.html')))
def test_evoked_arithmetic(): """Test evoked arithmetic """ ev = read_evokeds(fname, condition=0) ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10) # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2: # data should be added according to their `nave` weights # nave = ev1.nave + ev2.nave ev = ev1 + ev2 assert_equal(ev.nave, ev1.nave + ev2.nave) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) ev = ev1 - ev2 assert_equal(ev.nave, ev1.nave + ev2.nave) assert_equal(ev.comment, ev1.comment + ' - ' + ev2.comment) assert_allclose(ev.data, np.ones_like(ev1.data)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ev = merge_evoked([ev1, ev2]) assert_true(len(w) >= 1) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) # default comment behavior if evoked.comment is None old_comment1 = ev1.comment old_comment2 = ev2.comment ev1.comment = None with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') ev = ev1 - ev2 assert_equal(ev.comment, 'unknown') ev1.comment = old_comment1 ev2.comment = old_comment2 # equal weighting ev = combine_evoked([ev1, ev2], weights='equal') assert_allclose(ev.data, np.zeros_like(ev1.data)) # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1 ev = combine_evoked([ev1, ev2], weights=[1, 0]) assert_equal(ev.nave, ev1.nave) assert_allclose(ev.data, ev1.data) # simple subtraction (like in oddball) ev = combine_evoked([ev1, ev2], weights=[1, -1]) assert_allclose(ev.data, 2 * np.ones_like(ev1.data)) assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo') assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2)
def test_evoked_standard_error(): """Test calculation and read/write of standard error """ raw, events, picks = _get_data() tempdir = _TempDir() epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, 0)) evoked = [epochs.average(), epochs.standard_error()] write_evokeds(op.join(tempdir, 'evoked-ave.fif'), evoked) evoked2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), [0, 1]) evoked3 = [read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 'Unknown'), read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 'Unknown', kind='standard_error')] for evoked_new in [evoked2, evoked3]: assert_true(evoked_new[0]._aspect_kind == FIFF.FIFFV_ASPECT_AVERAGE) assert_true(evoked_new[0].kind == 'average') assert_true(evoked_new[1]._aspect_kind == 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 """ tempdir = _TempDir() # upsample, write it out, read it in ave = read_evokeds(fname, 0) sfreq_normal = ave.info['sfreq'] ave.resample(2 * sfreq_normal) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave) ave_up = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 0) # compare it to the original ave_normal = read_evokeds(fname, 0) # and compare the original to the downsampled upsampled version ave_new = read_evokeds(op.join(tempdir, 'evoked-ave.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_evoked_proj(): """Test SSP proj operations """ for proj in [True, False]: ave = read_evokeds(fname, condition=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_evokeds(fname, condition=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(record=True) as w: warnings.simplefilter("always") 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-ave.fif")) evoked2 = read_evokeds(op.join(tempdir, "evoked-ave.fif"))[0] 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(record=True) as w: warnings.simplefilter("always") 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-ave.fif")) evoked2 = read_evokeds(op.join(tempdir, "evoked-ave.fif"))[0] 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(record=True) as w: warnings.simplefilter("always") 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_io_evoked(): """Test IO for evoked data (fif + gz) with integer and str args """ tempdir = _TempDir() ave = read_evokeds(fname, 0) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave) ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.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) assert_true(repr(ave)) # 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 read_evokeds and write_evokeds aves1 = read_evokeds(fname)[1::2] aves2 = read_evokeds(fname, [1, 3]) aves3 = read_evokeds(fname, ['Right Auditory', 'Right visual']) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1) aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.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) # test warnings on bad filenames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') fname2 = op.join(tempdir, 'test-bad-name.fif') write_evokeds(fname2, ave) read_evokeds(fname2) assert_naming(w, 'test_evoked.py', 2) # constructor assert_raises(TypeError, Evoked, fname)
def test_evoked_detrend(): """Test for detrending evoked data.""" ave = read_evokeds(fname, 0) ave_normal = read_evokeds(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_plot_topomap(): """Test topomap plotting """ # evoked warnings.simplefilter("always", UserWarning) with warnings.catch_warnings(record=True): evoked = read_evokeds(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 # change to no-proj mode evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False) 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 = read_proj(ecg_fname) projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0] plot_projs_topomap(projs) plt.close("all") for ch in evoked.info["chs"]: if ch["coil_type"] == 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_hash_evoked(): """Test evoked hashing.""" ave = read_evokeds(fname, 0) ave_2 = read_evokeds(fname, 0) assert_equal(hash(ave), hash(ave_2)) # do NOT use assert_equal here, failing output is terrible assert_true(pickle.dumps(ave) == pickle.dumps(ave_2)) ave_2.data[0, 0] -= 1 assert_not_equal(hash(ave), hash(ave_2))
def test_evoked_to_nitime(): """ Test to_nitime """ ave = read_evokeds(fname, 0) evoked_ts = ave.to_nitime() assert_equal(evoked_ts.data, ave.data) picks2 = [1, 2] ave = read_evokeds(fname, 0) evoked_ts = ave.to_nitime(picks=picks2) assert_equal(evoked_ts.data, ave.data[picks2])
def test_hash_evoked(): """Test evoked hashing.""" ave = read_evokeds(fname, 0) ave_2 = read_evokeds(fname, 0) assert hash(ave) == hash(ave_2) assert ave == ave_2 # do NOT use assert_equal here, failing output is terrible assert pickle.dumps(ave) == pickle.dumps(ave_2) ave_2.data[0, 0] -= 1 assert hash(ave) != hash(ave_2)
def test_evoked_aspects(aspect_kind, tmpdir): """Test handling of evoked aspects.""" # gh-6359 ave = read_evokeds(fname, 0) ave._aspect_kind = aspect_kind assert 'Evoked' in repr(ave) # for completeness let's try a round-trip temp_fname = op.join(str(tmpdir), 'test-ave.fif') ave.save(temp_fname) ave_2 = read_evokeds(temp_fname, condition=0) assert_allclose(ave.data, ave_2.data) assert ave.kind == ave_2.kind
def apply_inverse_ave(fnevo, min_subject='fsaverage'): from mne import make_forward_solution from mne.minimum_norm import write_inverse_operator fnlist = get_files_from_list(fnevo) # loop across all filenames for fname in fnlist: fn_path = os.path.split(fname)[0] name = os.path.basename(fname) #fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' subject = name.split('_')[0] fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' %subject subject_path = subjects_dir + '/%s' %subject #min_dir = subjects_dir + '/%s' %min_subject fn_trans = fn_path + '/%s-trans.fif' % subject #fn_cov = fn_path + '/%s_empty,nr,fibp1-45-cov.fif' % subject fn_cov = fn_path + '/%s_empty,fibp1-45-cov.fif' %subject fn_src = subject_path + '/bem/%s-oct-6-src.fif' % subject fn_bem = subject_path + '/bem/%s-5120-5120-5120-bem-sol.fif' % subject [evoked] = mne.read_evokeds(fname) evoked.pick_types(meg=True, ref_meg=False) noise_cov = mne.read_cov(fn_cov) #noise_cov = mne.cov.regularize(noise_cov, evoked.info, # mag=0.05, grad=0.05, proj=True) fwd = make_forward_solution(evoked.info, fn_trans, fn_src, fn_bem) fwd['surf_ori'] = True inv = mne.minimum_norm.make_inverse_operator(evoked.info, fwd, noise_cov, loose=0.2, depth=0.8, limit_depth_chs=False) write_inverse_operator(fn_inv, inv)
def run_inverse(subject_id): subject = "sub%03d" % subject_id print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) fname_ave = op.join(data_path, '%s-ave.fif' % subject) fname_cov = op.join(data_path, '%s-cov.fif' % subject) fname_fwd = op.join(data_path, '%s-meg-%s-fwd.fif' % (subject, spacing)) fname_inv = op.join(data_path, '%s-meg-%s-inv.fif' % (subject, spacing)) evokeds = mne.read_evokeds(fname_ave, condition=[0, 1, 2, 3, 4, 5]) cov = mne.read_cov(fname_cov) # cov = mne.cov.regularize(cov, evokeds[0].info, # mag=0.05, grad=0.05, eeg=0.1, proj=True) forward = mne.read_forward_solution(fname_fwd, surf_ori=True) # forward = mne.pick_types_forward(forward, meg=True, eeg=False) # make an M/EEG, MEG-only, and EEG-only inverse operators info = evokeds[0].info inverse_operator = make_inverse_operator(info, forward, cov, loose=0.2, depth=0.8) write_inverse_operator(fname_inv, inverse_operator) # Compute inverse solution snr = 3.0 lambda2 = 1.0 / snr ** 2 for evoked in evokeds: stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM", pick_ori=None) stc.save(op.join(data_path, 'mne_dSPM_inverse-%s' % evoked.comment))
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) evoked.resample(50) evoked.crop(tmin=0, tmax=0.3) cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.2 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=True, update_mode=1, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) assert_true(np.concatenate(stc.vertices)[idx] == 96397) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=False, update_mode=1, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) assert_true(np.concatenate(stc.vertices)[idx] == 82010) # force fixed orientation stc, res = gamma_map(evoked, forward, cov, alpha, tol=1e-5, xyz_same_gamma=False, update_mode=2, loose=None, return_residual=True, verbose=False) idx = np.argmax(np.sum(stc.data ** 2, axis=1)) # assert_true(np.concatenate(stc.vertices)[idx] == 83398) # XXX FIX assert_array_almost_equal(evoked.times, res.times)
def compensate_mne(fname, comp): """Compensate using MNE-C.""" tmp_fname = '%s-%d-ave.fif' % (fname[:-4], comp) cmd = ['mne_compensate_data', '--in', fname, '--out', tmp_fname, '--grad', str(comp)] run_subprocess(cmd) return read_evokeds(tmp_fname)[0]
def apply_STC_ave(fnevo, method='dSPM', snr=3.0): ''' Inverse evoked data into the source space. Parameter --------- fnevo: string or list The evoked file with ECG, EOG and environmental noise free. method:string Inverse method, 'MNE' or 'dSPM' snr: float Signal to noise ratio for inverse solution. ''' #Get the default subjects_dir from mne.minimum_norm import apply_inverse, read_inverse_operator fnlist = get_files_from_list(fnevo) # loop across all filenames for fname in fnlist: name = os.path.basename(fname) fn_path = os.path.split(fname)[0] fn_stc = fname[:fname.rfind('-ave.fif')] # fn_inv = fname[:fname.rfind('-ave.fif')] + ',ave-inv.fif' subject = name.split('_')[0] fn_inv = fn_path + '/%s_fibp1-45,ave-inv.fif' % subject snr = snr lambda2 = 1.0 / snr ** 2 # noise_cov = mne.read_cov(fn_cov) [evoked] = mne.read_evokeds(fname) evoked.pick_types(meg=True, ref_meg=False) inv = read_inverse_operator(fn_inv) stc = apply_inverse(evoked, inv, lambda2, method, pick_ori='normal') stc.save(fn_stc)
def test_add_channels(): """Test evoked splitting / re-appending channel types """ evoked = read_evokeds(fname, condition=0) evoked.info['buffer_size_sec'] = None evoked_eeg = evoked.pick_types(meg=False, eeg=True, copy=True) evoked_meg = evoked.pick_types(meg=True, copy=True) evoked_stim = evoked.pick_types(meg=False, stim=True, copy=True) evoked_eeg_meg = evoked.pick_types(meg=True, eeg=True, copy=True) evoked_new = evoked_meg.add_channels([evoked_eeg, evoked_stim], copy=True) assert_true(all(ch in evoked_new.ch_names for ch in evoked_stim.ch_names + evoked_meg.ch_names)) evoked_new = evoked_meg.add_channels([evoked_eeg], copy=True) assert_true(ch in evoked_new.ch_names for ch in evoked.ch_names) assert_array_equal(evoked_new.data, evoked_eeg_meg.data) assert_true(all(ch not in evoked_new.ch_names for ch in evoked_stim.ch_names)) # Now test errors evoked_badsf = evoked_eeg.copy() evoked_badsf.info['sfreq'] = 3.1415927 evoked_eeg = evoked_eeg.crop(-.1, .1) assert_raises(RuntimeError, evoked_meg.add_channels, [evoked_badsf]) assert_raises(AssertionError, evoked_meg.add_channels, [evoked_eeg]) assert_raises(ValueError, evoked_meg.add_channels, [evoked_meg]) assert_raises(AssertionError, evoked_meg.add_channels, evoked_badsf)
def test_cov_scaling(): """Test rescaling covs""" evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=True) cov = read_cov(cov_fname)['data'] cov2 = read_cov(cov_fname)['data'] assert_array_equal(cov, cov2) evoked.pick_channels([evoked.ch_names[k] for k in pick_types( evoked.info, meg=True, eeg=True )]) picks_list = _picks_by_type(evoked.info) scalings = dict(mag=1e15, grad=1e13, eeg=1e6) _apply_scaling_cov(cov2, picks_list, scalings=scalings) _apply_scaling_cov(cov, picks_list, scalings=scalings) assert_array_equal(cov, cov2) assert_true(cov.max() > 1) _undo_scaling_cov(cov2, picks_list, scalings=scalings) _undo_scaling_cov(cov, picks_list, scalings=scalings) assert_array_equal(cov, cov2) assert_true(cov.max() < 1) data = evoked.data.copy() _apply_scaling_array(data, picks_list, scalings=scalings) _undo_scaling_array(data, picks_list, scalings=scalings) assert_allclose(data, evoked.data, atol=1e-20)
def run_forward(subject_id): subject = "sub%03d" % subject_id print("processing subject: %s" % subject) data_path = op.join(meg_dir, subject) fname_ave = op.join(data_path, '%s-ave.fif' % subject) fname_fwd = op.join(data_path, '%s-meg-%s-fwd.fif' % (subject, spacing)) fname_trans = op.join(study_path, 'ds117', subject, 'MEG', '%s-trans.fif' % subject) src = mne.setup_source_space(subject, spacing=spacing, subjects_dir=subjects_dir, overwrite=True, n_jobs=1, add_dist=False) src_fname = op.join(subjects_dir, subject, '%s-src.fif' % spacing) mne.write_source_spaces(src_fname, src) bem_model = mne.make_bem_model(subject, ico=4, subjects_dir=subjects_dir, conductivity=(0.3,)) bem = mne.make_bem_solution(bem_model) info = mne.read_evokeds(fname_ave, condition=0).info fwd = mne.make_forward_solution(info, trans=fname_trans, src=src, bem=bem, fname=None, meg=True, eeg=False, mindist=mindist, n_jobs=1, overwrite=True) fwd = mne.convert_forward_solution(fwd, surf_ori=True) mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
def test_gamma_map_vol_sphere(): """Gamma MAP with a sphere forward and volumic source space""" evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0), proj=False) evoked.resample(50, npad=100) evoked.crop(tmin=0.1, tmax=0.16) # crop to window around peak cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) info = evoked.info sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080) src = mne.setup_volume_source_space(subject=None, pos=15., mri=None, sphere=(0.0, 0.0, 0.0, 80.0), bem=None, mindist=5.0, exclude=2.0) fwd = mne.make_forward_solution(info, trans=None, src=src, bem=sphere, eeg=False, meg=True) alpha = 0.5 assert_raises(ValueError, gamma_map, evoked, fwd, cov, alpha, loose=0, return_residual=False) assert_raises(ValueError, gamma_map, evoked, fwd, cov, alpha, loose=0.2, return_residual=False) stc = gamma_map(evoked, fwd, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=2, return_residual=False) assert_array_almost_equal(stc.times, evoked.times, 5)
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd) forward = convert_forward_solution(forward, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0), proj=False) evoked.resample(50, npad=100) evoked.crop(tmin=0.1, tmax=0.16) # crop to window around peak cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.5 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=True, update_mode=1) _check_stc(stc, evoked, 68477) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1) _check_stc(stc, evoked, 82010) dips = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1, return_as_dipoles=True) assert_true(isinstance(dips[0], Dipole)) stc_dip = make_stc_from_dipoles(dips, forward['src']) _check_stcs(stc, stc_dip) # force fixed orientation stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=2, loose=0, return_residual=False) _check_stc(stc, evoked, 85739, 20)
def test_render_add_sections(): """Test adding figures/images to section. """ tempdir = _TempDir() import matplotlib.pyplot as plt report = Report(subjects_dir=subjects_dir) # Check add_figs_to_section functionality fig = plt.plot([1, 2], [1, 2])[0].figure report.add_figs_to_section(figs=fig, # test non-list input captions=['evoked response'], scale=1.2, image_format='svg') assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig], captions='H') assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=['foo'], scale=0, image_format='svg') assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=['foo'], scale=1e-10, image_format='svg') # need to recreate because calls above change size fig = plt.plot([1, 2], [1, 2])[0].figure # Check add_images_to_section img_fname = op.join(tempdir, 'testimage.png') fig.savefig(img_fname) report.add_images_to_section(fnames=[img_fname], captions=['evoked response']) assert_raises(ValueError, report.add_images_to_section, fnames=[img_fname, img_fname], captions='H') evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=(-0.2, 0.0)) fig = plot_trans(evoked.info, trans_fname, subject='sample', subjects_dir=subjects_dir) report.add_figs_to_section(figs=fig, # test non-list input captions='random image', scale=1.2)
def test_gamma_map(): """Test Gamma MAP inverse""" forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) forward = pick_types_forward(forward, meg=False, eeg=True) evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0), proj=False) evoked.resample(50, npad=100) evoked.crop(tmin=0.1, tmax=0.16) # crop to nice window near samp border cov = read_cov(fname_cov) cov = regularize(cov, evoked.info) alpha = 0.5 stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=True, update_mode=1) _check_stc(stc, evoked, 68477) stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=1) _check_stc(stc, evoked, 82010) # force fixed orientation stc = gamma_map(evoked, forward, cov, alpha, tol=1e-4, xyz_same_gamma=False, update_mode=2, loose=None, return_residual=False) _check_stc(stc, evoked, 85739, 20)
def test_add_channels(): """Test evoked splitting / re-appending channel types""" evoked = read_evokeds(fname, condition=0) evoked.info['buffer_size_sec'] = None hpi_coils = [{'event_bits': []}, {'event_bits': np.array([256, 0, 256, 256])}, {'event_bits': np.array([512, 0, 512, 512])}] evoked.info['hpi_subsystem'] = dict(hpi_coils=hpi_coils, ncoil=2) evoked_eeg = evoked.copy().pick_types(meg=False, eeg=True) evoked_meg = evoked.copy().pick_types(meg=True) evoked_stim = evoked.copy().pick_types(meg=False, stim=True) evoked_eeg_meg = evoked.copy().pick_types(meg=True, eeg=True) evoked_new = evoked_meg.copy().add_channels([evoked_eeg, evoked_stim]) assert_true(all(ch in evoked_new.ch_names for ch in evoked_stim.ch_names + evoked_meg.ch_names)) evoked_new = evoked_meg.copy().add_channels([evoked_eeg]) assert_true(ch in evoked_new.ch_names for ch in evoked.ch_names) assert_array_equal(evoked_new.data, evoked_eeg_meg.data) assert_true(all(ch not in evoked_new.ch_names for ch in evoked_stim.ch_names)) # Now test errors evoked_badsf = evoked_eeg.copy() evoked_badsf.info['sfreq'] = 3.1415927 evoked_eeg = evoked_eeg.crop(-.1, .1) assert_raises(RuntimeError, evoked_meg.add_channels, [evoked_badsf]) assert_raises(AssertionError, evoked_meg.add_channels, [evoked_eeg]) assert_raises(ValueError, evoked_meg.add_channels, [evoked_meg]) assert_raises(AssertionError, evoked_meg.add_channels, evoked_badsf)
def test_plot_trans(): """Test plotting of -trans.fif files and MEG sensor layouts """ evoked = read_evokeds(evoked_fname)[0] with warnings.catch_warnings(record=True): # 4D weight tables bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True, preload=False).info infos = dict( Neuromag=evoked.info, CTF=read_raw_ctf(ctf_fname).info, BTi=bti, KIT=read_raw_kit(sqd_fname).info, ) for system, info in infos.items(): ref_meg = False if system == 'KIT' else True plot_trans(info, trans_fname, subject='sample', meg_sensors=True, subjects_dir=subjects_dir, ref_meg=ref_meg) # KIT ref sensor coil def not defined assert_raises(RuntimeError, plot_trans, infos['KIT'], None, meg_sensors=True, ref_meg=True) info = infos['Neuromag'] assert_raises(ValueError, plot_trans, info, trans_fname, subject='sample', subjects_dir=subjects_dir, ch_type='bad-chtype') assert_raises(TypeError, plot_trans, 'foo', trans_fname, subject='sample', subjects_dir=subjects_dir) # no-head version plot_trans(info, None, meg_sensors=True, dig=True, coord_frame='head') # EEG only with strange options with warnings.catch_warnings(record=True) as w: plot_trans(evoked.copy().pick_types(meg=False, eeg=True).info, trans=trans_fname, meg_sensors=True) assert_true(['Cannot plot MEG' in str(ww.message) for ww in w])
def test_plot_topomap_neuromag122(): """Test topomap plotting.""" res = 8 fast_test = dict(res=res, contours=0, sensors=False) evoked = read_evokeds(evoked_fname, 'Left Auditory', baseline=(None, 0)) evoked.pick_types(meg='grad') evoked.pick_channels(evoked.ch_names[:122]) ch_names = ['MEG %03d' % k for k in range(1, 123)] for c in evoked.info['chs']: c['coil_type'] = FIFF.FIFFV_COIL_NM_122 evoked.rename_channels({c_old: c_new for (c_old, c_new) in zip(evoked.ch_names, ch_names)}) layout = find_layout(evoked.info) assert layout.kind.startswith('Neuromag_122') evoked.plot_topomap(times=[0.1], **fast_test) proj = Projection(active=False, desc="test", kind=1, data=dict(nrow=1, ncol=122, row_names=None, col_names=evoked.ch_names, data=np.ones(122)), explained_var=0.5) plot_projs_topomap([proj], info=evoked.info, **fast_test) plot_projs_topomap([proj], layout=layout, **fast_test) pytest.raises(RuntimeError, plot_projs_topomap, [proj], **fast_test)
def test_volume_labels_morph(tmpdir): """Test generating a source space from volume label.""" # see gh-5224 evoked = mne.read_evokeds(fname_evoked)[0].crop(0, 0) evoked.pick_channels(evoked.ch_names[:306:8]) evoked.info.normalize_proj() n_ch = len(evoked.ch_names) aseg_fname = op.join(subjects_dir, 'sample', 'mri', 'aseg.mgz') label_names = get_volume_labels_from_aseg(aseg_fname) src = setup_volume_source_space( 'sample', subjects_dir=subjects_dir, volume_label=label_names[:2], mri=aseg_fname) assert len(src) == 2 assert src.kind == 'volume' n_src = sum(s['nuse'] for s in src) sphere = make_sphere_model('auto', 'auto', evoked.info) fwd = make_forward_solution(evoked.info, fname_trans, src, sphere) assert fwd['sol']['data'].shape == (n_ch, n_src * 3) inv = make_inverse_operator(evoked.info, fwd, make_ad_hoc_cov(evoked.info), loose=1.) stc = apply_inverse(evoked, inv) assert stc.data.shape == (n_src, 1) img = stc.as_volume(src, mri_resolution=True) n_on = np.array(img.dataobj).astype(bool).sum() assert n_on == 291 # was 291 on `master` before gh-5590 img = stc.as_volume(src, mri_resolution=False) n_on = np.array(img.dataobj).astype(bool).sum() assert n_on == 44 # was 20 on `master` before gh-5590
def plot_average(filenames, save_plot=True, show_plot=False, dpi=100): ''' Plot Signal average from a list of averaged files. ''' fname = get_files_from_list(filenames) # plot averages pl.ioff() # switch off (interactive) plot visualisation factor = 1e15 for fnavg in fname: name = fnavg[0:len(fnavg) - 4] basename = os.path.splitext(os.path.basename(name))[0] print fnavg # mne.read_evokeds provides a list or a single evoked based on condition. # here we assume only one evoked is returned (requires further handling) avg = mne.read_evokeds(fnavg)[0] ymin, ymax = avg.data.min(), avg.data.max() ymin *= factor * 1.1 ymax *= factor * 1.1 fig = pl.figure(basename, figsize=(10, 8), dpi=100) pl.clf() pl.ylim([ymin, ymax]) pl.xlim([avg.times.min(), avg.times.max()]) pl.plot(avg.times, avg.data.T * factor, color='black') pl.title(basename) # save figure fnfig = os.path.splitext(fnavg)[0] + '.png' pl.savefig(fnfig, dpi=dpi) pl.ion() # switch on (interactive) plot visualisation
def evoked_ndvar(evoked, name=None, data=None, exclude='bads', vmax=None, sysname=None): """ Convert one or more mne :class:`Evoked` objects to an :class:`NDVar`. Parameters ---------- evoked : str | Evoked | list of Evoked The Evoked to convert to NDVar. Can be a string designating a file path to a evoked fiff file containing only one evoked. name : str Name of the NDVar. data : 'eeg' | 'mag' | 'grad' | None The kind of data to include. If None (default) based on ``epochs.info``. exclude : list of string | string Channels to exclude (:func:`mne.pick_types` kwarg). If 'bads' (default), exclude channels in info['bads']. If empty do not exclude any. vmax : None | scalar Set a default range for plotting. sysname : str Name of the sensor system (used to load sensor connectivity). Notes ----- If evoked objects have different channels, the intersection is used (i.e., only the channels present in all objects are retained). """ if isinstance(evoked, str): evoked = mne.read_evokeds(evoked) if isinstance(evoked, MNE_EVOKED): case_out = False evoked = (evoked,) if isinstance(evoked, (tuple, list)): case_out = True else: raise TypeError("evoked=%s" % repr(evoked)) # data type to load if data is None: data_set = {_guess_ndvar_data_type(e.info) for e in evoked} if len(data_set) > 1: raise ValueError("Different Evoked objects contain different " "data types: %s" % ', '.join(data_set)) data = data_set.pop() # MEG system kit_sys_ids = {e.info.get('kit_system_id') for e in evoked} kit_sys_ids -= {None} if len(kit_sys_ids) > 1: raise ValueError("Evoked objects from different KIT systems can not be " "combined because they have different sensor layouts") elif kit_sys_ids: sysname = KIT_NEIGHBORS.get(kit_sys_ids.pop(), sysname) if data == 'mag': info = _cs.meg_info(vmax) elif data == 'eeg': info = _cs.eeg_info(vmax) elif data == 'grad': info = _cs.meg_info(vmax, unit='T/cm') else: raise ValueError("data=%s" % repr(data)) e0 = evoked[0] if len(evoked) == 1: picks = _picks(e0.info, data, exclude) x = e0.data[picks] if case_out: x = x[None, :] first, last, sfreq = e0.first, e0.last, round(e0.info['sfreq'], 2) else: # timing: round sfreq because precision is lost by FIFF format timing_set = {(e.first, e.last, round(e.info['sfreq'], 2)) for e in evoked} if len(timing_set) == 1: first, last, sfreq = timing_set.pop() else: raise ValueError("Evoked objects have different timing " "information (first, last, sfreq): " + ', '.join(map(str, timing_set))) # find excluded channels ch_sets = [set(e.info['ch_names']) for e in evoked] all_chs = set.union(*ch_sets) common = set.intersection(*ch_sets) exclude = set.union(*list(map(set, (e.info['bads'] for e in evoked)))) exclude.update(all_chs.difference(common)) exclude = list(exclude) # get data x = [] for e in evoked: picks = _picks(e.info, data, exclude) x.append(e.data[picks]) sensor = sensor_dim(e0, picks, sysname) time = UTS.from_int(first, last, sfreq) if case_out: dims = ('case', sensor, time) else: dims = (sensor, time) return NDVar(x, dims, info=info, name=name)
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation""" # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file loose = 0.0 depth = 0.9 evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.crop(tmin=-0.05, tmax=0.2) evoked_l21 = evoked.copy() evoked_l21.crop(tmin=0.081, tmax=0.1) label = read_label(fname_label) forward = read_forward_solution(fname_fwd) forward = convert_forward_solution(forward, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked_l21.info, forward, cov, loose=loose, depth=depth, fixed=True, use_cps=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. weights_min = 0.5 # MxNE tests alpha = 70 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='prox') stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd') stc_bcd = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='bcd') 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_bcd.times, evoked_l21.times, 5) assert_allclose(stc_prox.data, stc_cd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_prox.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert_allclose(stc_cd.data, stc_bcd.data, rtol=1e-3, atol=0.0) assert stc_prox.vertices[1][0] in label.vertices assert stc_cd.vertices[1][0] in label.vertices assert stc_bcd.vertices[1][0] in label.vertices dips = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, weights=stc_dspm, weights_min=weights_min, solver='cd', return_as_dipoles=True) stc_dip = make_stc_from_dipoles(dips, forward['src']) assert isinstance(dips[0], Dipole) _check_stcs(stc_cd, stc_dip) stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, return_residual=True, solver='cd') assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert stc.vertices[1][0] in label.vertices # irMxNE tests stc = mixed_norm(evoked_l21, forward, cov, alpha, n_mxne_iter=5, loose=loose, depth=depth, maxit=300, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert stc.vertices[1][0] in label.vertices assert stc.vertices == [[63152], [79017]] # Do with TF-MxNE for test memory savings alpha = 60. # overall regularization parameter l1_ratio = 0.01 # temporal regularization proportion stc, _ = tf_mixed_norm(evoked, forward, cov, 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, alpha=alpha, l1_ratio=l1_ratio) assert_array_almost_equal(stc.times, evoked.times, 5) assert stc.vertices[1][0] in label.vertices pytest.raises(ValueError, tf_mixed_norm, evoked, forward, cov, alpha=101, l1_ratio=0.03) pytest.raises(ValueError, tf_mixed_norm, evoked, forward, cov, alpha=50., l1_ratio=1.01)
def test_arithmetic(): """Test evoked arithmetic.""" ev = read_evokeds(fname, condition=0) ev1 = EvokedArray(np.ones_like(ev.data), ev.info, ev.times[0], nave=20) ev2 = EvokedArray(-np.ones_like(ev.data), ev.info, ev.times[0], nave=10) # combine_evoked([ev1, ev2]) should be the same as ev1 + ev2: # data should be added according to their `nave` weights # nave = ev1.nave + ev2.nave ev = combine_evoked([ev1, ev2], weights='nave') assert_equal(ev.nave, ev1.nave + ev2.nave) assert_allclose(ev.data, 1. / 3. * np.ones_like(ev.data)) # with same trial counts, a bunch of things should be equivalent for weights in ('nave', 'equal', [0.5, 0.5]): ev = combine_evoked([ev1, ev1], weights=weights) assert_allclose(ev.data, ev1.data) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights=weights) assert_allclose(ev.data, 0., atol=1e-20) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev1], weights='equal') assert_allclose(ev.data, 0., atol=1e-20) assert_equal(ev.nave, 2 * ev1.nave) ev = combine_evoked([ev1, -ev2], weights='equal') expected = int(round(1. / (0.25 / ev1.nave + 0.25 / ev2.nave))) assert_equal(expected, 27) # this is reasonable assert_equal(ev.nave, expected) # default comment behavior if evoked.comment is None old_comment1 = ev1.comment old_comment2 = ev2.comment ev1.comment = None ev = combine_evoked([ev1, -ev2], weights=[1, -1]) assert_equal(ev.comment.count('unknown'), 2) assert_true('-unknown' in ev.comment) assert_true(' + ' in ev.comment) ev1.comment = old_comment1 ev2.comment = old_comment2 # equal weighting ev = combine_evoked([ev1, ev2], weights='equal') assert_allclose(ev.data, np.zeros_like(ev1.data)) # combine_evoked([ev1, ev2], weights=[1, 0]) should yield the same as ev1 ev = combine_evoked([ev1, ev2], weights=[1, 0]) assert_equal(ev.nave, ev1.nave) assert_allclose(ev.data, ev1.data) # simple subtraction (like in oddball) ev = combine_evoked([ev1, ev2], weights=[1, -1]) assert_allclose(ev.data, 2 * np.ones_like(ev1.data)) assert_raises(ValueError, combine_evoked, [ev1, ev2], weights='foo') assert_raises(ValueError, combine_evoked, [ev1, ev2], weights=[1]) # grand average evoked1, evoked2 = read_evokeds(fname, condition=[0, 1], proj=True) ch_names = evoked1.ch_names[2:] evoked1.info['bads'] = ['EEG 008'] # test interpolation evoked1.drop_channels(evoked1.ch_names[:1]) evoked2.drop_channels(evoked2.ch_names[1:2]) gave = grand_average([evoked1, evoked2]) assert_equal(gave.data.shape, [len(ch_names), evoked1.data.shape[1]]) assert_equal(ch_names, gave.ch_names) assert_equal(gave.nave, 2) assert_raises(ValueError, grand_average, [1, evoked1])
import numpy as np import matplotlib.pyplot as plt from mne.datasets import sample from mne import read_evokeds print(__doc__) path = sample.data_path() fname = path + '/MEG/sample/sample_audvis-ave.fif' # load evoked corresponding to a specific condition # from the fif file and subtract baseline condition = 'Left Auditory' evoked = read_evokeds(fname, condition=condition, baseline=(None, 0)) ############################################################################### # Basic `plot_topomap` options # ---------------------------- # # We plot evoked topographies using :func:`mne.Evoked.plot_topomap`. The first # argument, ``times`` allows to specify time instants (in seconds!) for which # topographies will be shown. We select timepoints from 50 to 150 ms with a # step of 20ms and plot magnetometer data: times = np.arange(0.05, 0.151, 0.02) evoked.plot_topomap(times, ch_type='mag', time_unit='s') ############################################################################### # If times is set to None at most 10 regularly spaced topographies will be # shown:
def grand_average_with_CI(overall_cond, component, plot=1): pairs = [13, 14, 15, 16, 17, 18] if overall_cond == 'Social': dfs_231 = [] dfs_224 = [] dfs_225 = [] for i in pairs: for root, dirs, files in os.walk(path): for f in files: if f.startswith(str(i) + '_evoked_231') and f.endswith( component + '_combined-ave.fif'): evoked_231 = mne.read_evokeds(f) dfs_231.append(evoked_231[0].to_data_frame()) if f.startswith(str(i) + '_evoked_233') and f.endswith( component + '_combined-ave.fif'): evoked_233 = mne.read_evokeds(f) dfs_231.append(evoked_233[0].to_data_frame()) if f.startswith(str(i) + '_evoked_224a') and f.endswith( component + '_combined-ave.fif'): evoked_224a = mne.read_evokeds(f) dfs_224.append(evoked_224a[0].to_data_frame()) if f.startswith(str(i) + '_evoked_224b') and f.endswith( component + '_combined-ave.fif'): evoked_224b = mne.read_evokeds(f) dfs_224.append(evoked_224b[0].to_data_frame()) if f.startswith(str(i) + '_evoked_225a') and f.endswith( component + '_combined-ave.fif'): evoked_225a = mne.read_evokeds(f) dfs_225.append(evoked_225a[0].to_data_frame()) if f.startswith(str(i) + '_evoked_225b') and f.endswith( component + '_combined-ave.fif'): evoked_225b = mne.read_evokeds(f) dfs_225.append(evoked_225b[0].to_data_frame()) df_social_erp_231 = pd.concat(dfs_231, axis=0, sort=False) l_231 = df_social_erp_231.shape l_231 = l_231[0] social_cond = ['Unshared'] * l_231 df_social_erp_231['Social Condition'] = social_cond df_social_erp_224 = pd.concat(dfs_224, axis=0, sort=False) l_224 = df_social_erp_224.shape l_224 = l_224[0] social_cond = ['Shared with feedback'] * l_224 df_social_erp_224['Social Condition'] = social_cond df_social_erp_225 = pd.concat(dfs_225, axis=0, sort=False) l_225 = df_social_erp_225.shape l_225 = l_225[0] social_cond = ['Shared without feedback'] * l_225 df_social_erp_225['Social Condition'] = social_cond full_df = pd.concat( [df_social_erp_231, df_social_erp_224, df_social_erp_225], axis=0, sort=False) full_df = full_df.rename(columns={'idx': 'Microvolt'}) full_df = full_df.rename(columns={'time': 'Time'}) if plot: plt.figure() sns.lineplot(x='Time', y='Microvolt', hue='Social Condition', data=full_df) #sns.lineplot(x = 'Time', y = 'Microvolt', data = full_df) if overall_cond == 'Emotional': dfs_happy = [] dfs_angry = [] dfs_neutral = [] for i in pairs: for root, dirs, files in os.walk(path): for f in files: if f.startswith(str(i) + '_evoked_Happy') and f.endswith( component + '_combined-ave.fif'): evoked_happy = mne.read_evokeds(f) dfs_happy.append(evoked_happy[0].to_data_frame()) if f.startswith(str(i) + '_evoked_Angry') and f.endswith( component + '_combined-ave.fif'): evoked_angry = mne.read_evokeds(f) dfs_angry.append(evoked_angry[0].to_data_frame()) if f.startswith(str(i) + '_evoked_Neutral') and f.endswith( component + '_combined-ave.fif'): evoked_neutral = mne.read_evokeds(f) dfs_neutral.append(evoked_neutral[0].to_data_frame()) df_emotional_erp_happy = pd.concat(dfs_happy, axis=0, sort=False) l_happy = df_emotional_erp_happy.shape l_happy = l_happy[0] emotional_cond = ['Happy'] * l_happy df_emotional_erp_happy['Emotion'] = emotional_cond df_emotional_erp_angry = pd.concat(dfs_angry, axis=0, sort=False) l_angry = df_emotional_erp_angry.shape l_angry = l_angry[0] emotional_cond = ['Angry'] * l_angry df_emotional_erp_angry['Emotion'] = emotional_cond df_emotional_erp_neutral = pd.concat(dfs_neutral, axis=0, sort=False) l_neutral = df_emotional_erp_neutral.shape l_neutral = l_neutral[0] emotional_cond = ['Neutral'] * l_neutral df_emotional_erp_neutral['Emotion'] = emotional_cond full_df = pd.concat([ df_emotional_erp_happy, df_emotional_erp_angry, df_emotional_erp_neutral ], axis=0, sort=False) full_df = full_df.rename(columns={'idx': 'Microvolt'}) full_df = full_df.rename(columns={'time': 'Time'}) if plot: plt.figure() sns.lineplot(x='Time', y='Microvolt', hue='Emotion', data=full_df) #sns.lineplot(x = 'Time', y = 'Microvolt', data = full_df) return full_df
def test_make_field_map_meg(): """Test interpolation of MEG field onto helmet | head.""" evoked = read_evokeds(evoked_fname, condition='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 = evoked.copy().pick_types(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(meg=True, eeg=False) evoked.info.normalize_proj() # avoid projection warnings fmd = make_field_map(evoked, 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') # now test the make_field_map on head surf for MEG evoked.pick_types(meg=True, eeg=False) evoked.info.normalize_proj() fmd = make_field_map(evoked, trans_fname, meg_surf='head', subject='sample', subjects_dir=subjects_dir) assert_true(len(fmd) == 1) assert_array_equal(fmd[0]['data'].shape, (642, 106)) # maps data onto surf assert_true(len(fmd[0]['ch_names']), 106) assert_raises(ValueError, make_field_map, evoked, meg_surf='foobar', subjects_dir=subjects_dir, trans=trans_fname)
def test_plot_alignment(tmpdir, backends_3d): """Test plotting of -trans.fif files and MEG sensor layouts.""" from mne.viz.backends.renderer import _Renderer backend_name = get_3d_backend() # generate fiducials file for testing tempdir = str(tmpdir) fiducials_path = op.join(tempdir, 'fiducials.fif') fid = [{'coord_frame': 5, 'ident': 1, 'kind': 1, 'r': [-0.08061612, -0.02908875, -0.04131077]}, {'coord_frame': 5, 'ident': 2, 'kind': 1, 'r': [0.00146763, 0.08506715, -0.03483611]}, {'coord_frame': 5, 'ident': 3, 'kind': 1, 'r': [0.08436285, -0.02850276, -0.04127743]}] write_dig(fiducials_path, fid, 5) if backend_name == 'mayavi': mlab = _import_mlab() evoked = read_evokeds(evoked_fname)[0] sample_src = read_source_spaces(src_fname) bti = read_raw_bti(pdf_fname, config_fname, hs_fname, convert=True, preload=False).info infos = dict( Neuromag=evoked.info, CTF=read_raw_ctf(ctf_fname).info, BTi=bti, KIT=read_raw_kit(sqd_fname).info, ) for system, info in infos.items(): meg = ['helmet', 'sensors'] if system == 'KIT': meg.append('ref') fig = plot_alignment(info, trans_fname, subject='sample', subjects_dir=subjects_dir, meg=meg) renderer = _Renderer(fig=fig) renderer.close() # KIT ref sensor coil def is defined if backend_name == 'mayavi': mlab.close(all=True) info = infos['Neuromag'] pytest.raises(TypeError, plot_alignment, 'foo', trans_fname, subject='sample', subjects_dir=subjects_dir) pytest.raises(OSError, plot_alignment, info, trans_fname, subject='sample', subjects_dir=subjects_dir, src='foo') pytest.raises(ValueError, plot_alignment, info, trans_fname, subject='fsaverage', subjects_dir=subjects_dir, src=sample_src) sample_src.plot(subjects_dir=subjects_dir, head=True, skull=True, brain='white') if backend_name == 'mayavi': mlab.close(all=True) # no-head version if backend_name == 'mayavi': mlab.close(all=True) # all coord frames pytest.raises(ValueError, plot_alignment, info) plot_alignment(info, surfaces=[]) for coord_frame in ('meg', 'head', 'mri'): fig = plot_alignment(info, meg=['helmet', 'sensors'], dig=True, coord_frame=coord_frame, trans=trans_fname, subject='sample', mri_fiducials=fiducials_path, subjects_dir=subjects_dir, src=src_fname) renderer = _Renderer(fig=fig) renderer.close() # EEG only with strange options evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True) evoked_eeg_ecog_seeg.info['projs'] = [] # "remove" avg proj evoked_eeg_ecog_seeg.set_channel_types({'EEG 001': 'ecog', 'EEG 002': 'seeg'}) with pytest.warns(RuntimeWarning, match='Cannot plot MEG'): plot_alignment(evoked_eeg_ecog_seeg.info, subject='sample', trans=trans_fname, subjects_dir=subjects_dir, surfaces=['white', 'outer_skin', 'outer_skull'], meg=['helmet', 'sensors'], eeg=['original', 'projected'], ecog=True, seeg=True) if backend_name == 'mayavi': mlab.close(all=True) sphere = make_sphere_model(info=evoked.info, r0='auto', head_radius='auto') bem_sol = read_bem_solution(op.join(subjects_dir, 'sample', 'bem', 'sample-1280-1280-1280-bem-sol.fif')) bem_surfs = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem', 'sample-1280-1280-1280-bem.fif')) sample_src[0]['coord_frame'] = 4 # hack for coverage plot_alignment(info, subject='sample', eeg='projected', meg='helmet', bem=sphere, dig=True, surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin']) plot_alignment(info, trans_fname, subject='sample', meg='helmet', subjects_dir=subjects_dir, eeg='projected', bem=sphere, surfaces=['head', 'brain'], src=sample_src) assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI for surf in bem_sol['surfs']) plot_alignment(info, trans_fname, subject='sample', meg=[], subjects_dir=subjects_dir, bem=bem_sol, eeg=True, surfaces=['head', 'inflated', 'outer_skull', 'inner_skull']) assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI for surf in bem_sol['surfs']) plot_alignment(info, trans_fname, subject='sample', meg=True, subjects_dir=subjects_dir, surfaces=['head', 'inner_skull'], bem=bem_surfs) sphere = make_sphere_model('auto', 'auto', evoked.info) src = setup_volume_source_space(sphere=sphere) plot_alignment(info, eeg='projected', meg='helmet', bem=sphere, src=src, dig=True, surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin']) sphere = make_sphere_model('auto', None, evoked.info) # one layer # no info is permitted fig = plot_alignment(trans=trans_fname, subject='sample', meg=False, coord_frame='mri', subjects_dir=subjects_dir, surfaces=['brain'], bem=sphere, show_axes=True) if backend_name == 'mayavi': import mayavi # noqa: F401 analysis:ignore assert isinstance(fig, mayavi.core.scene.Scene) # 3D coil with no defined draw (ConvexHull) info_cube = pick_info(info, [0]) info['dig'] = None info_cube['chs'][0]['coil_type'] = 9999 with pytest.raises(RuntimeError, match='coil definition not found'): plot_alignment(info_cube, meg='sensors', surfaces=()) coil_def_fname = op.join(tempdir, 'temp') with open(coil_def_fname, 'w') as fid: fid.write(coil_3d) with use_coil_def(coil_def_fname): plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True) # one layer bem with skull surfaces: pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['brain', 'head', 'inner_skull'], bem=sphere) # wrong eeg value: pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, eeg='foo') # wrong meg value: pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, meg='bar') # multiple brain surfaces: pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['white', 'pial']) pytest.raises(TypeError, plot_alignment, info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=[1]) pytest.raises(ValueError, plot_alignment, info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['foo']) if backend_name == 'mayavi': mlab.close(all=True)
from mne.minimum_norm import make_inverse_operator, apply_inverse from mne.viz import plot_sparse_source_estimates print(__doc__) 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-shrunk-cov.fif' subjects_dir = data_path + '/subjects' # Read noise covariance matrix cov = mne.read_cov(cov_fname) # Handling average file condition = 'Left Auditory' evoked = mne.read_evokeds(ave_fname, condition=condition, baseline=(None, 0)) evoked.crop(tmin=0, tmax=0.3) # Handling forward solution forward = mne.read_forward_solution(fwd_fname, surf_ori=True) ylim = dict(eeg=[-10, 10], grad=[-400, 400], mag=[-600, 600]) evoked.plot(ylim=ylim, proj=True) ############################################################################### # Run solver alpha = 50 # regularization parameter between 0 and 100 (100 is high) loose, depth = 0.2, 0.9 # loose orientation & depth weighting n_mxne_iter = 10 # if > 1 use L0.5/L2 reweighted mixed norm solver # if n_mxne_iter > 1 dSPM weighting can be avoided. # Compute dSPM solution to be used as weights in MxNE
def _real_vec_stc(): inv = read_inverse_operator(fname_inv_surf) evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0].crop(0, 0.01) return apply_inverse(evoked, inv, pick_ori='vector')
from mne.datasets import sample from mne import read_evokeds from mne.minimum_norm import apply_inverse, read_inverse_operator print(__doc__) data_path = sample.data_path() fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' snr = 3.0 lambda2 = 1.0 / snr**2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Load data evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) inverse_operator = read_inverse_operator(fname_inv) src = inverse_operator['src'] # Compute inverse solution stc = apply_inverse(evoked, inverse_operator, lambda2, method) stc.crop(0.0, 0.2) # Export result as a 4D nifti object img = stc.as_volume(src, mri_resolution=False) # set True for full MRI resolution # Save it as a nifti file # nib.save(img, 'mne_%s_inverse.nii.gz' % method) t1_fname = data_path + '/subjects/sample/mri/T1.mgz'
def test_time_as_index(): """Test time as index.""" evoked = read_evokeds(fname, condition=0).crop(-.1, .1) assert_array_equal(evoked.time_as_index([-.1, .1], use_rounding=True), [0, len(evoked.times) - 1])
def test_make_forward_dipole(): """Test forward-projecting dipoles.""" rng = np.random.RandomState(0) evoked = read_evokeds(fname_evo)[0] cov = read_cov(fname_cov) dip_c = read_dipole(fname_dip) # Only use magnetometers for speed! picks = pick_types(evoked.info, meg='mag', eeg=False) evoked.pick_channels([evoked.ch_names[p] for p in picks]) info = evoked.info # Make new Dipole object with n_test_dipoles picked from the dipoles # in the test dataset. n_test_dipoles = 3 # minimum 3 needed to get uneven sampling in time dipsel = np.sort(rng.permutation(np.arange(len(dip_c)))[:n_test_dipoles]) dip_test = Dipole(times=dip_c.times[dipsel], pos=dip_c.pos[dipsel], amplitude=dip_c.amplitude[dipsel], ori=dip_c.ori[dipsel], gof=dip_c.gof[dipsel]) sphere = make_sphere_model(head_radius=0.1) # Warning emitted due to uneven sampling in time with warnings.catch_warnings(record=True) as w: fwd, stc = make_forward_dipole(dip_test, sphere, info, trans=fname_trans) assert (issubclass(w[-1].category, RuntimeWarning)) # stc is list of VolSourceEstimate's assert isinstance(stc, list) for n_dip in range(n_test_dipoles): assert isinstance(stc[n_dip], VolSourceEstimate) # Now simulate evoked responses for each of the test dipoles, # and fit dipoles to them (sphere model, MEG and EEG) times, pos, amplitude, ori, gof = [], [], [], [], [] nave = 100 # add a tiny amount of noise to the simulated evokeds for s in stc: evo_test = simulate_evoked(fwd, s, info, cov, nave=nave, random_state=rng) # evo_test.add_proj(make_eeg_average_ref_proj(evo_test.info)) dfit, resid = fit_dipole(evo_test, cov, sphere, None) times += dfit.times.tolist() pos += dfit.pos.tolist() amplitude += dfit.amplitude.tolist() ori += dfit.ori.tolist() gof += dfit.gof.tolist() # Create a new Dipole object with the dipole fits dip_fit = Dipole(times, pos, amplitude, ori, gof) # check that true (test) dipoles and fits are "close" # cf. mne/tests/test_dipole.py diff = dip_test.pos - dip_fit.pos corr = np.corrcoef(dip_test.pos.ravel(), dip_fit.pos.ravel())[0, 1] dist = np.sqrt(np.mean(np.sum(diff * diff, axis=1))) gc_dist = 180 / np.pi * \ np.mean(np.arccos(np.sum(dip_test.ori * dip_fit.ori, axis=1))) amp_err = np.sqrt(np.mean((dip_test.amplitude - dip_fit.amplitude) ** 2)) # Make sure each coordinate is close to reference # NB tolerance should be set relative to snr of simulated evoked! assert_allclose(dip_fit.pos, dip_test.pos, rtol=0, atol=1e-2, err_msg='position mismatch') assert dist < 1e-2 # within 1 cm assert corr > 1 - 1e-2 assert gc_dist < 20 # less than 20 degrees assert amp_err < 10e-9 # within 10 nAm # Make sure rejection works with BEM: one dipole at z=1m # NB _make_forward.py:_prepare_for_forward will raise a RuntimeError # if no points are left after min_dist exclusions, hence 2 dips here! dip_outside = Dipole(times=[0., 0.001], pos=[[0., 0., 1.0], [0., 0., 0.040]], amplitude=[100e-9, 100e-9], ori=[[1., 0., 0.], [1., 0., 0.]], gof=1) pytest.raises(ValueError, make_forward_dipole, dip_outside, fname_bem, info, fname_trans) # if we get this far, can safely assume the code works with BEMs too # -> use sphere again below for speed # Now make an evenly sampled set of dipoles, some simultaneous, # should return a VolSourceEstimate regardless times = [0., 0., 0., 0.001, 0.001, 0.002] pos = np.random.rand(6, 3) * 0.020 + \ np.array([0., 0., 0.040])[np.newaxis, :] amplitude = np.random.rand(6) * 100e-9 ori = np.eye(6, 3) + np.eye(6, 3, -3) gof = np.arange(len(times)) / len(times) # arbitrary dip_even_samp = Dipole(times, pos, amplitude, ori, gof) fwd, stc = make_forward_dipole(dip_even_samp, sphere, info, trans=fname_trans) assert isinstance(stc, VolSourceEstimate) assert_allclose(stc.times, np.arange(0., 0.003, 0.001))
# Define the Subject ID and paths deriv_path = deriv_dir / sub if int(sub[-3:]) < 200: age = 'young' else: age = 'older' print(sub, age) # Move and copy epochs (reference average) epochs_file = f'{sub}_task-{task}_ref-avg_desc-cleaned_epo.fif.gz' epochs = read_epochs(deriv_path / epochs_file, verbose=False) epochs.save(out_epochs / epochs_file, overwrite=True) # Move and copy epochs (reference average, no low-pass filter) evoked_file = f'{sub}_task-{task}_ref-avg_lpf-none_ave.fif.gz' evokeds = read_evokeds(deriv_path / evoked_file, baseline=(None, 0), verbose=False) write_evokeds(out_erps / evoked_file, evokeds) # Add individual evokeds into dictionary conds = [e.comment for e in evokeds if 'abin' not in e.comment] for i, c in enumerate(conds): if c not in young_erps: young_erps[c] = [] older_erps[c] = [] all_erps[c] = [] all_erps[c].append(evokeds[i]) if age == 'young': young_erps[c].append(evokeds[i]) else: older_erps[c].append(evokeds[i])
self._app_layout = app def display(self): IPython.display.display(self._app_layout) if __name__ == '__main__': import mne data_path = pathlib.Path('data') fwd_path = data_path / 'fwd' subjects_dir = data_path / 'subjects' subject = 'sample' evoked_fname = data_path / 'sample-ave.fif' evoked = mne.read_evokeds(evoked_fname, verbose='warning')[0] evoked.pick_types(meg=True, eeg=True) info = evoked.info info['projs'] = [] info['bads'] = [] del evoked_fname t1_fname = str(subjects_dir / subject / 'mri' / 'T1.mgz') t1_img = nib.load(t1_fname) del t1_fname trans_fname = data_path / 'sample-trans.fif' head_to_mri_t = mne.read_trans(trans_fname) app = App(evoked=evoked,
def test_render_add_sections(): """Test adding figures/images to section. """ from PIL import Image tempdir = _TempDir() import matplotlib.pyplot as plt report = Report(subjects_dir=subjects_dir) # Check add_figs_to_section functionality fig = plt.plot([1, 2], [1, 2])[0].figure report.add_figs_to_section( figs=fig, # test non-list input captions=['evoked response'], scale=1.2, image_format='svg') assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig], captions='H') assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=['foo'], scale=0, image_format='svg') assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=['foo'], scale=1e-10, image_format='svg') # need to recreate because calls above change size fig = plt.plot([1, 2], [1, 2])[0].figure # Check add_images_to_section with png and then gif img_fname = op.join(tempdir, 'testimage.png') fig.savefig(img_fname) report.add_images_to_section(fnames=[img_fname], captions=['evoked response']) im = Image.open(img_fname) op.join(tempdir, 'testimage.gif') im.save(img_fname) # matplotlib does not support gif report.add_images_to_section(fnames=[img_fname], captions=['evoked response']) assert_raises(ValueError, report.add_images_to_section, fnames=[img_fname, img_fname], captions='H') assert_raises(ValueError, report.add_images_to_section, fnames=['foobar.xxx'], captions='H') evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=(-0.2, 0.0)) fig = plot_trans(evoked.info, trans_fname, subject='sample', subjects_dir=subjects_dir) report.add_figs_to_section( figs=fig, # test non-list input captions='random image', scale=1.2) assert_true(repr(report))
src2 = mne.setup_volume_source_space(subj, mri=freesurfer_dir + '/mri/aseg.mgz', volume_label='Right-Cerebral-Cortex', bem=freesurfer_dir + '/bem/%s-5120-bem.fif' % subj) src3 = mne.setup_volume_source_space(subj, mri=freesurfer_dir + '/mri/aseg.mgz', volume_label='Left-Cerebellum-Cortex', bem=freesurfer_dir + '/bem/%s-5120-bem.fif' % subj) src4 = mne.setup_volume_source_space(subj, mri=freesurfer_dir + '/mri/aseg.mgz', volume_label='Right-Cerebellum-Cortex', bem=freesurfer_dir + '/bem/%s-5120-bem.fif' % subj) srcs = src1 + src2 + src3 + src4 evoked = mne.read_evokeds(evoked_fname) fwd_fname = '%s/%s_task-vol-5-fwd.fif' % (fwd_dir, subj) trans_fname = '%s/%s-trans.fif' % (fwd_dir, subj) fwd = mne.make_forward_solution(evoked[0].info, trans_fname, srcs, freesurfer_dir + '/bem/%s-5120-bem-sol.fif' % subj, fname=fwd_fname, meg=True, eeg=False, n_jobs=1)
if not op.isfile(file_out): print(' Doing averaging...') evokeds = list() for si, subj in enumerate(subjects): print(' %s' % subj) evoked_file = op.join(data_dir, 'bad_%s' % subj, 'inverse', '%s_%d-sss_eq_bad_%s-ave.fif' % (analysis, lpf, subj)) evoked, ch_names = read_in_evoked(evoked_file) evokeds.append(evoked) # do grand averaging grandavr = grand_average(evokeds) grandavr.save(file_out) else: print('Reading...%s' % op.basename(file_out)) grandavr = read_evokeds(file_out)[0] # peak ERF latency bn 100-550ms ch, lat = grandavr.get_peak(ch_type='mag', tmin=.15, tmax=.55) if cond in ['all', 'deviant']: print(' Peak latency for %s in %s group:\n' ' %s at %0.3fms' % (cond, group, ch, lat)) # plot ERF topography at peak latency and 100ms before timing = [lat - .1, lat] hs = grandavr.plot_joint(title=nm + ' ' + cond, times=timing, ts_args=params.ts_args, topomap_args=params.topomap_args) for h, ch_type in zip(hs, ['grad', 'mag']): fig_out = op.join(fig_dir, '%s_%s_%s_%d_%s_grd-ave.eps' % (analysis, cond, nm.replace(' ', ''), lpf, ch_type)) h.savefig(fig_out, dpi=240, format='eps')
else: glmnum = 5 data = dict() data_t = dict() for i in contrasts: data[i] = [] data_t[i] = [] for i in subs: print('\n\ngetting subject ' + str(i) + '\n\n') sub = dict(loc='workstation', id=i) param = get_subject_info_wmConfidence(sub) #_baselined for name in contrasts: data[name].append( mne.read_evokeds(fname=op.join( param['path'], 'glms', 'feedback', 'epochs_glm' + str(glmnum), 'wmc_' + param['subid'] + '_feedbacklocked_tl_' + name + '_betas-ave.fif'))[0]) data_t[name].append( mne.read_evokeds(fname=op.join( param['path'], 'glms', 'feedback', 'epochs_glm' + str(glmnum), 'wmc_' + param['subid'] + '_feedbacklocked_tl_' + name + '_tstats-ave.fif'))[0]) #drop right mastoid from literally everything here lol its not useful anymore for cope in data.keys(): for i in range(subs.size): data[cope][i] = data[cope][i].drop_channels( ['RM']) #.set_eeg_reference(ref_channels='average') data_t[cope][i] = data_t[cope][i].drop_channels( ['RM']) #.set_eeg_reference(ref_channels='average') #%%
def test_logging(): """Test logging (to file).""" assert_raises(ValueError, set_log_level, 'foo') tempdir = _TempDir() test_name = op.join(tempdir, 'test.log') with open(fname_log, 'r') as old_log_file: # [:-1] used to strip an extra "No baseline correction applied" old_lines = clean_lines(old_log_file.readlines()) old_lines.pop(-1) with open(fname_log_2, 'r') as old_log_file_2: old_lines_2 = clean_lines(old_log_file_2.readlines()) old_lines_2.pop(14) old_lines_2.pop(-1) if op.isfile(test_name): os.remove(test_name) # test it one way (printing default off) set_log_file(test_name) set_log_level('WARNING') # should NOT print evoked = read_evokeds(fname_evoked, condition=1) with open(test_name) as fid: assert_true(fid.readlines() == []) # should NOT print evoked = read_evokeds(fname_evoked, condition=1, verbose=False) with open(test_name) as fid: assert_true(fid.readlines() == []) # should NOT print evoked = read_evokeds(fname_evoked, condition=1, verbose='WARNING') with open(test_name) as fid: assert_true(fid.readlines() == []) # SHOULD print evoked = read_evokeds(fname_evoked, condition=1, verbose=True) with open(test_name, 'r') as new_log_file: new_lines = clean_lines(new_log_file.readlines()) assert_equal(new_lines, old_lines) set_log_file(None) # Need to do this to close the old file os.remove(test_name) # now go the other way (printing default on) set_log_file(test_name) set_log_level('INFO') # should NOT print evoked = read_evokeds(fname_evoked, condition=1, verbose='WARNING') with open(test_name) as fid: assert_true(fid.readlines() == []) # should NOT print evoked = read_evokeds(fname_evoked, condition=1, verbose=False) with open(test_name) as fid: assert_true(fid.readlines() == []) # SHOULD print evoked = read_evokeds(fname_evoked, condition=1) with open(test_name, 'r') as new_log_file: new_lines = clean_lines(new_log_file.readlines()) assert_equal(new_lines, old_lines) # check to make sure appending works (and as default, raises a warning) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') set_log_file(test_name, overwrite=False) assert_equal(len(w), 0) set_log_file(test_name) assert_equal(len(w), 1) assert_true('test_utils.py' in w[0].filename) evoked = read_evokeds(fname_evoked, condition=1) with open(test_name, 'r') as new_log_file: new_lines = clean_lines(new_log_file.readlines()) assert_equal(new_lines, old_lines_2) # make sure overwriting works set_log_file(test_name, overwrite=True) # this line needs to be called to actually do some logging evoked = read_evokeds(fname_evoked, condition=1) del evoked with open(test_name, 'r') as new_log_file: new_lines = clean_lines(new_log_file.readlines()) assert_equal(new_lines, old_lines)
def test_io_evoked(): """Test IO for evoked data (fif + gz) with integer and str args.""" tempdir = _TempDir() ave = read_evokeds(fname, 0) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), ave) ave2 = read_evokeds(op.join(tempdir, 'evoked-ave.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) assert_true(repr(ave)) # 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 read_evokeds and write_evokeds aves1 = read_evokeds(fname)[1::2] aves2 = read_evokeds(fname, [1, 3]) aves3 = read_evokeds(fname, ['Right Auditory', 'Right visual']) write_evokeds(op.join(tempdir, 'evoked-ave.fif'), aves1) aves4 = read_evokeds(op.join(tempdir, 'evoked-ave.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) # test warnings on bad filenames fname2 = op.join(tempdir, 'test-bad-name.fif') with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') write_evokeds(fname2, ave) read_evokeds(fname2) assert_naming(w, 'test_evoked.py', 2) # constructor assert_raises(TypeError, Evoked, fname) # MaxShield fname_ms = op.join(tempdir, 'test-ave.fif') assert_true(ave.info['maxshield'] is False) ave.info['maxshield'] = True ave.save(fname_ms) assert_raises(ValueError, read_evokeds, fname_ms) with warnings.catch_warnings(record=True) as w: aves = read_evokeds(fname_ms, allow_maxshield=True) assert_true(all('Elekta' in str(ww.message) for ww in w)) assert_true(all(ave.info['maxshield'] is True for ave in aves)) with warnings.catch_warnings(record=True) as w: aves = read_evokeds(fname_ms, allow_maxshield='yes') assert_equal(len(w), 0) assert_true(all(ave.info['maxshield'] is True for ave in aves))
import mne from os import path as op from mne_sandbox.preprocessing import dss from mne.datasets import sample from matplotlib import pyplot as plt # file paths data_path = sample.data_path() raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') events_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-eve.fif') evokeds_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif') # import sample data raw = mne.io.Raw(raw_fname, preload=True) events = mne.read_events(events_fname) evokeds = mne.read_evokeds(evokeds_fname) # pick channels, filter, epoch picks = mne.pick_types(raw.info, meg=False, eeg=True) raw.filter(0.3, 30, method='iir', picks=picks) epochs = mne.Epochs(raw, events, event_id=1, preload=True, picks=picks) evoked = evokeds[0] # left auditory only evoked = evoked.pick_types(meg=False, eeg=True) # perform DSS dss_mat, dss_data = dss(epochs, data_thresh=1e-9, bias_thresh=1e-9) # plot fig, axs = plt.subplots(2, 1, figsize=(7, 7), sharex=True) plotdata = [evoked.data.T, dss_data[:, 0].T] linewidths = (1, 0.6) titles = ('evoked data (EEG only)',
def test_dipole_fitting(): """Test dipole fitting.""" amp = 100e-9 tempdir = _TempDir() rng = np.random.RandomState(0) fname_dtemp = op.join(tempdir, 'test.dip') fname_sim = op.join(tempdir, 'test-ave.fif') fwd = convert_forward_solution(read_forward_solution(fname_fwd), surf_ori=False, force_fixed=True, use_cps=True) evoked = read_evokeds(fname_evo)[0] cov = read_cov(fname_cov) n_per_hemi = 5 vertices = [ np.sort(rng.permutation(s['vertno'])[:n_per_hemi]) for s in fwd['src'] ] nv = sum(len(v) for v in vertices) stc = SourceEstimate(amp * np.eye(nv), vertices, 0, 0.001) evoked = simulate_evoked(fwd, stc, evoked.info, cov, nave=evoked.nave, random_state=rng) # For speed, let's use a subset of channels (strange but works) picks = np.sort( np.concatenate([ pick_types(evoked.info, meg=True, eeg=False)[::2], pick_types(evoked.info, meg=False, eeg=True)[::2] ])) evoked.pick_channels([evoked.ch_names[p] for p in picks]) evoked.add_proj(make_eeg_average_ref_proj(evoked.info)) write_evokeds(fname_sim, evoked) # Run MNE-C version run_subprocess([ 'mne_dipole_fit', '--meas', fname_sim, '--meg', '--eeg', '--noise', fname_cov, '--dip', fname_dtemp, '--mri', fname_fwd, '--reg', '0', '--tmin', '0', ]) dip_c = read_dipole(fname_dtemp) # Run mne-python version sphere = make_sphere_model(head_radius=0.1) with warnings.catch_warnings(record=True): dip, residuals = fit_dipole(evoked, cov, sphere, fname_fwd) # Sanity check: do our residuals have less power than orig data? data_rms = np.sqrt(np.sum(evoked.data**2, axis=0)) resi_rms = np.sqrt(np.sum(residuals**2, axis=0)) assert_true((data_rms > resi_rms * 0.95).all(), msg='%s (factor: %s)' % ((data_rms / resi_rms).min(), 0.95)) # Compare to original points transform_surface_to(fwd['src'][0], 'head', fwd['mri_head_t']) transform_surface_to(fwd['src'][1], 'head', fwd['mri_head_t']) assert_equal(fwd['src'][0]['coord_frame'], FIFF.FIFFV_COORD_HEAD) src_rr = np.concatenate([s['rr'][v] for s, v in zip(fwd['src'], vertices)], axis=0) src_nn = np.concatenate([s['nn'][v] for s, v in zip(fwd['src'], vertices)], axis=0) # MNE-C skips the last "time" point :( out = dip.crop(dip_c.times[0], dip_c.times[-1]) assert_true(dip is out) src_rr, src_nn = src_rr[:-1], src_nn[:-1] # check that we did about as well corrs, dists, gc_dists, amp_errs, gofs = [], [], [], [], [] for d in (dip_c, dip): new = d.pos diffs = new - src_rr corrs += [np.corrcoef(src_rr.ravel(), new.ravel())[0, 1]] dists += [np.sqrt(np.mean(np.sum(diffs * diffs, axis=1)))] gc_dists += [ 180 / np.pi * np.mean(np.arccos(np.sum(src_nn * d.ori, axis=1))) ] amp_errs += [np.sqrt(np.mean((amp - d.amplitude)**2))] gofs += [np.mean(d.gof)] factor = 0.8 assert_true(dists[0] / factor >= dists[1], 'dists: %s' % dists) assert_true(corrs[0] * factor <= corrs[1], 'corrs: %s' % corrs) assert_true(gc_dists[0] / factor >= gc_dists[1] * 0.8, 'gc-dists (ori): %s' % gc_dists) assert_true(amp_errs[0] / factor >= amp_errs[1], 'amplitude errors: %s' % amp_errs) # This one is weird because our cov/sim/picking is weird assert_true(gofs[0] * factor <= gofs[1] * 2, 'gof: %s' % gofs)
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable, ImageGrid import mne ############################################################################### # Suppose we want a figure with an evoked plot on top, and the brain activation # below, with the brain subplot slightly bigger than the evoked plot. Let's # start by loading some :ref:`example data <sample-dataset>`. data_path = mne.datasets.sample.data_path() subjects_dir = op.join(data_path, 'subjects') fname_stc = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-eeg-lh.stc') fname_evoked = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif') evoked = mne.read_evokeds(fname_evoked, 'Left Auditory') evoked.pick_types(meg='grad').apply_baseline((None, 0.)) max_t = evoked.get_peak()[1] stc = mne.read_source_estimate(fname_stc) ############################################################################### # During interactive plotting, we might see figures like this: evoked.plot() stc.plot(views='lat', hemi='split', size=(800, 400), subject='sample', subjects_dir=subjects_dir,
def test_plot_snr(): """Test plotting SNR estimate.""" inv = read_inverse_operator(inv_fname) evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0] plot_snr_estimate(evoked, inv)
def test_plot_alignment_basic(tmp_path, renderer, mixed_fwd_cov_evoked): """Test plotting of -trans.fif files and MEG sensor layouts.""" # generate fiducials file for testing tempdir = str(tmp_path) fiducials_path = op.join(tempdir, 'fiducials.fif') fid = [{ 'coord_frame': 5, 'ident': 1, 'kind': 1, 'r': [-0.08061612, -0.02908875, -0.04131077] }, { 'coord_frame': 5, 'ident': 2, 'kind': 1, 'r': [0.00146763, 0.08506715, -0.03483611] }, { 'coord_frame': 5, 'ident': 3, 'kind': 1, 'r': [0.08436285, -0.02850276, -0.04127743] }] write_dig(fiducials_path, fid, 5) evoked = read_evokeds(evoked_fname)[0] info = evoked.info sample_src = read_source_spaces(src_fname) pytest.raises(TypeError, plot_alignment, 'foo', trans_fname, subject='sample', subjects_dir=subjects_dir) pytest.raises(OSError, plot_alignment, info, trans_fname, subject='sample', subjects_dir=subjects_dir, src='foo') pytest.raises(ValueError, plot_alignment, info, trans_fname, subject='fsaverage', subjects_dir=subjects_dir, src=sample_src) sample_src.plot(subjects_dir=subjects_dir, head=True, skull=True, brain='white') # mixed source space mixed_src = mixed_fwd_cov_evoked[0]['src'] assert mixed_src.kind == 'mixed' plot_alignment(info, meg=['helmet', 'sensors'], dig=True, coord_frame='head', trans=Path(trans_fname), subject='sample', mri_fiducials=fiducials_path, subjects_dir=subjects_dir, src=mixed_src) renderer.backend._close_all() # no-head version renderer.backend._close_all() # trans required with pytest.raises(ValueError, match='transformation matrix is required'): plot_alignment(info, trans=None, src=src_fname) with pytest.raises(ValueError, match='transformation matrix is required'): plot_alignment(info, trans=None, mri_fiducials=True) with pytest.raises(ValueError, match='transformation matrix is required'): plot_alignment(info, trans=None, surfaces=['brain']) # all coord frames plot_alignment(info) # works: surfaces='auto' default for coord_frame in ('meg', 'head', 'mri'): plot_alignment(info, meg=['helmet', 'sensors'], dig=True, coord_frame=coord_frame, trans=Path(trans_fname), subject='sample', src=src_fname, mri_fiducials=fiducials_path, subjects_dir=subjects_dir) renderer.backend._close_all() # EEG only with strange options evoked_eeg_ecog_seeg = evoked.copy().pick_types(meg=False, eeg=True) with evoked_eeg_ecog_seeg.info._unlock(): evoked_eeg_ecog_seeg.info['projs'] = [] # "remove" avg proj evoked_eeg_ecog_seeg.set_channel_types({ 'EEG 001': 'ecog', 'EEG 002': 'seeg' }) with catch_logging() as log: plot_alignment(evoked_eeg_ecog_seeg.info, subject='sample', trans=trans_fname, subjects_dir=subjects_dir, surfaces=['white', 'outer_skin', 'outer_skull'], meg=['helmet', 'sensors'], eeg=['original', 'projected'], ecog=True, seeg=True, verbose=True) log = log.getvalue() assert 'ecog: 1' in log assert 'seeg: 1' in log renderer.backend._close_all() sphere = make_sphere_model(info=info, r0='auto', head_radius='auto') bem_sol = read_bem_solution( op.join(subjects_dir, 'sample', 'bem', 'sample-1280-1280-1280-bem-sol.fif')) bem_surfs = read_bem_surfaces( op.join(subjects_dir, 'sample', 'bem', 'sample-1280-1280-1280-bem.fif')) sample_src[0]['coord_frame'] = 4 # hack for coverage plot_alignment( info, trans_fname, subject='sample', eeg='projected', meg='helmet', bem=sphere, dig=True, surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin']) plot_alignment(info, subject='sample', meg='helmet', subjects_dir=subjects_dir, eeg='projected', bem=sphere, surfaces=['head', 'brain'], src=sample_src) # no trans okay, no mri surfaces plot_alignment(info, bem=sphere, surfaces=['brain']) with pytest.raises(ValueError, match='A head surface is required'): plot_alignment(info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, eeg='projected', surfaces=[]) with pytest.raises(RuntimeError, match='No brain surface found'): plot_alignment(info, trans=trans_fname, subject='foo', subjects_dir=subjects_dir, surfaces=['brain']) assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI for surf in bem_sol['surfs']) plot_alignment(info, trans_fname, subject='sample', meg=[], subjects_dir=subjects_dir, bem=bem_sol, eeg=True, surfaces=['head', 'inflated', 'outer_skull', 'inner_skull']) assert all(surf['coord_frame'] == FIFF.FIFFV_COORD_MRI for surf in bem_sol['surfs']) plot_alignment(info, trans_fname, subject='sample', meg=True, subjects_dir=subjects_dir, surfaces=['head', 'inner_skull'], bem=bem_surfs) # single-layer BEM can still plot head surface assert bem_surfs[-1]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN bem_sol_homog = read_bem_solution( op.join(subjects_dir, 'sample', 'bem', 'sample-1280-bem-sol.fif')) for use_bem in (bem_surfs[-1:], bem_sol_homog): with catch_logging() as log: plot_alignment(info, trans_fname, subject='sample', meg=True, subjects_dir=subjects_dir, surfaces=['head', 'inner_skull'], bem=use_bem, verbose=True) log = log.getvalue() assert 'not find the surface for head in the provided BEM model' in log # sphere model sphere = make_sphere_model('auto', 'auto', info) src = setup_volume_source_space(sphere=sphere) plot_alignment( info, trans=Transform('head', 'mri'), eeg='projected', meg='helmet', bem=sphere, src=src, dig=True, surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin']) sphere = make_sphere_model('auto', None, info) # one layer # if you ask for a brain surface with a 1-layer sphere model it's an error with pytest.raises(RuntimeError, match='Sphere model does not have'): plot_alignment(trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['brain'], bem=sphere) # but you can ask for a specific brain surface, and # no info is permitted plot_alignment(trans=trans_fname, subject='sample', meg=False, coord_frame='mri', subjects_dir=subjects_dir, surfaces=['white'], bem=sphere, show_axes=True) renderer.backend._close_all() # TODO: We need to make this class public and document it properly # assert isinstance(fig, some_public_class) # 3D coil with no defined draw (ConvexHull) info_cube = pick_info(info, np.arange(6)) with info._unlock(): info['dig'] = None info_cube['chs'][0]['coil_type'] = 9999 info_cube['chs'][1]['coil_type'] = 9998 with pytest.raises(RuntimeError, match='coil definition not found'): plot_alignment(info_cube, meg='sensors', surfaces=()) coil_def_fname = op.join(tempdir, 'temp') with open(coil_def_fname, 'w') as fid: fid.write(coil_3d) # make sure our other OPMs can be plotted, too for ii, kind in enumerate( ('QUSPIN_ZFOPM_MAG', 'QUSPIN_ZFOPM_MAG2', 'FIELDLINE_OPM_MAG_GEN1', 'KERNEL_OPM_MAG_GEN1'), 2): info_cube['chs'][ii]['coil_type'] = getattr(FIFF, f'FIFFV_COIL_{kind}') with use_coil_def(coil_def_fname): with catch_logging() as log: plot_alignment(info_cube, meg='sensors', surfaces=(), dig=True, verbose='debug') log = log.getvalue() assert 'planar geometry' in log # one layer bem with skull surfaces: with pytest.raises(RuntimeError, match='Sphere model does not.*boundary'): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['brain', 'head', 'inner_skull'], bem=sphere) # wrong eeg value: with pytest.raises(ValueError, match='Invalid value for the .eeg'): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, eeg='foo') # wrong meg value: with pytest.raises(ValueError, match='Invalid value for the .meg'): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, meg='bar') # multiple brain surfaces: with pytest.raises(ValueError, match='Only one brain surface can be plot'): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['white', 'pial']) with pytest.raises(TypeError, match='surfaces.*must be'): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=[1]) with pytest.raises(ValueError, match='Unknown surface type'): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=['foo']) with pytest.raises(TypeError, match="must be an instance of "): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=dict(brain='super clear')) with pytest.raises(ValueError, match="must be between 0 and 1"): plot_alignment(info=info, trans=trans_fname, subject='sample', subjects_dir=subjects_dir, surfaces=dict(brain=42)) fwd_fname = op.join(data_dir, 'MEG', 'sample', 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') fwd = read_forward_solution(fwd_fname) plot_alignment(subject='sample', subjects_dir=subjects_dir, trans=trans_fname, fwd=fwd, surfaces='white', coord_frame='head') fwd = convert_forward_solution(fwd, force_fixed=True) plot_alignment(subject='sample', subjects_dir=subjects_dir, trans=trans_fname, fwd=fwd, surfaces='white', coord_frame='head') fwd['coord_frame'] = FIFF.FIFFV_COORD_MRI # check required to get to MRI with pytest.raises(ValueError, match='transformation matrix is required'): plot_alignment(info, trans=None, fwd=fwd) # surfaces as dict plot_alignment(subject='sample', coord_frame='head', trans=trans_fname, subjects_dir=subjects_dir, surfaces={ 'white': 0.4, 'outer_skull': 0.6, 'head': None })
report.parse_folder(path, pattern=pattern, render_bem=False) report.save('report_cov.html', overwrite=True) ############################################################################### # Adding custom plots to a report # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # # The python interface has greater flexibility compared to the :ref:`command # line interface <mne report>`. For example, custom plots can be added via # the :meth:`~mne.Report.add_figs_to_section` method, and sliders via the # :meth:`~mne.Report.add_slider_to_section`: # generate a custom plot: fname_evoked = os.path.join(path, 'MEG', 'sample', 'sample_audvis-ave.fif') evoked = mne.read_evokeds(fname_evoked, condition='Left Auditory', baseline=(None, 0), verbose=True) fig = evoked.plot(show=False) # add the custom plot to the report: report.add_figs_to_section(fig, captions='Left Auditory', section='evoked') # Add a custom section with an evoked slider: figs = list() times = evoked.times[::30] for t in times: figs.append( evoked.plot_topomap(t, vmin=-300, vmax=300, res=100, show=False)) plt.close(figs[-1]) report.add_slider_to_section(figs, times,
run=None, processing=config.proc, recording=config.rec, space=config.space) if config.use_ica or config.use_ssp: extension = '_cleaned-epo' else: extension = '-epo' fname_in = op.join(deriv_path, bids_basename + '-ave.fif') msg = f'Input: {fname_in}' logger.info( gen_log_message(message=msg, step=7, subject=subject, session=session)) evokeds = mne.read_evokeds(fname_in) for idx, evoked in enumerate(evokeds): all_evokeds[idx].append(evoked) # Insert to the container for idx, evokeds in all_evokeds.items(): all_evokeds[idx] = mne.grand_average( evokeds, interpolate_bads=config.interpolate_bads_grand_average ) # Combine subjects extension = 'grand_average-ave' fname_out = op.join(config.bids_root, 'derivatives', config.PIPELINE_NAME, '{0}_{1}.fif'.format(config.study_name, extension)) msg = f'Saving grand-averaged sensor data: {fname_out}' logger.info( gen_log_message(message=msg, step=7, subject=subject, session=session))
def test_mxne_vol_sphere(): """(TF-)MxNE with a sphere forward and volumic source space""" evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.crop(tmin=-0.05, tmax=0.2) cov = read_cov(fname_cov) evoked_l21 = evoked.copy() evoked_l21.crop(tmin=0.081, tmax=0.1) info = evoked.info sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.080) src = mne.setup_volume_source_space(subject=None, pos=15., mri=None, sphere=(0.0, 0.0, 0.0, 80.0), bem=None, mindist=5.0, exclude=2.0) fwd = mne.make_forward_solution(info, trans=None, src=src, bem=sphere, eeg=False, meg=True) alpha = 80. pytest.raises(ValueError, mixed_norm, evoked, fwd, cov, alpha, loose=0.0, return_residual=False, maxit=3, tol=1e-8, active_set_size=10) pytest.raises(ValueError, mixed_norm, evoked, fwd, cov, alpha, loose=0.2, return_residual=False, maxit=3, tol=1e-8, active_set_size=10) # irMxNE tests stc = mixed_norm(evoked_l21, fwd, cov, alpha, n_mxne_iter=1, maxit=30, tol=1e-8, active_set_size=10) assert isinstance(stc, VolSourceEstimate) assert_array_almost_equal(stc.times, evoked_l21.times, 5) # Compare orientation obtained using fit_dipole and gamma_map # for a simulated evoked containing a single dipole stc = mne.VolSourceEstimate(50e-9 * np.random.RandomState(42).randn(1, 4), vertices=stc.vertices[:1], tmin=stc.tmin, tstep=stc.tstep) evoked_dip = mne.simulation.simulate_evoked(fwd, stc, info, cov, nave=1e9, use_cps=True) dip_mxne = mixed_norm(evoked_dip, fwd, cov, alpha=80, n_mxne_iter=1, maxit=30, tol=1e-8, active_set_size=10, return_as_dipoles=True) amp_max = [np.max(d.amplitude) for d in dip_mxne] dip_mxne = dip_mxne[np.argmax(amp_max)] assert dip_mxne.pos[0] in src[0]['rr'][stc.vertices] dip_fit = mne.fit_dipole(evoked_dip, cov, sphere)[0] assert np.abs(np.dot(dip_fit.ori[0], dip_mxne.ori[0])) > 0.99 # Do with TF-MxNE for test memory savings alpha = 60. # overall regularization parameter l1_ratio = 0.01 # temporal regularization proportion stc, _ = tf_mixed_norm(evoked, fwd, cov, maxit=3, tol=1e-4, tstep=16, wsize=32, window=0.1, alpha=alpha, l1_ratio=l1_ratio, return_residual=True) assert isinstance(stc, VolSourceEstimate) assert_array_almost_equal(stc.times, evoked.times, 5)
condition = 'visual' # or 'auditory' or 'somatosensory' # Load experimental RAW files for the visual condition raw_fnames = load_data(condition=condition, data_format='raw', data_type='experimental', verbose=True) # Load simulation evoked files for the visual condition evoked_fnames = load_data(condition=condition, data_format='evoked', data_type='simulation', verbose=True) raw = mne.io.read_raw_fif(raw_fnames[0], verbose='error') # Bad naming events = find_events(raw, stim_channel="STI 014", shortest_event=1) # Visualize raw file raw.plot() # Make an evoked file from the experimental data picks = pick_types(raw.info, meg=True, eog=True, exclude='bads') # Read epochs event_id, tmin, tmax = 9, -0.2, 0.5 epochs = Epochs(raw, events, event_id, tmin, tmax, baseline=(None, 0), picks=picks, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) evoked = epochs.average() # average epochs and get an Evoked dataset. evoked.plot() # Compare to the simulated data (use verbose='error' b/c of naming) evoked_sim = read_evokeds(evoked_fnames[0], condition=0, verbose='error') evoked_sim.plot()
fname_evo = data_path + '/MEG/sample/sample_audvis-ave.fif' # read forward solution with EEG and MEG forward_emeg = mne.read_forward_solution(fname_fwd_emeg) # forward operator with fixed source orientations forward_emeg = mne.convert_forward_solution(forward_emeg, surf_ori=True, force_fixed=True) # create a forward solution with MEG only forward_meg = mne.pick_types_forward(forward_emeg, meg=True, eeg=False) # noise covariance matrix noise_cov = mne.read_cov(fname_cov) # evoked data for info evoked = mne.read_evokeds(fname_evo, 0) # make inverse operator from forward solution for MEG and EEGMEG inv_emeg = mne.minimum_norm.make_inverse_operator( info=evoked.info, forward=forward_emeg, noise_cov=noise_cov, loose=0., depth=None) inv_meg = mne.minimum_norm.make_inverse_operator( info=evoked.info, forward=forward_meg, noise_cov=noise_cov, loose=0., depth=None) # regularisation parameter snr = 3.0 lambda2 = 1.0 / snr ** 2 ###############################################################################