Exemple #1
0
    def _get_single_subject_data(self, subject: Union[str, int], 
            verbose: Optional[Union[bool, str, int]] = None) -> Dict[str, Dict[str, Raw]]:
        dests = self.data_path(subject)
        montage = make_standard_montage('standard_1005')
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]
        
        sess = dict()
        for isess, run_dests in enumerate(dests):
            runs = dict()
            for irun, run_file in enumerate(run_dests):
                raw = read_raw_cnt(run_file,
                    eog=['VEOU', 'VEOL'], 
                    preload=True)
                raw = upper_ch_names(raw)
                raw.set_montage(montage)

                runs['run_{:d}'.format(irun)] = raw
            sess['session_{:d}'.format(isess)] = runs
        return sess
Exemple #2
0
    def _get_single_subject_data(
        self,
        subject: Union[str, int],
        verbose: Optional[Union[bool, str, int]] = None
    ) -> Dict[str, Dict[str, Raw]]:
        dests = self.data_path(subject)
        montage = make_standard_montage('standard_1005')
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]

        sess = dict()
        for isess, run_dests in enumerate(dests):
            runs = dict()
            for irun, run_file in enumerate(run_dests):
                raw_mat = loadmat(run_file)['eeg']
                eeg_data_l = np.concatenate((raw_mat['imagery_left'] * 1e-6,
                                             raw_mat['imagery_event'].reshape(
                                                 (1, -1))),
                                            axis=0)
                eeg_data_r = np.concatenate((raw_mat['imagery_right'] * 1e-6,
                                             raw_mat['imagery_event'].reshape(
                                                 (1, -1)) * 2),
                                            axis=0)

                data = np.hstack([
                    eeg_data_l,
                    np.zeros((eeg_data_l.shape[0], 500)), eeg_data_r
                ])
                ch_names = [ch_name.upper() for ch_name in self._CHANNELS
                            ] + ['EMG1', 'EMG2', 'EMG3', 'EMG4', 'STI 014']
                ch_types = ['eeg'] * len(self._CHANNELS) + ['emg'] * 4 + [
                    'stim'
                ]

                info = create_info(ch_names=ch_names,
                                   ch_types=ch_types,
                                   sfreq=self.srate)
                raw = RawArray(data=data, info=info, verbose=verbose)
                raw = upper_ch_names(raw)
                raw.set_montage(montage)

                runs['run_{:d}'.format(irun)] = raw
            sess['session_{:d}'.format(isess)] = runs
        return sess
Exemple #3
0
def test_get_montage():
    """Test ContainsMixin.get_montage()."""
    ch_names = make_standard_montage('standard_1020').ch_names
    sfreq = 512
    data = np.zeros((len(ch_names), sfreq * 2))
    raw = RawArray(data, create_info(ch_names, sfreq, 'eeg'))
    raw.set_montage('standard_1020')

    assert len(raw.get_montage().ch_names) == len(ch_names)
    raw.info['bads'] = [ch_names[0]]
    assert len(raw.get_montage().ch_names) == len(ch_names)

    # test info
    raw = RawArray(data, create_info(ch_names, sfreq, 'eeg'))
    raw.set_montage('standard_1020')

    assert len(raw.info.get_montage().ch_names) == len(ch_names)
    raw.info['bads'] = [ch_names[0]]
    assert len(raw.info.get_montage().ch_names) == len(ch_names)
def test_set_montage_with_mismatching_ch_names():
    """Test setting a DigMontage with mismatching ch_names."""
    raw = read_raw_fif(fif_fname)
    montage = make_standard_montage('mgh60')

    # 'EEG 001' and 'EEG001' won't match
    missing_err = '60 channel positions not present'
    with pytest.raises(ValueError, match=missing_err):
        raw.set_montage(montage)

    montage.ch_names = [  # modify the names in place
        name.replace('EEG', 'EEG ') for name in montage.ch_names
    ]
    raw.set_montage(montage)  # does not raise

    # Case sensitivity
    raw.rename_channels(lambda x: x.lower())
    with pytest.raises(ValueError, match=missing_err):
        raw.set_montage(montage)
    # should work
    raw.set_montage(montage, match_case=False)
    raw.rename_channels(lambda x: x.upper())  # restore
    assert 'EEG 001' in raw.ch_names and 'eeg 001' not in raw.ch_names
    raw.rename_channels({'EEG 002': 'eeg 001'})
    assert 'EEG 001' in raw.ch_names and 'eeg 001' in raw.ch_names
    raw.set_channel_types({'eeg 001': 'misc'})
    raw.set_montage(montage)
    raw.set_channel_types({'eeg 001': 'eeg'})
    with pytest.raises(ValueError, match='1 channel position not present'):
        raw.set_montage(montage)
    with pytest.raises(ValueError, match='match_case=False as 1 channel name'):
        raw.set_montage(montage, match_case=False)
    info = create_info(['EEG 001'], 1000., 'eeg')
    mon = make_dig_montage({
        'EEG 001': np.zeros(3),
        'eeg 001': np.zeros(3)
    },
                           nasion=[0, 1., 0],
                           rpa=[1., 0, 0],
                           lpa=[-1., 0, 0])
    info.set_montage(mon)
    with pytest.raises(ValueError, match='match_case=False as 1 montage name'):
        info.set_montage(mon, match_case=False)
Exemple #5
0
def test_plot_montage():
    """Test plotting montages."""
    m = make_standard_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_fif(fname=fif_fname)
    assert '61 channels' in repr(d)
    def __get_raw_data(self, raw_data_path, montage_type='easycap-M1'):
        """
        Extract the raw data from the given data path. Currently supports only
        .fif, .edf and .gdf extension types.

        Parameters
        ----------
        raw_data_path : List (str)
            Full path to the raw data. List is expected as input type.
        montage_type : str, optional
            Electrode montage to use with the data. The default is 'easycap-M1'.

        Returns
        -------
        raw : mne.io raw datatype
            MNE ready raw data for processing.

        """

        # Import raw data from mne.io using read_raw_*** for whichever extension
        if raw_data_path[-3:] == 'fif':

            print('...Importing raw .fif file...')
            raw = mne.io.read_raw_fif(raw_data_path, preload=True)
        elif raw_data_path[-3:] == 'edf':
            print('...Importing raw .edf file...')
            raw = mne.io.read_raw_edf(raw_data_path, preload=True)
        elif raw_data_path[-3:] == 'gdf':
            print('...Importing raw .gdf file...')
            raw = mne.io.read_raw_gdf(raw_data_path, preload=True)
        else:
            print('WARNING!')
            print('Extension type not recognized for this function!')
            print('You will need to manually import the data via MNE!')
            print(' ')
            return
        # Add the montage information
        montage = make_standard_montage(montage_type)
        # Set the montage
        raw.set_montage(montage)
        # Return vals
        return raw
Exemple #7
0
    def _generate_raw(self):
        montage = make_standard_montage("standard_1005")
        sfreq = 128
        duration = len(self.event_id) * 60
        eeg_data = 2e-5 * np.random.randn(duration * sfreq, len(self.channels))
        y = np.zeros((duration * sfreq))
        for ii, ev in enumerate(self.event_id):
            start_idx = (1 + 5 * ii) * 128
            jump = 5 * len(self.event_id) * 128
            y[start_idx::jump] = self.event_id[ev]

        ch_types = ["eeg"] * len(self.channels) + ["stim"]
        ch_names = list(self.channels) + ["stim"]

        eeg_data = np.c_[eeg_data, y]

        info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
        raw = RawArray(data=eeg_data.T, info=info, verbose=False)
        raw.set_montage(montage)
        return raw
Exemple #8
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        files = self.data_path(subject)

        out = {}
        for sess_ind, runlist in enumerate(files):
            sess_key = 'session_{}'.format(sess_ind)
            out[sess_key] = {}
            for run_ind, fname in enumerate(runlist):
                run_key = 'run_{}'.format(run_ind)
                raw = read_raw_cnt(fname, preload=True, eog=['VEOU', 'VEOL'])
                stim = raw.annotations.description.astype(np.dtype('<10U'))
                stim[stim == '1'] = 'left_hand'
                stim[stim == '2'] = 'right_hand'
                stim[stim == '3'] = 'feet'
                raw.annotations.description = stim
                out[sess_key][run_key] = raw
                out[sess_key][run_key].set_montage(
                    make_standard_montage('standard_1005'))
        return out
Exemple #9
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        files = self.data_path(subject)

        out = {}
        for sess_ind, runlist in enumerate(files):
            sess_key = "session_{}".format(sess_ind)
            out[sess_key] = {}
            for run_ind, fname in enumerate(runlist):
                run_key = "run_{}".format(run_ind)
                raw = read_raw_cnt(fname, preload=True, eog=["VEOU", "VEOL"])
                stim = raw.annotations.description.astype(np.dtype("<10U"))
                stim[stim == "1"] = "left_hand"
                stim[stim == "2"] = "right_hand"
                stim[stim == "3"] = "feet"
                raw.annotations.description = stim
                out[sess_key][run_key] = raw
                out[sess_key][run_key].set_montage(
                    make_standard_montage("standard_1005"))
        return out
Exemple #10
0
    def _get_single_subject_data(
        self,
        subject: Union[str, int],
        verbose: Optional[Union[bool, str, int]] = None
    ) -> Dict[str, Dict[str, Raw]]:
        dests = self.data_path(subject)
        raw_mat = loadmat(dests[0][0])
        epoch_data = raw_mat['data'] * 1e-6
        stim = np.zeros((1, *epoch_data.shape[1:]))
        # insert event label at stimulus-onset
        stim[0, 125] = np.tile(
            np.arange(1, 41)[:, np.newaxis], (1, epoch_data.shape[-1]))
        epoch_data = np.concatenate((epoch_data, stim), axis=0)
        data = np.transpose(epoch_data, (0, 3, 2, 1))

        montage = make_standard_montage('standard_1005')
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]
        ch_names = [ch_name.upper() for ch_name in self._CHANNELS]
        ch_names.insert(32, 'M1')
        ch_names.insert(42, 'M2')
        ch_names.insert(59, 'CB1')
        ch_names = ch_names + ['CB2', 'STI 014']
        ch_types = ['eeg'] * 65
        ch_types[59] = 'misc'
        ch_types[63] = 'misc'
        ch_types[-1] = 'stim'

        info = create_info(ch_names=ch_names,
                           ch_types=ch_types,
                           sfreq=self.srate)

        runs = dict()
        for i in range(data.shape[1]):
            raw = RawArray(data=np.reshape(data[:, i, ...],
                                           (data.shape[0], -1)),
                           info=info)
            raw.set_montage(montage)
            runs['run_{:d}'.format(i)] = raw

        sess = {'session_0': runs}
        return sess
Exemple #11
0
def test_make_info():
    """Test some create_info properties."""
    n_ch = np.longlong(1)
    info = create_info(n_ch, 1000., 'eeg')
    assert set(info.keys()) == set(RAW_INFO_FIELDS)

    coil_types = {ch['coil_type'] for ch in info['chs']}
    assert FIFF.FIFFV_COIL_EEG in coil_types

    pytest.raises(TypeError, create_info, ch_names='Test Ch', sfreq=1000)
    pytest.raises(ValueError, create_info, ch_names=['Test Ch'], sfreq=-1000)
    pytest.raises(ValueError,
                  create_info,
                  ch_names=['Test Ch'],
                  sfreq=1000,
                  ch_types=['eeg', 'eeg'])
    pytest.raises(TypeError, create_info, ch_names=[np.array([1])], sfreq=1000)
    pytest.raises(KeyError,
                  create_info,
                  ch_names=['Test Ch'],
                  sfreq=1000,
                  ch_types=np.array([1]))
    pytest.raises(KeyError,
                  create_info,
                  ch_names=['Test Ch'],
                  sfreq=1000,
                  ch_types='awesome')
    pytest.raises(TypeError,
                  create_info, ['Test Ch'],
                  sfreq=1000,
                  montage=np.array([1]))
    m = make_standard_montage('biosemi32')
    info = create_info(ch_names=m.ch_names, sfreq=1000., ch_types='eeg')
    info.set_montage(m)
    ch_pos = [ch['loc'][:3] for ch in info['chs']]
    ch_pos_mon = m._get_ch_pos()
    ch_pos_mon = np.array(
        [ch_pos_mon[ch_name] for ch_name in info['ch_names']])
    # transform to head
    ch_pos_mon += (0., 0., 0.04014)
    assert_allclose(ch_pos, ch_pos_mon, atol=1e-5)
Exemple #12
0
    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 = make_standard_montage("standard_1005")
            data = {}
            for ii, path in enumerate(paths):
                raw = read_raw_gdf(path,
                                   eog=eog,
                                   misc=range(64, 96),
                                   preload=True,
                                   verbose="ERROR")
                raw.set_montage(montage)
                # there is nan in the data
                raw._data[np.isnan(raw._data)] = 0
                # Modify the annotations to match the name of the command
                stim = raw.annotations.description.astype(np.dtype("<21U"))
                stim[stim == "1536"] = "right_elbow_flexion"
                stim[stim == "1537"] = "right_elbow_extension"
                stim[stim == "1538"] = "right_supination"
                stim[stim == "1539"] = "right_pronation"
                stim[stim == "1540"] = "right_hand_close"
                stim[stim == "1541"] = "right_hand_open"
                stim[stim == "1542"] = "rest"
                raw.annotations.description = stim
                data["run_%d" % ii] = raw

            out[session] = data
        return out
Exemple #13
0
    def _get_single_subject_data(self, subject):
        """Return the data of a single subject"""
        n_samples, n_channels, n_trials = 1500, 64, 6
        n_classes = len(self.event_id)

        fname = self.data_path(subject)
        Archive(fname).extractall(dirname(fname))
        mat = loadmat(fname[:-4])

        data = np.transpose(mat['data'], axes=(2, 3, 0, 1))
        data = np.reshape(data, newshape=(-1, n_channels, n_samples))
        data = data - data.mean(axis=2, keepdims=True)
        raw_events = np.zeros((data.shape[0], 1, n_samples))
        raw_events[:, 0, 0] = np.array([n_trials * [i + 1]
                                        for i in range(n_classes)]).flatten()
        data = np.concatenate([1e-6 * data, raw_events], axis=1)
        # add buffer in between trials
        log.warning("Trial data de-meaned and concatenated with a buffer"
                    " to create continuous data")
        buff = (data.shape[0], n_channels + 1, 50)
        data = np.concatenate([np.zeros(buff), data,
                               np.zeros(buff)], axis=2)

        ch_names = ['Fp1', 'Fpz', 'Fp2', 'AF3', 'AF4', 'F7', 'F5', 'F3', 'F1',
                    'Fz', 'F2', 'F4', 'F6', 'F8', 'FT7', 'FC5', 'FC3', 'FC1',
                    'FCz', 'FC2', 'FC4', 'FC6', 'FT8', 'T7', 'C5', 'C3', 'C1',
                    'Cz', 'C2', 'C4', 'C6', 'T8', 'M1', 'TP7', 'CP5', 'CP3',
                    'CP1', 'CPz', 'CP2', 'CP4', 'CP6', 'TP8', 'M2', 'P7', 'P5',
                    'P3', 'P1', 'Pz', 'P2', 'P4', 'P6', 'P8', 'PO7', 'PO5',
                    'PO3', 'POz', 'PO4', 'PO6', 'PO8', 'CB1', 'O1', 'Oz', 'O2',
                    'CB2', 'stim']
        ch_types = ['eeg'] * 59 + ['misc'] + 3 * ['eeg'] + ['misc', 'stim']
        sfreq = 250
        info = create_info(ch_names, sfreq, ch_types)
        raw = RawArray(data=np.concatenate(list(data), axis=1),
                       info=info, verbose=False)
        montage = make_standard_montage('standard_1005')
        raw.set_montage(montage)
        return {'session_0': {'run_0': raw}}
Exemple #14
0
    def _get_single_subject_data(self, subject, verbose=False):
        """return data for a single subject"""
        sessions = {}
        sess_dests = self.data_path(subject)
        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]

        for sess_id, run_dests in enumerate(sess_dests):
            runs = {}
            for run_id, run_dest in enumerate(run_dests):
                raw = read_raw_cnt(run_dest,
                                   eog=['VEOU', 'VEOL'],
                                   preload=True,
                                   stim_channel=False)
                raw = upper_ch_names(raw)

                raw.set_montage(montage)

                runs['run_%d' % run_id] = raw
            sessions['session_%d' % sess_id] = runs
        return sessions
Exemple #15
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
Exemple #16
0
    def _calculate_2d_channel_coordinates(self) -> np.ndarray:
        """
        Calculates 2d channel coordinates. Locations are taken from mne.channels.make_standard_montage and projected
        using azimuthal projection.
        :return: coordinates. numpy ndarray of shape (num_channels, 2)
        """
        montage = make_standard_montage(kind='standard_1020')
        if self.dataset == "BCI2000":
            positions_3d = np.asarray([
                montage.get_positions()['ch_pos'][ch_name]
                for ch_name in g.ch_names_bci2000
            ])
            positions_3d[:,
                         1] += 0.015  # parameter to adjust azimuthal projection
        elif self.dataset == "BCI2aIV":
            positions_3d = np.asarray([
                montage.get_positions()['ch_pos'][ch_name]
                for ch_name in g.ch_names_bci2aiv
            ])
        else:
            raise ValueError()

        azimuth_projected_positions = []
        for pos_3d in positions_3d:
            [_, elev, az] = cart2sph(pos_3d[0], pos_3d[1], pos_3d[2])
            azimuth_projected_positions.append(pol2cart(az, np.pi / 2 - elev))

        azimuth_projected_positions = np.asarray(azimuth_projected_positions)
        if self.pseudo_channels:
            x_min = np.min(azimuth_projected_positions[:, 0])
            x_max = np.max(azimuth_projected_positions[:, 0])
            y_min = np.min(azimuth_projected_positions[:, 1])
            y_max = np.max(azimuth_projected_positions[:, 1])
            corner_positions = np.asarray([[x_min, y_min], [x_min, y_max],
                                           [x_max, y_min], [x_max, y_max]])
            azimuth_projected_positions = np.concatenate(
                [azimuth_projected_positions, corner_positions])

        return azimuth_projected_positions
Exemple #17
0
    def _get_single_run(self, data):
        sfreq = data["fs"].item()
        file_mapping = {c.item(): int(v.item()) for v, c in data["class"]}
        self._check_mapping(file_mapping)

        # Create RawArray
        raw = self._make_raw_array(data["x"], data["chan"], "eeg", sfreq)
        montage = make_standard_montage("standard_1005")
        raw.set_montage(montage)

        # Create EMG channels
        emg_raw = self._make_raw_array(data["EMG"], data["EMG_index"], "emg",
                                       sfreq)

        # Create stim chan
        event_times_in_samples = data["t"].squeeze()
        event_id = data["y_dec"].squeeze()
        stim_chan = np.zeros(len(raw))
        for i_sample, id_class in zip(event_times_in_samples, event_id):
            stim_chan[i_sample] += id_class
        stim_raw = self._make_raw_array(stim_chan[:, None], ["STI 014"],
                                        "stim",
                                        sfreq,
                                        verbose="WARNING")

        # Add events
        event_arr = [
            event_times_in_samples,
            [0] * len(event_times_in_samples),
            event_id,
        ]
        raw.info["events"] = [
            dict(list=np.array(event_arr).T, channels=None),
        ]

        # Add EMG and stim channels
        raw = raw.add_channels([emg_raw, stim_raw])
        return raw
Exemple #18
0
def create_mock_data_egi(n_channels, n_samples, stim=True):
    """Load and configure testing data
    Parameters
    ----------
    n_channels : int
        The number of EEG channels.
    n_samples : int
        The number of time samples.
    stim : bool
        Whether to add a stim channel or not. Defaults to True.
    Returns
    -------
    raw : instance of mne.RawArry
        The testing data.
    """
    mat_contents = loadmat(
        op.join(op.realpath(op.dirname(__file__)), 'tests', 'data',
                'test-eeg.mat'))

    data = mat_contents['data'][:n_channels, :n_samples] * 1e-7
    sfreq = 250.
    if stim is True:
        ch_names = ['E%i' % i for i in range(1, n_channels + 1, 1)]
        ch_names += ['STI 014']
        ch_types = ['eeg'] * n_channels
        ch_types += ['stim']
        data = np.r_[data, data[-1:]]
        data[-1].fill(0)
    else:
        ch_names = ['E%i' % i for i in range(1, n_channels + 1, 1)]
        ch_types = ['eeg'] * n_channels

    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=data, info=info)
    montage = make_standard_montage('GSN-HydroCel-257')
    raw.set_montage(montage)
    info['description'] = 'egi/256'
    return raw
Exemple #19
0
    def _get_single_subject_data(
        self,
        subject: Union[str, int],
        verbose: Optional[Union[bool, str, int]] = None
    ) -> Dict[str, Dict[str, Raw]]:
        dests = self.data_path(subject)
        montage = make_standard_montage('standard_1005')
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]

        sess_arrays = loadmat(dests[0][0])['data'] + loadmat(
            dests[1][0])['data']

        sess = dict()
        for isess, sess_array in enumerate(sess_arrays):
            runs = dict()
            X = sess_array['X'].T * 1e-6  # volt
            trial = sess_array['trial']
            y = sess_array['y']
            stim = np.zeros((1, X.shape[-1]))

            if y.size > 0:
                stim[0, trial - 1] = y

            data = np.concatenate((X, stim), axis=0)

            ch_names = [ch_name.upper() for ch_name in self._CHANNELS
                        ] + ['EOG1', 'EOG2', 'EOG3']
            ch_types = ['eeg'] * len(self._CHANNELS) + ['eog'] * 3
            ch_names = ch_names + ['STI 014']
            ch_types = ch_types + ['stim']

            info = mne.create_info(ch_names, self.srate, ch_types=ch_types)
            raw = RawArray(data, info)
            raw = upper_ch_names(raw)
            raw.set_montage(montage)
            runs['run_0'] = raw
            sess['session_{:d}'.format(isess)] = runs
        return sess
Exemple #20
0
    def _get_single_subject_data(self, subject, verbose=False):
        """return data for a single subject"""
        dests = self.data_path(subject)
        sessions = {}
        for i_session, session in enumerate(('T', 'E')):
            runs = {}
            run_arrays = loadmat(dests[i_session])['data']
            for i_run, run_array in enumerate(run_arrays):
                X = run_array['X'].T
                trial = run_array['trial']
                y = run_array['y']
                stim = np.zeros((1, X.shape[-1]))

                if y.size > 0:
                    stim[0, trial - 1] = y

                data = np.concatenate((X, stim), axis=0)

                ch_names = [ch_name.upper() for ch_name in self._CHANNELS
                            ] + ['EOG1', 'EOG2', 'EOG3']
                ch_types = ['eeg'] * len(self._CHANNELS) + ['eog'] * 3
                ch_names = ch_names + ['STI 014']
                ch_types = ch_types + ['stim']
                montage = make_standard_montage('standard_1005')
                # 0.19.2 has no guarantee about case insensitive channel names
                montage.ch_names = [
                    ch_name.upper() for ch_name in montage.ch_names
                ]

                info = create_info(ch_names,
                                   self.srate,
                                   ch_types=ch_types,
                                   montage=montage)

                raw = RawArray(data, info)
                runs['run_%d' % i_run] = raw
            sessions['session_%d' % i_session] = runs
        return sessions
Exemple #21
0
def test_plot_bridged_electrodes():
    """Test plotting of bridged electrodes."""
    rng = np.random.default_rng(42)
    montage = make_standard_montage("biosemi64")
    info = create_info(montage.ch_names, 256, "eeg").set_montage("biosemi64")
    bridged_idx = [(0, 1), (2, 3)]
    n_epochs = 10
    ed_matrix = np.zeros(
        (n_epochs, len(info.ch_names), len(info.ch_names))) * np.nan
    triu_idx = np.triu_indices(len(info.ch_names), 1)
    for i in range(n_epochs):
        ed_matrix[i][triu_idx] = rng.random() + rng.random(triu_idx[0].size)
    fig = plot_bridged_electrodes(info,
                                  bridged_idx,
                                  ed_matrix,
                                  topomap_args=dict(names=info.ch_names,
                                                    vmax=1,
                                                    show_names=True))
    # two bridged lines plus head outlines
    assert len(fig.axes[0].lines) == 6

    with pytest.raises(RuntimeError, match='Expected'):
        plot_bridged_electrodes(info, bridged_idx, np.zeros((5, 6, 7)))
Exemple #22
0
def get_data(subject):
    event_id = dict(T0=subject, T1=subject, T2=subject)
    tmin, tmax = -1.0, 4.0

    raw_fnames = eegbci.load_data(subject, [14])
    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]

    return epochs.get_data
Exemple #23
0
    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 = make_standard_montage('standard_1005')
            data = {}
            for ii, path in enumerate(paths):
                raw = read_raw_gdf(path, eog=eog, misc=range(64, 96),
                                   preload=True, verbose='ERROR')
                raw.set_montage(montage)
                # there is nan in the data
                raw._data[np.isnan(raw._data)] = 0
                # Modify the annotations to match the name of the command
                stim = raw.annotations.description.astype(np.dtype('<21U'))
                stim[stim == '1536'] = "right_elbow_flexion"
                stim[stim == '1537'] = "right_elbow_extension"
                stim[stim == '1538'] = "right_supination"
                stim[stim == '1539'] = "right_pronation"
                stim[stim == '1540'] = "right_hand_close"
                stim[stim == '1541'] = "right_hand_open"
                stim[stim == '1542'] = "rest"
                raw.annotations.description = stim
                data['run_%d' % ii] = raw

            out[session] = data
        return out
Exemple #24
0
def raw_epochs_sphere():
    """Get the MATLAB EEG data."""
    n_times = 386
    mat_contents = sio.loadmat(eeg_fname)
    data = mat_contents['data']
    n_channels, n_epochs = data.shape[0], data.shape[1] // n_times
    sfreq = 250.
    ch_names = ['E%i' % i for i in range(1, n_channels + 1, 1)]
    ch_types = ['eeg'] * n_channels
    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=data, info=info)
    montage = make_standard_montage('GSN-HydroCel-257')
    raw.set_montage(montage)
    onset = raw.times[np.arange(50, n_epochs * n_times, n_times)]
    raw.set_annotations(Annotations(onset=onset,
                                    duration=np.repeat(0.1, 3),
                                    description=np.repeat('foo', 3)))

    events, event_id = events_from_annotations(raw)
    epochs = Epochs(raw, events, event_id, tmin=-.2, tmax=1.34,
                    preload=True, reject=None, picks=None,
                    baseline=(None, 0), verbose=False)
    sphere = (0., 0., 0., 0.095)
    return raw, epochs, sphere
Exemple #25
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""

        file_path_list = self.data_path(subject)
        sessions = {}
        for file_path in file_path_list:

            session_number = file_path.split(os.sep)[-2].replace("Session", "")
            session_name = "session_" + session_number
            if session_name not in sessions.keys():
                sessions[session_name] = {}

            run_number = file_path.split(os.sep)[-1]
            run_number = run_number.split("_")[-1]
            run_number = run_number.split(".gdf")[0]
            run_name = "run_" + run_number

            raw_original = mne.io.read_raw_gdf(file_path, preload=True)
            raw_original.rename_channels({"FP1": "Fp1", "FP2": "Fp2"})
            raw_original.set_montage(make_standard_montage("standard_1020"))

            sessions[session_name][run_name] = raw_original

        return sessions
Exemple #26
0
def test_plot_topomap_animation():
    """Test topomap plotting."""
    # evoked
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    # Test animation
    _, anim = evoked.animate_topomap(ch_type='grad', times=[0, 0.1],
                                     butterfly=False, time_unit='s')
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    plt.close('all')

    # Test plotting of fnirs types
    montage = make_standard_montage('biosemi16')
    ch_names = montage.ch_names
    ch_types = ['eeg'] * 16
    info = create_info(ch_names=ch_names, sfreq=20, ch_types=ch_types)
    evoked_data = np.random.randn(16, 30)
    evokeds = EvokedArray(evoked_data, info=info, tmin=-0.2, nave=4)
    evokeds.set_montage(montage)
    evokeds.set_channel_types({'Fp1': 'hbo', 'Fp2': 'hbo', 'F4': 'hbo',
                               'Fz': 'hbo'}, verbose='error')
    fig, anim = evokeds.animate_topomap(ch_type='hbo')
    anim._func(1)  # _animate has to be tested separately on 'Agg' backend.
    assert len(fig.axes) == 2
Exemple #27
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""

        file_path_list = self.data_path(subject)
        sessions = {}
        for file_path in file_path_list:

            session_number = file_path.split(os.sep)[-2].strip('Session')
            session_name = 'session_' + session_number
            if session_name not in sessions.keys():
                sessions[session_name] = {}

            run_number = file_path.split(os.sep)[-1]
            run_number = run_number.split('_')[-1]
            run_number = run_number.split('.gdf')[0]
            run_name = 'run_' + run_number

            raw_original = mne.io.read_raw_gdf(file_path, preload=True)
            raw_original.rename_channels({'FP1': 'Fp1', 'FP2': 'Fp2'})
            raw_original.set_montage(make_standard_montage('standard_1020'))

            sessions[session_name][run_name] = raw_original

        return sessions
Exemple #28
0
    def _get_single_subject_data(self, subject: Union[str, int], 
            verbose: Optional[Union[bool, str, int]] = None) -> Dict[str, Dict[str, Raw]]:
        dests = self.data_path(subject)
        montage = make_standard_montage('standard_1005')
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]

        sess = dict()
        for isess, run_dests in enumerate(dests):
            runs = dict()
            for irun, run_file in enumerate(run_dests):
                raw = read_raw_edf(run_file, preload=True)
                raw.rename_channels(lambda x: x.strip('.'))
                raw = upper_ch_names(raw)
                raw.set_montage(montage)

                # change event id
                ori_desc = np.copy(raw.annotations.description)
                if irun == 0:
                    raw.annotations.description[ori_desc=='T0'] = 6
                    raw.annotations.description[ori_desc!='T0'] = 0
                if irun == 1:
                    raw.annotations.description[ori_desc=='T0'] = 7
                    raw.annotations.description[ori_desc!='T0'] = 0

                if irun in [2, 3, 4]:
                    raw.annotations.description[ori_desc=='T0'] = 1
                    raw.annotations.description[ori_desc=='T1'] = 2
                    raw.annotations.description[ori_desc=='T2'] = 3
                if irun in [5, 6, 7]:
                    raw.annotations.description[ori_desc=='T0'] = 1
                    raw.annotations.description[ori_desc=='T1'] = 4
                    raw.annotations.description[ori_desc=='T2'] = 5 

                runs['run_{:d}'.format(irun)] = raw
            sess['session_{:d}'.format(isess)] = runs
        return sess
Exemple #29
0
    def _get_single_run_data(self, file_path):

        # data from the .mat
        data = loadmat(file_path)
        signals = data['data']
        stimuli = data['stimuli'].squeeze()
        events = data['events']
        target = data['target'][0][0]

        # meta-info from the readme.pdf
        sfreq = 2048
        ch_names = [
            'Fp1', 'AF3', 'F7', 'F3', 'FC1', 'FC5', 'T7', 'C3', 'CP1', 'CP5',
            'P7', 'P3', 'Pz', 'PO3', 'O1', 'Oz', 'O2', 'PO4', 'P4', 'P8',
            'CP6', 'CP2', 'C4', 'T8', 'FC6', 'FC2', 'F4', 'F8', 'AF4', 'Fp2',
            'Fz', 'Cz', 'MA1', 'MA2'
        ]
        ch_types = ['eeg'] * 32 + ['misc'] * 2

        # The last X entries are 0 for all signals. This leads to
        # artifacts when epoching and band-pass filtering the data.
        # Correct the signals for this.
        sig_i = np.where(
            np.diff(np.all(signals == 0, axis=0).astype(int)) != 0)[0][0]
        signals = signals[:, :sig_i]
        signals *= 1e-6  # data is stored as uV, but MNE expects V
        # we have to re-reference the signals
        # the average signal on the mastoids electrodes is used as reference
        references = [32, 33]
        ref = np.mean(signals[references, :], axis=0)
        signals = signals - ref

        # getting the event time in a Python standardized way
        events_datetime = []
        for eventi in events:
            events_datetime.append(
                dt.datetime(*eventi.astype(int),
                            int(eventi[-1] * 1e3) % 1000 * 1000))

        # get the indices of the stimuli
        pos = []
        n_trials = len(stimuli)
        for j in range(n_trials):
            delta_seconds = (events_datetime[j] -
                             events_datetime[0]).total_seconds()
            delta_indices = int(delta_seconds * sfreq)
            # has to add an offset
            pos.append(delta_indices + int(0.4 * sfreq))

        # create a stimulus channel
        stim_aux = np.copy(stimuli)
        stim_aux[stimuli == target] = 2
        stim_aux[stimuli != target] = 1
        stim_channel = np.zeros(signals.shape[1])
        stim_channel[pos] = stim_aux
        ch_names = ch_names + ['STI']
        ch_types = ch_types + ['stim']
        signals = np.concatenate([signals, stim_channel[None, :]])

        # create info dictionary
        info = mne.create_info(ch_names, sfreq, ch_types)
        info['description'] = 'EPFL P300 dataset'

        # create the Raw structure
        raw = mne.io.RawArray(signals, info, verbose=False)
        montage = make_standard_montage('biosemi32')
        raw.set_montage(montage)

        return raw



#
#
######## Authors: Martin Billinger <*****@*****.**> ########
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])
eegbci.standardize(raw)  # set channel names
montage = make_standard_montage('standard_1005')
raw.set_montage(montage)

# 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, event_id=dict(T1=2, T2=3))

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)