def test_io_set_epochs(fnames): """Test importing EEGLAB .set epochs files.""" epochs_fname, epochs_fname_onefile = fnames with pytest.warns(RuntimeWarning, match='multiple events'): epochs = read_epochs_eeglab(epochs_fname) with pytest.warns(RuntimeWarning, match='multiple events'): epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_array_equal(epochs.get_data(), epochs2.get_data())
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) raw = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage) raw2 = read_raw_eeglab(input_fname=raw_fname, montage=montage) assert_array_equal(raw[:][0], raw2[:][0]) # one warning per each preload=False or str with raw_fname_onefile assert_equal(len(w), 3) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # 3 warnings for each read_epochs_eeglab because there are 3 epochs # associated with multiple events assert_equal(len(w), 6) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat(bad_epochs_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs}}) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 3)
def test_io_set_epochs(fnames): """Test importing EEGLAB .set epochs files.""" epochs_fname, epochs_fname_onefile = fnames with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_equal(len(w), 2) assert_array_equal(epochs.get_data(), epochs2.get_data())
def test_export_epochs_eeglab(tmp_path, preload): """Test saving an Epochs instance to EEGLAB's set format.""" raw, events = _get_data()[:2] raw.load_data() epochs = Epochs(raw, events, preload=preload) temp_fname = op.join(str(tmp_path), 'test.set') epochs.export(temp_fname) epochs.drop_channels( [ch for ch in ['epoc', 'STI 014'] if ch in epochs.ch_names]) epochs_read = read_epochs_eeglab(temp_fname) assert epochs.ch_names == epochs_read.ch_names cart_coords = np.array([d['loc'][:3] for d in epochs.info['chs']]) # just xyz cart_coords_read = np.array( [d['loc'][:3] for d in epochs_read.info['chs']]) assert_allclose(cart_coords, cart_coords_read) assert_array_equal(epochs.events[:, 0], epochs_read.events[:, 0]) # latency assert epochs.event_id.keys() == epochs_read.event_id.keys() # just keys assert_allclose(epochs.times, epochs_read.times) assert_allclose(epochs.get_data(), epochs_read.get_data()) # test overwrite with pytest.raises(FileExistsError, match='Destination file exists'): epochs.export(temp_fname, overwrite=False) epochs.export(temp_fname, overwrite=True) # test pathlib.Path files epochs.export(Path(temp_fname), overwrite=True)
def test_io_set_epochs_events(tmpdir): """Test different combinations of events and event_ids.""" tmpdir = str(tmpdir) out_fname = op.join(tmpdir, 'test-eve.fif') events = np.array([[4, 0, 1], [12, 0, 2], [20, 0, 3], [26, 0, 3]]) write_events(out_fname, events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} out_fname = op.join(tmpdir, 'test-eve.fif') epochs = read_epochs_eeglab(epochs_fname_mat, events, event_id) assert_equal(len(epochs.events), 4) assert epochs.preload assert epochs._bad_dropped epochs = read_epochs_eeglab(epochs_fname_mat, out_fname, event_id) pytest.raises(ValueError, read_epochs_eeglab, epochs_fname_mat, None, event_id) pytest.raises(ValueError, read_epochs_eeglab, epochs_fname_mat, epochs.events, None)
def process_existing_epochs(set_files): with tqdm(total=len(set_files)) as pbar: for set_file in set_files: source = os.path.join(source_path, set_file) epochs = read_epochs_eeglab(source) new_epochs = create_new_epochs(epochs=epochs, duration_in_seconds=2.048, overlap_ratio=0.5) file_name_no_extension = str(set_file.split('.')[0]) subject, period = file_name_no_extension.split('_')[:2] new_epochs.info['file_name'] = f'{subject}_asrt_{period}' save_epochs(epochs=new_epochs, target=target_path) pbar.update(1)
def get_files_with_mne(directory, extension='.set'): """ Esta función retorna los archivos abiertos con mne con la extensión especificada, esta retorna un arreglo con los archivos abiertos. Args: ____ - directory (str): Ruta que va al directorio en el cual se encuentran los archivos - extension (str): Extensión de los archivos que se desea leer (por defecto es .set) Returns: ____ - array: Arreglo que contiene todos los sarchivos abiertos con mne Examples: ____ Se requiere acceder a los sets de datos clasificados del set1 para el caso de emoticones alegres, es decir la ruta: /Users/wilsonforero/Documents/Universidad/Proyecto/python/sets/Set1-500ms/Emoticon/AlE Entonces se usa esta función >>> sets_package='Set1-500ms' >>> sub_category='AlE' >>> path = op.join(CLASSIFIED_SETS_FOLDER, sets_package, 'Emoticon', sub_category) >>> files=get_files_with_mne(path) # Retorna todos los archivos con esa extensión """ sets = [] for file in os.listdir(path=directory): if file.endswith(extension): file_path = op.join(directory, file) set_file = mne.read_epochs( file_path) if extension == '.fif' else mne.read_epochs_eeglab( file_path) if set_file is None: print( '\n\n\n====================================\n' + 'Fallo al cargar un archivo .set con el nombre:', file + '\n====================================\n\n\n') else: sets.append(set_file) print('Un total de', len(sets), ' archivos fueron abiertos con mne') return sets #op.join(MAIN_SETS_FOLDER, path, file_name)
def test_export_epochs_eeglab(tmpdir, preload): """Test saving an Epochs instance to EEGLAB's set format.""" raw, events = _get_data()[:2] raw.load_data() epochs = Epochs(raw, events, preload=preload) temp_fname = op.join(str(tmpdir), 'test.set') epochs.export(temp_fname) epochs.drop_channels( [ch for ch in ['epoc', 'STI 014'] if ch in epochs.ch_names]) epochs_read = read_epochs_eeglab(temp_fname) assert epochs.ch_names == epochs_read.ch_names cart_coords = np.array([d['loc'][:3] for d in epochs.info['chs']]) # just xyz cart_coords_read = np.array( [d['loc'][:3] for d in epochs_read.info['chs']]) assert_allclose(cart_coords, cart_coords_read) assert_array_equal(epochs.events[:, 0], epochs_read.events[:, 0]) # latency assert epochs.event_id.keys() == epochs_read.event_id.keys() # just keys assert_allclose(epochs.times, epochs_read.times) assert_allclose(epochs.get_data(), epochs_read.get_data())
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io with warnings.catch_warnings(record=True) as w1: warnings.simplefilter('always') # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) assert_equal(len(w1), 20) # f3 or preload_false and a lot for dropping events with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # test finding events in continuous data event_id = {'rt': 1, 'square': 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id) epochs = Epochs(raw1, find_events(raw1), event_id) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None) # test that preloading works with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # 3 warnings for each read_epochs_eeglab because there are 3 epochs # associated with multiple events assert_equal(len(w), 6) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat( bad_epochs_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs } }) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 3)
def test_read_single_epoch(): """Test reading raw set file as an Epochs instance.""" with pytest.raises(ValueError, match='trials less than 2'): read_epochs_eeglab(raw_fname_mat)
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io with warnings.catch_warnings(record=True) as w1: warnings.simplefilter('always') # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) assert_equal(len(w1), 20) # f3 or preload_false and a lot for dropping events with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # test finding events in continuous data event_id = {'rt': 1, 'square': 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id, add_eeg_ref=False) epochs = Epochs(raw1, find_events(raw1), event_id, add_eeg_ref=False) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None, l_trans_bandwidth='auto', filter_length='auto', phase='zero') # test that preloading works # test that using uin16_codec does not break stuff raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False, uint16_codec='ascii') # test old EEGLAB version event import eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] for event in eeg.event: # old version allows integer events event.type = 1 assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) eeg.event = eeg.event[0] # single event assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_equal(len(w), 2) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) assert_equal(len(epochs.events), 4) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test reading file with one event eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] one_event_fname = op.join(temp_dir, 'test_one_event.set') io.savemat( one_event_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': 'test_one_event.fdt', 'epoch': eeg.epoch, 'event': eeg.event[0], 'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts } }) shutil.copyfile(op.join(base_dir, 'test_raw.fdt'), op.join(temp_dir, 'test_one_event.fdt')) event_id = {eeg.event[0].type: 1} read_raw_eeglab(input_fname=one_event_fname, montage=montage, event_id=event_id, preload=True) # test reading file with one channel one_chan_fname = op.join(temp_dir, 'test_one_channel.set') io.savemat( one_chan_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 1, 'data': np.random.random((1, 3)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': { 'labels': 'E1', 'Y': -6.6069, 'X': 6.3023, 'Z': -2.9423 }, 'times': eeg.times[:3], 'pnts': 3 } }) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') read_raw_eeglab(input_fname=one_chan_fname, preload=True) # no warning for 'no events found' assert_equal(len(w), 0) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat( bad_epochs_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs } }) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 1)
"avg_reward", "reward", "iti", "trial_num", "run_num", "trial_in_run", "rt", "congruencyDC", "accDC", "previousCongruencyDC", "previousAcc", "trialType", "keyRep", "cnvAmplitude" ]) # Only consider trials with valid data by removing NaN and artifactFlag = 0 values labels = labels[labels.artifactFlag != 0].dropna() # Label we are trying to predict y = labels.congruencyDC.real # Load selected channels around the FCz area from the EEG data # After loading the EEG data the 'eegData' variable is composed by trials[868],channels[9],time[2560] eegData = mne.read_epochs_eeglab( "SimonConflictTask/Subject_ID_25/Data and design matrices/ID_25_epochsAll.set" ).pick_channels(["F1", "Fz", "F2", "FC1", "FCz", "FC2", "C1", "Cz", "C2"]).get_data() # Now we remove the trials from the eegData that have invalid data (as established before) X = np.ndarray(shape=(labels.epochN.size, eegData.shape[1], eegData.shape[2]), dtype='float64') counter = 0 for index in labels.epochN.astype(int): X[counter] += eegData[index - 1, :X.shape[1], :X.shape[2]] counter += 1 # keep track of the accuracy over time predictorTime = pd.DataFrame(columns=["Time", "Accuracy"]) # We use a Support Vector Machine with a linear kernel classifier = svm.SVC()
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) for want in ('Events like', 'consist entirely', 'could not be mapped', 'string preload is not supported'): assert_true(any(want in str(ww.message) for ww in w)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # test finding events in continuous data event_id = {'rt': 1, 'square': 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id) epochs = Epochs(raw1, find_events(raw1), event_id) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None, l_trans_bandwidth='auto', filter_length='auto', phase='zero') # test that preloading works # test that using uint16_codec does not break stuff raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False, uint16_codec='ascii') # test old EEGLAB version event import eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] for event in eeg.event: # old version allows integer events event.type = 1 assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) eeg.event = eeg.event[0] # single event assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_equal(len(w), 2) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) assert_equal(len(epochs.events), 4) assert_true(epochs.preload) assert_true(epochs._bad_dropped) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test reading file with one event eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] one_event_fname = op.join(temp_dir, 'test_one_event.set') io.savemat( one_event_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': 'test_one_event.fdt', 'epoch': eeg.epoch, 'event': eeg.event[0], 'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts } }) shutil.copyfile(op.join(base_dir, 'test_raw.fdt'), op.join(temp_dir, 'test_one_event.fdt')) event_id = {eeg.event[0].type: 1} read_raw_eeglab(input_fname=one_event_fname, montage=montage, event_id=event_id, preload=True) # test reading file with one channel one_chan_fname = op.join(temp_dir, 'test_one_channel.set') io.savemat( one_chan_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 1, 'data': np.random.random((1, 3)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': { 'labels': 'E1', 'Y': -6.6069, 'X': 6.3023, 'Z': -2.9423 }, 'times': eeg.times[:3], 'pnts': 3 } }) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') read_raw_eeglab(input_fname=one_chan_fname, preload=True) # no warning for 'no events found' assert_equal(len(w), 0) # test reading file with 3 channels - one without position information # first, create chanlocs structured array ch_names = ['F3', 'unknown', 'FPz'] x, y, z = [1., 2., np.nan], [4., 5., np.nan], [7., 8., np.nan] dt = [('labels', 'S10'), ('X', 'f8'), ('Y', 'f8'), ('Z', 'f8')] chanlocs = np.zeros((3, ), dtype=dt) for ind, vals in enumerate(zip(ch_names, x, y, z)): for fld in range(4): chanlocs[ind][dt[fld][0]] = vals[fld] # save set file one_chanpos_fname = op.join(temp_dir, 'test_chanpos.set') io.savemat( one_chanpos_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 3, 'data': np.random.random((3, 3)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': chanlocs, 'times': eeg.times[:3], 'pnts': 3 } }) # load it with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=one_chanpos_fname, preload=True) # one warning because some channels are not found in Montage assert_equal(len(w), 1) # position should be present for first two channels for i in range(2): assert_array_equal( raw.info['chs'][i]['loc'][:3], np.array([-chanlocs[i]['Y'], chanlocs[i]['X'], chanlocs[i]['Z']])) # position of the last channel should be zero assert_array_equal(raw.info['chs'][-1]['loc'][:3], np.array([0., 0., 0.])) # test reading channel names from set and positions from montage with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=one_chanpos_fname, preload=True, montage=montage) # one warning because some channels are not found in Montage assert_equal(len(w), 1) # when montage was passed - channel positions should be taken from there correct_pos = [[-0.56705965, 0.67706631, 0.46906776], [0., 0., 0.], [0., 0.99977915, -0.02101571]] for ch_ind in range(3): assert_array_almost_equal(raw.info['chs'][ch_ind]['loc'][:3], np.array(correct_pos[ch_ind])) # test reading channel names but not positions when there is no X (only Z) # field in the EEG.chanlocs structure nopos_chanlocs = chanlocs[['labels', 'Z']] nopos_fname = op.join(temp_dir, 'test_no_chanpos.set') io.savemat( nopos_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 3, 'data': np.random.random((3, 2)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': nopos_chanlocs, 'times': eeg.times[:2], 'pnts': 2 } }) # load the file with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=nopos_fname, preload=True) # test that channel names have been loaded but not channel positions for i in range(3): assert_equal(raw.info['chs'][i]['ch_name'], ch_names[i]) assert_array_equal(raw.info['chs'][i]['loc'][:3], np.array([0., 0., 0.])) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat( bad_epochs_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs } }) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 1)
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) raw = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage) raw2 = read_raw_eeglab(input_fname=raw_fname, montage=montage) assert_array_equal(raw[:][0], raw2[:][0]) # one warning per each preload=False or str with raw_fname_onefile assert_equal(len(w), 3) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # 3 warnings for each read_epochs_eeglab because there are 3 epochs # associated with multiple events assert_equal(len(w), 6) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat( bad_epochs_fname, { 'EEG': { 'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs } }) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 3)
mat = mat['python_args'] #one_value = mat['one_value'][0][0][0][0] #double_array = mat['double_array'][0][0][0] #string_value = mat['path'][0][0][0] #print one_value, double_array, string_value def get_array(array): if len(array[0][0]) > 0: return array[0][0][0] return [] picked_channels = get_array(mat['picked_channels']) event_1 = get_array(mat['event_1']) event_0 = get_array(mat['event_0']) fold_nr = mat['fold_nr'][0][0][0][0] outputfile = mat['outputfile'][0][0][0] semfactor = mat['semfactor'][0][0][0][0] #import ipdb; ipdb.set_trace() epochs = mne.read_epochs_eeglab(input_fname) y, epochs_decode = create_y_data_for_decoding(epochs, event_1, event_0) scores = calculate_diagonal_decoding(epochs_decode, picked_channels, y, fold_nr, outputfile) plot_diagonal_decoding(epochs_decode, scores, semfactor, outputfile) #eeg = mat['eeg_data'] #eeg = eeg*3 #scipy.io.savemat(matrix, {'eeg_data': eeg})
input_fname = sys.argv[1] print args mat = scipy.io.loadmat(args, chars_as_strings=True) print mat mat = mat['python_args'] #one_value = mat['one_value'][0][0][0][0] #double_array = mat['double_array'][0][0][0] #string_value = mat['path'][0][0][0] #print one_value, double_array, string_value def get_array(array): if len(array[0][0]) > 0: return array[0][0][0] return [] picked_channels = get_array(mat['picked_channels']) event_1 = get_array(mat['event_1']) event_0 = get_array(mat['event_0']) fold_nr = mat['fold_nr'][0][0][0][0] outputfile = mat['outputfile'][0][0][0] semfactor = mat['semfactor'][0][0][0][0] #import ipdb; ipdb.set_trace() epochs = mne.read_epochs_eeglab(input_fname) y,epochs_decode = create_y_data_for_decoding(epochs,event_1,event_0) scores = calculate_diagonal_decoding(epochs_decode,picked_channels,y,fold_nr,outputfile) plot_diagonal_decoding(epochs_decode,scores,semfactor,outputfile) #eeg = mat['eeg_data'] #eeg = eeg*3 #scipy.io.savemat(matrix, {'eeg_data': eeg})
def test_io_set(): """Test importing EEGLAB .set files.""" with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) for want in ('Events like', 'consist entirely', 'could not be mapped', 'string preload is not supported'): assert_true(any(want in str(ww.message) for ww in w)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # test finding events in continuous data event_id = {'rt': 1, 'square': 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id) epochs = Epochs(raw1, find_events(raw1), event_id) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None, l_trans_bandwidth='auto', filter_length='auto', phase='zero') # test that preloading works # test that using uint16_codec does not break stuff raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False, uint16_codec='ascii') # test old EEGLAB version event import eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] for event in eeg.event: # old version allows integer events event.type = 1 assert_equal(read_events_eeglab(eeg)[-1, -1], 1) eeg.event = eeg.event[0] # single event assert_equal(read_events_eeglab(eeg)[-1, -1], 1) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_equal(len(w), 2) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) assert_equal(len(epochs.events), 4) assert_true(epochs.preload) assert_true(epochs._bad_dropped) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test reading file with one event eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] one_event_fname = op.join(temp_dir, 'test_one_event.set') io.savemat(one_event_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': 'test_one_event.fdt', 'epoch': eeg.epoch, 'event': eeg.event[0], 'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}}) shutil.copyfile(op.join(base_dir, 'test_raw.fdt'), op.join(temp_dir, 'test_one_event.fdt')) event_id = {eeg.event[0].type: 1} read_raw_eeglab(input_fname=one_event_fname, montage=montage, event_id=event_id, preload=True) # test overlapping events overlap_fname = op.join(temp_dir, 'test_overlap_event.set') io.savemat(overlap_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': 'test_overlap_event.fdt', 'epoch': eeg.epoch, 'event': [eeg.event[0], eeg.event[0]], 'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}}) shutil.copyfile(op.join(base_dir, 'test_raw.fdt'), op.join(temp_dir, 'test_overlap_event.fdt')) event_id = {'rt': 1, 'square': 2} with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=overlap_fname, montage=montage, event_id=event_id, preload=True) assert_equal(len(w), 1) # one warning for the dropped event events_stimchan = find_events(raw) events_read_events_eeglab = read_events_eeglab(overlap_fname, event_id) assert_true(len(events_stimchan) == 1) assert_true(len(events_read_events_eeglab) == 2) # test reading file with one channel one_chan_fname = op.join(temp_dir, 'test_one_channel.set') io.savemat(one_chan_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 1, 'data': np.random.random((1, 3)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': {'labels': 'E1', 'Y': -6.6069, 'X': 6.3023, 'Z': -2.9423}, 'times': eeg.times[:3], 'pnts': 3}}) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') read_raw_eeglab(input_fname=one_chan_fname, preload=True) # no warning for 'no events found' assert_equal(len(w), 0) # test reading file with 3 channels - one without position information # first, create chanlocs structured array ch_names = ['F3', 'unknown', 'FPz'] x, y, z = [1., 2., np.nan], [4., 5., np.nan], [7., 8., np.nan] dt = [('labels', 'S10'), ('X', 'f8'), ('Y', 'f8'), ('Z', 'f8')] chanlocs = np.zeros((3,), dtype=dt) for ind, vals in enumerate(zip(ch_names, x, y, z)): for fld in range(4): chanlocs[ind][dt[fld][0]] = vals[fld] if LooseVersion(np.__version__) == '1.14.0': # There is a bug in 1.14.0 (or maybe with SciPy 1.0.0?) that causes # this write to fail! raise SkipTest('Need to fix bug in NumPy 1.14.0!') # save set file one_chanpos_fname = op.join(temp_dir, 'test_chanpos.set') io.savemat(one_chanpos_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 3, 'data': np.random.random((3, 3)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': chanlocs, 'times': eeg.times[:3], 'pnts': 3}}) # load it with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=one_chanpos_fname, preload=True) # one warning because some channels are not found in Montage assert_equal(len(w), 1) # position should be present for first two channels for i in range(2): assert_array_equal(raw.info['chs'][i]['loc'][:3], np.array([-chanlocs[i]['Y'], chanlocs[i]['X'], chanlocs[i]['Z']])) # position of the last channel should be zero assert_array_equal(raw.info['chs'][-1]['loc'][:3], [np.nan] * 3) # test reading channel names from set and positions from montage with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=one_chanpos_fname, preload=True, montage=montage) # one warning because some channels are not found in Montage assert_equal(len(w), 1) # when montage was passed - channel positions should be taken from there correct_pos = [[-0.56705965, 0.67706631, 0.46906776], [np.nan] * 3, [0., 0.99977915, -0.02101571]] for ch_ind in range(3): assert_array_almost_equal(raw.info['chs'][ch_ind]['loc'][:3], np.array(correct_pos[ch_ind])) # test reading channel names but not positions when there is no X (only Z) # field in the EEG.chanlocs structure nopos_chanlocs = chanlocs[['labels', 'Z']] nopos_fname = op.join(temp_dir, 'test_no_chanpos.set') io.savemat(nopos_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 3, 'data': np.random.random((3, 2)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': nopos_chanlocs, 'times': eeg.times[:2], 'pnts': 2}}) # load the file with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') raw = read_raw_eeglab(input_fname=nopos_fname, preload=True) # test that channel names have been loaded but not channel positions for i in range(3): assert_equal(raw.info['chs'][i]['ch_name'], ch_names[i]) assert_array_equal(raw.info['chs'][i]['loc'][:3], np.array([0., 0., 0.]))
spi_fname = os.path.join(cartool_dir,'sub-'+subject,'sub-'+subject+'.spi') spi = pycartool.source_space.read_spi(spi_fname) eegpath = os.path.join(eeglab_dir,'sub-'+subject) # Path to EEGlab files set_file = [elem.split('.')[0] for elem in os.listdir(eegpath) if (elem.endswith('.set') and ('FACES' in elem))] EEG_path = os.path.join(eegpath,set_file[0]+'.set') # Load epoch metadata into a table with header [COND, ACC, RT, nameCOND, outliers, bat_trials] Behav_path = os.path.join(eegpath,'sub-'+subject+'_FACES_250HZ_behav.txt') Behavfile = pd.read_csv(Behav_path, sep=",") Behavfile = Behavfile[Behavfile.bad_trials == 0] epochs = mne.read_epochs_eeglab(EEG_path, events=None, event_id=None, eog=(), verbose=None, uint16_codec=None) epochs.events[:,2] = list(Behavfile.COND) epochs.event_id = {"Scrambled":0, "Faces":1} # compute inverse solutions for each ROI r = 6 IS = is_file['regularisation_solutions'][r] TCs_1D,SCS,nSPI,maindir = project_dipoles_inv3D(epochs,roi_file,IS,spi,epochs.times,verbose=None) X = np.array(TCs_1D)[cort] # Flip ROIs for n in range(X.shape[0]): direction = np.sign(X[n][deflect_time].mean()) X[n] *= direction
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io with warnings.catch_warnings(record=True) as w1: warnings.simplefilter('always') # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) assert_equal(len(w1), 20) # f3 or preload_false and a lot for dropping events with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # test finding events in continuous data event_id = {'rt': 1, 'square': 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id) epochs = Epochs(raw1, find_events(raw1), event_id) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None, l_trans_bandwidth='auto', filter_length='auto', phase='zero') # test that preloading works # test that using uin16_codec does not break stuff raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False, uint16_codec='ascii') # test old EEGLAB version event import eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] for event in eeg.event: # old version allows integer events event.type = 1 assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) eeg.event = eeg.event[0] # single event assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_equal(len(w), 2) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) assert_equal(len(epochs.events), 4) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test reading file with one event eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] one_event_fname = op.join(temp_dir, 'test_one_event.set') io.savemat(one_event_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': 'test_one_event.fdt', 'epoch': eeg.epoch, 'event': eeg.event[0], 'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}}) shutil.copyfile(op.join(base_dir, 'test_raw.fdt'), op.join(temp_dir, 'test_one_event.fdt')) event_id = {eeg.event[0].type: 1} read_raw_eeglab(input_fname=one_event_fname, montage=montage, event_id=event_id, preload=True) # test reading file with one channel one_chan_fname = op.join(temp_dir, 'test_one_channel.set') io.savemat(one_chan_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 1, 'data': np.random.random((1, 3)), 'epoch': eeg.epoch, 'event': eeg.epoch, 'chanlocs': {'labels': 'E1', 'Y': -6.6069, 'X': 6.3023, 'Z': -2.9423}, 'times': eeg.times[:3], 'pnts': 3}}) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') read_raw_eeglab(input_fname=one_chan_fname, preload=True) # no warning for 'no events found' assert_equal(len(w), 0) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat(bad_epochs_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs}}) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 1)
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io with warnings.catch_warnings(record=True) as w1: warnings.simplefilter('always') # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) assert_equal(len(w1), 20) # f3 or preload_false and a lot for dropping events with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') # test finding events in continuous data event_id = {'rt': 1, 'square': 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id) epochs = Epochs(raw1, find_events(raw1), event_id) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None) # test that preloading works with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # 3 warnings for each read_epochs_eeglab because there are 3 epochs # associated with multiple events assert_equal(len(w), 6) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, 'test-eve.fif') write_events(out_fname, epochs.events) event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test reading file with one event eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)['EEG'] one_event_fname = op.join(temp_dir, 'test_one_event.set') io.savemat(one_event_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': 'test_one_event.fdt', 'epoch': eeg.epoch, 'event': eeg.event[0], 'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}}) shutil.copyfile(op.join(base_dir, 'test_raw.fdt'), op.join(temp_dir, 'test_one_event.fdt')) event_id = {eeg.event[0].type: 1} read_raw_eeglab(input_fname=one_event_fname, montage=montage, event_id=event_id, preload=True) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)['EEG'] eeg.data = 'epochs_fname.dat' bad_epochs_fname = op.join(temp_dir, 'test_epochs.set') io.savemat(bad_epochs_fname, {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': eeg.nbchan, 'data': eeg.data, 'epoch': eeg.epoch, 'event': eeg.event, 'chanlocs': eeg.chanlocs}}) shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'), op.join(temp_dir, 'test_epochs.dat')) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 3)
def load_epoch_reject(epoch_path: str, reject_path: str) -> Tuple[mne.Epochs, np.ndarray]: epoch_file = read_epochs_eeglab(epoch_path) reject_file = sio.loadmat(reject_path)['reject'].flatten() return epoch_file, reject_file
import scipy.io as sio from iclabelpy.mat import loadmat data = loadmat('Y:\code\iclabelpy\data\sub-010317_PREP_clean_ICA.mat') ica = loadmat('Y:\code\iclabelpy\data\ica.mat') print('ok') flag_autocorr = True EEG = data['EEG'] mixing = ica['icawinv'] demixing = ica['icaweights'] @ ica['icasphere'] #ICL_feature_extractor(EEG, flag_autocorr) ncomp = mixing.shape[1] nchannels = mixing.shape[0] average_reference = False if not average_reference: data = reref(EEG['data']) # Rereference ICA Matrix newICAchaninds = reref(mixing) icaact = EEG['icaact'] assert np.all(np.isreal(icaact)) == True # Check Activations are real test = True raw = mne.read_epochs_eeglab( 'Y:\code\iclabelpy\data\sub-010317_PREP_clean_ICA.set') features = iclabel(raw, mixing, demixing, True, True, test) sio.savemat('features_python.mat', {'features_python': features}) print('ok')
def test_io_set(): """Test importing EEGLAB .set files""" from scipy import io with warnings.catch_warnings(record=True) as w1: warnings.simplefilter("always") # main tests, and test missing event_id _test_raw_reader(read_raw_eeglab, input_fname=raw_fname, montage=montage) _test_raw_reader(read_raw_eeglab, input_fname=raw_fname_onefile, montage=montage) assert_equal(len(w1), 20) # f3 or preload_false and a lot for dropping events with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # test finding events in continuous data event_id = {"rt": 1, "square": 2} raw0 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=True) raw1 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id, preload=False) raw2 = read_raw_eeglab(input_fname=raw_fname_onefile, montage=montage, event_id=event_id) raw3 = read_raw_eeglab(input_fname=raw_fname, montage=montage, event_id=event_id) raw4 = read_raw_eeglab(input_fname=raw_fname, montage=montage) Epochs(raw0, find_events(raw0), event_id) epochs = Epochs(raw1, find_events(raw1), event_id) assert_equal(len(find_events(raw4)), 0) # no events without event_id assert_equal(epochs["square"].average().nave, 80) # 80 with assert_array_equal(raw0[:][0], raw1[:][0], raw2[:][0], raw3[:][0]) assert_array_equal(raw0[:][-1], raw1[:][-1], raw2[:][-1], raw3[:][-1]) assert_equal(len(w), 4) # 1 for preload=False / str with fname_onefile, 3 for dropped events raw0.filter(1, None, l_trans_bandwidth="auto", filter_length="auto", phase="zero") # test that preloading works # test that using uint16_codec does not break stuff raw0 = read_raw_eeglab( input_fname=raw_fname, montage=montage, event_id=event_id, preload=False, uint16_codec="ascii" ) # test old EEGLAB version event import eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)["EEG"] for event in eeg.event: # old version allows integer events event.type = 1 assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) eeg.event = eeg.event[0] # single event assert_equal(_read_eeglab_events(eeg)[-1, -1], 1) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") epochs = read_epochs_eeglab(epochs_fname) epochs2 = read_epochs_eeglab(epochs_fname_onefile) # one warning for each read_epochs_eeglab because both files have epochs # associated with multiple events assert_equal(len(w), 2) assert_array_equal(epochs.get_data(), epochs2.get_data()) # test different combinations of events and event_ids temp_dir = _TempDir() out_fname = op.join(temp_dir, "test-eve.fif") write_events(out_fname, epochs.events) event_id = {"S255/S8": 1, "S8": 2, "S255/S9": 3} epochs = read_epochs_eeglab(epochs_fname, epochs.events, event_id) assert_equal(len(epochs.events), 4) assert_true(epochs.preload) assert_true(epochs._bad_dropped) epochs = read_epochs_eeglab(epochs_fname, out_fname, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, None, event_id) assert_raises(ValueError, read_epochs_eeglab, epochs_fname, epochs.events, None) # test reading file with one event eeg = io.loadmat(raw_fname, struct_as_record=False, squeeze_me=True)["EEG"] one_event_fname = op.join(temp_dir, "test_one_event.set") io.savemat( one_event_fname, { "EEG": { "trials": eeg.trials, "srate": eeg.srate, "nbchan": eeg.nbchan, "data": "test_one_event.fdt", "epoch": eeg.epoch, "event": eeg.event[0], "chanlocs": eeg.chanlocs, "pnts": eeg.pnts, } }, ) shutil.copyfile(op.join(base_dir, "test_raw.fdt"), op.join(temp_dir, "test_one_event.fdt")) event_id = {eeg.event[0].type: 1} read_raw_eeglab(input_fname=one_event_fname, montage=montage, event_id=event_id, preload=True) # test reading file with one channel one_chan_fname = op.join(temp_dir, "test_one_channel.set") io.savemat( one_chan_fname, { "EEG": { "trials": eeg.trials, "srate": eeg.srate, "nbchan": 1, "data": np.random.random((1, 3)), "epoch": eeg.epoch, "event": eeg.epoch, "chanlocs": {"labels": "E1", "Y": -6.6069, "X": 6.3023, "Z": -2.9423}, "times": eeg.times[:3], "pnts": 3, } }, ) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") read_raw_eeglab(input_fname=one_chan_fname, preload=True) # no warning for 'no events found' assert_equal(len(w), 0) # test if .dat file raises an error eeg = io.loadmat(epochs_fname, struct_as_record=False, squeeze_me=True)["EEG"] eeg.data = "epochs_fname.dat" bad_epochs_fname = op.join(temp_dir, "test_epochs.set") io.savemat( bad_epochs_fname, { "EEG": { "trials": eeg.trials, "srate": eeg.srate, "nbchan": eeg.nbchan, "data": eeg.data, "epoch": eeg.epoch, "event": eeg.event, "chanlocs": eeg.chanlocs, } }, ) shutil.copyfile(op.join(base_dir, "test_epochs.fdt"), op.join(temp_dir, "test_epochs.dat")) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") assert_raises(NotImplementedError, read_epochs_eeglab, bad_epochs_fname) assert_equal(len(w), 1)
import pandas as pd import mne from kurtosis import KURTOSIS from adhd_theta_beta import Ratio_Theta_Beta import scipy.io as sio from mne.decoding import CSP import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from scipy import signal import matplotlib.pyplot as plt from scipy.integrate import simps path = r'G:\Mi unidad\Trabajo\2021\Kurtosis\TBR\data\data\adhd\set\SST_DC_AM_new.set' labels = r'G:\Mi unidad\Trabajo\2021\Kurtosis\TBR\data\data\adhd\csv\SST_DC_AM_new.csv' x = mne.read_epochs_eeglab(path) X = x.get_data() y = pd.read_csv(labels)['Block'] X_filt = KURTOSIS(th=3).fit_transform(X, y) def indices(fvec, flow, fhigh): al = abs(fvec - flow * np.ones([fvec.shape[0]])).tolist() indl = al.index(min(al)) ah = abs(fvec - fhigh * np.ones([fvec.shape[0]])).tolist() indh = ah.index(min(ah)) return np.arange(indl, indh + 1, 1)