Ejemplo n.º 1
0
    def _get_single_subject_data(self, subject, stack_sessions):
        """return data for a single subject"""
        all_files = []
        raw_fnames = eegbci.load_data(
            subject,
            runs=self.hand_runs,
            verbose='ERROR',
            base_url='http://www.physionet.org/pn4/eegmmidb/')
        raw_files = [
            read_raw_edf(f, preload=True, verbose='ERROR') for f in raw_fnames
        ]

        # strip channel names of "." characters
        [raw.rename_channels(lambda x: x.strip('.')) for raw in raw_files]
        all_files.extend(raw_files)

        raw_feet_fnames = eegbci.load_data(subject,
                                           runs=self.feet_runs,
                                           verbose='ERROR')
        raw_feet_files = [
            read_raw_edf(f, preload=True, verbose='ERROR')
            for f in raw_feet_fnames
        ]
        for raw in raw_feet_files:
            events = mne.find_events(raw)
            # Event values are added together, previous and current (1,2,3->1,4,5)
            events[events[:, 2] != 1, 2] = 2
            events[events[:, 2] == 1, 2] = 0
            raw.add_events(events)
            raw.rename_channels(lambda x: x.strip('.'))
        all_files.extend(raw_feet_files)
        if stack_sessions:
            return [all_files]
        else:
            return [[all_files]]
Ejemplo n.º 2
0
    def _get_single_subject_data(self, subject, stack_sessions):
        """return data for a single subject"""
        all_files = []
        raw_fnames = eegbci.load_data(subject,
                                      runs=self.hand_runs,
                                      verbose='ERROR')
        raw_files = [
            read_raw_edf(f, preload=True, verbose='ERROR') for f in raw_fnames
        ]

        # strip channel names of "." characters
        [raw.rename_channels(lambda x: x.strip('.')) for raw in raw_files]
        all_files.extend(raw_files)

        raw_feet_fnames = eegbci.load_data(subject,
                                           runs=self.feet_runs,
                                           verbose='ERROR')
        raw_feet_files = [
            read_raw_edf(f, preload=True, verbose='ERROR')
            for f in raw_feet_fnames
        ]
        for raw in raw_feet_files:
            events = mne.find_events(raw)
            events[events[:, 2] == 2, 2] = 2
            events[events[:, 2] == 3, 2] = 2
            events[events[:, 2] == 1, 2] = 0
            raw.add_events(events)
            raw.rename_channels(lambda x: x.strip('.'))
        all_files.extend(raw_feet_files)
        if not stack_sessions:
            return [[all_files]]
        else:
            return [all_files]
Ejemplo n.º 3
0
def loadthings(subject):
    runs = [6, 10, 14]
    raw_fnames = eegbci.load_data(subject, runs)
    raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])

    raw_fnames = eegbci.load_data(subject, runs)
    raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])
    eegbci.standardize(raw)
    #create 10-05 system
    montage = make_standard_montage('standard_1005')
    raw.set_montage(montage)
    raw.filter(7, 13)
    events, _ = events_from_annotations(raw, event_id=dict(T1=0, T2=1))
    #0: left, 1:right
    picks = pick_types(raw.info,
                       meg=False,
                       eeg=True,
                       stim=False,
                       eog=False,
                       exclude='bads')

    tmin, tmax = -1, 4
    epochs = Epochs(raw,
                    events,
                    None,
                    tmin,
                    tmax,
                    proj=True,
                    picks=picks,
                    baseline=None,
                    preload=True)
    #epochs_train=epochs.copy().crop(0,2)
    epochs_train = epochs.copy().crop(0, 2)
    labels = epochs.events[:, -1]

    # %%
    epochs_train_data = epochs_train.get_data()
    labels = epochs_train.events[:, -1]

    ad = np.array(epochs_train_data)
    All_Data = ad.reshape(
        64, epochs_train_data.shape[2] * epochs_train_data.shape[0])

    labels = labels.reshape(45, 1)

    extended = []
    for i in range(321):
        extended.append(labels)
    extended = np.array(extended)
    extended = extended.reshape(45, 321)
    extended = extended.T
    Labels = extended
    #np.savetxt("pythondata/extended.csv", extended)

    row, column = Labels.shape
    Labels = Labels.reshape(1, row * column)
    Labels = Labels.T

    return All_Data, Labels
Ejemplo n.º 4
0
    def data_path(self, subject, path=None, force_update=False,
                  update_path=None, verbose=None):
        if subject not in self.subject_list:
            raise(ValueError("Invalid subject number"))

        paths = []
        paths += eegbci.load_data(subject, runs=self.feet_runs,
                                  verbose=verbose)
        paths += eegbci.load_data(subject, runs=self.hand_runs,
                                  verbose=verbose)
        return paths
Ejemplo n.º 5
0
def get_eeg_data(subject, runs, event_id):
    tmin, tmax = -1.0, 4.0

    # Get and prepare the raw data
    raw_fnames = eegbci.load_data(subject, runs)
    raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])
    eegbci.standardize(raw)
    montage = make_standard_montage('standard_1005')
    raw.set_montage(montage)
    raw.rename_channels(lambda x: x.strip('.'))
    raw.filter(7.0, 30.0, fir_design='firwin', skip_by_annotation='edge')

    events, _ = events_from_annotations(raw, event_id=event_id)

    picks = pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False,
                exclude='bads')

    epochs = Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks,
                baseline=None, preload=True)

    labels = epochs.events[:, -1]

    epochs_data = epochs.get_data()

    return raw.info['sfreq'], epochs_data, labels
Ejemplo n.º 6
0
def get_real_eeg_data(start=0, stop=4, chans=4):
    """Get real EEG data for plotting.

    Keyword Args:
        start (float): start of the EEG segment, in seconds.
        stop (float): end of the EEG segment, in seconds.
        chans (int or list): number of channels to extract, or list of channel
            indices to be interpreted by MNE's get_data() function.
    """
    raw_fnames = eegbci.load_data(1, 2)
    raws = [read_raw_edf(f, preload=True) for f in raw_fnames]
    raw = concatenate_raws(raws)

    fs = raw.info['sfreq']
    start = int(fs * start)
    stop = int(fs * stop)

    if not isinstance(chans, list):
        chans = np.arange(chans)
    data, t = raw.get_data(picks=chans,
                           start=start,
                           stop=stop,
                           return_times=True)
    data = data.T

    return data, t, fs
Ejemplo n.º 7
0
 def _load_one_run(self, subject, run, preload=True):
     if get_config("MNE_DATASETS_EEGBCI_PATH") is None:
         set_config("MNE_DATASETS_EEGBCI_PATH",
                    osp.join(osp.expanduser("~"), "mne_data"))
     raw_fname = eegbci.load_data(subject,
                                  runs=[run],
                                  verbose="ERROR",
                                  base_url=BASE_URL)[0]
     raw = read_raw_edf(raw_fname, preload=preload, verbose="ERROR")
     raw.rename_channels(lambda x: x.strip("."))
     raw.rename_channels(lambda x: x.upper())
     # fmt: off
     renames = {
         "AFZ": "AFz",
         "PZ": "Pz",
         "FPZ": "Fpz",
         "FCZ": "FCz",
         "FP1": "Fp1",
         "CZ": "Cz",
         "OZ": "Oz",
         "POZ": "POz",
         "IZ": "Iz",
         "CPZ": "CPz",
         "FP2": "Fp2",
         "FZ": "Fz",
     }
     # fmt: on
     raw.rename_channels(renames)
     raw.set_montage(mne.channels.make_standard_montage("standard_1005"))
     return raw
Ejemplo n.º 8
0
def raw_clean(montage):
    """Return an `mne.io.Raw` object with no bad channels for use with tests.

    This fixture downloads and reads in subject 30, run 2 from the Physionet
    BCI2000 (eegbci) open dataset, which contains no bad channels on an initial
    pass of :class:`pyprep.NoisyChannels`. Intended for use with tests where
    channels are made artificially bad.

    File attributes:
    - Channels: 64 EEG
    - Sample rate: 160 Hz
    - Duration: 61 seconds

    This is only run once per session to save time downloading.

    """
    mne.set_log_level("WARNING")

    # Download and read S030R02.edf from the BCI2000 dataset
    edf_fpath = eegbci.load_data(30, 2, update_path=True)[0]
    raw = mne.io.read_raw_edf(edf_fpath, preload=True)
    eegbci.standardize(raw)  # Fix non-standard channel names

    # Set a montage for use with RANSAC
    raw.set_montage(montage)

    return raw
Ejemplo n.º 9
0
 def _load_one_run(self, subject, run, preload=True):
     if get_config('MNE_DATASETS_EEGBCI_PATH') is None:
         set_config('MNE_DATASETS_EEGBCI_PATH',
                    osp.join(osp.expanduser("~"), "mne_data"))
     raw_fname = eegbci.load_data(subject,
                                  runs=[run],
                                  verbose='ERROR',
                                  base_url=BASE_URL)[0]
     raw = read_raw_edf(raw_fname, preload=preload, verbose='ERROR')
     raw.rename_channels(lambda x: x.strip('.'))
     raw.rename_channels(lambda x: x.upper())
     raw.rename_channels({
         'AFZ': 'AFz',
         'PZ': 'Pz',
         'FPZ': 'Fpz',
         'FCZ': 'FCz',
         'FP1': 'Fp1',
         'CZ': 'Cz',
         'OZ': 'Oz',
         'POZ': 'POz',
         'IZ': 'Iz',
         'CPZ': 'CPz',
         'FP2': 'Fp2',
         'FZ': 'Fz'
     })
     raw.set_montage(mne.channels.make_standard_montage('standard_1005'))
     return raw
Ejemplo n.º 10
0
 def _load_one_run(self, subject, run, preload=True):
     raw_fname = eegbci.load_data(subject, runs=[run], verbose='ERROR',
                                  base_url=BASE_URL)[0]
     raw = read_raw_edf(raw_fname, preload=preload, verbose='ERROR')
     raw.rename_channels(lambda x: x.strip('.'))
     raw.set_montage(mne.channels.read_montage('standard_1005'))
     return raw
Ejemplo n.º 11
0
 def _load_one_run(self, subject, run, preload=True):
     raw_fname = eegbci.load_data(subject,
                                  runs=[run],
                                  verbose="ERROR",
                                  base_url=BASE_URL)[0]
     raw = read_raw_edf(raw_fname, preload=preload, verbose="ERROR")
     raw.rename_channels(lambda x: x.strip("."))
     raw.rename_channels(lambda x: x.upper())
     # fmt: off
     renames = {
         "AFZ": "AFz",
         "PZ": "Pz",
         "FPZ": "Fpz",
         "FCZ": "FCz",
         "FP1": "Fp1",
         "CZ": "Cz",
         "OZ": "Oz",
         "POZ": "POz",
         "IZ": "Iz",
         "CPZ": "CPz",
         "FP2": "Fp2",
         "FZ": "Fz",
     }
     # fmt: on
     raw.rename_channels(renames)
     raw.set_montage(mne.channels.make_standard_montage("standard_1005"))
     return raw
Ejemplo n.º 12
0
def get_data():
    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 = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])

    # strip channel names of "." characters
    raw.rename_channels(lambda x: x.strip('.'))

    # Apply band-pass filter
    raw.filter(7., 30., fir_design='firwin', skip_by_annotation='edge')

    events, _ = events_from_annotations(raw)

    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)
    epochs.crop(tmin=1., tmax=None)
    labels = epochs.events[:, 2] - 2
    return epochs.get_data()[:, :, :256], labels
def load_data ():
    
    ls_run_tot = [] #list of lists, contains lists of Raw files to be concatenated
                    # e.g. for subjects = [2, 45] 
                    #ls_run_tot = [[S2Raw03,S2Raw07,S2Raw11],
                    #              [S45Raw03,S45Raw07,S45Raw11]]
    
    for subj in subjects:
        ls_run = []#Lista dove inseriamo le run
        
        for run in runs:
            fname = eegbci.load_data(subj, runs=run)[0] #Prendo le run
            raw_run = read_raw_edf(fname, preload=True) #Le carico
            len_run = np.sum((raw_run._annotations).duration) #Controllo la durata
            
            if len_run > 123:
                raw_run.crop(tmax=124.4) #Taglio la parte finale
            
            
                
            ls_run.append(raw_run) 
            
        ls_run_tot.append(ls_run)
        
        
        
      
        
    return ls_run_tot
Ejemplo n.º 14
0
def load_eeg_bci(targets=4, tmin=0, tlen=3, t_ev=0, t_sub=None, normalizer=zscore, low_f=None, high_f=None,
                 alignment=True):

    paths = [eegbci.load_data(s+1, IMAGERY_FISTS, path=str(TOPLEVEL_EEGBCI), update_path=False) for s in SUBJECTS_EEGBCI]
    raws = [mne.io.concatenate_raws([mne.io.read_raw_edf(p, preload=True) for p in path])
            for path in tqdm.tqdm(paths, unit='subj', desc='Loading')]
    datasets = OrderedDict()
    for i, raw in tqdm.tqdm(list(zip(SUBJECTS_EEGBCI, raws)), desc='Preprocessing'):
        if raw.info['sfreq'] != 160:
            tqdm.tqdm.write('Skipping..., sampling frequency: {}'.format(raw.info['sfreq']))
            continue
        raw.rename_channels(lambda x: x.strip('.'))
        if low_f or high_f:
            raw.filter(low_f, high_f, fir_design='firwin', skip_by_annotation='edge')
        events, _ = mne.events_from_annotations(raw, event_id=dict(T1=0, T2=1))
        picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads')
        epochs = mne.Epochs(raw, events[:41, ...], tmin=tmin, tmax=tmin + tlen - 1 / raw.info['sfreq'], picks=picks,
                            baseline=None, reject_by_annotation=False)#.drop_bad()
        if targets > 2:
            paths = eegbci.load_data(i + 1, BASELINE_EYES_OPEN, path=str(TOPLEVEL_EEGBCI), update_path=False)
            raw = mne.io.concatenate_raws([mne.io.read_raw_edf(p, preload=True) for p in paths])
            raw.rename_channels(lambda x: x.strip('.'))
            if low_f or high_f:
                raw.filter(low_f, high_f, fir_design='firwin', skip_by_annotation='edge')
            events = np.zeros((events.shape[0] // 2, 3)).astype('int')
            events[:, -1] = 2
            events[:, 0] = np.linspace(0, raw.info['sfreq'] * (60 - 2 * tlen), num=events.shape[0]).astype(np.int)
            picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads')
            eyes_epochs = mne.Epochs(raw, events, tmin=tmin, tmax=tmin + tlen - 1 / raw.info['sfreq'], picks=picks,
                                     baseline=None, reject_by_annotation=False)#.drop_bad()
            epochs = mne.concatenate_epochs([eyes_epochs, epochs])
        if targets > 3:
            paths = eegbci.load_data(i+1, IMAGERY_FEET_V_FISTS, path=str(TOPLEVEL_EEGBCI), update_path=False)
            raw = mne.io.concatenate_raws([mne.io.read_raw_edf(p, preload=True) for p in paths])
            raw.rename_channels(lambda x: x.strip('.'))
            if low_f or high_f:
                raw.filter(low_f, high_f, fir_design='firwin', skip_by_annotation='edge')
            events, _ = mne.events_from_annotations(raw, event_id=dict(T2=3))
            picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=False, eog=False, exclude='bads')
            feet_epochs = mne.Epochs(raw, events[:20, ...], tmin=tmin, tmax=tmin + tlen - 1 / raw.info['sfreq'],
                                     picks=picks, baseline=None, reject_by_annotation=False)#.drop_bad()
            epochs = mne.concatenate_epochs([epochs, feet_epochs])

        datasets[i] = EpochsDataset(epochs, preproccesors=EuclideanAlignment if alignment else [],
                                    normalizer=normalizer, runs=3)

    return datasets
Ejemplo n.º 15
0
def make_filepath(dir_save, subs):
    filepaths = []
    for i in subs:
        load_path = eegbci.load_data(int(i), [4, 6, 8, 10, 12, 14])
        filepaths.append(
            FilePath(subject='s{}'.format(int(i)),
                     filetype='edf',
                     load_path=load_path,
                     save_path=dir_save))
    return filepaths
Ejemplo n.º 16
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        raw_fnames = eegbci.load_data(subject, runs=self.selected_runs)
        raw_files = [
            read_raw_edf(f, preload=True, verbose=False) for f in raw_fnames
        ]

        # strip channel names of "." characters
        [raw.rename_channels(lambda x: x.strip('.')) for raw in raw_files]

        return raw_files
Ejemplo n.º 17
0
def raw():
    """Fixture for physionet EEG subject 4, dataset 1."""
    mne.set_log_level("WARNING")
    # load in subject 1, run 1 dataset
    edf_fpath = eegbci.load_data(4, 1, update_path=True)[0]

    # using sample EEG data (https://physionet.org/content/eegmmidb/1.0.0/)
    raw = mne.io.read_raw_edf(edf_fpath, preload=True)

    # The eegbci data has non-standard channel names. We need to rename them:
    eegbci.standardize(raw)

    return raw
Ejemplo n.º 18
0
    def data_path(self,
                  subject,
                  path=None,
                  force_update=False,
                  update_path=None,
                  verbose=None):
        if subject not in self.subject_list:
            raise (ValueError("Invalid subject number"))

        paths = eegbci.load_data(subject,
                                 runs=[1, 2] + self.hand_runs + self.feet_runs,
                                 base_url=BASE_URL)
        return paths
Ejemplo n.º 19
0
def get_raw(subject, runs=[6, 10, 14]):
    raw_fnames = eegbci.load_data(subject, runs)
    raw_files = [
        read_raw_edf(f, preload=True, stim_channel='auto') for f in raw_fnames
    ]
    raw = concatenate_raws(raw_files)
    raw.rename_channels(lambda x: x.strip('.'))
    raw.pick_channels(ch_names)
    raw.filter(low_freq,
               high_freq,
               fir_design='firwin',
               skip_by_annotation='edge')
    return raw
Ejemplo n.º 20
0
def raw():
    """Fixture for physionet EEG subject 4, dataset 1."""
    mne.set_log_level("WARNING")
    # load in subject 1, run 1 dataset
    edf_fpath = eegbci.load_data(4, 1, update_path=True)[0]

    # using sample EEG data (https://physionet.org/content/eegmmidb/1.0.0/)
    raw = mne.io.read_raw_edf(edf_fpath, preload=True)
    raw.rename_channels(lambda s: s.strip("."))
    raw.rename_channels(
        lambda s: s.replace("c", "C").replace("o", "O").replace("f", "F").
        replace("t", "T").replace("Tp", "TP").replace("Cp", "CP"))
    return raw
Ejemplo n.º 21
0
def get_classification_dataset(subject=1, typeInt=4):
    #TypeInt:
    #Task 1 (open and close left or right fist)
    #Task 2 (imagine opening and closing left or right fist)
    #Task 3 (open and close both fists or both feet)
    #Task 4 (imagine opening and closing both fists or both feet)
    assert (typeInt >= 1)
    assert (typeInt <= 4)
    from mne.io import concatenate_raws, read_raw_edf
    from mne.datasets import eegbci
    tmin, tmax = -1., 4.
    runs = [3, 7, 11]
    runs = [r + typeInt - 1 for r in runs]
    print("loading subject {} with runs {}".format(subject, runs))
    if typeInt <= 1:
        event_id = dict(left=2, right=3)
    else:
        event_id = dict(hands=2, feet=3)

    raw_fnames = eegbci.load_data(subject, runs)
    raws = [read_raw_edf(f, preload=True) for f in raw_fnames]
    raw = concatenate_raws(raws)

    raw.filter(7., 30., fir_design='firwin', skip_by_annotation='edge')

    eegbci.standardize(raw)  # set channel names
    montage = mne.channels.make_standard_montage('standard_1005')
    raw.set_montage(montage)
    raw.rename_channels(lambda x: x.strip('.'))
    events, _ = mne.events_from_annotations(raw, event_id=dict(T1=2, T2=3))

    picks = mne.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 = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        proj=True,
                        picks=picks,
                        baseline=None,
                        preload=True)
    return (epochs)
Ejemplo n.º 22
0
    def data_path(self,
                  subject,
                  path=None,
                  force_update=False,
                  update_path=None,
                  verbose=None):
        if subject not in self.subject_list:
            raise (ValueError("Invalid subject number"))

        sign = "EEGBCI"
        get_dataset_path(sign, None)
        paths = eegbci.load_data(subject,
                                 runs=[1, 2] + self.hand_runs + self.feet_runs,
                                 verbose=verbose)
        return paths
    def load_nme_data(self):
        raw_fnames = eegbci.load_data(1, self.RUNS)

        raw_files = []
        raw_files.extend([
            read_raw_edf(f, preload=True, stim_channel='auto')
            for f in raw_fnames
        ])

        raw = concatenate_raws(raw_files)
        raw.rename_channels(lambda x: x.strip('.'))

        self.raw = raw
        self.data = raw.get_data()
        self.times = self.raw[-1, :][-1] * 1000
Ejemplo n.º 24
0
    def data_path(self,
                  subject,
                  path=None,
                  force_update=False,
                  update_path=None,
                  verbose=None):
        if subject not in self.subject_list:
            raise (ValueError("Invalid subject number"))

        if get_config('MNE_DATASETS_EEGBCI_PATH') is None:
            set_config('MNE_DATASETS_EEGBCI_PATH',
                       osp.join(osp.expanduser("~"), "mne_data"))
        paths = eegbci.load_data(subject,
                                 runs=[1, 2] + self.hand_runs + self.feet_runs,
                                 verbose=verbose)
        return paths
Ejemplo n.º 25
0
def load_subject(id_num, runs):
    '''
    Loads raw EEG recordings for one subject and at least one run of
    experiments.

    Arguments:
        id_num: int, the subject's ID number
        runs: int or list of ints -- which experiment(s) to read data from

    Returns:
        MNE Raw object
    '''
    edf_files = load_data(id_num, runs)
    if len(edf_files) > 1:
        raw_objects = [read_raw_edf(file, preload=True) for file in edf_files]
        mne_raw = concatenate_raws(raw_objects, preload=True)
    else:
        mne_raw = read_raw_edf(edf_files[0], preload=True)
    return mne_raw
Ejemplo n.º 26
0
    def _load_one_run(self, subject, run, preload=True):
        if get_config('MNE_DATASETS_EEGBCI_PATH') is None:
            set_config('MNE_DATASETS_EEGBCI_PATH',
                       osp.join(osp.expanduser("~"), "mne_data"))
        raw_fname = eegbci.load_data(subject,
                                     runs=[run],
                                     verbose='ERROR',
                                     base_url=BASE_URL)[0]
        raw = read_raw_edf(raw_fname, preload=preload, verbose='ERROR')
        raw.rename_channels(lambda x: x.strip('.'))
        raw.rename_channels(lambda x: x.upper())
        raw.rename_channels({
            'AFZ': 'AFz',
            'PZ': 'Pz',
            'FPZ': 'Fpz',
            'FCZ': 'FCz',
            'FP1': 'Fp1',
            'CZ': 'Cz',
            'OZ': 'Oz',
            'POZ': 'POz',
            'IZ': 'Iz',
            'CPZ': 'CPz',
            'FP2': 'Fp2',
            'FZ': 'Fz'
        })
        raw.set_montage(mne.channels.make_standard_montage('standard_1005'))

        # creat simulate stim channel
        # mne >= 0.18
        events, _ = mne.events_from_annotations(raw)
        stim_channel = np.zeros((1, raw.n_times))
        for event in events:
            stim_channel[0, event[0]] = event[2]

        info = mne.create_info(['STI 014'],
                               raw.info['sfreq'],
                               ch_types=['stim'])
        raw = raw.add_channels([mne.io.RawArray(stim_channel, info)],
                               force_update_info=True)
        return raw
Ejemplo n.º 27
0
    def _load_one_run(self, subject, run, preload=True, verbose=None):
        raw_fname = eegbci.load_data(subject, runs=[run], base_url=BASE_URL)[0]
        raw = read_raw_edf(raw_fname, preload=preload)
        raw.rename_channels(lambda x: x.strip('.'))
        montage = make_standard_montage('standard_1005')
        # 0.19.2 can not guarante channel name case insensitive
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]
        raw = upper_ch_names(raw)
        raw.set_montage(montage)

        # creat simulate stim channel
        # mne >= 0.18
        events, _ = mne.events_from_annotations(raw)
        stim_channel = np.zeros((1, raw.n_times))
        for event in events:
            stim_channel[0, event[0]] = event[2]
        info = mne.create_info(['STI 014'],
                               raw.info['sfreq'],
                               ch_types=['stim'])
        raw = raw.add_channels([RawArray(stim_channel, info)],
                               force_update_info=True)
        return raw
Ejemplo n.º 28
0
def raw():
    """Return an `mne.io.Raw` object for use with unit tests.

    This fixture downloads and reads in subject 4, run 1 from the Physionet
    BCI2000 (eegbci) open dataset. This recording is quite noisy and is thus a
    good candidate for testing the PREP pipeline.

    File attributes:
    - Channels: 64 EEG
    - Sample rate: 160 Hz
    - Duration: 61 seconds

    This is only run once per session to save time downloading.

    """
    mne.set_log_level("WARNING")

    # Download and read S004R01.edf from the BCI2000 dataset
    edf_fpath = eegbci.load_data(4, 1, update_path=True)[0]
    raw = mne.io.read_raw_edf(edf_fpath, preload=True)
    eegbci.standardize(raw)  # Fix non-standard channel names

    return raw
Ejemplo n.º 29
0
from mne import Epochs, pick_types, events_from_annotations
from mne.channels import read_layout
from mne.io import concatenate_raws, read_raw_edf
from mne.datasets import eegbci
from mne.decoding import CSP

from smica import ICA
import pickle

tmin, tmax = -1., 4.

subject = 1
runs = [6, 10, 14]  # motor imagery: hands vs feet

raw_fnames = eegbci.load_data(subject, runs)
raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames])

# strip channel names of "." characters
raw.rename_channels(lambda x: x.strip('.'))

# Apply band-pass filter
raw.filter(7., 30., fir_design='firwin', skip_by_annotation='edge')

events, _ = events_from_annotations(raw)

picks = pick_types(raw.info,
                   meg=False,
                   eeg=True,
                   stim=False,
                   eog=False,
Ejemplo n.º 30
0
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,
Ejemplo n.º 31
0
fs_dir = fetch_fsaverage(verbose=True)
subjects_dir = op.dirname(fs_dir)

# The files live in:
subject = 'fsaverage'
trans = op.join(fs_dir, 'bem', 'fsaverage-trans.fif')
src = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')
bem = op.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')

##############################################################################
# Load the data
# -------------
#
# We use here EEG data from the BCI dataset.

raw_fname, = eegbci.load_data(subject=1, runs=[6])
raw = mne.io.read_raw_edf(raw_fname, preload=True)

# Clean channel names to be able to use a standard 1005 montage
ch_names = [c.replace('.', '') for c in raw.ch_names]
raw.rename_channels({old: new for old, new in zip(raw.ch_names, ch_names)})

# Read and set the EEG electrode locations
montage = mne.channels.read_montage('standard_1005',
                                    ch_names=raw.ch_names,
                                    transform=True)

raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

# Check that the locations of EEG electrodes is correct with respect to MRI
Ejemplo n.º 32
0
fs_dir = fetch_fsaverage(verbose=True)
subjects_dir = op.dirname(fs_dir)

# The files live in:
subject = 'fsaverage'
trans = op.join(fs_dir, 'bem', 'fsaverage-trans.fif')
src = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')
bem = op.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')

##############################################################################
# Load the data
# -------------
#
# We use here EEG data from the BCI dataset.

raw_fname, = eegbci.load_data(subject=1, runs=[6])
raw = mne.io.read_raw_edf(raw_fname, preload=True)


# Clean channel names to be able to use a standard 1005 montage
ch_names = [c.replace('.', '') for c in raw.ch_names]
raw.rename_channels({old: new for old, new in zip(raw.ch_names, ch_names)})

# Read and set the EEG electrode locations
montage = mne.channels.read_montage('standard_1005', ch_names=raw.ch_names,
                                    transform=True)

raw.set_montage(montage)
raw.set_eeg_reference(projection=True)  # needed for inverse modeling

# Check that the locations of EEG electrodes is correct with respect to MRI
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')

raw.filter(7., 35., method='iir', picks=picks)
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()
Ejemplo n.º 35
0
from mne.datasets import eegbci
from mne.decoding import CSP

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 of "." characters
raw.rename_channels(lambda x: x.strip('.'))

# 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)