def test_doesnt_change_elc_montages(tmp_path): montage_orig = read_montage('standard_1005') save_montage(montage_orig, tmp_path) saved_path = op.join(tmp_path, 'standard_1005.elc') montage_saved = read_montage(saved_path) assert montage_orig.ch_names == montage_saved.ch_names assert np.allclose(montage_orig.pos, montage_saved.pos) assert np.allclose(montage_orig.lpa, montage_saved.lpa) assert np.allclose(montage_orig.rpa, montage_saved.rpa) assert np.allclose(montage_orig.nasion, montage_saved.nasion) assert montage_orig.kind == montage_saved.kind
def creat_mne_raw_object(fname, read_events=True): """ Creates a mne raw instance from csv file Arguments fname: file path read_events: boolean indicating whether we want to read events file """ data = pd.read_csv(fname) # get chanel names ch_names = list(data.columns[1:]) # read EEG standard montage from mne montage = read_montage('standard_1005', ch_names) ch_type = ['eeg'] * len(ch_names) data = 1e-6 * np.array(data[ch_names]).T if read_events: ev_fname = fname.replace('_data', '_events') events = pd.read_csv(ev_fname) events_names = events.columns[1:] #ignore id column events_data = np.array(events[events_names]).T # define channel type, the first is EEG, the last 6 are stimulations ch_type.extend(['stim'] * 6) ch_names.extend(events_names) # concatenate event file and data data = np.concatenate((data, events_data)) # create and populate MNE info structure info = create_info(ch_names, sfreq=500.0, ch_types=ch_type, montage=montage) info['filename'] = fname # create raw object raw = RawArray(data, info, verbose=False) return raw
def _get_single_subject_data(self, subject): """return data for a single subject""" fname = '%s/s%02d.mat' % (self.base_folder, subject) data = loadmat(fname, squeeze_me=True, struct_as_record=False, verify_compressed_data_integrity=False)['eeg'] eeg_ch_names = [ 'Fp1', 'AF7', 'AF3', 'F1', 'F3', 'F5', 'F7', 'FT7', 'FC5', 'FC3', 'FC1', 'C1', 'C3', 'C5', 'T7', 'TP7', 'CP5', 'CP3', 'CP1', 'P1', 'P3', 'P5', 'P7', 'P9', 'PO7', 'PO3', 'O1', 'Iz', 'Oz', 'POz', 'Pz', 'CPz', 'FPz', 'FP2', 'AF8', 'AF4', 'AFz', 'Fz', 'F2', 'F4', 'F6', 'F8', 'FT8', 'FC6', 'FC4', 'FC2', 'FCz', 'Cz', 'C2', 'C4', 'C6', 'T8', 'TP8', 'CP6', 'CP4', 'CP2', 'P2', 'P4', 'P6', 'P8', 'P10', 'PO8', 'PO4', 'O2' ] emg_ch_names = ['EMG1', 'EMG2', 'EMG3', 'EMG4'] ch_names = eeg_ch_names + emg_ch_names + ['Stim'] ch_types = ['eeg'] * 64 + ['misc'] * 4 + ['stim'] montage = read_montage('standard_1005') eeg_data_l = np.vstack([data.imagery_left * 1e-6, data.imagery_event]) eeg_data_r = np.vstack( [data.imagery_right * 1e-6, data.imagery_event * 2]) eeg_data = np.hstack([eeg_data_l, eeg_data_r]) info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=data.srate, montage=montage) raw = RawArray(data=eeg_data, info=info, verbose=False) return [raw]
def plotRawEEG(self, event_code1=769, event_code2=770, filename="", bad_ch=[]): tmin, tmax = -1., 4. event_id = dict(class1=event_code1, class2=event_code2) # load file raw_fnames = [filename] raw_files = [ read_raw_edf(f, preload=True, stim_channel='auto') for f in raw_fnames ] raw = concatenate_raws(raw_files) montage = channels.read_montage('standard_1020') raw.set_montage(montage) raw.info['bads'] = bad_ch events = find_events(raw, shortest_event=0) # Apply band-pass filter raw.filter(1., 45., fir_design='firwin', skip_by_annotation='edge') # plot channels raw.plot(block=True, lowpass=40, title="EEG Traces : Click on channels to exclude them!")
def _get_single_subject_data(self, subject): """return data for a single subject""" sessions = [] if self.imagined: sessions.append('imagination') if self.executed: sessions.append('execution') out = {} for session in sessions: paths = self.data_path(subject, session=session) eog = ['eog-l', 'eog-m', 'eog-r'] montage = read_montage('standard_1005') data = {} for ii, path in enumerate(paths): raw = read_raw_edf(path, montage=montage, eog=eog, misc=range(64, 96), preload=True, verbose='ERROR') # there is nan in the data raw._data[np.isnan(raw._data)] = 0 data['run_%d' % ii] = raw out[session] = data return out
def test_montage(): """Test making montages""" # no pep8 input_str = ["""FidNz 0.00000 10.56381 -2.05108 FidT9 -7.82694 0.45386 -3.76056 FidT10 7.82694 0.45386 -3.76056""", """// MatLab Sphere coordinates [degrees] Cartesian coordinates // Label Theta Phi Radius X Y Z off sphere surface E1 37.700 -14.000 1.000 0.7677 0.5934 -0.2419 -0.00000000000000011 E2 44.600 -0.880 1.000 0.7119 0.7021 -0.0154 0.00000000000000000 E3 51.700 11.000 1.000 0.6084 0.7704 0.1908 0.00000000000000000""", """# ASA electrode file ReferenceLabel avg UnitPosition mm NumberPositions= 68 Positions -86.0761 -19.9897 -47.9860 85.7939 -20.0093 -48.0310 0.0083 86.8110 -39.9830 Labels LPA RPA Nz """, """Site Theta Phi Fp1 -92 -72 Fp2 92 72 F3 -60 -51 """, """346 EEG F3 -62.027 -50.053 85 EEG Fz 45.608 90 85 EEG F4 62.01 50.103 85 """] kinds = ['test.sfp', 'test.csd', 'test.elc', 'test.txt', 'test.elp'] for kind, text in zip(kinds, input_str): fname = op.join(tempdir, kind) with open(fname, 'w') as fid: fid.write(text) montage = read_montage(fname) assert_equal(len(montage.ch_names), 3) assert_equal(len(montage.ch_names), len(montage.pos)) assert_equal(montage.pos.shape, (3, 3)) assert_equal(montage.kind, kind[:-4]) if kind.endswith('csd'): dtype = [('label', 'S4'), ('theta', 'f8'), ('phi', 'f8'), ('radius', 'f8'), ('x', 'f8'), ('y', 'f8'), ('z', 'f8'), ('off_sph', 'f8')] table = np.loadtxt(fname, skiprows=2, dtype=dtype) pos2 = np.c_[table['x'], table['y'], table['z']] assert_array_almost_equal(pos2, montage.pos, 4) # test with last info = create_info(montage.ch_names, 1e3, ['eeg'] * len(montage.ch_names)) apply_montage(info, montage) pos2 = np.array([c['loc'][:3] for c in info['chs']]) pos3 = np.array([c['eeg_loc'][:, 0] for c in info['chs']]) assert_array_equal(pos2, montage.pos) assert_array_equal(pos3, montage.pos) assert_equal(montage.ch_names, info['ch_names'])
def _get_single_subject_data(self, subject): """return data for a single subject""" data_path = '/Users/emmanuelkalunga/Documents/School/EEG_covariance_classification/data/dataset-ssvep-exoskeleton/' path_subject = data_path + 'subject{0:0>2}/'.format(subject) raw_files = [] sample_rate = 256 ch_names = [ 'Oz', 'O1', 'O2', 'PO3', 'POz', 'PO7', 'PO8', 'PO4', 'Stim' ] ch_types = ['eeg'] * 8 + ['stim'] montage = read_montage('standard_1005') info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=256., montage=montage) for fn in os.listdir(path_subject): if fn.endswith('.pz'): with gzip.open(path_subject + fn, 'rb') as f: o = pickle.load(f, encoding='latin1') raw_signal = o['raw_signal'] event_pos = o['event_pos'].reshape((o['event_pos'].shape[0])) event_type = o['event_type'].reshape( (o['event_type'].shape[0])) data = pd.DataFrame(raw_signal) data['Stim'] = 0 data.loc[event_pos[np.where(event_type >= 33024)], 'Stim'] = event_type[np.where(event_type >= 33024)] raw_files.append( RawArray(data=data.values.T, info=info, verbose=False)) return raw_files
def _convert_run(run, ch_names=None, ch_types=None, verbose=None): """Convert one run to raw.""" # parse eeg data event_id = {} n_chan = run.X.shape[1] montage = read_montage('standard_1005') eeg_data = 1e-6 * run.X sfreq = run.fs if not ch_names: ch_names = ['EEG%d' % ch for ch in range(1, n_chan + 1)] montage = None # no montage if not ch_types: ch_types = ['eeg'] * n_chan trigger = np.zeros((len(eeg_data), 1)) # some runs does not contains trials i.e baseline runs if len(run.trial) > 0: trigger[run.trial - 1, 0] = run.y eeg_data = np.c_[eeg_data, trigger] ch_names = ch_names + ['stim'] ch_types = ch_types + ['stim'] event_id = {ev: (ii + 1) for ii, ev in enumerate(run.classes)} info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq, montage=montage) raw = RawArray(data=eeg_data.T, info=info, verbose=verbose) return raw, event_id
def _get_single_subject_data(self, subject): """return data for a single subject""" fname = self.data_path(subject) data = loadmat(fname, squeeze_me=True, struct_as_record=False, verify_compressed_data_integrity=False)['eeg'] eeg_ch_names = ['Fp1', 'AF7', 'AF3', 'F1', 'F3', 'F5', 'F7', 'FT7', 'FC5', 'FC3', 'FC1', 'C1', 'C3', 'C5', 'T7', 'TP7', 'CP5', 'CP3', 'CP1', 'P1', 'P3', 'P5', 'P7', 'P9', 'PO7', 'PO3', 'O1', 'Iz', 'Oz', 'POz', 'Pz', 'CPz', 'FPz', 'FP2', 'AF8', 'AF4', 'AFz', 'Fz', 'F2', 'F4', 'F6', 'F8', 'FT8', 'FC6', 'FC4', 'FC2', 'FCz', 'Cz', 'C2', 'C4', 'C6', 'T8', 'TP8', 'CP6', 'CP4', 'CP2', 'P2', 'P4', 'P6', 'P8', 'P10', 'PO8', 'PO4', 'O2'] emg_ch_names = ['EMG1', 'EMG2', 'EMG3', 'EMG4'] ch_names = eeg_ch_names + emg_ch_names + ['Stim'] ch_types = ['eeg'] * 64 + ['emg'] * 4 + ['stim'] montage = read_montage('standard_1005') eeg_data_l = np.vstack([data.imagery_left * 1e-6, data.imagery_event]) eeg_data_r = np.vstack([data.imagery_right * 1e-6, data.imagery_event * 2]) # trials are already non continuous. edge artifact can appears but # are likely to be present during rest / inter-trial activity eeg_data = np.hstack([eeg_data_l, eeg_data_r]) info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=data.srate, montage=montage) raw = RawArray(data=eeg_data, info=info, verbose=False) return {'session_0': {'run_0': raw}}
def _get_single_subject_data(self, subject): """return data for a single subject""" fname = '%s/subject %02d/with occular artifact/cnt.mat' % (self.base_folder, subject) fname_mrk = '%s/subject %02d/with occular artifact/mrk.mat' % (self.base_folder, subject) raws = [] data = loadmat(fname, squeeze_me=True, struct_as_record=False)['cnt'] mrk = loadmat(fname_mrk, squeeze_me=True, struct_as_record=False)['mrk'] montage = read_montage('standard_1005') if self.motor: runs = [0, 2, 4] else: runs = [1, 3, 5] for ii in runs: eeg = data[ii].x.T * 1e-6 trig = np.zeros((1, eeg.shape[1])) idx = (mrk[ii].time - 1) // 5 trig[0, idx] = mrk[ii].event.desc // 16 eeg = np.vstack([eeg, trig]) ch_names = list(data[ii].clab) + ['Stim'] ch_types = ['eeg'] * 30 + ['eog'] * 2 + ['stim'] info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=200., montage=montage) raw = RawArray(data=eeg, info=info, verbose=False) raws.append(raw) return raws
def creat_mne_raw_object(fname, read_events = True): print ("loading data from %s" %fname) data = pd.read_csv(fname) ch_names = list(data.columns[1:]) montage = read_montage('standard_1005', ch_names) ch_type = ['eeg']*len(ch_names) data = 1e-6*np.array(data[ch_names]).T if read_events: ev_fname = fname.replace('_data', '_events') print (ev_fname) events = pd.read_csv(ev_fname) events_names = events.columns[1:] events_data = np.array(events[events_names]).T ch_type.extend(['stim']*6) ch_names.extend(events_names) data = np.concatenate((data, events_data)) info = create_info(ch_names, sfreq=500.0, ch_types=ch_type, montage=montage) info['filename'] = fname raw = RawArray(data, info, verbose=True) return raw
def _convert_run_bbci(run, ch_types, verbose=None): """Convert one run to raw.""" # parse eeg data montage = read_montage('standard_1005') eeg_data = 1e-6 * run.X sfreq = run.fs ch_names = list(run.channels) trigger = np.zeros((len(eeg_data), 1)) trigger[run.trial - 1, 0] = run.y event_id = {ev: (ii + 1) for ii, ev in enumerate(run.classes)} flash = np.zeros((len(eeg_data), 1)) flash[run.trial - 1, 0] = run.y_stim + 2 ev_fl = {'Stim%d' % (stim): (stim + 2) for stim in np.unique(run.y_stim)} event_id.update(ev_fl) eeg_data = np.c_[eeg_data, trigger, flash] ch_names = ch_names + ['Target', 'Flash'] ch_types = ch_types + ['stim'] * 2 info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq, montage=montage) raw = RawArray(data=eeg_data.T, info=info, verbose=verbose) return raw, event_id
def creat_mne_raw_object(fname): """Create a mne raw instance from csv file""" # Read EEG file data = pd.read_csv(fname) # get chanel names ch_names = list(data.columns[1:]) # read EEG standard montage from mne montage = read_montage('standard_1005', ch_names) # events file ev_fname = fname.replace('_data', '_events') # read event file events = pd.read_csv(ev_fname) events_names = events.columns[1:] events_data = np.array(events[events_names]).T # concatenate event file and data data = np.concatenate((1e-6 * np.array(data[ch_names]).T, events_data)) # define channel type, the first is EEG, the last 6 are stimulations ch_type = ['eeg'] * len(ch_names) + ['stim'] * 6 # create and populate MNE info structure ch_names.extend(events_names) info = create_info(ch_names, sfreq=500.0, ch_types=ch_type, montage=montage) info['filename'] = fname # create raw object raw = RawArray(data, info, verbose=False) return raw
def _infer_eeg_placement_scheme(raw): """Based on the channel names, try to infer an EEG placement scheme. Parameters ---------- raw : instance of Raw The data as MNE-Python Raw object. Returns ------- placement_scheme : str Description of the EEG placement scheme. Will be "n/a" for unsuccessful extraction. """ placement_scheme = 'n/a' # Check if the raw data contains eeg data at all if 'eeg' not in raw: return placement_scheme # How many of the channels in raw are based on the extended 10/20 system raw.load_data() sel = pick_types(raw.info, meg=False, eeg=True) ch_names = [raw.ch_names[i] for i in sel] channel_names = [ch.lower() for ch in ch_names] montage1005 = read_montage(kind='standard_1005') montage1005_names = [ch.lower() for ch in montage1005.ch_names] if set(channel_names).issubset(set(montage1005_names)): placement_scheme = 'based on the extended 10/20 system' return placement_scheme
def creat_mne_raw_object(fname,read_events): # Read EEG file data = pd.read_csv(fname) # get chanel names ch_names = list(data.columns[1:]) # read EEG standard montage from mne montage = read_montage('standard_1005',ch_names) ch_type = ['eeg']*len(ch_names) data = 1e-6*np.array(data[ch_names]).T if read_events: # events file ev_fname = fname.replace('_data','_events') # read event file events = pd.read_csv(ev_fname) events_names = events.columns[1:] events_data = np.array(events[events_names]).T # define channel type, the first is EEG, the last 6 are stimulations ch_type.extend(['stim']*6) ch_names.extend(events_names) # concatenate event file and data data = np.concatenate((data,events_data)) # create and populate MNE info structure info = create_info(ch_names,sfreq=500.0, ch_types=ch_type, montage=montage) info['filename'] = fname # create raw object raw = RawArray(data,info,verbose=False) return raw
def _convert_run_epfl(run, verbose=None): """Convert one run to raw.""" # parse eeg data event_id = {} montage = read_montage('standard_1005') eeg_data = 1e-6 * run.eeg sfreq = run.header.SampleRate ch_names = list(run.header.Label[:-1]) ch_types = ['eeg'] * len(ch_names) trigger = np.zeros((len(eeg_data), 1)) for ii, typ in enumerate(run.header.EVENT.TYP): if typ in [6, 9]: # Error trigger[run.header.EVENT.POS[ii] - 1, 0] = 2 elif typ in [5, 10]: # correct trigger[run.header.EVENT.POS[ii] - 1, 0] = 1 eeg_data = np.c_[eeg_data, trigger] ch_names = ch_names + ['stim'] ch_types = ch_types + ['stim'] event_id = {'correct': 1, 'error': 2} info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq, montage=montage) raw = RawArray(data=eeg_data.T, info=info, verbose=verbose) return raw, event_id
def load_muse_csv_as_raw(filename, sfreq=256., ch_ind=[0, 1, 2, 3], stim_ind=5, replace_ch_names=None, verbose=1): """Load CSV files into a Raw object. Args: filename (str or list): path or paths to CSV files to load Keyword Args: subject_nb (int or str): subject number. If 'all', load all subjects. session_nb (int or str): session number. If 'all', load all sessions. sfreq (float): EEG sampling frequency ch_ind (list): indices of the EEG channels to keep stim_ind (int): index of the stim channel replace_ch_names (dict or None): dictionary containing a mapping to rename channels. Useful when an external electrode was used. Returns: (mne.io.array.array.RawArray): loaded EEG """ n_channel = len(ch_ind) raw = [] for fname in filename: # read the file data = pd.read_csv(fname, index_col=0) # name of each channels ch_names = list(data.columns)[0:n_channel] + ['Stim'] if replace_ch_names is not None: ch_names = [c if c not in replace_ch_names.keys() else replace_ch_names[c] for c in ch_names] # type of each channels ch_types = ['eeg'] * n_channel + ['stim'] montage = read_montage('standard_1005') # get data and exclude Aux channel data = data.values[:, ch_ind + [stim_ind]].T # convert in Volts (from uVolts) data[:-1] *= 1e-6 # create MNE object info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq, montage=montage, verbose=verbose) raw.append(RawArray(data=data, info=info, verbose=verbose)) # concatenate all raw objects if len(raw) > 0: raws = concatenate_raws(raw, verbose=verbose) else: print('No files for subject with filename ' + str(filename)) raws = raw return raws
def test_overwrite(tmp_path): saved_path = op.join(tmp_path, 'GSN-HydroCel-128.elc') Path(saved_path).touch() montage_orig = read_montage('GSN-HydroCel-128') save_montage(montage_orig, tmp_path, overwrite=True) montage_saved = read_montage(saved_path) scale = 1000 # in when loading elc mne-python converts to meters # Channels names should be good up to fiducials assert montage_orig.ch_names[3:] == montage_saved.ch_names[3:] assert np.allclose(montage_orig.pos, montage_saved.pos * scale) assert np.allclose(montage_orig.lpa, montage_saved.lpa * scale) assert np.allclose(montage_orig.rpa, montage_saved.rpa * scale) assert np.allclose(montage_orig.nasion, montage_saved.nasion * scale) assert montage_orig.kind == montage_saved.kind
def _set_raw_montage(raw): """Set montage for the raw object.""" montage = read_montage('standard_1005') raw.rename_channels(lambda x: str(x.strip('.')).upper() if str(x.strip( '.')).upper() in montage.ch_names else str(x.strip('.'))) raw.rename_channels(dict(Cpz='CPz', Poz='POz', Fcz='FCz', Afz='AFz')) raw.set_channel_types({'Fp1': 'eog'}) # artificially make an EOG channel raw.set_montage(montage)
def test_read_locs(): """Test reading EEGLAB locs.""" pos = read_montage(locs_montage_fname).pos expected = [[0., 9.99779165e-01, -2.10157875e-02], [3.08738197e-01, 7.27341573e-01, -6.12907052e-01], [-5.67059636e-01, 6.77066318e-01, 4.69067752e-01], [0., 7.14575231e-01, 6.99558616e-01]] assert_allclose(pos[:4], expected, atol=1e-7)
def validate_ch_names(list_of_ch_names, kind='standard_1005'): montage = read_montage(kind) upper_list_of_ch_names = [ch.upper() for ch in list_of_ch_names] upper_montage_ch_names = [ch.upper() for ch in montage.ch_names] if DEBUG or seems_to_come_from_neuromag(list_of_ch_names): bool_indices = [True for ch in upper_list_of_ch_names] else: bool_indices = [ch in upper_montage_ch_names for ch in upper_list_of_ch_names] return bool_indices
def test_plot_montage(): """Test plotting montages """ m = read_montage('easycap-M1') m.plot() m.plot(show_names=True) d = read_dig_montage(hsp, hpi, elp, point_names) d.plot() d.plot(show_names=True)
def _set_raw_montage(raw): """Set montage for the raw object.""" montage = read_montage('standard_1005') raw.rename_channels(lambda x: str(x.strip('.')).upper() if str(x.strip('.')).upper() in montage.ch_names else str(x.strip('.'))) raw.rename_channels(dict(Cpz='CPz', Poz='POz', Fcz='FCz', Afz='AFz')) raw.set_channel_types({'Fp1': 'eog'}) # artificially make an EOG channel raw.set_montage(montage)
def _load_data_003_2015(subject, path=None, force_update=False, update_path=None, base_url=BNCI_URL, verbose=None): """Load data for 003-2015 dataset.""" if (subject < 1) or (subject > 10): raise ValueError("Subject must be between 1 and 12. Got %d." % subject) url = '{u}003-2015/s{s:d}.mat'.format(u=base_url, s=subject) filename = data_path(url, path, force_update, update_path)[0] raws = list() event_id = {'Target': 2, 'Non-Target': 1} from scipy.io import loadmat data = loadmat(filename, struct_as_record=False, squeeze_me=True) data = data['s%d' % subject] sfreq = 256. ch_names = [ 'Fz', 'Cz', 'P3', 'Pz', 'P4', 'PO7', 'Oz', 'PO8', 'Target', 'Flash' ] ch_types = ['eeg'] * 8 + ['stim'] * 2 montage = read_montage('standard_1005') info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq, montage=montage) for run in [data.train, data.test]: # flash events on the channel 9 flashs = run[9:10] ix_flash = flashs[0] > 0 flashs[0, ix_flash] += 2 # add 2 to avoid overlapp on event id flash_code = np.unique(flashs[0, ix_flash]) if len(flash_code) == 36: # char mode evd = {'Char%d' % ii: (ii + 2) for ii in range(1, 37)} else: # row / column mode evd = {'Col%d' % ii: (ii + 2) for ii in range(1, 7)} evd.update({'Row%d' % ii: (ii + 8) for ii in range(1, 7)}) # target events are on channel 10 targets = np.zeros_like(flashs) targets[0, ix_flash] = run[10, ix_flash] + 1 eeg_data = np.r_[run[1:-2] * 1e-6, targets, flashs] raw = RawArray(data=eeg_data, info=info, verbose=verbose) raws.append(raw) event_id.update(evd) return raws, event_id
def view_montage(self): montage = read_montage(self.montages.selectedItems()[0].data(0)) fig = montage.plot(show_names=True, show=False) win = fig.canvas.manager.window win.setWindowModality(Qt.WindowModal) win.setWindowTitle("Montage") win.findChild(QStatusBar).hide() win.findChild(QToolBar).hide() fig.show()
def test_standard_superset(): """Test some properties that should hold for superset montages.""" with pytest.deprecated_call(): o_1005 = read_montage('standard_1005') # old montages o_1020 = read_montage('standard_1020') # new montages, tweaked to end up at the same size as the others m_1005 = make_standard_montage('standard_1005', 0.0970) m_1020 = make_standard_montage('standard_1020', 0.0991) assert len(set(m_1005.ch_names) - set(m_1020.ch_names)) > 0 # XXX weird that this is not a proper superset... assert set(m_1020.ch_names) - set(m_1005.ch_names) == {'O10', 'O9'} c_1005 = m_1005._get_ch_pos() for key, value in m_1020._get_ch_pos().items(): want = o_1020.pos[o_1020.ch_names.index(key)] assert_allclose(value, want, err_msg=key, atol=1e-4) if key not in ('O10', 'O9'): assert_allclose(o_1005.pos[o_1005.ch_names.index(key)], want, err_msg=key, atol=1e-4) assert_allclose(c_1005[key], value, atol=1e-4, err_msg=key)
def bci_to_raw(self, data): eeg_data = data[self.eeg_info[0], :] ch_types = ['eeg'] * 16 montage = read_montage('standard_1020') info = create_info(ch_names=self.eeg_info[2], sfreq=self.eeg_info[1], ch_types=ch_types, montage=montage) raw = RawArray(eeg_data, info) return raw
def test_plot_defect_montage(): """Test plotting defect montages (i.e. with duplicate labels).""" # montage name and number of unique labels montages = [('standard_1005', 342), ('standard_postfixed', 85), ('standard_primed', 85), ('standard_1020', 93)] for name, n in montages: m = read_montage(name) fig = m.plot() collection = fig.axes[0].collections[0] assert collection._edgecolors.shape[0] == n assert collection._facecolors.shape[0] == n assert collection._offsets.shape[0] == n
def creat_mne_raw_object(fname, idx_subject, read_events='HO'): """Create a mne raw instance from csv file.""" # Read EEG file # data = pd.read_csv(fname) data = np.loadtxt(fname, delimiter=',') data = data.T[2:, :] # get chanel names # ch_names = list(data.columns[1:]) ch_names = CH_NAMES # read EEG standard montage from mne montage = read_montage('standard_1005', ch_names) ch_type = ['eeg'] * len(ch_names) data = 1e-6 * np.array(data[:]) if read_events: # events file ev_fname = fname.replace('_data', '_events') # read event file events = pd.read_csv(ev_fname) events_names = ['Nothing', 'Positive', 'Negative'] # events_data = np.array(events[events_names]).T events_data = get_horizo_velocity() if read_events == 'HO' else \ get_vertic_velocity() if read_events == 'VE' else None events_data = events_data.T[idx_subject, :] events = np.zeros([3, events_data.shape[0]]) events[0, events_data == 0] = 1 events[1, events_data > 0] = 1 events[2, events_data < 0] = 1 # define channel type, the first is EEG, the last 6 are stimulations ch_type.extend(['stim'] * 3) # ch_names.extend(events_names) ch_names = ch_names + events_names # concatenate event file and data data = np.concatenate((data, events)) # create and populate MNE info structure info = create_info(ch_names, sfreq=128.0, ch_types=ch_type, montage=montage) info['experimento'] = fname # create raw object raw = RawArray(data, info, verbose=False) return raw
def ch_names_to_2d_pos(list_of_ch_names, kind='standard_1005', azimuthal=True): montage = read_montage(kind) if DEBUG or seems_to_come_from_neuromag(list_of_ch_names): return random.normal(size=(len(list_of_ch_names), 2)) upper_list_of_ch_names = [ch.upper() for ch in list_of_ch_names] upper_montage_ch_names = [ch.upper() for ch in montage.ch_names] indices = [upper_montage_ch_names.index(ch) if ch in upper_montage_ch_names else 0 for ch in upper_list_of_ch_names] if len(list(indices)) < len(list_of_ch_names): raise IndexError('Channels {} not found'.format( set(upper_list_of_ch_names).difference(set(array(upper_montage_ch_names)[indices])) )) pos = montage.pos[indices, :2] if not azimuthal else azimuthal_equidistant_projection(montage.pos[indices, :3]) return array(pos)
def load_csv_as_raw(filename, sfreq, ch_ind, stim_ind, replace_ch_names): """Load CSV files into a Raw object. Args: filename (str or list): path or paths to CSV files to load Keyword Args: sfreq (float): EEG sampling frequency ch_ind (list): indices of the EEG channels to keep stim_ind (int): index of the stim channel replace_ch_names (dict or None): dictionary containing a mapping to rename channels. Returns: (mne.io.array.array.RawArray): loaded EEG """ n_channel = len(ch_ind) raw = [] print(filename) for fname in filename: # read the file data = pd.read_csv(fname, index_col=0) # name of each channels ch_names = list(data.columns)[0:n_channel] + ['Stim'] if replace_ch_names is not None: ch_names = [ c if c not in replace_ch_names.keys() else replace_ch_names[c] for c in ch_names ] # type of each channels ch_types = ['eeg'] * n_channel + ['stim'] montage = read_montage('standard_1005') # get data and exclude Aux channel data = data.values[:, ch_ind + [stim_ind]].T # create MNE object info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq, montage=montage) raw.append(RawArray(data=data, info=info)) # concatenate all raw objects raws = concatenate_raws(raw) return raws
def test_gen_raw_ch(): """Test that _generate_raw responds to channel settings.""" raw = _generate_raw(duration=1, n_chan=1) assert_sequence_equal(raw.ch_names, ['0', 'STI 014']) raw = _generate_raw(duration=1, n_chan=1, ch_names=['bob']) assert_sequence_equal(raw.ch_names, ['bob', 'STI 014']) raw = _generate_raw(duration=1, n_chan=1, ch_names='standard_1020') montage = read_montage('standard_1020') raw = raw.pick_types(eeg=True) assert_true(np.all([ch in montage.ch_names for ch in raw.ch_names]))
def view_montage(self): if self.montage_path == '': kind = self.montages.selectedItems()[0].data(0) montage = read_montage(kind) else: from ..utils.montage import xyz_to_montage montage = xyz_to_montage(self.montage_path) fig = montage.plot(show_names=True, show=False) win = fig.canvas.manager.window win.setWindowModality(Qt.WindowModal) win.setWindowTitle("Montage") win.findChild(QStatusBar).hide() win.findChild(QToolBar).hide() fig.show()
def add_montage(mne_raw, channels='data/misc/channel-names.txt'): ''' Creates 'standard_1005' montage with corrected channel names and adds it to MNE raw object. Arguments: mne_raw: MNE Raw object Returns: MNE Raw object (modified in place) ''' ch_names = open(channels).read().splitlines() montage = read_montage('standard_1005', ch_names=ch_names) mne_raw.set_montage(montage)
def test_set_montage(): """Test setting a montage.""" raw = read_raw_fif(fif_fname) orig_pos = np.array([ch['loc'][:3] for ch in raw.info['chs'] if ch['ch_name'].startswith('EEG')]) raw.set_montage('mgh60') # test loading with string argument new_pos = np.array([ch['loc'][:3] for ch in raw.info['chs'] if ch['ch_name'].startswith('EEG')]) assert ((orig_pos != new_pos).all()) r0 = _fit_sphere(new_pos)[1] assert_allclose(r0, [0., -0.016, 0.], atol=1e-3) # mgh70 has no 61/62/63/64 (these are EOG/ECG) mon = read_montage('mgh70') assert 'EEG061' not in mon.ch_names assert 'EEG074' in mon.ch_names
def toMNE(X, y=None): """Tranform array into MNE for epoching.""" ch_names = getChannelNames() montage = read_montage('standard_1005', ch_names) ch_type = ['eeg']*len(ch_names) data = X.T if y is not None: y = y.transpose() ch_type.extend(['stim']*6) event_names = getEventNames() ch_names.extend(event_names) # concatenate event file and data data = np.concatenate((data, y)) info = create_info(ch_names, sfreq=500.0, ch_types=ch_type, montage=montage) raw = RawArray(data, info, verbose=False) return raw
def test_plot_montage(): """Test plotting montages.""" m = read_montage('easycap-M1') m.plot() plt.close('all') m.plot(kind='3d') plt.close('all') m.plot(kind='3d', show_names=True) plt.close('all') m.plot(kind='topomap') plt.close('all') m.plot(kind='topomap', show_names=True) plt.close('all') d = read_dig_montage(hsp, hpi, elp, point_names) assert '0 channels' in repr(d) with pytest.raises(RuntimeError, match='No valid channel positions'): d.plot() d = read_dig_montage(fif=fif_fname) assert '61 channels' in repr(d)
def convert_to_raw(file_series, file_events): """Create a mne raw instance from csv file""" data = pd.read_csv(file_series) channels = list(data.columns[1:]) m1 = read_montage('standard_1005',channels) ch_type = ['eeg']*len(channels) data = 1e-6*np.array(data[channels]).T # read event file events_data = pd.read_csv(file_events) events_names = events_data.columns[1:] events_data = np.array(events_data[events_names]).T #print events_data # define channel type, the first is EEG, the last 6 are stimulations ch_type.extend(['stim']*6) channels.extend(events_names) # concatenate event file and data data = np.concatenate((data,events_data)) info = create_info(channels, sfreq=500.0, ch_types=ch_type, montage=m1) info['filename'] = file_series raw = RawArray(data,info,verbose=False) print raw print raw[0:] print raw[0][0] print raw[0][1] return raw
def test_plot_montage(): """Test plotting montages.""" import matplotlib.pyplot as plt m = read_montage('easycap-M1') m.plot() plt.close('all') m.plot(kind='3d') plt.close('all') m.plot(kind='3d', show_names=True) plt.close('all') m.plot(kind='topomap') plt.close('all') m.plot(kind='topomap', show_names=True) plt.close('all') d = read_dig_montage(hsp, hpi, elp, point_names) d.plot() plt.close('all') d.plot(kind='3d') plt.close('all') d.plot(kind='3d', show_names=True) plt.close('all')
def create_mne_raw_object(fname, read_events=True): """Create a mne raw instance from csv file.""" # Read EEG file data = pd.read_csv(fname) print fname, data.shape # get chanel names ch_names = list(data.columns[1:]) print ch_names # read EEG standard montage from mne montage = read_montage("standard_1005", ch_names) ch_type = ["eeg"] * len(ch_names) data = 1e-6 * np.array(data[ch_names]).T if read_events: # events file ev_fname = fname.replace("_data", "_events") # read event file events = pd.read_csv(ev_fname) events_names = events.columns[1:] events_data = np.array(events[events_names]).T # define channel type, the first is EEG, the last 6 are stimulations ch_type.extend(["stim"] * 6) ch_names.extend(events_names) # concatenate event file and data data = np.concatenate((data, events_data)) # create and populate MNE info structure info = create_info(ch_names, sfreq=500.0, ch_types=ch_type, montage=montage) info["filename"] = fname # create raw object raw = RawArray(data, info, verbose=False) return raw
def test_plot_montage(): """Test plotting montages """ read_montage('easycap-M1').plot()
def importbdf(bdfname, nchans=34, refchans=['EXG1', 'EXG2'], hptsname=None, mask=255, extrachans=[], exclude=None, verbose=None): """Wrapper around mne-python to import BDF files Parameters ---------- bdfname - Name of the biosemi .bdf filename with full path nchans - Number of EEG channels (including references) (Optional) By default, 34 (32 + 2 references) refchans - list of strings with reference channel names (Optional) By default ['EXG1','EXG2']. Use None for average reference. hptsname - Name of the electrode position file in .hpts format with path (Optional) By default a 32 channel Biosemi layout is used. If the nchans is >= 64 and < 96, a 64 channel Biosemi layout is used. If nchans >= 96, a 96 channel biosemi layout is used. Formats other than .hpts will also likely work, but behavior may vary. mask - Integer mask to use for trigger channel (Default is 255). extrachans - Additional channels other than EEG and EXG that may be in the bdf file. These will be marked as MISC in mne-python. Specify as list of names. excllude - List of channel names to exclude from importing verbose - bool, str, int, or None (Optional) The verbosity of messages to print. If a str, it can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Returns ------- raw - MNE raw data object of rereferences and preloaded data eves - Event list (3 column array as required by mne.Epochs) Requires -------- mne-python module > release 0.7 """ # Default HPTS file if(hptsname is None): anlffr_root = os.path.dirname(sys.modules['anlffr'].__file__) if nchans >= 64 and nchans < 96: logger.info('Number of channels is greater than 64.' ' Hence loading a 64 channel montage.') hptspath = os.path.join(anlffr_root, 'helper/sysfiles/') hptsname = 'biosemi64' montage = read_montage(kind=hptsname, path=hptspath, transform=True) misc = ['EXG3', 'EXG4', 'EXG5', 'EXG6', 'EXG7', 'EXG8'] else: if nchans >= 96: logger.info('Number of channels is greater than 96.' ' Hence loading a 96 channel montage.') hptspath = os.path.join(anlffr_root, 'helper/sysfiles/') hptsname = 'biosemi96' montage = read_montage(kind=hptsname, path=hptspath, transform=True) misc = ['EXG3', 'EXG4', 'EXG5', 'EXG6', 'EXG7', 'EXG8'] else: if nchans == 2: logger.info('Number of channels is 2.' 'Guessing ABR montage.') montage = None misc = [] else: logger.info('Loading a default 32 channel montage.') hptspath = os.path.join(anlffr_root, 'helper/sysfiles/') hptsname = 'biosemi32' montage = read_montage(kind=hptsname, path=hptspath, transform=True) misc = ['EXG3', 'EXG4', 'EXG5', 'EXG6', 'EXG7', 'EXG8'] misc += extrachans raw = edf.read_raw_edf(bdfname, montage=montage, preload=True, misc=misc, exclude=exclude, stim_channel='Status') # Rereference if refchans is not None: sys.stdout.write('Re-referencing data to: ' + ' '.join(refchans)) (raw, ref_data) = set_eeg_reference(raw, refchans, copy=False) raw.info['bads'] += refchans else: # Add average reference operator for possible use later ave_ref_operator = make_eeg_average_ref_proj(raw.info, activate=False) raw = raw.add_proj(ave_ref_operator) eves = find_events(raw, shortest_event=1, mask=mask) return (raw, eves)
def test_montage(): """Test making montages""" tempdir = _TempDir() # no pep8 input_str = ["""FidNz 0.00000 10.56381 -2.05108 FidT9 -7.82694 0.45386 -3.76056 FidT10 7.82694 0.45386 -3.76056""", """// MatLab Sphere coordinates [degrees] Cartesian coordinates // Label Theta Phi Radius X Y Z off sphere surface E1 37.700 -14.000 1.000 0.7677 0.5934 -0.2419 -0.00000000000000011 E2 44.600 -0.880 1.000 0.7119 0.7021 -0.0154 0.00000000000000000 E3 51.700 11.000 1.000 0.6084 0.7704 0.1908 0.00000000000000000""", # noqa """# ASA electrode file ReferenceLabel avg UnitPosition mm NumberPositions= 68 Positions -86.0761 -19.9897 -47.9860 85.7939 -20.0093 -48.0310 0.0083 86.8110 -39.9830 Labels LPA RPA Nz """, """Site Theta Phi Fp1 -92 -72 Fp2 92 72 F3 -60 -51 """, """346 EEG F3 -62.027 -50.053 85 EEG Fz 45.608 90 85 EEG F4 62.01 50.103 85 """, """ eeg Fp1 -95.0 -31.0 -3.0 eeg AF7 -81 -59 -3 eeg AF3 -87 -41 28 """] kinds = ['test.sfp', 'test.csd', 'test.elc', 'test.txt', 'test.elp', 'test.hpts'] for kind, text in zip(kinds, input_str): fname = op.join(tempdir, kind) with open(fname, 'w') as fid: fid.write(text) montage = read_montage(fname) assert_equal(len(montage.ch_names), 3) assert_equal(len(montage.ch_names), len(montage.pos)) assert_equal(montage.pos.shape, (3, 3)) assert_equal(montage.kind, op.splitext(kind)[0]) if kind.endswith('csd'): dtype = [('label', 'S4'), ('theta', 'f8'), ('phi', 'f8'), ('radius', 'f8'), ('x', 'f8'), ('y', 'f8'), ('z', 'f8'), ('off_sph', 'f8')] try: table = np.loadtxt(fname, skip_header=2, dtype=dtype) except TypeError: table = np.loadtxt(fname, skiprows=2, dtype=dtype) pos2 = np.c_[table['x'], table['y'], table['z']] assert_array_almost_equal(pos2, montage.pos, 4) # test transform input_str = """ eeg Fp1 -95.0 -31.0 -3.0 eeg AF7 -81 -59 -3 eeg AF3 -87 -41 28 cardinal nasion -91 0 -42 cardinal lpa 0 -91 -42 cardinal rpa 0 91 -42 """ kind = 'test_fid.hpts' fname = op.join(tempdir, kind) with open(fname, 'w') as fid: fid.write(input_str) montage = read_montage(op.join(tempdir, 'test_fid.hpts'), transform=True) # check coordinate transformation pos = np.array([-95.0, -31.0, -3.0]) nasion = np.array([-91, 0, -42]) lpa = np.array([0, -91, -42]) rpa = np.array([0, 91, -42]) fids = np.vstack((nasion, lpa, rpa)) trans = get_ras_to_neuromag_trans(fids[0], fids[1], fids[2]) pos = apply_trans(trans, pos) assert_array_equal(montage.pos[0], pos) idx = montage.ch_names.index('nasion') assert_array_equal(montage.pos[idx, [0, 2]], [0, 0]) idx = montage.ch_names.index('lpa') assert_array_equal(montage.pos[idx, [1, 2]], [0, 0]) idx = montage.ch_names.index('rpa') assert_array_equal(montage.pos[idx, [1, 2]], [0, 0]) pos = np.array([-95.0, -31.0, -3.0]) montage = read_montage(op.join(tempdir, 'test_fid.hpts'), unit='mm') assert_array_equal(montage.pos[0], pos * 1e-3) # test with last info = create_info(montage.ch_names, 1e3, ['eeg'] * len(montage.ch_names)) apply_montage(info, montage) pos2 = np.array([c['loc'][:3] for c in info['chs']]) pos3 = np.array([c['eeg_loc'][:, 0] for c in info['chs']]) assert_array_equal(pos2, montage.pos) assert_array_equal(pos3, montage.pos) assert_equal(montage.ch_names, info['ch_names'])