def test_restrict_forward_to_label(): """Test restriction of source space to label """ fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) vertno_lh = fwd['src'][0]['vertno'][src_sel_lh] nuse_lh = fwd['src'][0]['nuse'] src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) vertno_rh = fwd['src'][1]['vertno'][src_sel_rh] src_sel_rh += nuse_lh assert_equal(fwd_out['sol']['ncol'], len(src_sel_lh) + len(src_sel_rh)) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], vertno_lh) assert_equal(fwd_out['src'][1]['vertno'], vertno_rh) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) vertno_lh = fwd['src'][0]['vertno'][src_sel_lh] nuse_lh = fwd['src'][0]['nuse'] src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) vertno_rh = fwd['src'][1]['vertno'][src_sel_rh] src_sel_rh += nuse_lh assert_equal(fwd_out['sol']['ncol'], 3 * (len(src_sel_lh) + len(src_sel_rh))) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], vertno_lh) assert_equal(fwd_out['src'][1]['vertno'], vertno_rh)
def test_apply_mne_inverse_epochs(): """Test MNE with precomputed inverse operator on Epochs """ inverse_operator = read_inverse_operator(fname_inv) label_lh = read_label(fname_label % 'Aud-lh') label_rh = read_label(fname_label % 'Aud-rh') event_id, tmin, tmax = 1, -0.2, 0.5 raw = fiff.Raw(fname_raw) picks = fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) flat = dict(grad=1e-15, mag=1e-15) events = read_events(fname_event)[:15] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject, flat=flat) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh, pick_ori="normal") assert_true(len(stcs) == 4) assert_true(3 < stcs[0].data.max() < 10) assert_true(stcs[0].subject == 'sample') data = sum(stc.data for stc in stcs) / len(stcs) flip = label_sign_flip(label_lh, inverse_operator['src']) label_mean = np.mean(data, axis=0) label_mean_flip = np.mean(flip[:, np.newaxis] * data, axis=0) assert_true(label_mean.max() < label_mean_flip.max()) # test extracting a BiHemiLabel stcs_rh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_rh, pick_ori="normal") stcs_bh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh + label_rh, pick_ori="normal") n_lh = len(stcs[0].data) assert_array_almost_equal(stcs[0].data, stcs_bh[0].data[:n_lh]) assert_array_almost_equal(stcs_rh[0].data, stcs_bh[0].data[n_lh:]) # test without using a label (so delayed computation is used) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", pick_ori="normal") assert_true(stcs[0].subject == 'sample') label_stc = stcs[0].in_label(label_rh) assert_true(label_stc.subject == 'sample') assert_array_almost_equal(stcs_rh[0].data, label_stc.data)
def test_apply_mne_inverse_fixed_raw(): """Test MNE with fixed-orientation inverse operator on Raw """ raw = fiff.Raw(fname_raw) start = 3 stop = 10 _, times = raw[0, start:stop] label_lh = read_label(fname_label % 'Aud-lh') # create a fixed-orientation inverse operator fwd = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) noise_cov = read_cov(fname_cov) inv_op = make_inverse_operator(raw.info, fwd, noise_cov, loose=None, depth=0.8, fixed=True) stc = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None) stc2 = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=3) assert_true(stc.subject == 'sample') assert_true(stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc.data, stc2.data)
def test_apply_mne_inverse_raw(): """Test MNE with precomputed inverse operator on Raw.""" start = 3 stop = 10 raw = read_raw_fif(fname_raw) label_lh = read_label(fname_label % 'Aud-lh') _, times = raw[0, start:stop] inverse_operator = read_inverse_operator(fname_full) inverse_operator = prepare_inverse_operator(inverse_operator, nave=1, lambda2=lambda2, method="dSPM") for pick_ori in [None, "normal", "vector"]: stc = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=pick_ori, buffer_size=None, prepared=True) stc2 = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=pick_ori, buffer_size=3, prepared=True) if pick_ori is None: assert_true(np.all(stc.data > 0)) assert_true(np.all(stc2.data > 0)) assert_true(stc.subject == 'sample') assert_true(stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc.data, stc2.data)
def test_tfr_with_inverse_operator(): """Test time freq with MNE inverse computation""" tmin, tmax, event_id = -0.2, 0.5, 1 # Setup for reading the raw data raw = io.Raw(fname_data) events = find_events(raw, stim_channel='STI 014') inverse_operator = read_inverse_operator(fname_inv) inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg=True, eeg=False, eog=True, stim=False, exclude='bads') # Load condition 1 event_id = 1 events3 = events[:3] # take 3 events to keep the computation time low epochs = Epochs(raw, events3, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) # Compute a source estimate per frequency band bands = dict(alpha=[10, 10]) label = read_label(fname_label) stcs = source_band_induced_power(epochs, inv, bands, n_cycles=2, use_fft=False, pca=True, label=label, prepared=True) stc = stcs['alpha'] assert_true(len(stcs) == len(list(bands.keys()))) assert_true(np.all(stc.data > 0)) assert_array_almost_equal(stc.times, epochs.times) stcs_no_pca = source_band_induced_power(epochs, inv, bands, n_cycles=2, use_fft=False, pca=False, label=label, prepared=True) assert_array_almost_equal(stcs['alpha'].data, stcs_no_pca['alpha'].data) # Compute a source estimate per frequency band epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) frequencies = np.arange(7, 30, 2) # define frequencies of interest power, phase_lock = source_induced_power(epochs, inv, frequencies, label, baseline=(-0.1, 0), baseline_mode='percent', n_cycles=2, n_jobs=1, prepared=True) assert_true(np.all(phase_lock > 0)) assert_true(np.all(phase_lock <= 1)) assert_true(np.max(power) > 10)
def test_restrict_forward_to_label(): """Test restriction of source space to label """ fwd = read_forward_solution(fname_meeg, force_fixed=True) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, "MEG", "sample", "labels") labels = ["Aud-lh", "Vis-rh"] label_lh = read_label(op.join(label_path, labels[0] + ".label")) label_rh = read_label(op.join(label_path, labels[1] + ".label")) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd["src"][0]["vertno"], label_lh.vertices) src_sel_lh = np.searchsorted(fwd["src"][0]["vertno"], src_sel_lh) src_sel_rh = np.intersect1d(fwd["src"][1]["vertno"], label_rh.vertices) src_sel_rh = np.searchsorted(fwd["src"][1]["vertno"], src_sel_rh) + len(fwd["src"][0]["vertno"]) assert_equal(fwd_out["sol"]["ncol"], len(src_sel_lh) + len(src_sel_rh)) assert_equal(fwd_out["src"][0]["nuse"], len(src_sel_lh)) assert_equal(fwd_out["src"][1]["nuse"], len(src_sel_rh)) assert_equal(fwd_out["src"][0]["vertno"], src_sel_lh) assert_equal(fwd_out["src"][1]["vertno"], src_sel_rh) fwd = read_forward_solution(fname_meeg, force_fixed=False) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, "MEG", "sample", "labels") labels = ["Aud-lh", "Vis-rh"] label_lh = read_label(op.join(label_path, labels[0] + ".label")) label_rh = read_label(op.join(label_path, labels[1] + ".label")) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd["src"][0]["vertno"], label_lh.vertices) src_sel_lh = np.searchsorted(fwd["src"][0]["vertno"], src_sel_lh) src_sel_rh = np.intersect1d(fwd["src"][1]["vertno"], label_rh.vertices) src_sel_rh = np.searchsorted(fwd["src"][1]["vertno"], src_sel_rh) + len(fwd["src"][0]["vertno"]) assert_equal(fwd_out["sol"]["ncol"], 3 * (len(src_sel_lh) + len(src_sel_rh))) assert_equal(fwd_out["src"][0]["nuse"], len(src_sel_lh)) assert_equal(fwd_out["src"][1]["nuse"], len(src_sel_rh)) assert_equal(fwd_out["src"][0]["vertno"], src_sel_lh) assert_equal(fwd_out["src"][1]["vertno"], src_sel_rh)
def test_source_psd_epochs(): """Test multi-taper source PSD computation in label from epochs""" raw = fiff.Raw(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) event_id, tmin, tmax = 1, -0.2, 0.5 lambda2, method = 1. / 9., 'dSPM' bandwidth = 8. fmin, fmax = 0, 100 picks = fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) events = find_events(raw) epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # only look at one epoch epochs.drop_bad_epochs() one_epochs = epochs[:1] # return list stc_psd = compute_source_psd_epochs(one_epochs, inverse_operator, lambda2=lambda2, method=method, pick_normal=True, label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax)[0] # return generator stcs = compute_source_psd_epochs(one_epochs, inverse_operator, lambda2=lambda2, method=method, pick_normal=True, label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, return_generator=True) for stc in stcs: stc_psd_gen = stc assert_array_almost_equal(stc_psd.data, stc_psd_gen.data) # compare with direct computation stc = apply_inverse_epochs(one_epochs, inverse_operator, lambda2=lambda2, method=method, pick_normal=True, label=label)[0] sfreq = epochs.info['sfreq'] psd, freqs = multitaper_psd(stc.data, sfreq=sfreq, bandwidth=bandwidth, fmin=fmin, fmax=fmax) assert_array_almost_equal(psd, stc_psd.data) assert_array_almost_equal(freqs, stc_psd.times)
def test_apply_inverse_operator(): """Test MNE inverse application """ inverse_operator = read_inverse_operator(fname_full) evoked = _get_evoked() # Inverse has 306 channels - 4 proj = 302 assert_true(compute_rank_inverse(inverse_operator) == 302) # Inverse has 306 channels - 4 proj = 302 assert_true(compute_rank_inverse(inverse_operator) == 302) stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE") assert_true(stc.subject == 'sample') assert_true(stc.data.min() > 0) assert_true(stc.data.max() < 10e-9) assert_true(stc.data.mean() > 1e-11) # test if using prepared and not prepared inverse operator give the same # result inv_op = prepare_inverse_operator(inverse_operator, nave=evoked.nave, lambda2=lambda2, method="MNE") stc2 = apply_inverse(evoked, inv_op, lambda2, "MNE") assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.times, stc2.times) stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA") assert_true(stc.subject == 'sample') assert_true(stc.data.min() > 0) assert_true(stc.data.max() < 10.0) assert_true(stc.data.mean() > 0.1) stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM") assert_true(stc.subject == 'sample') assert_true(stc.data.min() > 0) assert_true(stc.data.max() < 35) assert_true(stc.data.mean() > 0.1) # test without using a label (so delayed computation is used) label = read_label(fname_label % 'Aud-lh') stc = apply_inverse(evoked, inv_op, lambda2, "MNE") stc_label = apply_inverse(evoked, inv_op, lambda2, "MNE", label=label) assert_equal(stc_label.subject, 'sample') label_stc = stc.in_label(label) assert_true(label_stc.subject == 'sample') assert_array_almost_equal(stc_label.data, label_stc.data) # Test we get errors when using custom ref or no average proj is present evoked.info['custom_ref_applied'] = True assert_raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") evoked.info['custom_ref_applied'] = False evoked.info['projs'] = [] # remove EEG proj assert_raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
def test_apply_mne_inverse_raw(): """Test MNE with precomputed inverse operator on Raw.""" start = 3 stop = 10 raw = read_raw_fif(fname_raw) label_lh = read_label(fname_label % 'Aud-lh') _, times = raw[0, start:stop] inverse_operator = read_inverse_operator(fname_full) with pytest.raises(ValueError, match='has not been prepared'): apply_inverse_raw(raw, inverse_operator, lambda2, prepared=True) inverse_operator = prepare_inverse_operator(inverse_operator, nave=1, lambda2=lambda2, method="dSPM") for pick_ori in [None, "normal", "vector"]: stc = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=pick_ori, buffer_size=None, prepared=True) stc2 = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=pick_ori, buffer_size=3, prepared=True) if pick_ori is None: assert (np.all(stc.data > 0)) assert (np.all(stc2.data > 0)) assert (stc.subject == 'sample') assert (stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc.data, stc2.data)
def test_source_psd(): """Test source PSD computation in label.""" raw = read_raw_fif(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) tmin, tmax = 0, 20 # seconds fmin, fmax = 55, 65 # Hz n_fft = 2048 stc = compute_source_psd(raw, inverse_operator, lambda2=1. / 9., method="dSPM", tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, pick_ori="normal", n_fft=n_fft, label=label, overlap=0.1) assert_true(stc.times[0] >= fmin * 1e-3) assert_true(stc.times[-1] <= fmax * 1e-3) # Time max at line frequency (60 Hz in US) assert_true(59e-3 <= stc.times[np.argmax(np.sum(stc.data, axis=0))] <= 61e-3)
def test_apply_mne_inverse_fixed_raw(): """Test MNE with fixed-orientation inverse operator on Raw """ raw = Raw(fname_raw) start = 3 stop = 10 _, times = raw[0, start:stop] label_lh = read_label(fname_label % 'Aud-lh') # create a fixed-orientation inverse operator fwd = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) noise_cov = read_cov(fname_cov) inv_op = make_inverse_operator(raw.info, fwd, noise_cov, loose=None, depth=0.8, fixed=True) stc = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None) stc2 = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=3) assert_true(stc.subject == 'sample') assert_true(stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc.data, stc2.data)
def test_brain_add_label(renderer): """Test adding data in _Brain instance.""" from mne.label import read_label brain = _Brain(subject_id, hemi='lh', size=500, surf=surf, subjects_dir=subjects_dir) label = read_label(fname_label) brain.add_label(label, scalar_thresh=0.) brain.close() brain = _Brain(subject_id, hemi='split', size=500, surf=surf, subjects_dir=subjects_dir) brain.add_label(fname_label) brain.close()
def get_lab_list(conn_params, s_name, src): """Helper to get list of labels and all vertices""" assert ('rsn_labels' in conn_params.keys()) print 'Loading %i labels for subject: %s' % \ (len(conn_params['rsn_labels']), s_name) lab_list = [] lab_vert_list = [] for label_name in conn_params['rsn_labels']: # Load label, get vertices fname_label = op.join(struct_dir, s_name, 'label', label_name) temp_label = read_label(fname_label, subject=s_name) lab_list.append(temp_label) lab_vert_list.extend(list(lab_list[-1].vertices)) return lab_list, lab_vert_list
def test_apply_mne_inverse_raw(): """Test MNE with precomputed inverse operator on Raw """ start = 3 stop = 10 raw = Raw(fname_raw) label_lh = read_label(fname_label % 'Aud-lh') _, times = raw[0, start:stop] inverse_operator = read_inverse_operator(fname_inv) for pick_ori in [None, "normal"]: stc = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=pick_ori, buffer_size=None) stc2 = apply_inverse_raw(raw, inverse_operator, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=pick_ori, buffer_size=3) if pick_ori is None: assert_true(np.all(stc.data > 0)) assert_true(np.all(stc2.data > 0)) assert_true(stc.subject == 'sample') assert_true(stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc.data, stc2.data)
def test_apply_inverse_cov(method, pick_ori): """Test MNE with precomputed inverse operator on cov.""" raw = read_raw_fif(fname_raw, preload=True) # use 10 sec of data raw.crop(0, 10) raw.filter(1, None) label_lh = read_label(fname_label % 'Aud-lh') # test with a free ori inverse inverse_operator = read_inverse_operator(fname_inv) data_cov = compute_raw_covariance(raw, tstep=None) with pytest.raises(ValueError, match='has not been prepared'): apply_inverse_cov(data_cov, raw.info, inverse_operator, lambda2=lambda2, prepared=True) this_inv_op = prepare_inverse_operator(inverse_operator, nave=1, lambda2=lambda2, method=method) raw_ori = 'normal' if pick_ori == 'normal' else 'vector' stc_raw = apply_inverse_raw( raw, this_inv_op, lambda2, method, label=label_lh, nave=1, pick_ori=raw_ori, prepared=True) stc_cov = apply_inverse_cov( data_cov, raw.info, this_inv_op, method=method, pick_ori=pick_ori, label=label_lh, prepared=True, lambda2=lambda2) n_sources = np.prod(stc_cov.data.shape[:-1]) raw_data = stc_raw.data.reshape(n_sources, -1) exp_res = np.diag(np.cov(raw_data, ddof=1)).copy() exp_res *= 1 if raw_ori == pick_ori else 3. # There seems to be some precision penalty when combining orientations, # but it's probably acceptable rtol = 5e-4 if pick_ori is None else 1e-12 assert_allclose(exp_res, stc_cov.data.ravel(), rtol=rtol) with pytest.raises(ValueError, match='Invalid value'): apply_inverse_cov( data_cov, raw.info, this_inv_op, method=method, pick_ori='vector')
def test_apply_mne_inverse_fixed_raw(): """Test MNE with fixed-orientation inverse operator on Raw.""" raw = read_raw_fif(fname_raw) start = 3 stop = 10 _, times = raw[0, start:stop] label_lh = read_label(fname_label % 'Aud-lh') # create a fixed-orientation inverse operator fwd = read_forward_solution_meg(fname_fwd, force_fixed=False, surf_ori=True) noise_cov = read_cov(fname_cov) assert_raises(ValueError, make_inverse_operator, raw.info, fwd, noise_cov, loose=1., fixed=True) inv_op = make_inverse_operator(raw.info, fwd, noise_cov, fixed=True, use_cps=True) inv_op2 = prepare_inverse_operator(inv_op, nave=1, lambda2=lambda2, method="dSPM") stc = apply_inverse_raw(raw, inv_op2, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None, prepared=True) stc2 = apply_inverse_raw(raw, inv_op2, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=3, prepared=True) stc3 = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None) assert_true(stc.subject == 'sample') assert_true(stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc3.times, times) assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.data, stc3.data)
def test_apply_mne_inverse_fixed_raw(): """Test MNE with fixed-orientation inverse operator on Raw.""" raw = read_raw_fif(fname_raw) start = 3 stop = 10 _, times = raw[0, start:stop] label_lh = read_label(fname_label % 'Aud-lh') # create a fixed-orientation inverse operator fwd = read_forward_solution_meg(fname_fwd, force_fixed=False, surf_ori=True) noise_cov = read_cov(fname_cov) pytest.raises(ValueError, make_inverse_operator, raw.info, fwd, noise_cov, loose=1., fixed=True) inv_op = make_inverse_operator(raw.info, fwd, noise_cov, fixed=True, use_cps=True) inv_op2 = prepare_inverse_operator(inv_op, nave=1, lambda2=lambda2, method="dSPM") stc = apply_inverse_raw(raw, inv_op2, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None, prepared=True) stc2 = apply_inverse_raw(raw, inv_op2, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=3, prepared=True) stc3 = apply_inverse_raw(raw, inv_op, lambda2, "dSPM", label=label_lh, start=start, stop=stop, nave=1, pick_ori=None, buffer_size=None) assert (stc.subject == 'sample') assert (stc2.subject == 'sample') assert_array_almost_equal(stc.times, times) assert_array_almost_equal(stc2.times, times) assert_array_almost_equal(stc3.times, times) assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.data, stc3.data)
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation""" # Handling forward solution evoked = read_evokeds(fname_data, condition=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file loose = None depth = 0.9 evoked = read_evokeds(fname_data, condition=0, baseline=(None, 0)) evoked.crop(tmin=-0.1, tmax=0.4) evoked_l21 = copy.deepcopy(evoked) evoked_l21.crop(tmin=0.08, tmax=0.1) label = read_label(fname_label) weights_min = 0.5 forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=loose, depth=depth, fixed=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. # MxNE tests alpha = 60 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='prox') stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_prox.data, stc_cd.data, 5) assert_true(stc_prox.vertno[1][0] in label.vertices) assert_true(stc_cd.vertno[1][0] in label.vertices) stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=depth, maxit=500, tol=1e-4, active_set_size=10, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert_true(stc.vertno[1][0] in label.vertices) # Do with TF-MxNE for test memory savings alpha_space = 60. # spatial regularization parameter alpha_time = 1. # temporal regularization parameter stc, _ = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked.times, 5) assert_true(stc.vertno[1][0] in label.vertices)
def test_source_psd_epochs(): """Test multi-taper source PSD computation in label from epochs.""" raw = read_raw_fif(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) event_id, tmin, tmax = 1, -0.2, 0.5 lambda2, method = 1. / 9., 'dSPM' bandwidth = 8. fmin, fmax = 0, 100 picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) events = find_events(raw, stim_channel='STI 014') epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # only look at one epoch epochs.drop_bad() one_epochs = epochs[:1] inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") # return list stc_psd = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, prepared=True)[0] # return generator stcs = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, return_generator=True, prepared=True) for stc in stcs: stc_psd_gen = stc assert_allclose(stc_psd.data, stc_psd_gen.data, atol=1e-7) # compare with direct computation stc = apply_inverse_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, prepared=True)[0] sfreq = epochs.info['sfreq'] psd, freqs = psd_array_multitaper(stc.data, sfreq=sfreq, bandwidth=bandwidth, fmin=fmin, fmax=fmax) assert_allclose(psd, stc_psd.data, atol=1e-7) assert_allclose(freqs, stc_psd.times) # Check corner cases caused by tiny bandwidth with pytest.raises(ValueError, match='use a value of at least'): compute_source_psd_epochs( one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=0.01, low_bias=True, fmin=fmin, fmax=fmax, return_generator=False, prepared=True)
def test_apply_mne_inverse_epochs(): """Test MNE with precomputed inverse operator on Epochs """ inverse_operator = read_inverse_operator(fname_inv) label_lh = read_label(fname_label % 'Aud-lh') label_rh = read_label(fname_label % 'Aud-rh') event_id, tmin, tmax = 1, -0.2, 0.5 raw = Raw(fname_raw) picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) flat = dict(grad=1e-15, mag=1e-15) events = read_events(fname_event)[:15] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject, flat=flat) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh, pick_ori="normal") assert_true(len(stcs) == 4) assert_true(3 < stcs[0].data.max() < 10) assert_true(stcs[0].subject == 'sample') data = sum(stc.data for stc in stcs) / len(stcs) flip = label_sign_flip(label_lh, inverse_operator['src']) label_mean = np.mean(data, axis=0) label_mean_flip = np.mean(flip[:, np.newaxis] * data, axis=0) assert_true(label_mean.max() < label_mean_flip.max()) # test extracting a BiHemiLabel stcs_rh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_rh, pick_ori="normal") stcs_bh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh + label_rh, pick_ori="normal") n_lh = len(stcs[0].data) assert_array_almost_equal(stcs[0].data, stcs_bh[0].data[:n_lh]) assert_array_almost_equal(stcs_rh[0].data, stcs_bh[0].data[n_lh:]) # test without using a label (so delayed computation is used) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", pick_ori="normal") assert_true(stcs[0].subject == 'sample') label_stc = stcs[0].in_label(label_rh) assert_true(label_stc.subject == 'sample') assert_array_almost_equal(stcs_rh[0].data, label_stc.data)
def test_restrict_forward_to_label(): """Test restriction of source space to label """ fwd = read_forward_solution(fname_meeg) fwd = convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) vertno_lh = fwd['src'][0]['vertno'][src_sel_lh] nuse_lh = fwd['src'][0]['nuse'] src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) vertno_rh = fwd['src'][1]['vertno'][src_sel_rh] src_sel_rh += nuse_lh assert_equal(fwd_out['sol']['ncol'], len(src_sel_lh) + len(src_sel_rh)) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], vertno_lh) assert_equal(fwd_out['src'][1]['vertno'], vertno_rh) fwd = read_forward_solution(fname_meeg) fwd = pick_types_forward(fwd, meg=True) label_path = op.join(data_path, 'MEG', 'sample', 'labels') labels = ['Aud-lh', 'Vis-rh'] label_lh = read_label(op.join(label_path, labels[0] + '.label')) label_rh = read_label(op.join(label_path, labels[1] + '.label')) fwd_out = restrict_forward_to_label(fwd, [label_lh, label_rh]) src_sel_lh = np.intersect1d(fwd['src'][0]['vertno'], label_lh.vertices) src_sel_lh = np.searchsorted(fwd['src'][0]['vertno'], src_sel_lh) vertno_lh = fwd['src'][0]['vertno'][src_sel_lh] nuse_lh = fwd['src'][0]['nuse'] src_sel_rh = np.intersect1d(fwd['src'][1]['vertno'], label_rh.vertices) src_sel_rh = np.searchsorted(fwd['src'][1]['vertno'], src_sel_rh) vertno_rh = fwd['src'][1]['vertno'][src_sel_rh] src_sel_rh += nuse_lh assert_equal(fwd_out['sol']['ncol'], 3 * (len(src_sel_lh) + len(src_sel_rh))) assert_equal(fwd_out['src'][0]['nuse'], len(src_sel_lh)) assert_equal(fwd_out['src'][1]['nuse'], len(src_sel_rh)) assert_equal(fwd_out['src'][0]['vertno'], vertno_lh) assert_equal(fwd_out['src'][1]['vertno'], vertno_rh) # Test saving the restricted forward object. This only works if all fields # are properly accounted for. temp_dir = _TempDir() fname_copy = op.join(temp_dir, 'copy-fwd.fif') write_forward_solution(fname_copy, fwd_out, overwrite=True) fwd_out_read = read_forward_solution(fname_copy) compare_forwards(fwd_out, fwd_out_read)
def test_source_psd_epochs(): """Test multi-taper source PSD computation in label from epochs.""" raw = read_raw_fif(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) event_id, tmin, tmax = 1, -0.2, 0.5 lambda2, method = 1. / 9., 'dSPM' bandwidth = 8. fmin, fmax = 0, 100 picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) events = find_events(raw, stim_channel='STI 014') epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # only look at one epoch epochs.drop_bad() one_epochs = epochs[:1] inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") # return list stc_psd = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, prepared=True)[0] # return generator stcs = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, return_generator=True, prepared=True) for stc in stcs: stc_psd_gen = stc assert_array_almost_equal(stc_psd.data, stc_psd_gen.data) # compare with direct computation stc = apply_inverse_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, prepared=True)[0] sfreq = epochs.info['sfreq'] psd, freqs = psd_array_multitaper(stc.data, sfreq=sfreq, bandwidth=bandwidth, fmin=fmin, fmax=fmax) assert_array_almost_equal(psd, stc_psd.data) assert_array_almost_equal(freqs, stc_psd.times) # Check corner cases caused by tiny bandwidth with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=0.01, low_bias=True, fmin=fmin, fmax=fmax, return_generator=False, prepared=True) compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=0.01, low_bias=False, fmin=fmin, fmax=fmax, return_generator=False, prepared=True) assert_true(len(w) >= 2) assert_true(any('not properly use' in str(ww.message) for ww in w)) assert_true(any('Bandwidth too small' in str(ww.message) for ww in w))
def test_source_psd_epochs(): """Test multi-taper source PSD computation in label from epochs.""" raw = read_raw_fif(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) event_id, tmin, tmax = 1, -0.2, 0.5 lambda2, method = 1. / 9., 'dSPM' bandwidth = 8. fmin, fmax = 0, 100 picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) events = find_events(raw, stim_channel='STI 014') epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # only look at one epoch epochs.drop_bad() one_epochs = epochs[:1] inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") # return list stc_psd = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, prepared=True)[0] # return generator stcs = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, return_generator=True, prepared=True) for stc in stcs: stc_psd_gen = stc assert_array_almost_equal(stc_psd.data, stc_psd_gen.data) # compare with direct computation stc = apply_inverse_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, prepared=True)[0] sfreq = epochs.info['sfreq'] psd, freqs = _psd_multitaper(stc.data, sfreq=sfreq, bandwidth=bandwidth, fmin=fmin, fmax=fmax) assert_array_almost_equal(psd, stc_psd.data) assert_array_almost_equal(freqs, stc_psd.times) # Check corner cases caused by tiny bandwidth with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=0.01, low_bias=True, fmin=fmin, fmax=fmax, return_generator=False, prepared=True) compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=0.01, low_bias=False, fmin=fmin, fmax=fmax, return_generator=False, prepared=True) assert_true(len(w) >= 2) assert_true(any('not properly use' in str(ww.message) for ww in w)) assert_true(any('Bandwidth too small' in str(ww.message) for ww in w))
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_true(stc_prox.vertices[1][0] in label.vertices) assert_true(stc_cd.vertices[1][0] in label.vertices) assert_true(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_true(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_true(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_true(stc.vertices[1][0] in label.vertices) assert_equal(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, None, None, 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_true(stc.vertices[1][0] in label.vertices) with warnings.catch_warnings(record=True) as w: assert_raises(ValueError, tf_mixed_norm, evoked, forward, cov, 101., 3.) assert_raises(ValueError, tf_mixed_norm, evoked, forward, cov, 50, 101.) assert_true(len(w) == 2) assert_raises(ValueError, tf_mixed_norm, evoked, forward, cov, None, None, alpha=101, l1_ratio=0.03) assert_raises(ValueError, tf_mixed_norm, evoked, forward, cov, None, None, alpha=50., l1_ratio=1.01)
def test_source_psd_epochs(): """Test multi-taper source PSD computation in label from epochs""" raw = fiff.Raw(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) event_id, tmin, tmax = 1, -0.2, 0.5 lambda2, method = 1. / 9., 'dSPM' bandwidth = 8. fmin, fmax = 0, 100 picks = fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) events = find_events(raw, stim_channel='STI 014') epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # only look at one epoch epochs.drop_bad_epochs() one_epochs = epochs[:1] # return list stc_psd = compute_source_psd_epochs(one_epochs, inverse_operator, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax)[0] # return generator stcs = compute_source_psd_epochs(one_epochs, inverse_operator, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, return_generator=True) for stc in stcs: stc_psd_gen = stc assert_array_almost_equal(stc_psd.data, stc_psd_gen.data) # compare with direct computation stc = apply_inverse_epochs(one_epochs, inverse_operator, lambda2=lambda2, method=method, pick_ori="normal", label=label)[0] sfreq = epochs.info['sfreq'] psd, freqs = multitaper_psd(stc.data, sfreq=sfreq, bandwidth=bandwidth, fmin=fmin, fmax=fmax) assert_array_almost_equal(psd, stc_psd.data) assert_array_almost_equal(freqs, stc_psd.times)
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif') fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif') fname_inv_nodepth = op.join(s_path, 'sample_audvis-meg-oct-6-meg-nodepth-fixed-inv.fif') fname_inv_diag = op.join(s_path, 'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif') fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif') fname_data = op.join(s_path, 'sample_audvis-ave.fif') fname_cov = op.join(s_path, 'sample_audvis-cov.fif') fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif') fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif') fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif') fname_label = op.join(s_path, 'labels', '%s.label') inverse_operator = read_inverse_operator(fname_inv) label_lh = read_label(fname_label % 'Aud-lh') label_rh = read_label(fname_label % 'Aud-rh') noise_cov = read_cov(fname_cov) raw = fiff.Raw(fname_raw) evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0)) evoked.crop(0, 0.2) snr = 3.0 lambda2 = 1.0 / snr ** 2 tempdir = _TempDir() last_keys = [None] * 10 def _compare(a, b): global last_keys skip_types = ['whitener', 'proj', 'reginv', 'noisenorm', 'nchan',
def test_apply_inverse_operator(): """Test MNE inverse application.""" # use fname_inv as it will be faster than fname_full (fewer verts and chs) inverse_operator = read_inverse_operator(fname_inv) evoked = _get_evoked() # Inverse has 306 channels - 4 proj = 302 assert (compute_rank_inverse(inverse_operator) == 302) # Inverse has 306 channels - 4 proj = 302 assert (compute_rank_inverse(inverse_operator) == 302) stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 13e-9 assert stc.data.mean() > 1e-11 # test if using prepared and not prepared inverse operator give the same # result inv_op = prepare_inverse_operator(inverse_operator, nave=evoked.nave, lambda2=lambda2, method="MNE") stc2 = apply_inverse(evoked, inv_op, lambda2, "MNE") assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.times, stc2.times) # This is little more than a smoke test... stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 10.0 assert stc.data.mean() > 0.1 stc = apply_inverse(evoked, inverse_operator, lambda2, "eLORETA") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 3.0 assert stc.data.mean() > 0.1 stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 35 assert stc.data.mean() > 0.1 # test without using a label (so delayed computation is used) label = read_label(fname_label % 'Aud-lh') stc = apply_inverse(evoked, inv_op, lambda2, "MNE") stc_label = apply_inverse(evoked, inv_op, lambda2, "MNE", label=label) assert_equal(stc_label.subject, 'sample') label_stc = stc.in_label(label) assert label_stc.subject == 'sample' assert_allclose(stc_label.data, label_stc.data) # Test that no errors are raised with loose inverse ops and picking normals noise_cov = read_cov(fname_cov) fwd = read_forward_solution_meg(fname_fwd) inv_op_meg = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1, fixed='auto', depth=None) apply_inverse(evoked, inv_op_meg, 1 / 9., method='MNE', pick_ori='normal') # Test we get errors when using custom ref or no average proj is present evoked.info['custom_ref_applied'] = True pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") evoked.info['custom_ref_applied'] = False evoked.info['projs'] = [] # remove EEG proj pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") # But test that we do not get EEG-related errors on MEG-only inv (gh-4650) apply_inverse(evoked, inv_op_meg, 1. / 9.)
def test_source_psd_epochs(method): """Test multi-taper source PSD computation in label from epochs.""" raw = read_raw_fif(fname_data) inverse_operator = read_inverse_operator(fname_inv) label = read_label(fname_label) event_id, tmin, tmax = 1, -0.2, 0.5 lambda2 = 1. / 9. bandwidth = 8. fmin, fmax = 0, 100 picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) events = find_events(raw, stim_channel='STI 014') epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # only look at one epoch epochs.drop_bad() one_epochs = epochs[:1] inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") # return list stc_psd = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, prepared=True)[0] # return generator stcs = compute_source_psd_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=bandwidth, fmin=fmin, fmax=fmax, return_generator=True, prepared=True) for stc in stcs: stc_psd_gen = stc assert_allclose(stc_psd.data, stc_psd_gen.data, atol=1e-7) # compare with direct computation stc = apply_inverse_epochs(one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, prepared=True)[0] sfreq = epochs.info['sfreq'] psd, freqs = psd_array_multitaper(stc.data, sfreq=sfreq, bandwidth=bandwidth, fmin=fmin, fmax=fmax) assert_allclose(psd, stc_psd.data, atol=1e-7) assert_allclose(freqs, stc_psd.times) # Check corner cases caused by tiny bandwidth with pytest.raises(ValueError, match='use a value of at least'): compute_source_psd_epochs( one_epochs, inv, lambda2=lambda2, method=method, pick_ori="normal", label=label, bandwidth=0.01, low_bias=True, fmin=fmin, fmax=fmax, return_generator=False, prepared=True)
def test_brain_init(renderer, tmpdir, pixel_ratio): """Test initialization of the _Brain instance.""" from mne.label import read_label hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): _Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(TypeError, match='figure'): _Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): _Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): _Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) with pytest.raises(KeyError): _Brain(hemi='foo', surf=surf, **kwargs) brain = _Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', **kwargs) assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh', ) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) brain.add_label(label, scalar_thresh=0.) brain.remove_labels() brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') # add annotation annots = [ 'aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot') ] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = _Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') if renderer._get_3d_backend() == 'mayavi': pixel_ratio = 1. # no HiDPI when using the testing backend want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close()
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') with pytest.warns(None): # CD 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', pca=False) # pca=False deprecated, doesn't matter 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 with pytest.warns(None): # CD 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) assert stc_dip.subject == "sample" _check_stcs(stc_cd, stc_dip) with pytest.warns(None): # CD 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 with pytest.warns(None): # CD 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)
evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file setno = 0 loose = None evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0)) evoked.crop(tmin=0.08, tmax=0.12) # Handling forward solution forward = read_forward_solution(fname_fwd, force_fixed=True) label = read_label(fname_label) def test_MxNE_inverse(): """Test MxNE inverse computation""" alpha = 60 # spatial regularization parameter stc = mixed_norm(evoked, forward, cov, alpha, loose=None, depth=0.9, maxit=500, tol=1e-4, active_set_size=10)
def test_brain_init(renderer, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" if renderer._get_3d_backend() != 'pyvista': pytest.skip('TimeViewer tests only supported on PyVista') from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(KeyError): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) renderer.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemi(hemi='foo') with pytest.raises(ValueError, match='either "lh" or "rh"'): brain._check_hemis(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh', ) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = [ 'aparc', path.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot') ] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500) # image and screenshot fname = path.join(str(tmpdir), 'test.png') assert not path.isfile(fname) brain.save_image(fname) assert path.isfile(fname) brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') if renderer._get_3d_backend() == 'mayavi': pixel_ratio = 1. # no HiDPI when using the testing backend want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3]) assert_allclose(img.shape, want_size) brain.close()
def test_mxne_inverse_standard(): """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) assert label.hemi == 'rh' 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') with pytest.warns(None): # CD 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 # vector with pytest.warns(None): # no convergence stc = mixed_norm(evoked_l21, forward, cov, alpha, loose=1, maxit=2) with pytest.warns(None): # no convergence stc_vec = mixed_norm(evoked_l21, forward, cov, alpha, loose=1, maxit=2, pick_ori='vector') assert_stcs_equal(stc_vec.magnitude(), stc) with pytest.warns(None), pytest.raises(ValueError, match='pick_ori='): mixed_norm(evoked_l21, forward, cov, alpha, loose=0, maxit=2, pick_ori='vector') with pytest.warns(None): # CD 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) assert stc_dip.subject == "sample" assert_stcs_equal(stc_cd, stc_dip) with pytest.warns(None): # CD stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=loose, depth=depth, maxit=300, tol=1e-8, weights=stc_dspm, # gh-6382 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 with pytest.warns(None): # CD 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 # vector stc_nrm = tf_mixed_norm( evoked, forward, cov, loose=1, depth=depth, maxit=2, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, alpha=alpha, l1_ratio=l1_ratio) stc_vec = tf_mixed_norm( evoked, forward, cov, loose=1, depth=depth, maxit=2, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, alpha=alpha, l1_ratio=l1_ratio, pick_ori='vector') assert_stcs_equal(stc_vec.magnitude(), stc_nrm) 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_brain(renderer): """Test initialization of the _Brain instance.""" from mne.label import read_label hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) with pytest.raises(ValueError, match='"size" parameter must be'): _Brain(subject_id=subject_id, hemi=hemi, surf=surf, size=[1, 2, 3]) with pytest.raises(TypeError, match='figure'): _Brain(subject_id=subject_id, hemi=hemi, surf=surf, figure='foo') with pytest.raises(ValueError, match='interaction'): _Brain(subject_id=subject_id, hemi=hemi, surf=surf, interaction=0) with pytest.raises(KeyError): _Brain(subject_id=subject_id, hemi='foo', surf=surf) brain = _Brain(subject_id, hemi=hemi, surf=surf, size=size, subjects_dir=subjects_dir, title=title, cortex=cortex) # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError): brain.add_data(array=np.array([0, 1, 2]), hemi=h) with pytest.raises(ValueError): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=None) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=None) # add label label = read_label(fname_label) brain.add_label(label, scalar_thresh=0.) brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add text brain.add_text(x=0, y=0, text='foo') # screenshot brain.show_view(view=dict(azimuth=180., elevation=90.)) img = brain.screenshot(mode='rgb') assert_allclose(img.shape, (size[0], size[1], 3), atol=70) # XXX undo once size is fixed # add annotation annots = ['aparc', 'PALS_B12_Lobes'] borders = [True, 2] alphas = [1, 0.5] brain = _Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p in zip(annots, borders, alphas): brain.add_annotation(a, b, p) brain.close()
def test_tfr_with_inverse_operator(method): """Test time freq with MNE inverse computation.""" tmin, tmax, event_id = -0.2, 0.5, 1 # Setup for reading the raw data raw = read_raw_fif(fname_data) events = find_events(raw, stim_channel='STI 014') inv = read_inverse_operator(fname_inv) inv = prepare_inverse_operator(inv, nave=1, lambda2=1. / 9., method=method) raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg=True, eeg=False, eog=True, stim=False, exclude='bads') # Load condition 1 event_id = 1 events3 = events[:3] # take 3 events to keep the computation time low epochs = Epochs(raw, events3, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) # Compute a source estimate per frequency band bands = dict(alpha=[10, 10]) label = read_label(fname_label) # XXX someday we should refactor this so that you don't have to pass # method -- maybe `prepare_inverse_operator` should add a `method` # to it and when `prepared=True` the value passed in can be ignored # (or better, default method=None means "dSPM if unprepared" and if they # actually pass a value, we check against `inv['method']`) stcs = source_band_induced_power(epochs, inv, bands, method=method, n_cycles=2, use_fft=False, pca=True, label=label, prepared=True) stc = stcs['alpha'] assert len(stcs) == len(list(bands.keys())) assert np.all(stc.data > 0) assert_allclose(stc.times, epochs.times, atol=1e-6) stcs_no_pca = source_band_induced_power(epochs, inv, bands, method=method, n_cycles=2, use_fft=False, pca=False, label=label, prepared=True) assert_allclose(stcs['alpha'].data, stcs_no_pca['alpha'].data) # Compute a source estimate per frequency band epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) freqs = np.arange(7, 30, 2) # define frequencies of interest power, phase_lock = source_induced_power(epochs, inv, freqs, label, baseline=(-0.1, 0), baseline_mode='percent', n_cycles=2, n_jobs=1, method=method, prepared=True) assert np.all(phase_lock > 0) assert np.all(phase_lock <= 1) assert 5 < np.max(power) < 7
fname_cov = op.join(data_path, 'MEG', 'sample', 'sample_audvis-cov.fif') fname_fwd = op.join(data_path, 'MEG', 'sample', 'sample_audvis-meg-oct-6-fwd.fif') # 'sample_audvis-meg-eeg-oct-6-fwd.fif') fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') fname_event = op.join(data_path, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw-eve.fif') label = 'Aud-lh' fname_label = op.join(data_path, 'MEG', 'sample', 'labels', '%s.label' % label) inverse_operator = read_inverse_operator(fname_inv) inverse_operator_fixed = read_inverse_operator(fname_inv_fixed) inverse_operator_vol = read_inverse_operator(fname_vol_inv) label = read_label(fname_label) noise_cov = read_cov(fname_cov) raw = fiff.Raw(fname_raw) snr = 3.0 lambda2 = 1.0 / snr ** 2 def _compare(a, b): if isinstance(a, dict): assert_true(isinstance(b, dict)) for k, v in a.iteritems(): if not k in b: raise ValueError('%s not in %s' % (k, b)) _compare(v, b[k]) elif isinstance(a, list): assert_true(len(a) == len(b))
def test_mxne_inverse(): """Test (TF-)MxNE inverse computation""" # Handling forward solution evoked = fiff.Evoked(fname_data, setno=1, baseline=(None, 0)) # Read noise covariance matrix cov = read_cov(fname_cov) # Handling average file setno = 0 loose = None depth = 0.9 evoked = fiff.read_evoked(fname_data, setno=setno, baseline=(None, 0)) evoked.crop(tmin=-0.1, tmax=0.4) evoked_l21 = copy.deepcopy(evoked) evoked_l21.crop(tmin=0.08, tmax=0.1) label = read_label(fname_label) weights_min = 0.5 forward = read_forward_solution(fname_fwd, force_fixed=False, surf_ori=True) # Reduce source space to make test computation faster inverse_operator = make_inverse_operator(evoked.info, forward, cov, loose=loose, depth=depth, fixed=True) stc_dspm = apply_inverse(evoked_l21, inverse_operator, lambda2=1. / 9., method='dSPM') stc_dspm.data[np.abs(stc_dspm.data) < 12] = 0.0 stc_dspm.data[np.abs(stc_dspm.data) >= 12] = 1. # MxNE tests alpha = 60 # spatial regularization parameter stc_prox = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='prox') stc_cd = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=0.9, maxit=1000, tol=1e-8, active_set_size=10, solver='cd') assert_array_almost_equal(stc_prox.times, evoked_l21.times, 5) assert_array_almost_equal(stc_cd.times, evoked_l21.times, 5) assert_array_almost_equal(stc_prox.data, stc_cd.data, 5) assert_true(stc_prox.vertno[1][0] in label.vertices) assert_true(stc_cd.vertno[1][0] in label.vertices) stc, _ = mixed_norm(evoked_l21, forward, cov, alpha, loose=None, depth=depth, maxit=500, tol=1e-4, active_set_size=10, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked_l21.times, 5) assert_true(stc.vertno[1][0] in label.vertices) # Do with TF-MxNE for test memory savings alpha_space = 60. # spatial regularization parameter alpha_time = 1. # temporal regularization parameter stc, _ = tf_mixed_norm(evoked, forward, cov, alpha_space, alpha_time, loose=loose, depth=depth, maxit=100, tol=1e-4, tstep=4, wsize=16, window=0.1, weights=stc_dspm, weights_min=weights_min, return_residual=True) assert_array_almost_equal(stc.times, evoked.times, 5) assert_true(stc.vertno[1][0] in label.vertices)
def test_tfr_with_inverse_operator(): """Test time freq with MNE inverse computation.""" tmin, tmax, event_id = -0.2, 0.5, 1 # Setup for reading the raw data raw = read_raw_fif(fname_data) events = find_events(raw, stim_channel='STI 014') inverse_operator = read_inverse_operator(fname_inv) inv = prepare_inverse_operator(inverse_operator, nave=1, lambda2=1. / 9., method="dSPM") raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg=True, eeg=False, eog=True, stim=False, exclude='bads') # Load condition 1 event_id = 1 events3 = events[:3] # take 3 events to keep the computation time low epochs = Epochs(raw, events3, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) # Compute a source estimate per frequency band bands = dict(alpha=[10, 10]) label = read_label(fname_label) stcs = source_band_induced_power(epochs, inv, bands, n_cycles=2, use_fft=False, pca=True, label=label, prepared=True) stc = stcs['alpha'] assert_true(len(stcs) == len(list(bands.keys()))) assert_true(np.all(stc.data > 0)) assert_array_almost_equal(stc.times, epochs.times) stcs_no_pca = source_band_induced_power(epochs, inv, bands, n_cycles=2, use_fft=False, pca=False, label=label, prepared=True) assert_array_almost_equal(stcs['alpha'].data, stcs_no_pca['alpha'].data) # Compute a source estimate per frequency band epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6), preload=True) freqs = np.arange(7, 30, 2) # define frequencies of interest power, phase_lock = source_induced_power(epochs, inv, freqs, label, baseline=(-0.1, 0), baseline_mode='percent', n_cycles=2, n_jobs=1, prepared=True) assert_true(np.all(phase_lock > 0)) assert_true(np.all(phase_lock <= 1)) assert_true(np.max(power) > 10)
def test_apply_inverse_operator(evoked): """Test MNE inverse application.""" # use fname_inv as it will be faster than fname_full (fewer verts and chs) inverse_operator = read_inverse_operator(fname_inv) # Inverse has 306 channels - 4 proj = 302 assert (compute_rank_inverse(inverse_operator) == 302) # Inverse has 306 channels - 4 proj = 302 assert (compute_rank_inverse(inverse_operator) == 302) stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 13e-9 assert stc.data.mean() > 1e-11 # test if using prepared and not prepared inverse operator give the same # result inv_op = prepare_inverse_operator(inverse_operator, nave=evoked.nave, lambda2=lambda2, method="MNE") stc2 = apply_inverse(evoked, inv_op, lambda2, "MNE") assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.times, stc2.times) # This is little more than a smoke test... stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 10.0 assert stc.data.mean() > 0.1 stc = apply_inverse(evoked, inverse_operator, lambda2, "eLORETA") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 3.0 assert stc.data.mean() > 0.1 stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM") assert stc.subject == 'sample' assert stc.data.min() > 0 assert stc.data.max() < 35 assert stc.data.mean() > 0.1 # test without using a label (so delayed computation is used) label = read_label(fname_label % 'Aud-lh') stc = apply_inverse(evoked, inv_op, lambda2, "MNE") stc_label = apply_inverse(evoked, inv_op, lambda2, "MNE", label=label) assert_equal(stc_label.subject, 'sample') label_stc = stc.in_label(label) assert label_stc.subject == 'sample' assert_allclose(stc_label.data, label_stc.data) # Test that no errors are raised with loose inverse ops and picking normals noise_cov = read_cov(fname_cov) fwd = read_forward_solution_meg(fname_fwd) inv_op_meg = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1, fixed='auto', depth=None) apply_inverse(evoked, inv_op_meg, 1 / 9., method='MNE', pick_ori='normal') # Test we get errors when using custom ref or no average proj is present evoked.info['custom_ref_applied'] = True pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") evoked.info['custom_ref_applied'] = False evoked.info['projs'] = [] # remove EEG proj pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") # But test that we do not get EEG-related errors on MEG-only inv (gh-4650) apply_inverse(evoked, inv_op_meg, 1. / 9.)
def test_apply_inverse_operator(): """Test MNE inverse application.""" inverse_operator = read_inverse_operator(fname_full) evoked = _get_evoked() # Inverse has 306 channels - 4 proj = 302 assert_true(compute_rank_inverse(inverse_operator) == 302) # Inverse has 306 channels - 4 proj = 302 assert_true(compute_rank_inverse(inverse_operator) == 302) stc = apply_inverse(evoked, inverse_operator, lambda2, "MNE") assert_true(stc.subject == 'sample') assert_true(stc.data.min() > 0) assert_true(stc.data.max() < 10e-9) assert_true(stc.data.mean() > 1e-11) # test if using prepared and not prepared inverse operator give the same # result inv_op = prepare_inverse_operator(inverse_operator, nave=evoked.nave, lambda2=lambda2, method="MNE") stc2 = apply_inverse(evoked, inv_op, lambda2, "MNE") assert_array_almost_equal(stc.data, stc2.data) assert_array_almost_equal(stc.times, stc2.times) stc = apply_inverse(evoked, inverse_operator, lambda2, "sLORETA") assert_true(stc.subject == 'sample') assert_true(stc.data.min() > 0) assert_true(stc.data.max() < 10.0) assert_true(stc.data.mean() > 0.1) stc = apply_inverse(evoked, inverse_operator, lambda2, "dSPM") assert_true(stc.subject == 'sample') assert_true(stc.data.min() > 0) assert_true(stc.data.max() < 35) assert_true(stc.data.mean() > 0.1) # test without using a label (so delayed computation is used) label = read_label(fname_label % 'Aud-lh') stc = apply_inverse(evoked, inv_op, lambda2, "MNE") stc_label = apply_inverse(evoked, inv_op, lambda2, "MNE", label=label) assert_equal(stc_label.subject, 'sample') label_stc = stc.in_label(label) assert_true(label_stc.subject == 'sample') assert_allclose(stc_label.data, label_stc.data) # Test that no errors are raised with loose inverse ops and picking normals noise_cov = read_cov(fname_cov) fwd = read_forward_solution_meg(fname_fwd) inv_op2 = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1, fixed='auto', depth=None) apply_inverse(evoked, inv_op2, 1 / 9., method='MNE', pick_ori='normal') # Test we get errors when using custom ref or no average proj is present evoked.info['custom_ref_applied'] = True assert_raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE") evoked.info['custom_ref_applied'] = False evoked.info['projs'] = [] # remove EEG proj assert_raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
def test_brain_init(renderer_pyvistaqt, tmpdir, pixel_ratio, brain_gc): """Test initialization of the Brain instance.""" from mne.source_estimate import _BaseSourceEstimate class FakeSTC(_BaseSourceEstimate): def __init__(self): pass hemi = 'lh' surf = 'inflated' cortex = 'low_contrast' title = 'test' size = (300, 300) kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir) with pytest.raises(ValueError, match='"size" parameter must be'): Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs) with pytest.raises(ValueError, match='.*hemi.*Allowed values.*'): Brain(hemi='foo', surf=surf, **kwargs) with pytest.raises(ValueError, match='.*view.*Allowed values.*'): Brain(hemi='lh', surf=surf, views='foo', **kwargs) with pytest.raises(TypeError, match='figure'): Brain(hemi=hemi, surf=surf, figure='foo', **kwargs) with pytest.raises(TypeError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction=0, **kwargs) with pytest.raises(ValueError, match='interaction'): Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs) with pytest.raises(FileNotFoundError, match=r'lh\.whatever'): Brain(subject_id, 'lh', 'whatever') with pytest.raises(ValueError, match='`surf` cannot be seghead'): Brain(hemi='lh', surf='seghead', **kwargs) Brain(subject_id, hemi=None, surf=None) # test no surfaces renderer_pyvistaqt.backend._close_all() brain = Brain(hemi=hemi, surf=surf, size=size, title=title, cortex=cortex, units='m', silhouette=dict(decimate=0.95), **kwargs) with pytest.raises(TypeError, match='not supported'): brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None) with pytest.raises(ValueError, match='add_data'): brain.setup_time_viewer(time_viewer=True) brain._hemi = 'foo' # for testing: hemis with pytest.raises(ValueError, match='not be None'): brain._check_hemi(hemi=None) with pytest.raises(ValueError, match='Invalid.*hemi.*Allowed'): brain._check_hemi(hemi='foo') brain._hemi = hemi # end testing: hemis with pytest.raises(ValueError, match='bool or positive'): brain._to_borders(None, None, 'foo') assert brain.interaction == 'trackball' # add_data stc = read_source_estimate(fname_stc) fmin = stc.data.min() fmax = stc.data.max() for h in brain._hemis: if h == 'lh': hi = 0 else: hi = 1 hemi_data = stc.data[:len(stc.vertices[hi]), 10] hemi_vertices = stc.vertices[hi] with pytest.raises(TypeError, match='scale_factor'): brain.add_data(hemi_data, hemi=h, scale_factor='foo') with pytest.raises(TypeError, match='vector_alpha'): brain.add_data(hemi_data, hemi=h, vector_alpha='foo') with pytest.raises(ValueError, match='thresh'): brain.add_data(hemi_data, hemi=h, thresh=-1) with pytest.raises(ValueError, match='remove_existing'): brain.add_data(hemi_data, hemi=h, remove_existing=-1) with pytest.raises(ValueError, match='time_label_size'): brain.add_data(hemi_data, hemi=h, time_label_size=-1, vertices=hemi_vertices) with pytest.raises(ValueError, match='is positive'): brain.add_data(hemi_data, hemi=h, smoothing_steps=-1, vertices=hemi_vertices) with pytest.raises(TypeError, match='int or NoneType'): brain.add_data(hemi_data, hemi=h, smoothing_steps='foo') with pytest.raises(ValueError, match='dimension mismatch'): brain.add_data(array=np.array([0, 1, 2]), hemi=h, vertices=hemi_vertices) with pytest.raises(ValueError, match='vertices parameter must not be'): brain.add_data(hemi_data, fmin=fmin, hemi=hemi, fmax=fmax, vertices=None) with pytest.raises(ValueError, match='has shape'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=hemi, fmax=fmax, vertices=None, time=[0, 1]) brain.add_data(hemi_data, fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=(0, 0), time=None) with pytest.raises(ValueError, match='brain has no defined times'): brain.set_time(0.) assert brain.data['lh']['array'] is hemi_data assert brain.views == ['lateral'] assert brain.hemis == ('lh', ) brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps=1, initial_time=0., colorbar=False, time=[0]) with pytest.raises(ValueError, match='the range of available times'): brain.set_time(7.) brain.set_time(0.) brain.set_time_point(0) # should hit _safe_interp1d with pytest.raises(ValueError, match='consistent with'): brain.add_data(hemi_data[:, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices, smoothing_steps='nearest', colorbar=False, time=[1]) with pytest.raises(ValueError, match='different from'): brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='need shape'): brain.add_data(hemi_data[:, np.newaxis], time=[0, 1], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) with pytest.raises(ValueError, match='If array has 3'): brain.add_data(hemi_data[:, np.newaxis, np.newaxis], fmin=fmin, hemi=h, fmax=fmax, colormap='hot', vertices=hemi_vertices) # add label label = read_label(fname_label) with pytest.raises(ValueError, match="not a filename"): brain.add_label(0) with pytest.raises(ValueError, match="does not exist"): brain.add_label('foo', subdir='bar') label.name = None # test unnamed label brain.add_label(label, scalar_thresh=0., color="green") assert isinstance(brain.labels[label.hemi], list) overlays = brain._layered_meshes[label.hemi]._overlays assert 'unnamed0' in overlays assert np.allclose(overlays['unnamed0']._colormap[0], [0, 0, 0, 0]) # first component is transparent assert np.allclose(overlays['unnamed0']._colormap[1], [0, 128, 0, 255]) # second is green brain.remove_labels() assert 'unnamed0' not in overlays brain.add_label(fname_label) brain.add_label('V1', borders=True) brain.remove_labels() brain.remove_labels() # add foci brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue') # add head and skull brain.add_head(color='red', alpha=0.1) brain.add_skull(outer=True, color='green', alpha=0.1) # add volume labels brain.add_volume_labels(aseg='aseg', labels=('Brain-Stem', 'Left-Hippocampus', 'Left-Amygdala')) # add sensors info = read_info(fname_raw_testing) brain.add_sensors(info, trans=fname_trans) info['chs'][0]['coord_frame'] = 99 with pytest.raises(RuntimeError, match='must be "meg", "head" or "mri"'): brain.add_sensors(info, trans=fname_trans) # add text brain.add_text(x=0, y=0, text='foo') brain.close() # add annotation annots = [ 'aparc', op.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot') ] borders = [True, 2] alphas = [1, 0.5] colors = [None, 'r'] brain = Brain(subject_id='fsaverage', hemi='both', size=size, surf='inflated', subjects_dir=subjects_dir) with pytest.raises(RuntimeError, match="both hemispheres"): brain.add_annotation(annots[-1]) with pytest.raises(ValueError, match="does not exist"): brain.add_annotation('foo') brain.close() brain = Brain(subject_id='fsaverage', hemi=hemi, size=size, surf='inflated', subjects_dir=subjects_dir) for a, b, p, color in zip(annots, borders, alphas, colors): brain.add_annotation(a, b, p, color=color) view_args = dict(roll=1, distance=500, focalpoint=(1e-5, 1e-5, 1e-5)) cam = brain._renderer.figure.plotter.camera previous_roll = cam.GetRoll() brain.show_view(**view_args) assert_allclose(cam.GetFocalPoint(), view_args["focalpoint"]) assert_allclose(cam.GetDistance(), view_args["distance"]) assert_allclose(cam.GetRoll(), previous_roll + view_args["roll"]) del view_args with pytest.warns(DeprecationWarning, match='`view` is a dict'): brain.show_view(view=dict(azimuth=180., elevation=90.)) # image and screenshot fname = op.join(str(tmpdir), 'test.png') assert not op.isfile(fname) brain.save_image(fname) assert op.isfile(fname) fp = np.array( brain._renderer.figure.plotter.renderer.ComputeVisiblePropBounds()) fp = (fp[1::2] + fp[::2]) * 0.5 azimuth, elevation = 180., 90. for view_args in (dict(azimuth=azimuth, elevation=elevation, focalpoint='auto'), dict(view='lateral', hemi='lh')): brain.show_view(**view_args) assert_allclose(brain._renderer.figure._azimuth, azimuth) assert_allclose(brain._renderer.figure._elevation, elevation) assert_allclose(cam.GetFocalPoint(), fp) del view_args img = brain.screenshot(mode='rgba') want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 4]) assert_allclose(img.shape, want_size) brain.close()
s_path = op.join(sample.data_path(), 'MEG', 'sample') fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif') fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif') fname_inv_nodepth = op.join(s_path, 'sample_audvis-meg-oct-6-meg-nodepth-fixed-inv.fif') fname_inv_diag = op.join(s_path, 'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif') fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif') fname_data = op.join(s_path, 'sample_audvis-ave.fif') fname_cov = op.join(s_path, 'sample_audvis-cov.fif') fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif') fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif') fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif') fname_label = op.join(s_path, 'labels', '%s.label') label_lh = read_label(fname_label % 'Aud-lh') label_rh = read_label(fname_label % 'Aud-rh') noise_cov = read_cov(fname_cov) raw = fiff.Raw(fname_raw) evoked = fiff.Evoked(fname_data, setno=0, baseline=(None, 0)) evoked.crop(0, 0.2) snr = 3.0 lambda2 = 1.0 / snr ** 2 tempdir = _TempDir() def _compare(a, b): skip_types = ['whitener', 'proj', 'reginv', 'noisenorm', 'nchan'] if isinstance(a, dict):
def test_apply_mne_inverse_epochs(): """Test MNE with precomputed inverse operator on Epochs.""" inverse_operator = read_inverse_operator(fname_full) label_lh = read_label(fname_label % 'Aud-lh') label_rh = read_label(fname_label % 'Aud-rh') event_id, tmin, tmax = 1, -0.2, 0.5 raw = read_raw_fif(fname_raw) picks = pick_types(raw.info, meg=True, eeg=False, stim=True, ecg=True, eog=True, include=['STI 014'], exclude='bads') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) flat = dict(grad=1e-15, mag=1e-15) events = read_events(fname_event)[:15] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject, flat=flat) inverse_operator = prepare_inverse_operator(inverse_operator, nave=1, lambda2=lambda2, method="dSPM") for pick_ori in [None, "normal", "vector"]: stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh, pick_ori=pick_ori) stcs2 = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh, pick_ori=pick_ori, prepared=True) # test if using prepared and not prepared inverse operator give the # same result assert_array_almost_equal(stcs[0].data, stcs2[0].data) assert_array_almost_equal(stcs[0].times, stcs2[0].times) assert (len(stcs) == 2) assert (3 < stcs[0].data.max() < 10) assert (stcs[0].subject == 'sample') inverse_operator = read_inverse_operator(fname_full) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh, pick_ori='normal') data = sum(stc.data for stc in stcs) / len(stcs) flip = label_sign_flip(label_lh, inverse_operator['src']) label_mean = np.mean(data, axis=0) label_mean_flip = np.mean(flip[:, np.newaxis] * data, axis=0) assert (label_mean.max() < label_mean_flip.max()) # test extracting a BiHemiLabel inverse_operator = prepare_inverse_operator(inverse_operator, nave=1, lambda2=lambda2, method="dSPM") stcs_rh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_rh, pick_ori="normal", prepared=True) stcs_bh = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", label=label_lh + label_rh, pick_ori="normal", prepared=True) n_lh = len(stcs[0].data) assert_array_almost_equal(stcs[0].data, stcs_bh[0].data[:n_lh]) assert_array_almost_equal(stcs_rh[0].data, stcs_bh[0].data[n_lh:]) # test without using a label (so delayed computation is used) stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, "dSPM", pick_ori="normal", prepared=True) assert (stcs[0].subject == 'sample') label_stc = stcs[0].in_label(label_rh) assert (label_stc.subject == 'sample') assert_array_almost_equal(stcs_rh[0].data, label_stc.data)