def test_io_layout(): """Test IO with .lout files""" layout = read_layout('Vectorview-all', scale=False) layout.save('foobar.lout') layout_read = read_layout('foobar.lout', path='./', scale=False) assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2) assert_true(layout.names, layout_read.names)
def test_make_eeg_layout(): """ Test creation of EEG layout """ tmp_name = 'foo' lout_name = 'test_raw' lout_orig = read_layout(kind=lout_name, path=lout_path) info = Raw(fif_fname).info layout = make_eeg_layout(info) layout.save(op.join(tempdir, tmp_name + '.lout')) lout_new = read_layout(kind=tmp_name, path=tempdir, scale=False) assert_array_equal(lout_new.kind, tmp_name) assert_allclose(layout.pos, lout_new.pos, atol=0.1) assert_array_equal(lout_orig.names, lout_new.names) # Test input validation assert_raises(ValueError, make_eeg_layout, info, radius=-0.1) assert_raises(ValueError, make_eeg_layout, info, radius=0.6) assert_raises(ValueError, make_eeg_layout, info, width=-0.1) assert_raises(ValueError, make_eeg_layout, info, width=1.1) assert_raises(ValueError, make_eeg_layout, info, height=-0.1) assert_raises(ValueError, make_eeg_layout, info, height=1.1) bad_info = info.copy() bad_info['dig'] = None assert_raises(RuntimeError, make_eeg_layout, bad_info) bad_info['dig'] = [] assert_raises(RuntimeError, make_eeg_layout, bad_info)
def test_make_eeg_layout(): """ Test creation of EEG layout """ tempdir = _TempDir() tmp_name = 'foo' lout_name = 'test_raw' lout_orig = read_layout(kind=lout_name, path=lout_path) info = Raw(fif_fname).info layout = make_eeg_layout(info) layout.save(op.join(tempdir, tmp_name + '.lout')) lout_new = read_layout(kind=tmp_name, path=tempdir, scale=False) assert_array_equal(lout_new.kind, tmp_name) assert_allclose(layout.pos, lout_new.pos, atol=0.1) assert_array_equal(lout_orig.names, lout_new.names) # Test input validation assert_raises(ValueError, make_eeg_layout, info, radius=-0.1) assert_raises(ValueError, make_eeg_layout, info, radius=0.6) assert_raises(ValueError, make_eeg_layout, info, width=-0.1) assert_raises(ValueError, make_eeg_layout, info, width=1.1) assert_raises(ValueError, make_eeg_layout, info, height=-0.1) assert_raises(ValueError, make_eeg_layout, info, height=1.1) bad_info = info.copy() bad_info['dig'] = None assert_raises(RuntimeError, make_eeg_layout, bad_info) bad_info['dig'] = [] assert_raises(RuntimeError, make_eeg_layout, bad_info)
def test_io_layout_lay(): """Test IO with .lay files""" layout = read_layout('CTF151', scale=False) layout.save(op.join(tempdir, 'foobar.lay')) layout_read = read_layout(op.join(tempdir, 'foobar.lay'), path='./', scale=False) assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2) assert_true(layout.names, layout_read.names)
def test_io_layout_lout(): """Test IO with .lout files""" layout = read_layout('Vectorview-all', scale=False) layout.save(op.join(tempdir, 'foobar.lout')) layout_read = read_layout(op.join(tempdir, 'foobar.lout'), path='./', scale=False) assert_array_almost_equal(layout.pos, layout_read.pos, decimal=2) assert_true(layout.names, layout_read.names) print(layout) # test repr
def test_make_grid_layout(): """ Test creation of grid layout """ tmp_name = 'bar' lout_name = 'test_ica' lout_orig = read_layout(kind=lout_name, path=lout_path) layout = make_grid_layout(test_info) layout.save(op.join(tempdir, tmp_name + '.lout')) lout_new = read_layout(kind=tmp_name, path=tempdir) assert_array_equal(lout_new.kind, tmp_name) assert_array_equal(lout_orig.pos, lout_new.pos) assert_array_equal(lout_orig.names, lout_new.names)
def test_make_eeg_layout(): """ Test creation of EEG layout """ tmp_name = 'foo' lout_name = 'test_raw' lout_orig = read_layout(kind=lout_name, path=lout_path) layout = make_eeg_layout(Raw(fif_fname).info) layout.save(op.join(tempdir, tmp_name + '.lout')) lout_new = read_layout(kind=tmp_name, path=tempdir) assert_array_equal(lout_new.kind, tmp_name) assert_array_equal(lout_orig.pos, lout_new.pos) assert_array_equal(lout_orig.names, lout_new.names)
def test_plot_topo(): """Test plotting of ERP topography """ layout = read_layout('Vectorview-all') # Show topography plot_topo(evoked, layout)
def test_make_grid_layout(): """ Test creation of grid layout """ tmp_name = 'bar' lout_name = 'test_ica' lout_orig = read_layout(kind=lout_name, path=lout_path) layout = make_grid_layout(test_info) layout.save(op.join(tempdir, tmp_name + '.lout')) lout_new = read_layout(kind=tmp_name, path=tempdir) assert_array_equal(lout_new.kind, tmp_name) assert_array_equal(lout_orig.pos, lout_new.pos) assert_array_equal(lout_orig.names, lout_new.names) # Test creating grid layout with specified number of columns layout = make_grid_layout(test_info, n_col=2) # Vertical positions should be equal assert_true(layout.pos[0, 1] == layout.pos[1, 1]) # Horizontal positions should be unequal assert_true(layout.pos[0, 0] != layout.pos[1, 0]) # Box sizes should be equal assert_array_equal(layout.pos[0, 3:], layout.pos[1, 3:])
def test_make_grid_layout(): """ Test creation of grid layout """ tempdir = _TempDir() tmp_name = 'bar' lout_name = 'test_ica' lout_orig = read_layout(kind=lout_name, path=lout_path) layout = make_grid_layout(test_info) layout.save(op.join(tempdir, tmp_name + '.lout')) lout_new = read_layout(kind=tmp_name, path=tempdir) assert_array_equal(lout_new.kind, tmp_name) assert_array_equal(lout_orig.pos, lout_new.pos) assert_array_equal(lout_orig.names, lout_new.names) # Test creating grid layout with specified number of columns layout = make_grid_layout(test_info, n_col=2) # Vertical positions should be equal assert_true(layout.pos[0, 1] == layout.pos[1, 1]) # Horizontal positions should be unequal assert_true(layout.pos[0, 0] != layout.pos[1, 0]) # Box sizes should be equal assert_array_equal(layout.pos[0, 3:], layout.pos[1, 3:])
T0, p_values, H0 = permutation_t_test(data, n_permutations, n_jobs=2) significant_sensors = picks[p_values <= 0.05] significant_sensors_names = [raw.info["ch_names"][k] for k in significant_sensors] print "Number of significant sensors : %d" % len(significant_sensors) print "Sensors names : %s" % significant_sensors_names ############################################################################### # View location of significantly active sensors import pylab as pl # load sensor layout from mne.layouts import read_layout layout = read_layout("Vectorview-grad") # Extract mask and indices of active sensors in layout idx_of_sensors = [layout.names.index(name) for name in significant_sensors_names if name in layout.names] mask_significant_sensors = np.zeros(len(layout.pos), dtype=np.bool) mask_significant_sensors[idx_of_sensors] = True mask_non_significant_sensors = mask_significant_sensors == False # plot it pl.figure(facecolor="k") pl.axis("off") pl.axis("tight") pl.scatter(layout.pos[mask_significant_sensors, 0], layout.pos[mask_significant_sensors, 1], s=50, c="r") pl.scatter(layout.pos[mask_non_significant_sensors, 0], layout.pos[mask_non_significant_sensors, 1], c="w") title = "MNE sample data (Left auditory between 40 and 60 ms)" pl.figtext(0.03, 0.93, title, color="w", fontsize=18)
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) # plot CSP patterns estimated on full data for visualization csp.fit_transform(epochs_data, labels) evoked = epochs.average() evoked.data = csp.patterns_.T evoked.times = np.arange(evoked.data.shape[0]) layout = read_layout('EEG1005') evoked.plot_topomap(times=[0, 1, 2, 61, 62, 63], ch_type='eeg', layout=layout, scale_time=1, time_format='%i', scale=1, unit='Patterns (AU)', size=1.5) ############################################################################### # Look at performance over time sfreq = raw.info['sfreq'] w_length = int(sfreq * 0.5) # running classifier: window length w_step = int(sfreq * 0.1) # running classifier: window step size
picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, include=include, exclude='bads') # Create epochs including different events epochs = mne.Epochs(raw, events, dict(audio_l=1, visual_r=3), tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # Generate list of evoked objects from conditions names evokeds = [epochs[name].average() for name in 'audio_l', 'visual_r'] ############################################################################### # Show topography for two different conditions layout = read_layout('Vectorview-all.lout') pl.close('all') title = 'MNE sample data - left auditory and visual' plot_topo(evokeds, layout, color=['y', 'g'], title=title) pl.show()
T0, p_values, H0 = permutation_t_test(data, n_permutations, n_jobs=2) significant_sensors = picks[p_values <= 0.05] significant_sensors_names = [raw.info['ch_names'][k] for k in significant_sensors] print "Number of significant sensors : %d" % len(significant_sensors) print "Sensors names : %s" % significant_sensors_names ############################################################################### # View location of significantly active sensors import matplotlib.pyplot as plt # load sensor layout from mne.layouts import read_layout layout = read_layout('Vectorview-grad') # Extract mask and indices of active sensors in layout idx_of_sensors = [layout.names.index(name) for name in significant_sensors_names if name in layout.names] mask_significant_sensors = np.zeros(len(layout.pos), dtype=np.bool) mask_significant_sensors[idx_of_sensors] = True mask_non_significant_sensors = mask_significant_sensors == False # plot it plt.figure(figsize=(5, 3.5), facecolor='k') plt.axis('off') plt.scatter(layout.pos[mask_significant_sensors, 0], layout.pos[mask_significant_sensors, 1], s=50, c='r') plt.scatter(layout.pos[mask_non_significant_sensors, 0],
raw = Raw(raw_fname) events = mne.read_events(event_fname) # Set up pick list: MEG + STI 014 - bad channels (modify to your needs) include = [] # or stim channels ['STI 014'] # bad channels in raw.info['bads'] will be automatically excluded # Set up amplitude-peak rejection values for MEG channels reject = dict(grad=4000e-13, mag=4e-12) # pick MEG channels picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, include=include, exclude='bads') # Create epochs including different events epochs = mne.Epochs(raw, events, dict(audio_l=1, visual_r=3), tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # Generate list of evoked objects from conditions names evokeds = [epochs[name].average() for name in 'audio_l', 'visual_r'] ############################################################################### # Show topography for two different conditions layout = read_layout('Vectorview-all.lout') pl.close('all') title = 'MNE sample data - left auditory and visual' plot_topo(evokeds, layout, color=['y', 'g'], title=title) pl.show()
T0, p_values, H0 = permutation_t_test(data, n_permutations, n_jobs=2) significant_sensors = picks[p_values <= 0.05] significant_sensors_names = [raw.info['ch_names'][k] for k in significant_sensors] print "Number of significant sensors : %d" % len(significant_sensors) print "Sensors names : %s" % significant_sensors_names ############################################################################### # View location of significantly active sensors import pylab as pl # load sensor layout from mne.layouts import read_layout layout = read_layout('Vectorview-grad') # Extract mask and indices of active sensors in layout idx_of_sensors = [layout.names.index(name) for name in significant_sensors_names if name in layout.names] mask_significant_sensors = np.zeros(len(layout.pos), dtype=np.bool) mask_significant_sensors[idx_of_sensors] = True mask_non_significant_sensors = mask_significant_sensors == False # plot it pl.figure(facecolor='k') pl.axis('off') pl.axis('tight') pl.scatter(layout.pos[mask_significant_sensors, 0], layout.pos[mask_significant_sensors, 1], s=50, c='r')
scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1. - class_balance) print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) # plot CSP patterns estimated on full data for visualization csp.fit_transform(epochs_data, labels) evoked = epochs.average() evoked.data = csp.patterns_.T evoked.times = np.arange(evoked.data.shape[0]) layout = read_layout('EEG1005') evoked.plot_topomap(times=[0, 1, 2, 61, 62, 63], ch_type='eeg', layout=layout, scale_time=1, time_format='%i', scale=1, unit='Patterns (AU)', size=1.5) ############################################################################### # Look at performance over time sfreq = raw.info['sfreq'] w_length = int(sfreq * 0.5) # running classifier: window length w_step = int(sfreq * 0.1) # running classifier: window step size w_start = np.arange(0, epochs_data.shape[2] - w_length, w_step) scores_windows = [] for train_idx, test_idx in cv:
############################################################################### # Set parameters raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' event_id, tmin, tmax = 1, -0.2, 0.5 # Setup for reading the raw data raw = fiff.Raw(raw_fname) events = mne.read_events(event_fname) # Set up pick list: EEG + MEG - bad channels (modify to your needs) raw.info['bads'] = ['MEG 2443', 'EEG 053'] picks = fiff.pick_types(raw.info, meg='grad', eeg=False, stim=True, eog=True, exclude=raw.info['bads']) # 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, eog=150e-6)) ############################################################################### # Show event related fields images layout = read_layout('Vectorview-all') mne.viz.plot_topo_image_epochs(epochs, layout, sigma=0.5, vmin=-200, vmax=200, colorbar=True) title = 'ERF images - MNE sample data' pl.figtext(0.03, 0.9, title, color='w', fontsize=19) pl.show()
if not lacks_mayavi: mlab.options.backend = "test" data_dir = sample.data_path(download=False) subjects_dir = op.join(data_dir, "subjects") ecg_fname = op.join(data_dir, "MEG", "sample", "sample_audvis_ecg_proj.fif") base_dir = op.join(op.dirname(__file__), "..", "io", "tests", "data") evoked_fname = op.join(base_dir, "test-ave.fif") fname = op.join(base_dir, "test-ave.fif") raw_fname = op.join(base_dir, "test_raw.fif") cov_fname = op.join(base_dir, "test-cov.fif") event_name = op.join(base_dir, "test-eve.fif") event_id, tmin, tmax = 1, -0.2, 0.5 n_chan = 15 layout = read_layout("Vectorview-all") def _fake_click(fig, ax, point, xform="ax"): """Helper to fake a click at a relative point within axes""" if xform == "ax": x, y = ax.transAxes.transform_point(point) elif xform == "data": x, y = ax.transData.transform_point(point) else: raise ValueError("unknown transform") try: fig.canvas.button_press_event(x, y, 1, False, None) except: # for old MPL fig.canvas.button_press_event(x, y, 1, False)
clf = Pipeline([("CSP", csp), ("SVC", svc)]) scores = cross_val_score(clf, epochs_data_train, labels, cv=cv, n_jobs=1) # Printing the results class_balance = np.mean(labels == labels[0]) class_balance = max(class_balance, 1.0 - class_balance) print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores), class_balance)) # plot CSP patterns estimated on full data for visualization csp.fit_transform(epochs_data, labels) evoked = epochs.average() evoked.data = csp.patterns_.T evoked.times = np.arange(evoked.data.shape[0]) layout = read_layout("EEG1005") evoked.plot_topomap( times=[0, 1, 2, 61, 62, 63], ch_type="eeg", layout=layout, scale_time=1, time_format="%i", scale=1, unit="Patterns (AU)", size=1.5, ) ############################################################################### # Look at performance over time sfreq = raw.info["sfreq"]
if not lacks_mayavi: mlab.options.backend = 'test' data_dir = sample.data_path(download=False) subjects_dir = op.join(data_dir, 'subjects') ecg_fname = op.join(data_dir, 'MEG', 'sample', 'sample_audvis_ecg_proj.fif') base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data') evoked_fname = op.join(base_dir, 'test-ave.fif') fname = op.join(base_dir, 'test-ave.fif') raw_fname = op.join(base_dir, 'test_raw.fif') cov_fname = op.join(base_dir, 'test-cov.fif') event_name = op.join(base_dir, 'test-eve.fif') event_id, tmin, tmax = 1, -0.2, 0.5 n_chan = 15 layout = read_layout('Vectorview-all') def _fake_click(fig, ax, point, xform='ax'): """Helper to fake a click at a relative point within axes""" if xform == 'ax': x, y = ax.transAxes.transform_point(point) elif xform == 'data': x, y = ax.transData.transform_point(point) else: raise ValueError('unknown transform') try: fig.canvas.button_press_event(x, y, 1, False, None) except: # for old MPL fig.canvas.button_press_event(x, y, 1, False)
mean = values.mean(0) values[np.diag_indices(values.shape[0])] = mean # set a common range for colors: if vmin is None: vmin = values.min() if vmax is None: vmax = values.max() for i in range(values.shape[0]): topography(values[i], x*zoom_factor + x[i], y*zoom_factor + y[i], nx=nx, ny=nx, plotsensors=False, vmin=vmin, vmax=vmax, colorbar=False) if plotsensors: plt.plot(x[i]*zoom_factor + x[i], y[i]*zoom_factor + y[i], 'k.', markersize=8) if colorbar: plt.colorbar() if __name__ == '__main__': from mne.layouts import read_layout layout = read_layout('Vectorview-mag.lout') x = layout.pos[:,0] y = layout.pos[:,1] # generate some values: # value = np.sin((layout.pos[:,:2]**2).sum(1)*10) value = np.random.rand(x.size) plt.figure() topography(value, x, y) plt.figure() values = np.random.rand(x.size, x.size) hypertopography(values, x, y) plt.show()