def _get_channel_subsets(raw): """ Return defined sensor locations as a list of relevant sensors """ # TODO: fill in with sensor names for left and right parietal_left = mne.read_selection(name=["Left-parietal"], info=raw.info) parietal_right = mne.read_selection(name=["Right-parietal"], info=raw.info) occipital_left = mne.read_selection(name=["Left-occipital"], info=raw.info) occipital_right = mne.read_selection(name=["Right-occipital"], info=raw.info) frontal_left = mne.read_selection(name=["Left-frontal"], info=raw.info) frontal_right = mne.read_selection(name=["Right-frontal"], info=raw.info) vertex_sensors = mne.read_selection(name=["Vertex"], info=raw.info) temporal_left = mne.read_selection(name=["Left-temporal"], info=raw.info) temporal_right = mne.read_selection(name=["Right-temporal"], info=raw.info) sensors = { "lpar": parietal_left, "rpar": parietal_right, "locc": occipital_left, "rocc": occipital_right, "lfro": frontal_left, "rfro": frontal_right, "ltem": temporal_left, "rtem": temporal_right, "ver": vertex_sensors, } return sensors
def test_read_selection(): """Test reading of selections.""" # test one channel for each selection ch_names = ['MEG 2211', 'MEG 0223', 'MEG 1312', 'MEG 0412', 'MEG 1043', 'MEG 2042', 'MEG 2032', 'MEG 0522', 'MEG 1031'] sel_names = ['Vertex', 'Left-temporal', 'Right-temporal', 'Left-parietal', 'Right-parietal', 'Left-occipital', 'Right-occipital', 'Left-frontal', 'Right-frontal'] raw = read_raw_fif(raw_fname) for i, name in enumerate(sel_names): sel = read_selection(name) assert_true(ch_names[i] in sel) sel_info = read_selection(name, info=raw.info) assert_equal(sel, sel_info) # test some combinations all_ch = read_selection(['L', 'R']) left = read_selection('L') right = read_selection('R') assert_true(len(all_ch) == len(left) + len(right)) assert_true(len(set(left).intersection(set(right))) == 0) frontal = read_selection('frontal') occipital = read_selection('Right-occipital') assert_true(len(set(frontal).intersection(set(occipital))) == 0) ch_names_new = [ch.replace(' ', '') for ch in ch_names] raw_new = read_raw_fif(raw_new_fname) for i, name in enumerate(sel_names): sel = read_selection(name, info=raw_new.info) assert_true(ch_names_new[i] in sel) assert_raises(TypeError, read_selection, name, info='foo')
def test_lcmv_raw(): """Test LCMV with raw data """ raw, _, _, _, noise_cov, label, forward, _, _, _ =\ _get_data(all_forward=False, epochs=False, data_cov=False) tmin, tmax = 0, 20 start, stop = raw.time_as_index([tmin, tmax]) # use only the left-temporal MEG channels for LCMV left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, exclude='bads', selection=left_temporal_channels) data_cov = mne.compute_raw_data_covariance(raw, tmin=tmin, tmax=tmax) stc = lcmv_raw(raw, forward, noise_cov, data_cov, reg=0.01, label=label, start=start, stop=stop, picks=picks) assert_array_almost_equal(np.array([tmin, tmax]), np.array([stc.times[0], stc.times[-1]]), decimal=2) # make sure we get an stc with vertices only in the lh vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] assert_true(len(stc.vertno[0]) == len(np.intersect1d(vertno[0], label.vertices))) assert_true(len(stc.vertno[1]) == 0)
def test_lcmv(): """Test LCMV """ event_id, tmin, tmax = 1, -0.2, 0.2 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude=raw.info['bads'], selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.)
def _get_data(): """Read in data used in tests.""" # read forward model forward = mne.read_forward_solution(fname_fwd) # read data raw = mne.io.read_raw_fif(fname_raw, preload=True) events = mne.read_events(fname_event) event_id, tmin, tmax = 1, -0.1, 0.15 # decimate for speed left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, selection=left_temporal_channels) picks = picks[::2] raw.pick_channels([raw.ch_names[ii] for ii in picks]) del picks raw.info.normalize_proj() # avoid projection warnings epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0.), preload=True, reject=reject) noise_cov = mne.compute_covariance(epochs, tmin=None, tmax=0.) data_cov = mne.compute_covariance(epochs, tmin=0.01, tmax=0.15) return epochs, data_cov, noise_cov, forward
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True, epochs_preload=True, data_cov=True): """Read in data used in tests.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.read_raw_fif(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) if all_forward: forward_surf_ori = _read_forward_solution_meg( fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg( fname_fwd, force_fixed=True, surf_ori=True, use_cps=False) forward_vol = _read_forward_solution_meg(fname_fwd_vol) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bad channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, ref_meg=False, exclude='bads', selection=left_temporal_channels) raw.pick_channels([raw.ch_names[ii] for ii in picks]) raw.info.normalize_proj() # avoid projection warnings if epochs: # Read epochs epochs = mne.Epochs( raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=epochs_preload, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) if epochs_preload: epochs.resample(200, npad=0, n_jobs=2) epochs.crop(0, None) evoked = epochs.average() info = evoked.info else: epochs = None evoked = None info = raw.info noise_cov = mne.read_cov(fname_cov) noise_cov['projs'] = [] # avoid warning with warnings.catch_warnings(record=True): # bad proj noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05, eeg=0.1, proj=True) if data_cov: with warnings.catch_warnings(record=True): # too few samples data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145) else: data_cov = None return raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True): """Read in real MEG data. Used to test deprecated dics_* functions.""" """Read in data used in tests.""" if read_all_forward: fwd_free, fwd_surf, fwd_fixed, fwd_vol, _ = _load_forward() label_fname = op.join(data_path, 'MEG', 'sample', 'labels', 'Aud-lh.label') label = mne.read_label(label_fname) events = mne.read_events(fname_event)[:10] raw = mne.io.read_raw_fif(fname_raw, preload=False) raw.add_proj([], remove_existing=True) # we'll subselect so remove proj event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average().crop(0, None) # Computing the data and noise cross-spectral density matrices if compute_csds: data_csd = csd_multitaper(epochs, tmin=0.045, tmax=None, fmin=8, fmax=12, bandwidth=72.72).sum() noise_csd = csd_multitaper(epochs, tmin=None, tmax=0, fmin=8, fmax=12, bandwidth=72.72).sum() else: data_csd, noise_csd = None, None return (raw, epochs, evoked, data_csd, noise_csd, label, fwd_free, fwd_surf, fwd_fixed, fwd_vol)
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True, epochs_preload=True, data_cov=True): """Read in data used in tests.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.read_raw_fif(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) if all_forward: forward_surf_ori = _read_forward_solution_meg( fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg( fname_fwd, force_fixed=True, surf_ori=True, use_cps=False) forward_vol = _read_forward_solution_meg(fname_fwd_vol) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bad channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, selection=left_temporal_channels) picks = picks[::2] # decimate for speed raw.pick_channels([raw.ch_names[ii] for ii in picks]) del picks raw.info.normalize_proj() # avoid projection warnings if epochs: # Read epochs epochs = mne.Epochs( raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=epochs_preload, reject=reject) if epochs_preload: epochs.resample(200, npad=0, n_jobs=2) epochs.crop(0, None) evoked = epochs.average() info = evoked.info else: epochs = None evoked = None info = raw.info noise_cov = mne.read_cov(fname_cov) noise_cov['projs'] = [] # avoid warning with warnings.catch_warnings(record=True): # bad proj noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05, eeg=0.1, proj=True) if data_cov: with warnings.catch_warnings(record=True): # too few samples data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145) else: data_cov = None return raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True, epochs_preload=True, data_cov=True): """Read in data used in tests """ label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.fiff.Raw(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) if all_forward: forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True) forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels if epochs: # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, ref_meg=False, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=epochs_preload, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) if epochs_preload: epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() info = evoked.info else: epochs = None evoked = None info = raw.info noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05, eeg=0.1, proj=True) if data_cov: data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) else: data_cov = None return raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def test_read_selection(): """Test reading of selections""" # test one channel for each selection ch_names = [ "MEG 2211", "MEG 0223", "MEG 1312", "MEG 0412", "MEG 1043", "MEG 2042", "MEG 2032", "MEG 0522", "MEG 1031", ] sel_names = [ "Vertex", "Left-temporal", "Right-temporal", "Left-parietal", "Right-parietal", "Left-occipital", "Right-occipital", "Left-frontal", "Right-frontal", ] raw = read_raw_fif(raw_fname) for i, name in enumerate(sel_names): sel = read_selection(name) assert_true(ch_names[i] in sel) sel_info = read_selection(name, info=raw.info) assert_equal(sel, sel_info) # test some combinations all_ch = read_selection(["L", "R"]) left = read_selection("L") right = read_selection("R") assert_true(len(all_ch) == len(left) + len(right)) assert_true(len(set(left).intersection(set(right))) == 0) frontal = read_selection("frontal") occipital = read_selection("Right-occipital") assert_true(len(set(frontal).intersection(set(occipital))) == 0) ch_names_new = [ch.replace(" ", "") for ch in ch_names] raw_new = read_raw_fif(raw_new_fname) for i, name in enumerate(sel_names): sel = read_selection(name, info=raw_new.info) assert_true(ch_names_new[i] in sel) assert_raises(TypeError, read_selection, name, info="foo")
def test_lcmv(): """Test LCMV with evoked data and single trials """ event_id, tmin, tmax = 1, -0.1, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stc.data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data)
def test_lcmv_raw(): """Test LCMV with raw data """ tmin, tmax = 0, 20 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, raw.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) start, stop = raw.time_as_index([tmin, tmax]) # use only the left-temporal MEG channels for LCMV picks = mne.fiff.pick_types(raw.info, meg=True, exclude='bads', selection=left_temporal_channels) data_cov = mne.compute_raw_data_covariance(raw, tmin=tmin, tmax=tmax) stc = lcmv_raw(raw, forward, noise_cov, data_cov, reg=0.01, label=label, start=start, stop=stop, picks=picks) assert_array_almost_equal(np.array([tmin, tmax]), np.array([stc.times[0], stc.times[-1]]), decimal=2) # make sure we get an stc with vertices only in the lh vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] assert_true( len(stc.vertno[0]) == len(np.intersect1d(vertno[0], label.vertices))) assert_true(len(stc.vertno[1]) == 0)
def test_read_selection(): """Test reading of selections""" # test one channel for each selection ch_names = [ 'MEG 2211', 'MEG 0223', 'MEG 1312', 'MEG 0412', 'MEG 1043', 'MEG 2042', 'MEG 2032', 'MEG 0522', 'MEG 1031' ] sel_names = [ 'Vertex', 'Left-temporal', 'Right-temporal', 'Left-parietal', 'Right-parietal', 'Left-occipital', 'Right-occipital', 'Left-frontal', 'Right-frontal' ] for i, name in enumerate(sel_names): sel = read_selection(name) assert (ch_names[i] in sel) # test some combinations all_ch = read_selection(['L', 'R']) left = read_selection('L') right = read_selection('R') assert (len(all_ch) == len(left) + len(right)) assert (len(set(left).intersection(set(right))) == 0) frontal = read_selection('frontal') occipital = read_selection('Right-occipital') assert (len(set(frontal).intersection(set(occipital))) == 0)
def pickChannels(channelLocation, sensortype): channelNames = mne.read_selection(channelLocation) channelShortNames = [ channelName.replace(' ', '') for channelName in channelNames ] channelIDs = mne.pick_types(raw.info, meg=sensortype.lower(), eeg=False, eog=False, stim=False, exclude='bads', selection=channelShortNames) return channelIDs
def _get_data(tmin=-0.11, tmax=0.15, read_all_forward=True, compute_csds=True): """Read in data used in tests.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event)[:10] raw = mne.io.read_raw_fif(fname_raw, preload=False) raw.add_proj([], remove_existing=True) # we'll subselect so remove proj forward = mne.read_forward_solution(fname_fwd) if read_all_forward: forward_surf_ori = _read_forward_solution_meg( fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg( fname_fwd, force_fixed=True, use_cps=False) forward_vol = mne.read_forward_solution(fname_fwd_vol) forward_vol = mne.convert_forward_solution(forward_vol, surf_ori=True) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average().crop(0, None) # Computing the data and noise cross-spectral density matrices if compute_csds: data_csd = csd_epochs(epochs, mode='multitaper', tmin=0.045, tmax=None, fmin=8, fmax=12, mt_bandwidth=72.72) noise_csd = csd_epochs(epochs, mode='multitaper', tmin=None, tmax=0.0, fmin=8, fmax=12, mt_bandwidth=72.72) else: data_csd, noise_csd = None, None return raw, epochs, evoked, data_csd, noise_csd, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def test_lcmv_raw(): """Test LCMV with raw data """ forward = mne.read_forward_solution(fname_fwd) label = mne.read_label(fname_label) noise_cov = mne.read_cov(fname_cov) raw = mne.fiff.Raw(fname_raw, preload=False) tmin, tmax = 0, 20 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, raw.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) start, stop = raw.time_as_index([tmin, tmax]) # use only the left-temporal MEG channels for LCMV picks = mne.fiff.pick_types(raw.info, meg=True, exclude='bads', selection=left_temporal_channels) data_cov = mne.compute_raw_data_covariance(raw, tmin=tmin, tmax=tmax) stc = lcmv_raw(raw, forward, noise_cov, data_cov, reg=0.01, label=label, start=start, stop=stop, picks=picks) assert_array_almost_equal(np.array([tmin, tmax]), np.array([stc.times[0], stc.times[-1]]), decimal=2) # make sure we get an stc with vertices only in the lh vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] assert_true(len(stc.vertno[0]) == len(np.intersect1d(vertno[0], label.vertices))) assert_true(len(stc.vertno[1]) == 0)
def test_read_selection(): """Test reading of selections.""" # test one channel for each selection ch_names = [ 'MEG 2211', 'MEG 0223', 'MEG 1312', 'MEG 0412', 'MEG 1043', 'MEG 2042', 'MEG 2032', 'MEG 0522', 'MEG 1031' ] sel_names = [ 'Vertex', 'Left-temporal', 'Right-temporal', 'Left-parietal', 'Right-parietal', 'Left-occipital', 'Right-occipital', 'Left-frontal', 'Right-frontal' ] raw = read_raw_fif(raw_fname) for i, name in enumerate(sel_names): sel = read_selection(name) assert ch_names[i] in sel sel_info = read_selection(name, info=raw.info) assert sel == sel_info # test some combinations all_ch = read_selection(['L', 'R']) left = read_selection('L') right = read_selection('R') assert len(all_ch) == len(left) + len(right) assert len(set(left).intersection(set(right))) == 0 frontal = read_selection('frontal') occipital = read_selection('Right-occipital') assert len(set(frontal).intersection(set(occipital))) == 0 ch_names_new = [ch.replace(' ', '') for ch in ch_names] raw_new = read_raw_fif(raw_new_fname) for i, name in enumerate(sel_names): sel = read_selection(name, info=raw_new.info) assert ch_names_new[i] in sel pytest.raises(TypeError, read_selection, name, info='foo')
def pickChannels(markerID): if markerID in [0, 1]: channelLocation = hemisphere + '-' + location elif markerID == 2: channelLocation = hemisphere + '-occipital' elif markerID == 3: channelLocation = hemisphere + '-temporal' elif markerID in [4, 5]: channelLocation = hemisphere + '-parietal' channelNames = mne.read_selection(channelLocation) channelShortNames = [ channelName.replace(' ', '') for channelName in channelNames ] channelIDs = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=channelShortNames) return channelIDs
def read_data(): """Read in data used in tests """ label = mne.read_label(fname_label) events = mne.read_events(fname_event)[:10] raw = mne.fiff.Raw(fname_raw, preload=False) forward = mne.read_forward_solution(fname_fwd) forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True) forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True) event_id, tmin, tmax = 1, -0.11, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() # Computing the data and noise cross-spectral density matrices data_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=0.04, tmax=None, fmin=8, fmax=12) noise_csd = compute_epochs_csd(epochs, mode='multitaper', tmin=None, tmax=0.0, fmin=8, fmax=12) return raw, epochs, evoked, data_csd, noise_csd, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def test_lcmv_raw(): """Test LCMV with raw data """ raw, _, _, _, noise_cov, label, forward, _, _, _ =\ _get_data(all_forward=False, epochs=False, data_cov=False) tmin, tmax = 0, 20 start, stop = raw.time_as_index([tmin, tmax]) # use only the left-temporal MEG channels for LCMV left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, exclude='bads', selection=left_temporal_channels) data_cov = mne.compute_raw_data_covariance(raw, tmin=tmin, tmax=tmax) stc = lcmv_raw(raw, forward, noise_cov, data_cov, reg=0.01, label=label, start=start, stop=stop, picks=picks) assert_array_almost_equal(np.array([tmin, tmax]), np.array([stc.times[0], stc.times[-1]]), decimal=2) # make sure we get an stc with vertices only in the lh vertno = [forward['src'][0]['vertno'], forward['src'][1]['vertno']] assert_true( len(stc.vertno[0]) == len(np.intersect1d(vertno[0], label.vertices))) assert_true(len(stc.vertno[1]) == 0)
def global_RMS(sub, session, baseline=500, selection="Vertex"): """ make global RMS baseline is in indexes """ f_load = "sub_%d_%s_tsss_mc_epochs.fif" % (sub, session) epochs = mne.read_epochs(f_load) if selection is not None: selection = mne.viz._clean_names(mne.read_selection(selection)) data_picks = mne.epochs.pick_types(epochs.info, meg='grad', exclude='bads', selection=None) else: data_picks = mne.epochs.pick_types(epochs.info, meg='grad', exclude='bads') data = epochs.get_data()[:, data_picks, :] data = np.sqrt(np.square(data.mean(axis=0))) data = data.mean(axis=0) baseline_std = data[:baseline].std().mean() grms = data/baseline_std return grms
def test_read_selection(): """Test reading of selections""" # test one channel for each selection ch_names = [ "MEG 2211", "MEG 0223", "MEG 1312", "MEG 0412", "MEG 1043", "MEG 2042", "MEG 2032", "MEG 0522", "MEG 1031", ] sel_names = [ "Vertex", "Left-temporal", "Right-temporal", "Left-parietal", "Right-parietal", "Left-occipital", "Right-occipital", "Left-frontal", "Right-frontal", ] for i, name in enumerate(sel_names): sel = read_selection(name) assert ch_names[i] in sel # test some combinations all_ch = read_selection(["L", "R"]) left = read_selection("L") right = read_selection("R") assert len(all_ch) == len(left) + len(right) assert len(set(left).intersection(set(right))) == 0 frontal = read_selection("frontal") occipital = read_selection("Right-occipital") assert len(set(frontal).intersection(set(occipital))) == 0
############################################################################### # Plot a cleaned PSD # ------------------ # # Next we'll focus the visualization on a subset of channels. # This can be useful for identifying particularly noisy channels or # investigating how the power spectrum changes across channels. # # We'll visualize how this PSD changes after applying some standard # filtering techniques. We'll first apply the SSP projections, which is # accomplished with the ``proj=True`` kwarg. We'll then perform a notch filter # to remove particular frequency bands. # Pick MEG magnetometers in the Left-temporal region selection = read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=selection) # Let's just look at the first few channels for demonstration purposes picks = picks[:4] plt.figure() ax = plt.axes() raw.plot_psd(tmin=tmin, tmax=tmax,
] ] if not all(filesExist): allFilesExist = False if not allFilesExist: for subjectID, subject in enumerate(group): ############################################################################### # Read epochs for the channel of interest epoch1_fname = data_path + '/' + subject + '/filtered_Obj-epo.fif' epoch2_fname = data_path + '/' + subject + '/filtered_Subj-epo.fif' epochs1 = mne.read_epochs(fname=epoch1_fname) epochs2 = mne.read_epochs(fname=epoch2_fname) for region in regions: channelNames = mne.read_selection(region) channelShortNames = [ channelName.replace(' ', '') for channelName in channelNames ] channelIDs = mne.pick_types(raw.info, meg=sensor, eeg=False, eog=False, stim=False, selection=channelShortNames) if region not in condition1: condition1[region] = [] if region not in condition2: condition2[region] = [] if sensor == 'grad':
noise_fname = data_path + '/MEG/sample/ernoise_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif' fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' subjects_dir = data_path + '/subjects' label_name = 'Aud-lh' fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name ############################################################################### # Read raw data, preload to allow filtering raw = Raw(raw_fname, preload=True) raw.info['bads'] = ['MEG 2443'] # 1 bad MEG channel # Pick a selection of magnetometer channels. A subset of all channels was used # to speed up the example. For a solution based on all MEG channels use # meg=True, selection=None and add grad=4000e-13 to the reject dictionary. left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=left_temporal_channels) reject = dict(mag=4e-12) # Read epochs. Note that preload is set to False to enable tf_lcmv to read the # underlying raw object from epochs.raw, which would be set to None during # preloading. Filtering is then performed on raw data in tf_lcmv and the epochs # parameters passed here are used to create epochs from filtered data. However, # reading epochs without preloading means that bad epoch rejection is delayed # until later. To perform bad epoch rejection based on the reject parameter
tmin, tmax = 0, 100 #going to use first 100 of training data raw = mne.io.read_raw_fif(raw_fname) raw = raw.crop(tmin, tmax) raw.info['bads'] = ['EEGn1','EEGn2'] #the numbers of the channels will be filtered out at fmin, fmax = 10, 300 #choose the frequency values we look to inspect power_fft = 2048 #the FFT size (number of size of professor) #region name tat we will be filtering out region_name = 'Left-Temporal' #wherever the region of the brain where commands are given #pick a subset of channels(here for a speed reason{) selection = mne.read_selection(region_name) picks = mne.pick_types(raw.info,meg=False,eeg=True,eog=False,stim=False,exclude='bads',selection=selection) raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False) sampling_rate = 400 #how much to be determined # EEGsize1 = tbd depends on how much data # EEGsize2 = tbd depends on how much data # EEGsize3 = tbd depends on how much data highPassFilter = False #choose what type of filter you want if(highPassFilter):
#n_times = len(epochs_plan.times) # Take only the data channels (here the gradiometers) #data_picks = fiff.pick_types(epochs_plan.info, meg='grad', exclude='bads') # Make arrays X and y such that : # X is 3d with X.shape[0] is the total number of epochs to classify # y is filled with integers coding for the class to predict # We must have X.shape[0] equal to y.shape[0] #X = [e.get_data()[:, data_picks, :] for e in epochs_list] #y = [k * np.ones(len(this_X)) for k, this_X in enumerate(X)] #X = np.concatenate(X) #y = np.concatenate(y) #### setup X & y #### vertex_parietal = ["Vertex", "parietal"] selection = mne.viz._clean_names(mne.read_selection(vertex_parietal)) data_picks = mne.fiff.pick_types(sub_2_plan.info, meg='grad', exclude='bads', selection = selection) #cond_A = sub_8_classic.get_data()[:, data_picks, :] #cond_B = sub_8_plan.get_data()[:, data_picks, :] #cond_C = sub_8_interupt.get_data()[:, data_picks, :] n_trials = np.min([len(cmb_A), len(cmb_B), len(cmb_C)]) for i in range(n_trials): foo = cmb_A[i, :, :] if i == 0: X = foo.reshape(-1) else:
def test_tf_lcmv(): """Test TF beamforming based on LCMV """ fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.fiff.Raw(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) event_id, tmin, tmax = 1, -0.2, 0.2 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=False, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.drop_bad_epochs() freq_bins = [(4, 12), (15, 40)] time_windows = [(-0.1, 0.1), (0.0, 0.2)] win_lengths = [0.2, 0.2] tstep = 0.1 reg = 0.05 source_power = [] noise_covs = [] for (l_freq, h_freq), win_length in zip(freq_bins, win_lengths): raw_band = raw.copy() raw_band.filter(l_freq, h_freq, method='iir', n_jobs=1, picks=picks) epochs_band = mne.Epochs(raw_band, epochs.events, epochs.event_id, tmin=tmin, tmax=tmax, proj=True) with warnings.catch_warnings(record=True): # not enough samples noise_cov = compute_covariance(epochs_band, tmin=tmin, tmax=tmin + win_length) noise_cov = mne.cov.regularize(noise_cov, epochs_band.info, mag=reg, grad=reg, eeg=reg, proj=True) noise_covs.append(noise_cov) del raw_band # to save memory # Manually calculating source power in on frequency band and several # time windows to compare to tf_lcmv results and test overlapping if (l_freq, h_freq) == freq_bins[0]: for time_window in time_windows: with warnings.catch_warnings(record=True): data_cov = compute_covariance(epochs_band, tmin=time_window[0], tmax=time_window[1]) stc_source_power = _lcmv_source_power(epochs.info, forward, noise_cov, data_cov, reg=reg, label=label) source_power.append(stc_source_power.data) stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label) assert_true(len(stcs) == len(freq_bins)) assert_true(stcs[0].shape[1] == 4) # Averaging all time windows that overlap the time period 0 to 100 ms source_power = np.mean(source_power, axis=0) # Selecting the first frequency bin in tf_lcmv results stc = stcs[0] # Comparing tf_lcmv results with _lcmv_source_power results assert_array_almost_equal(stc.data[:, 2], source_power[:, 0]) # Test if using unsupported max-power orientation is detected assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, pick_ori='max-power') # Test if incorrect number of noise CSDs is detected # Test if incorrect number of noise covariances is detected assert_raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin, tmax, tstep, win_lengths, freq_bins) # Test if freq_bins and win_lengths incompatibility is detected assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins) # Test if time step exceeding window lengths is detected assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins) # Test correct detection of preloaded epochs objects that do not contain # the underlying raw object epochs_preloaded = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=True) assert_raises(ValueError, tf_lcmv, epochs_preloaded, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins) with warnings.catch_warnings(record=True): # not enough samples # Pass only one epoch to test if subtracting evoked # responses yields zeros stcs = tf_lcmv(epochs[0], forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, subtract_evoked=True, reg=reg, label=label) assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
def test_tf_lcmv(): """Test TF beamforming based on LCMV.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.read_raw_fif(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) event_id, tmin, tmax = 1, -0.2, 0.2 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, selection=left_temporal_channels) picks = picks[::4] # decimate for speed raw.pick_channels([raw.ch_names[ii] for ii in picks]) raw.info.normalize_proj() # avoid projection warnings del picks # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=None, preload=False, reject=reject) epochs.load_data() freq_bins = [(4, 12), (15, 40)] time_windows = [(-0.1, 0.1), (0.0, 0.2)] win_lengths = [0.2, 0.2] tstep = 0.1 reg = 0.05 source_power = [] noise_covs = [] for (l_freq, h_freq), win_length in zip(freq_bins, win_lengths): raw_band = raw.copy() raw_band.filter(l_freq, h_freq, method='iir', n_jobs=1, iir_params=dict(output='ba')) epochs_band = mne.Epochs(raw_band, epochs.events, epochs.event_id, tmin=tmin, tmax=tmax, baseline=None, proj=True) with warnings.catch_warnings(record=True): # not enough samples noise_cov = mne.compute_covariance(epochs_band, tmin=tmin, tmax=tmin + win_length) noise_cov = mne.cov.regularize(noise_cov, epochs_band.info, mag=reg, grad=reg, eeg=reg, proj=True) noise_covs.append(noise_cov) del raw_band # to save memory # Manually calculating source power in on frequency band and several # time windows to compare to tf_lcmv results and test overlapping if (l_freq, h_freq) == freq_bins[0]: for time_window in time_windows: with warnings.catch_warnings(record=True): # bad samples data_cov = mne.compute_covariance(epochs_band, tmin=time_window[0], tmax=time_window[1]) with warnings.catch_warnings(record=True): # bad proj stc_source_power = _lcmv_source_power( epochs.info, forward, noise_cov, data_cov, reg=reg, label=label, weight_norm='unit-noise-gain') source_power.append(stc_source_power.data) pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label) stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label, raw=raw) assert (len(stcs) == len(freq_bins)) assert (stcs[0].shape[1] == 4) # Averaging all time windows that overlap the time period 0 to 100 ms source_power = np.mean(source_power, axis=0) # Selecting the first frequency bin in tf_lcmv results stc = stcs[0] # Comparing tf_lcmv results with _lcmv_source_power results assert_array_almost_equal(stc.data[:, 2], source_power[:, 0]) # Test if using unsupported max-power orientation is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, pick_ori='max-power') # Test if incorrect number of noise CSDs is detected # Test if incorrect number of noise covariances is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin, tmax, tstep, win_lengths, freq_bins) # Test if freq_bins and win_lengths incompatibility is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins) # Test if time step exceeding window lengths is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins) # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs=None, tmin=tmin, tmax=tmax, tstep=tstep, win_lengths=win_lengths, freq_bins=freq_bins) # Test if unsupported weight normalization specification is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, weight_norm='nai') # Test unsupported pick_ori (vector not supported here) with pytest.raises(ValueError, match='pick_ori must be one of'): tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, pick_ori='vector') # Test correct detection of preloaded epochs objects that do not contain # the underlying raw object epochs_preloaded = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=True) epochs_preloaded._raw = None with warnings.catch_warnings(record=True): # not enough samples pytest.raises(ValueError, tf_lcmv, epochs_preloaded, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins) with warnings.catch_warnings(record=True): # not enough samples # Pass only one epoch to test if subtracting evoked # responses yields zeros stcs = tf_lcmv(epochs[0], forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, subtract_evoked=True, reg=reg, label=label, raw=raw) assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
def test_lcmv(): """Test LCMV with evoked data and single trials """ event_id, tmin, tmax = 1, -0.1, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True) assert_array_equal(stcs[0].data, stcs_.next().data) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stc.data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label) assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
data_path = os.environ['EXPDIR'] docPath = os.environ['DOCDIR'] + 'MEG-Epochs-Conditions/' groups = [stringify(range(4,20)), stringify(range(52,72))] rawFile = os.environ['RAWDIR'] + 'dh53a/dh53a1.fif' raw = mne.fiff.Raw(rawFile) tmin = -1.0 tmax = 3.0 for group in groups: for subject in group: event1_fname = data_path + '/' + subject + '/Obj-epo.fif' event2_fname = data_path + '/' + subject + '/Subj-epo.fif' figFilename = docPath + subject + '.png' statFilename = docPath + subject + '.txt' channelNames = mne.read_selection('Left-frontal') channelShortNames = [channelName.replace(' ','') for channelName in channelNames] channelIDs = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, selection=channelShortNames) ############################################################################### # Read epochs for the channel of interest epochs1 = mne.read_epochs(fname=event1_fname) condition1 = epochs1.get_data() # as 3D matrix epochs2 = mne.read_epochs(fname=event2_fname) condition2 = epochs2.get_data() # as 3D matrix condition1 = np.mean(condition1[:, channelIDs, :],axis=1) # take only one channel to get a 2D array condition2 = np.mean(condition2[:, channelIDs, :],axis=1) # take only one channel to get a 2D array ###############################################################################
include=include, exclude='bads') # Load condition 1 event_id = 1 epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, eog=150e-6)) # just use right temporal sensors for speed epochs.pick_channels(mne.read_selection('Right-temporal')) evoked = epochs.average() # Factor to down-sample the temporal dimension of the TFR computed by # tfr_morlet. Decimation occurs after frequency decomposition and can # be used to reduce memory usage (and possibly computational time of downstream # operations such as nonparametric statistics) if you don't need high # spectrotemporal resolution. decim = 5 freqs = np.arange(8, 40, 2) # define frequencies of interest sfreq = raw.info['sfreq'] # sampling in Hz tfr_epochs = tfr_morlet(epochs, freqs, n_cycles=4., decim=decim, average=False,
for hem, hemisphere in enumerate(hemispheres): hemisphereData = {markers[0]: {}, markers[1]: {}} filesFound = True for markerID, marker in enumerate(markers): # Load average activity activityFile = os.environ[ 'EXPDIR'] + subject + '/' + marker + '_average-ave.fif' if os.path.exists(activityFile): evokedFile = mne.fiff.Evoked(fname=activityFile, condition=0, baseline=None, kind='average', verbose=False) for location in locations: channelLocation = directions[hem] + location channelNames = mne.read_selection(channelLocation) channelShortNames = [ channelName.replace(' ', '') for channelName in channelNames ] selectedChannels = mne.pick_types( evokedFile.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=channelShortNames) data = np.mean(evokedFile.data[selectedChannels, :], axis=0) hemisphereData[marker][location] = data
proj_fname = data_path + '/MEG/sample/sample_audvis_eog_proj.fif' tmin, tmax = 0, 20 # use the first 60s of data # Setup for reading the raw data raw = mne.io.read_raw_fif(raw_fname) raw.info['bads'] = ['MEG 2443', 'EEG 053'] # bads + 2 more # To save memory, crop the raw data before loading data raw.crop(tmin, tmax, copy=False).load_data() fmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2 # Pick a subset of channels (here for speed reason) selection = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=selection) # Let's first check out all channel types raw.plot_psd(area_mode='range', tmax=10.0, picks=picks) ############################################################################### # Removing power-line noise with notch filtering # ---------------------------------------------- # # Removing power-line noise can be done with a Notch filter, directly on the # Raw object, specifying an array of frequency to be cut off: raw.notch_filter(np.arange(60, 241, 60), picks=picks) raw.plot_psd(area_mode='range', tmax=10.0, picks=picks)
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True, epochs_preload=True, data_cov=True): """Read in data used in tests.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.read_raw_fif(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) if all_forward: forward_surf_ori = _read_forward_solution_meg( fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg( fname_fwd, force_fixed=True, surf_ori=True, use_cps=False) forward_vol = _read_forward_solution_meg(fname_fwd_vol) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bad channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, selection=left_temporal_channels) picks = picks[::2] # decimate for speed # add a couple channels we will consider bad bad_picks = [100, 101] bads = [raw.ch_names[pick] for pick in bad_picks] assert not any(pick in picks for pick in bad_picks) picks = np.concatenate([picks, bad_picks]) raw.pick_channels([raw.ch_names[ii] for ii in picks]) del picks raw.info['bads'] = bads # add more bads raw.info.normalize_proj() # avoid projection warnings if epochs: # Read epochs epochs = mne.Epochs( raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=epochs_preload, reject=reject) if epochs_preload: epochs.resample(200, npad=0, n_jobs=2) epochs.crop(0, None) evoked = epochs.average() info = evoked.info else: epochs = None evoked = None info = raw.info noise_cov = mne.read_cov(fname_cov) noise_cov['projs'] = [] # avoid warning noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05, eeg=0.1, proj=True, rank=None) if data_cov: data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.145) else: data_cov = None return raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
############################################################################### # Set parameters data_path = sample.data_path("..") raw_fname = data_path + "/MEG/sample/sample_audvis_raw.fif" proj_fname = data_path + "/MEG/sample/sample_audvis_eog_proj.fif" # Setup for reading the raw data raw = fiff.Raw(raw_fname) exclude = raw.info["bads"] + ["MEG 2443", "EEG 053"] # bads + 2 more # Add SSP projection vectors to reduce EOG and ECG artifacts projs = read_proj(proj_fname) raw.add_proj(projs, remove_existing=True) # Pick MEG magnetometers in the Left-temporal region selection = read_selection("Left-temporal") picks = fiff.pick_types(raw.info, meg="mag", eeg=False, eog=False, stim=False, exclude=exclude, selection=selection) tmin, tmax = 0, 60 # use the first 60s of data fmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz NFFT = 2048 # the FFT size (NFFT). Ideally a power of 2 psds, freqs = compute_raw_psd( raw, tmin=tmin, tmax=tmax, picks=picks, fmin=fmin, fmax=fmax, NFFT=NFFT, n_jobs=1, plot=False, proj=False ) # And now do the same with SSP applied psds_ssp, freqs = compute_raw_psd( raw, tmin=tmin, tmax=tmax, picks=picks, fmin=fmin, fmax=fmax, NFFT=NFFT, n_jobs=1, plot=False, proj=True ) # Convert PSDs to dB
raw_sss.plot_psd(fmax=100) ##..........................................................................## ## Band-pass Filter ## tmin, tmax = 0, 20 # use the first 20s of data # Setup for reading the raw data (save memory by cropping the raw data # before loading it) raw_sss.crop(tmin, tmax).load_data() raw_sss.info['bads'] = ['MEG 2443', 'EEG 053'] # bads + 2 more n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2 # Pick a subset of channels (here for speed reasons) selection = mne.read_selection('Left-temporal') picks = mne.pick_types(raw_sss.info, meg=True, eeg=True, eog=False, stim=False, exclude='bads', selection=selection) raw_sss.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False) # Low-pass Filter raw_sss.filter(None, 58., fir_design='firwin') raw_sss.plot_psd(fmax=100, area_mode='range', tmax=10.0, average=False) #raw_sss.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False)
from mne import read_selection from mne import pick_channels import matplotlib.pyplot as plt import mne.time_frequency as tf import mne.io as io import sys import numpy as np import os.path as pth fname_B=sys.argv[1] fname_A=sys.argv[2] Raw_B=io.read_raw_fif(fname_B, preload=True) Raw_A=io.read_raw_fif(fname_A, preload=True) sel=read_selection(ch_selection, info=Raw_B.info) Raw_B.pick_channels(sel) sel=read_selection(ch_selection, info=Raw_A.info) Raw_A.pick_channels(sel) Raw_B.pick_types(meg=meg) Raw_A.pick_types(meg=meg) psd_B, freqs = tf.psd_welch(Raw_B, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, proj=False, n_fft=1000, n_overlap=500) psd_A, freqs = tf.psd_welch(Raw_A, tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, proj=False, n_fft=1000, n_overlap=500) mpsd_B=np.mean(psd_B, axis=0) mpsd_A=np.mean(psd_A, axis=0) plt.plot(freqs, mpsd_B, freqs, mpsd_A) plt.legend(('before' ,'after')) plt.xlabel('Frequency')
sessions2 = mne.Epochs(raws, events, event_id=None, tmin=0., tmax=tDur, proj=True, baseline=None, reject=None, detrend=1) yyy = sessions2.get_data() plt.plot(np.mean(yyy[:, 201, :], axis=0), 'r-') #%% temp_selection = mne.read_selection('Left-occipital') selection = [] for i in np.arange(0, len(temp_selection)): selection.append(temp_selection[i][:3] + temp_selection[i][4:]) picks = mne.pick_types(raw1.info, meg='mag', eeg=False, eog=False, selection=['MEG1941', 'MEG1942', 'MEG1943']) #['MEG1641','MEG1642','MEG1643','MEG1941','MEG1942','MEG1943','MEG1731','MEG1732','MEG1733'] #%% # Let's just look at the first few channels for demonstration purposes #picks = picks[:4]
evoked = epochs[name].average() return evoked except: return None left = joblib.Parallel(n_jobs=5)( joblib.delayed(get_evoked)(_id, 'L_CUE') for _id in good_ids) left = [i for i in left if i!=None] right = joblib.Parallel(n_jobs=5)( joblib.delayed(get_evoked)(_id, 'R_CUE') for _id in good_ids) right = [i for i in right if i!=None] neutral = joblib.Parallel(n_jobs=5)( joblib.delayed(get_evoked)(_id, 'N_CUE') for _id in good_ids) neutral = [i for i in neutral if i!=None] #%% have a look sel = mne.read_selection(name='Left-occipital', info=left[1].info) mne.viz.plot_compare_evokeds({'Left':left, 'Right':right, 'Neutral':neutral}, picks=sel, combine='mean', show_sensors=True, title='Post cue - Left') sel = mne.read_selection(name='Right-occipital', info=left[1].info) mne.viz.plot_compare_evokeds({'Left':left, 'Right':right, 'Neutral':neutral}, picks=sel, combine='mean', show_sensors=True, title='Post cue - Right') #%% Sort out per participant data
n_fft = 2000 raw_file = argv[1] ch_sets = [ 'Left-temporal', 'Right-temporal', 'Left-parietal', 'Right-parietal', 'Left-occipital', 'Right-occipital', 'Left-frontal', 'Right-frontal', 'Vertex' ] Raw = mne.io.read_raw_fif(raw_file, preload=True) Raw.pick_types(meg=ch_type) fig = plt.figure() fig.suptitle(raw_file) nn = 0 for ch_set in ch_sets: ch_sel = mne.read_selection(ch_set, info=Raw.info) picks = mne.pick_channels(Raw.info['ch_names'], ch_sel) nn += 1 ax = plt.subplot(5, 2, nn) ax.set_title(ch_set) ax.set_xlim((0, 100)) Raw.plot_psd(fmin=fmin, fmax=fmax, n_fft=n_fft, ax=ax, proj=False, picks=picks, area_mode='std', show=False, average=True) plt.show()
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True, epochs_preload=True, data_cov=True): """Read in data used in tests """ label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.Raw(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) if all_forward: forward_surf_ori = mne.read_forward_solution(fname_fwd, surf_ori=True) forward_fixed = mne.read_forward_solution(fname_fwd, force_fixed=True, surf_ori=True) forward_vol = mne.read_forward_solution(fname_fwd_vol, surf_ori=True) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels if epochs: # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, ref_meg=False, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=epochs_preload, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) if epochs_preload: epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() info = evoked.info else: epochs = None evoked = None info = raw.info noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05, eeg=0.1, proj=True) if data_cov: data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) else: data_cov = None return raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def _get_data(tmin=-0.1, tmax=0.15, all_forward=True, epochs=True, epochs_preload=True, data_cov=True, proj=True): """Read in data used in tests.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.read_raw_fif(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) if all_forward: forward_surf_ori = _read_forward_solution_meg( fname_fwd, surf_ori=True) forward_fixed = _read_forward_solution_meg( fname_fwd, force_fixed=True, surf_ori=True, use_cps=False) forward_vol = _read_forward_solution_meg(fname_fwd_vol) else: forward_surf_ori = None forward_fixed = None forward_vol = None event_id, tmin, tmax = 1, tmin, tmax # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bad channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, selection=left_temporal_channels) picks = picks[::2] # decimate for speed # add a couple channels we will consider bad bad_picks = [100, 101] bads = [raw.ch_names[pick] for pick in bad_picks] assert not any(pick in picks for pick in bad_picks) picks = np.concatenate([picks, bad_picks]) raw.pick_channels([raw.ch_names[ii] for ii in picks]) del picks raw.info['bads'] = bads # add more bads if proj: raw.info.normalize_proj() # avoid projection warnings else: raw.del_proj() if epochs: # Read epochs epochs = mne.Epochs( raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=epochs_preload, reject=reject) if epochs_preload: epochs.resample(200, npad=0) epochs.crop(0, None) evoked = epochs.average() info = evoked.info else: epochs = None evoked = None info = raw.info noise_cov = mne.read_cov(fname_cov) noise_cov['projs'] = [] # avoid warning noise_cov = mne.cov.regularize(noise_cov, info, mag=0.05, grad=0.05, eeg=0.1, proj=True, rank=None) if data_cov: data_cov = mne.compute_covariance( epochs, tmin=0.04, tmax=0.145, verbose='error') # baseline warning else: data_cov = None return raw, epochs, evoked, data_cov, noise_cov, label, forward,\ forward_surf_ori, forward_fixed, forward_vol
def test_lcmv(): """Test LCMV with evoked data and single trials """ event_id, tmin, tmax = 1, -0.1, 0.15 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: EEG + MEG - bad channels (modify to your needs) left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=(None, 0), preload=True, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.resample(200, npad=0, n_jobs=2) evoked = epochs.average() noise_cov = mne.read_cov(fname_cov) noise_cov = mne.cov.regularize(noise_cov, evoked.info, mag=0.05, grad=0.05, eeg=0.1, proj=True) data_cov = mne.compute_covariance(epochs, tmin=0.04, tmax=0.15) stc = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01) stc_pow = np.sum(stc.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Test picking normal orientation stc_normal = lcmv(evoked, forward_surf_ori, noise_cov, data_cov, reg=0.01, pick_ori="normal") stc_pow = np.sum(np.abs(stc_normal.data), axis=1) idx = np.argmax(stc_pow) max_stc = stc_normal.data[idx] tmax = stc_normal.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.11) assert_true(1. < np.max(max_stc) < 2.) # The amplitude of normal orientation results should always be smaller than # free orientation results assert_true((np.abs(stc_normal.data) <= stc.data).all()) # Test picking source orientation maximizing output source power stc_max_power = lcmv(evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="max-power") stc_pow = np.sum(stc_max_power.data, axis=1) idx = np.argmax(stc_pow) max_stc = stc_max_power.data[idx] tmax = stc.times[np.argmax(max_stc)] assert_true(0.09 < tmax < 0.1) assert_true(2. < np.max(max_stc) < 3.) # Maximum output source power orientation results should be similar to free # orientation results assert_true((stc_max_power.data - stc.data < 0.5).all()) # Test if fixed forward operator is detected when picking normal or # max-power orientation assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="normal") assert_raises(ValueError, lcmv, evoked, forward_fixed, noise_cov, data_cov, reg=0.01, pick_ori="max-power") # Test if non-surface oriented forward operator is detected when picking # normal orientation assert_raises(ValueError, lcmv, evoked, forward, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Test if volume forward operator is detected when picking normal # orientation assert_raises(ValueError, lcmv, evoked, forward_vol, noise_cov, data_cov, reg=0.01, pick_ori="normal") # Now test single trial using fixed orientation forward solution # so we can compare it to the evoked solution stcs = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01) stcs_ = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, return_generator=True) assert_array_equal(stcs[0].data, stcs_.next().data) epochs.drop_bad_epochs() assert_true(len(epochs.events) == len(stcs)) # average the single trial estimates stc_avg = np.zeros_like(stc.data) for this_stc in stcs: stc_avg += this_stc.data stc_avg /= len(stcs) # compare it to the solution using evoked with fixed orientation stc_fixed = lcmv(evoked, forward_fixed, noise_cov, data_cov, reg=0.01) assert_array_almost_equal(stc_avg, stc_fixed.data) # use a label so we have few source vertices and delayed computation is # not used stcs_label = lcmv_epochs(epochs, forward_fixed, noise_cov, data_cov, reg=0.01, label=label) assert_array_almost_equal(stcs_label[0].data, stcs[0].in_label(label).data)
def test_tf_lcmv(): """Test TF beamforming based on LCMV """ fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.Raw(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) event_id, tmin, tmax = 1, -0.2, 0.2 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=True, eog=True, exclude='bads', selection=left_temporal_channels) # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=False, reject=dict(grad=4000e-13, mag=4e-12, eog=150e-6)) epochs.drop_bad_epochs() freq_bins = [(4, 12), (15, 40)] time_windows = [(-0.1, 0.1), (0.0, 0.2)] win_lengths = [0.2, 0.2] tstep = 0.1 reg = 0.05 source_power = [] noise_covs = [] for (l_freq, h_freq), win_length in zip(freq_bins, win_lengths): raw_band = raw.copy() raw_band.filter(l_freq, h_freq, method='iir', n_jobs=1, picks=picks) epochs_band = mne.Epochs(raw_band, epochs.events, epochs.event_id, tmin=tmin, tmax=tmax, baseline=None, proj=True) with warnings.catch_warnings(record=True): # not enough samples noise_cov = compute_covariance(epochs_band, tmin=tmin, tmax=tmin + win_length) noise_cov = mne.cov.regularize(noise_cov, epochs_band.info, mag=reg, grad=reg, eeg=reg, proj=True) noise_covs.append(noise_cov) del raw_band # to save memory # Manually calculating source power in on frequency band and several # time windows to compare to tf_lcmv results and test overlapping if (l_freq, h_freq) == freq_bins[0]: for time_window in time_windows: with warnings.catch_warnings(record=True): data_cov = compute_covariance(epochs_band, tmin=time_window[0], tmax=time_window[1]) stc_source_power = _lcmv_source_power(epochs.info, forward, noise_cov, data_cov, reg=reg, label=label) source_power.append(stc_source_power.data) stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label) assert_true(len(stcs) == len(freq_bins)) assert_true(stcs[0].shape[1] == 4) # Averaging all time windows that overlap the time period 0 to 100 ms source_power = np.mean(source_power, axis=0) # Selecting the first frequency bin in tf_lcmv results stc = stcs[0] # Comparing tf_lcmv results with _lcmv_source_power results assert_array_almost_equal(stc.data[:, 2], source_power[:, 0]) # Test if using unsupported max-power orientation is detected assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, pick_ori='max-power') # Test if incorrect number of noise CSDs is detected # Test if incorrect number of noise covariances is detected assert_raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin, tmax, tstep, win_lengths, freq_bins) # Test if freq_bins and win_lengths incompatibility is detected assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins) # Test if time step exceeding window lengths is detected assert_raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins) # Test correct detection of preloaded epochs objects that do not contain # the underlying raw object epochs_preloaded = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=True) assert_raises(ValueError, tf_lcmv, epochs_preloaded, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins) with warnings.catch_warnings(record=True): # not enough samples # Pass only one epoch to test if subtracting evoked # responses yields zeros stcs = tf_lcmv(epochs[0], forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, subtract_evoked=True, reg=reg, label=label) assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))
# We create an :class:`mne.Epochs` object containing two trials: one with # both noise and signal and one with just noise t0 = raw.first_samp # First sample in the data t1 = t0 + n_times - 1 # Sample just before the second trial epochs = mne.Epochs( raw, events=np.array([[t0, 0, 1], [t1, 0, 2]]), event_id=dict(signal=1, noise=2), tmin=0, tmax=10, preload=True, ) # Plot some of the channels of the simulated data that are situated above one # of our simulated sources. picks = mne.pick_channels(epochs.ch_names, mne.read_selection('Left-frontal')) epochs.plot(picks=picks) ############################################################################### # Power mapping # ------------- # With our simulated dataset ready, we can now pretend to be researchers that # have just recorded this from a real subject and are going to study what parts # of the brain communicate with each other. # # First, we'll create a source estimate of the MEG data. We'll use both a # straightforward MNE-dSPM inverse solution for this, and the DICS beamformer # which is specifically designed to work with oscillatory data. ############################################################################### # Computing the inverse using MNE-dSPM:
# both noise and signal and one with just noise t0 = raw.first_samp # First sample in the data t1 = t0 + n_times - 1 # Sample just before the second trial epochs = mne.Epochs( raw, events=np.array([[t0, 0, 1], [t1, 0, 2]]), event_id=dict(signal=1, noise=2), tmin=0, tmax=10, preload=True, ) # Plot some of the channels of the simulated data that are situated above one # of our simulated sources. picks = mne.pick_channels(epochs.ch_names, mne.read_selection('Left-frontal')) epochs.plot(picks=picks) ############################################################################### # Power mapping # ------------- # With our simulated dataset ready, we can now pretend to be researchers that # have just recorded this from a real subject and are going to study what parts # of the brain communicate with each other. # # First, we'll create a source estimate of the MEG data. We'll use both a # straightforward MNE-dSPM inverse solution for this, and the DICS beamformer # which is specifically designed to work with oscillatory data. ############################################################################### # Computing the inverse using MNE-dSPM:
print(raw) print("sfreq:", raw.info['sfreq']) def ch_names_to_types(ch_names): ch_types = [] for ch in ch_names: _ch = int(ch[-1:]) if _ch == 1: ch_types.append('mag') if _ch == 2 or _ch == 3: ch_types.append('grad') return ch_types selection = mne.read_selection('Right-temporal') ch_names = selection ch_types = ch_names_to_types(ch_names) print("ch_names", ch_names) print( "ch_types:", ch_types ) #"kind must be one of ['ecg', 'bio', 'hbo', 'stim', 'eog', 'emg', 'ref_meg', 'misc', 'ecog', 'seeg', 'mag', 'eeg', 'grad', 'hbr'] sfreq = raw.info['sfreq'] picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=False, stim=False, selection=selection)
raw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more # Add SSP projection vectors to reduce EOG and ECG artifacts projs = read_proj(proj_fname) raw.add_proj(projs, remove_existing=True) fmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2 # Let's first check out all channel types raw.plot_psd(area_mode='range', tmax=10.0, show=False) # Now let's focus on a smaller subset: # Pick MEG magnetometers in the Left-temporal region selection = read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=selection) # Let's just look at the first few channels for demonstration purposes picks = picks[:4] plt.figure() ax = plt.axes() raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft, n_jobs=1, proj=False, ax=ax, color=(0, 0, 1), picks=picks, show=False) # And now do the same with SSP applied raw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft, n_jobs=1, proj=True, ax=ax, color=(0, 1, 0), picks=picks,
@author: mje @email: mads [] cnru.dk """ from my_settings import (epochs_folder, tf_folder) import numpy as np import mne import sys import matplotlib.pyplot as plt subject = sys.argv[1] epochs = mne.read_epochs( epochs_folder + "%s_trial_start-epo.fif" % subject, preload=False) selection = mne.read_selection("Left-occipital") selection = [f.replace(' ', '') for f in selection] left_idx = mne.pick_types( epochs.info, meg="grad", eeg=False, eog=False, stim=False, exclude=[], selection=selection) selection = mne.read_selection("Right-occipital") selection = [f.replace(' ', '') for f in selection] right_idx = mne.pick_types( epochs.info, meg="grad",
noise_fname = data_path + '/MEG/sample/ernoise_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif' fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' subjects_dir = data_path + '/subjects' label_name = 'Aud-lh' fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name ############################################################################### # Read raw data, preload to allow filtering raw = Raw(raw_fname, preload=True) raw.info['bads'] = ['MEG 2443'] # 1 bad MEG channel # Pick a selection of magnetometer channels. A subset of all channels was used # to speed up the example. For a solution based on all MEG channels use # meg=True, selection=None and add grad=4000e-13 to the reject dictionary. left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=left_temporal_channels) reject = dict(mag=4e-12) # Setting time limits for reading epochs. Note that tmin and tmax are set so # that time-frequency beamforming will be performed for a wider range of time # points than will later be displayed on the final spectrogram. This ensures # that all time bins displayed represent an average of an equal number of time # windows. tmin, tmax = -0.55, 0.75 # s tmin_plot, tmax_plot = -0.3, 0.5 # s # Read epochs. Note that preload is set to False to enable tf_lcmv to read the # underlying raw object from epochs.raw, which would be set to None during
def test_tf_lcmv(): """Test TF beamforming based on LCMV.""" label = mne.read_label(fname_label) events = mne.read_events(fname_event) raw = mne.io.read_raw_fif(fname_raw, preload=True) forward = mne.read_forward_solution(fname_fwd) event_id, tmin, tmax = 1, -0.2, 0.2 # Setup for reading the raw data raw.info['bads'] = ['MEG 2443', 'EEG 053'] # 2 bads channels # Set up pick list: MEG - bad channels left_temporal_channels = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, selection=left_temporal_channels) picks = picks[::2] # decimate for speed raw.pick_channels([raw.ch_names[ii] for ii in picks]) raw.info.normalize_proj() # avoid projection warnings del picks # Read epochs epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=None, preload=False, reject=reject) epochs.load_data() freq_bins = [(4, 12), (15, 40)] time_windows = [(-0.1, 0.1), (0.0, 0.2)] win_lengths = [0.2, 0.2] tstep = 0.1 reg = 0.05 source_power = [] noise_covs = [] for (l_freq, h_freq), win_length in zip(freq_bins, win_lengths): raw_band = raw.copy() raw_band.filter(l_freq, h_freq, method='iir', n_jobs=1, iir_params=dict(output='ba')) epochs_band = mne.Epochs( raw_band, epochs.events, epochs.event_id, tmin=tmin, tmax=tmax, baseline=None, proj=True) noise_cov = mne.compute_covariance( epochs_band, tmin=tmin, tmax=tmin + win_length) noise_cov = mne.cov.regularize( noise_cov, epochs_band.info, mag=reg, grad=reg, eeg=reg, proj=True) noise_covs.append(noise_cov) del raw_band # to save memory # Manually calculating source power in on frequency band and several # time windows to compare to tf_lcmv results and test overlapping if (l_freq, h_freq) == freq_bins[0]: for time_window in time_windows: data_cov = mne.compute_covariance( epochs_band, tmin=time_window[0], tmax=time_window[1]) stc_source_power = _lcmv_source_power( epochs.info, forward, noise_cov, data_cov, reg=reg, label=label, weight_norm='unit-noise-gain') source_power.append(stc_source_power.data) pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label) stcs = tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, reg=reg, label=label, raw=raw) assert (len(stcs) == len(freq_bins)) assert (stcs[0].shape[1] == 4) # Averaging all time windows that overlap the time period 0 to 100 ms source_power = np.mean(source_power, axis=0) # Selecting the first frequency bin in tf_lcmv results stc = stcs[0] # Comparing tf_lcmv results with _lcmv_source_power results assert_array_almost_equal(stc.data[:, 2], source_power[:, 0]) # Test if using unsupported max-power orientation is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins=freq_bins, pick_ori='max-power') # Test if incorrect number of noise CSDs is detected # Test if incorrect number of noise covariances is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, [noise_covs[0]], tmin, tmax, tstep, win_lengths, freq_bins) # Test if freq_bins and win_lengths incompatibility is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths=[0, 1, 2], freq_bins=freq_bins) # Test if time step exceeding window lengths is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep=0.15, win_lengths=[0.2, 0.1], freq_bins=freq_bins) # Test if missing of noise covariance matrix is detected when more than # one channel type is present in the data pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs=None, tmin=tmin, tmax=tmax, tstep=tstep, win_lengths=win_lengths, freq_bins=freq_bins) # Test if unsupported weight normalization specification is detected pytest.raises(ValueError, tf_lcmv, epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, weight_norm='nai') # Test unsupported pick_ori (vector not supported here) with pytest.raises(ValueError, match='pick_ori must be one of'): tf_lcmv(epochs, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, pick_ori='vector') # Test correct detection of preloaded epochs objects that do not contain # the underlying raw object epochs_preloaded = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, baseline=(None, 0), preload=True) epochs_preloaded._raw = None pytest.raises(ValueError, tf_lcmv, epochs_preloaded, forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins) # Pass only one epoch to test if subtracting evoked # responses yields zeros with pytest.warns(RuntimeWarning, match='Too few samples .* estimate may be unreliable'): stcs = tf_lcmv(epochs[0], forward, noise_covs, tmin, tmax, tstep, win_lengths, freq_bins, subtract_evoked=True, reg=reg, label=label, raw=raw) assert_array_almost_equal(stcs[0].data, np.zeros_like(stcs[0].data))