from pyriemann.stats import PermutationTestTwoWay, PermutationTest from pyriemann.estimation import Covariances ############################################################################### ## Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = -2., 6. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [ read_raw_edf(f, preload=True, verbose=False) for f in eegbci.load_data(subject, runs) ] raw = concatenate_raws(raw_files) # strip channel names raw.info['ch_names'] = [chn.strip('.') for chn in raw.info['ch_names']] events = find_events(raw, shortest_event=0, stim_channel='STI 014') picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads')
from mne.event import find_events from pyriemann.stats import PermutationTest from pyriemann.estimation import Covariances ############################################################################### ## Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 3. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [read_raw_edf(f, preload=True,verbose=False) for f in eegbci.load_data(subject, runs) ] raw = concatenate_raws(raw_files) # strip channel names raw.info['ch_names'] = [chn.strip('.') for chn in raw.info['ch_names']] # Apply band-pass filter raw.filter(7., 35., method='iir') events = find_events(raw, shortest_event=0, stim_channel='STI 014') picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,
from mne.channels import read_layout print(__doc__) # ############################################################################# # # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = -1., 4. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_fnames = eegbci.load_data(subject, runs) raw_files = [read_raw_edf(f, preload=True) for f in raw_fnames] raw = concatenate_raws(raw_files) # strip channel names raw.info['ch_names'] = [chn.strip('.') for chn in raw.info['ch_names']] # Apply band-pass filter raw.filter(7., 30., method='iir') events = find_events(raw, shortest_event=0, stim_channel='STI 014') picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier
from mne.event import find_events from pyriemann.stats import PermutationTest from pyriemann.estimation import CospCovariances ############################################################################### # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 3. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [read_raw_edf(f, preload=True, verbose=False) for f in eegbci.load_data(subject, runs)] raw = concatenate_raws(raw_files) events = find_events(raw, shortest_event=0, stim_channel='STI 014') picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=True, add_eeg_ref=False, verbose=False) labels = epochs.events[:, -1] - 2 # get epochs epochs_data = epochs.get_data()
sns.lineplot(data=dfd, x="wlen", y="dist", hue="estimator", ax=ax) ax.set_title("Distance to groundtruth covariance matrix") ax.set_xlabel("Number of time samples") ax.set_ylabel(r"$\delta(\Sigma, \hat{\Sigma})$") plt.tight_layout() ############################################################################### # Choice of estimator for motor imagery data # ------------------------------------------- # Loading data from PhysioNet MI dataset, for subject 1. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [ read_raw_edf(f, preload=True, stim_channel="auto") for f in eegbci.load_data(subject, runs) ] raw = concatenate_raws(raw_files) picks = pick_types(raw.info, eeg=True, exclude="bads") # subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7.0, 35.0, method="iir", picks=picks, skip_by_annotation="edge") events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) event_ids = dict(hands=2, feet=3) ############################################################################### # Influence of shrinkage to estimate covariance # -----------------------------------------------
from sklearn.cross_validation import cross_val_score, KFold from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression ############################################################################### # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 2. event_id = dict(hands=2, feet=3) subject = 7 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [ read_raw_edf(f, preload=True) for f in eegbci.load_data(subject, runs) ] raw = concatenate_raws(raw_files) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7., 35., method='iir', picks=picks)
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 get_score(subject=7): ############################################################################### # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 2. event_id = dict(hands=2, feet=3) runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [ read_raw_edf(f, preload=True) for f in eegbci.load_data(subject, runs) ] raw = concatenate_raws(raw_files) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7., 35., method='iir', picks=picks) events = find_events(raw, shortest_event=0, stim_channel='STI 014') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=None, preload=True, verbose=False) labels = epochs.events[:, -1] - 2 # cross validation cv = KFold(len(labels), 10, shuffle=True, random_state=42) # get epochs epochs_data_train = 1e6 * epochs.get_data() # compute covariance matrices cov_data_train = Covariances().transform(epochs_data_train) ############################################################################### # Classification with Minimum distance to mean mdm = MDM(metric=dict(mean='riemann', distance='riemann')) # Use scikit-learn Pipeline with cross_val_score function mdm.fit(cov_data_train, labels) print(123) ############################################################################### # Classification with Tangent Space Logistic Regression clf = TSclassifier() # Use scikit-learn Pipeline with cross_val_score function scores = cross_val_score(clf, cov_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) ts_score = np.mean(scores) print("Tangent space Classification accuracy: %f / Chance level: %f" % (ts_score, class_balance)) ############################################################################### return [subject, mdm_score, ts_score]
def edf_loader(self, single_file): raw = read_raw_edf(single_file, preload=True) # print "raw: " # print raw # print "number of channels: %d, type: %s, raw.ch_names: " % (len(raw.ch_names), type(raw.ch_names)) # print raw.ch_names start, stop = raw.time_as_index([0, 150]) ch_start = 2 ch_end = 16 data, times = raw[ch_start:ch_end, start:stop] # print data.shape # print type(data) # print raw.ch_names[2:16] # print "TTTTTTTTTTTTTTTTTTTTTTT" # print type(times) # print np.shape(times) # print times # print "TTTTTTTTTTTTTTTTTTTTTTT" cha_names = [] for n in raw.ch_names: str_n = str(n) # str_n = str(unicodedata.normalize('NFKD', n).encode('ascii', 'ignore')) cha_names.append(str_n) # print type(raw.ch_names[0]) # print "cha_names: " # print cha_names data_dict = {i[0]: i[1:] for i in zip(cha_names[2:16], data)} # print "data: " # print data # print "data_dict['AF3']: " # print len(data_dict['AF3'][0]) d_dict = {} for k, v in data_dict.iteritems(): d_dict[k] = v[0] # print "d_dict['AF3']:" # print len(d_dict['AF3']) raw.info['ch_names'] = [chn.strip('.') for chn in raw.info['ch_names']] raw.filter(2., 30., method='iir') events = find_events(raw, shortest_event=0, stim_channel='STI 014') print "events: " print events picks = pick_types(raw.info, meg=False, eeg=True, stim=False, exclude='bads') """ epochs = Epochs(raw, events, self.event_id, self.tmin, self.tmax, proj=True, picks=picks, baseline=None, preload=True, add_eeg_ref=False) epoch_train = epochs.crop(tmin=1., tmax=2., copy=True) labels = epochs.event[:, -1] - 2 """ # raw.info['ch_names'] = [chn.strip('.') for chn in raw.info['ch_names']] # epochs = Epochs() # print "picks: " # print picks # print raw[picks] # print type(raw) # print raw.info # print d_dict # print d_dict.keys() return d_dict
from mne.event import find_events from mne.decoding import CSP from mne.layouts import read_layout ############################################################################### ## Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = -1.0, 4.0 event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_fnames = eegbci.load_data(subject, runs) raw_files = [read_raw_edf(f, tal_channel=-1, preload=True) for f in raw_fnames] raw = concatenate_raws(raw_files) # strip channel names raw.info["ch_names"] = [chn.strip(".") for chn in raw.info["ch_names"]] # Apply band-pass filter raw.filter(7.0, 30.0, method="iir") events = find_events(raw, shortest_event=0, stim_channel="STI 014") picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(
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)
from sklearn.cross_validation import cross_val_score, KFold from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.lda import LDA ############################################################################### # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 2. event_id = dict(hands=2, feet=3) subject = 7 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [read_raw_edf(f, preload=True) for f in eegbci.load_data(subject, runs)] raw = concatenate_raws(raw_files) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7., 35., method='iir', picks=picks) events = find_events(raw, shortest_event=0, stim_channel='STI 014') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier
from mne.event import find_events from mne.decoding import CSP from mne.layouts import read_layout ############################################################################### ## Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = -1., 4. event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_fnames = eegbci.load_data(subject, runs) raw_files = [read_raw_edf(f, tal_channel=-1, preload=True) for f in raw_fnames] raw = concatenate_raws(raw_files) # strip channel names raw.info['ch_names'] = [chn.strip('.') for chn in raw.info['ch_names']] # Apply band-pass filter raw.filter(7., 30., method='iir') events = find_events(raw, shortest_event=0, stim_channel='STI 014') picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False,
# sklearn imports from sklearn.cross_validation import cross_val_score, KFold from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression ############################################################################### # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = 1., 2. event_id = dict(hands=2, feet=3) subject = 7 runs = [6, 10, 14] # motor imagery: hands vs feet raw_files = [read_raw_edf(f, preload=True) for f in eegbci.load_data(subject, runs)] raw = concatenate_raws(raw_files) picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads') # subsample elecs picks = picks[::2] # Apply band-pass filter raw.filter(7., 35., method='iir', picks=picks) events = find_events(raw, shortest_event=0, stim_channel='STI 014') # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier
from mne.channels import read_layout print(__doc__) # ############################################################################# # # Set parameters and read data # avoid classification of evoked responses by using epochs that start 1s after # cue onset. tmin, tmax = -1.0, 4.0 event_id = dict(hands=2, feet=3) subject = 1 runs = [6, 10, 14] # motor imagery: hands vs feet raw_fnames = eegbci.load_data(subject, runs) raw_files = [read_raw_edf(f, preload=True) for f in raw_fnames] raw = concatenate_raws(raw_files) # strip channel names raw.info["ch_names"] = [chn.strip(".") for chn in raw.info["ch_names"]] # Apply band-pass filter raw.filter(7.0, 30.0, method="iir") events = find_events(raw, shortest_event=0, stim_channel="STI 014") picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude="bads") # Read epochs (train will be done only between 1 and 2s) # Testing will be done with a running classifier epochs = Epochs(