Ejemplo n.º 1
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_types = ["eeg"] * 59 + ["misc"] + 3 * ["eeg"] + ["misc", "stim"]
        sfreq = 250
        info = create_info(self._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}}
Ejemplo n.º 2
0
    def _get_single_subject_data(self, subject):
        """Return the data of a single subject"""
        n_samples, n_channels, n_trials = 1114, 8, 15
        n_classes = len(self.event_id)

        fname = self.data_path(subject)
        mat = loadmat(fname, squeeze_me=True)
        data = np.transpose(mat["eeg"], axes=(0, 3, 1, 2))
        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 = [
            "PO7", "PO3", "POz", "PO4", "PO8", "O1", "Oz", "O2", "stim"
        ]
        ch_types = ["eeg"] * 8 + ["stim"]
        sfreq = 256
        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}}
Ejemplo n.º 3
0
def load_raw(filename,
             sfreq=256.,
             ch_ind=[0, 1, 2, 3],
             stim_ind=5,
             replace_ch_names=None):
    '''
        [!] FUNCIÓN de creación del objeto Raw a partir del fichero con los datos del experimento.
    '''
    n_channel = len(ch_ind)
    data = pd.read_csv(filename)

    if "Timestamp" in data.columns:
        del data['Timestamp']
    if "Time" in data.columns:
        del data['Time']

    ch_names = list(data.columns)[0:n_channel] + ['Stim']

    if replace_ch_names is not None:
        ch_names = [
            c if c not in replace_ch_names.keys() else replace_ch_names[c]
            for c in ch_names
        ]

    ch_types = ['eeg'] * n_channel + ['stim']
    # montage = read_custom_montage('openbcipos.sfp')
    montage = 'standard_1020'
    data = data.values[:, ch_ind + [stim_ind]].T
    data[:-1] *= 1e-6

    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=data, info=info)
    raw.set_montage(montage)

    return raw
Ejemplo n.º 4
0
    def _get_single_subject_data(self, subject: Union[str, int], 
            verbose: Optional[Union[bool, str, int]] = None) -> Dict[str, Dict[str, Raw]]:
        montage = make_standard_montage('standard_1005')
        montage.ch_names = [ch_name.upper() for ch_name in montage.ch_names]
        
        dests = self.data_path(subject)
        raw_mat = loadmat(dests[0][0])
        n_samples, n_channels, n_trials = 1114, 8, 15
        n_classes = 12

        data = np.transpose(raw_mat['eeg'], axes=(0, 3, 1, 2))
        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)

        buff = (data.shape[0], n_channels + 1, 50)
        data = np.concatenate([np.zeros(buff), data,
                               np.zeros(buff)], axis=2)
        ch_names = self._CHANNELS + ['stim']
        ch_types = ['eeg']*len(self._CHANNELS) + ['stim']

        info = create_info(
            ch_names=ch_names, ch_types=ch_types, sfreq=self.srate
        )
        raw = RawArray(data=np.concatenate(list(data), axis=1), info=info)
        raw = upper_ch_names(raw)
        raw.set_montage(montage)

        sess = {
            'session_0': {'run_0': raw}
        }
        return sess
Ejemplo n.º 5
0
    def _get_single_subject_data(self, subject: int):
        record = self.read_hdf(self.data_path(subject))

        info = create_info(
            self.ch_names + ["mult_target", "target"],
            self.sampling_rate,
            ["eeg"] * len(self.ch_names) + ["misc", "stim"],
        )
        montage = make_standard_montage("standard_1020")

        runs_raw = {}
        for i, act in enumerate(record):
            # target and stims are increased by 1
            # because the channel is filled with zeros by default
            target = act["target"] + 1
            run_data = []
            for eeg, starts, stims in act["sessions"]:
                starts = starts * self.sampling_rate / self._ms_in_sec
                starts = starts.round().astype(np.int)
                stims = stims + 1
                stims_channel = np.zeros(eeg.shape[1])
                target_channel = np.zeros(eeg.shape[1])

                for start, stimul in zip(starts, stims):
                    stims_channel[start] = stimul
                    target_channel[start] = 1 if stimul == target else 2

                round_data = np.vstack(
                    (eeg, stims_channel[None, :], target_channel[None, :]))
                run_data.append(round_data)

            raw = RawArray(np.hstack(run_data), info)
            raw.set_montage(montage)
            runs_raw[f"run_{i}"] = raw
        return {"session_0": runs_raw}
Ejemplo n.º 6
0
Archivo: bnci.py Proyecto: xkazm/moabb
def _convert_run(run, ch_names=None, ch_types=None, verbose=None):
    """Convert one run to raw."""
    # parse eeg data
    event_id = {}
    n_chan = run.X.shape[1]
    montage = make_standard_montage('standard_1005')
    eeg_data = 1e-6 * run.X
    sfreq = run.fs

    if not ch_names:
        ch_names = ['EEG%d' % ch for ch in range(1, n_chan + 1)]
        montage = None  # no montage

    if not ch_types:
        ch_types = ['eeg'] * n_chan

    trigger = np.zeros((len(eeg_data), 1))
    # some runs does not contains trials i.e baseline runs
    if len(run.trial) > 0:
        trigger[run.trial - 1, 0] = run.y
    else:
        return None, None

    eeg_data = np.c_[eeg_data, trigger]
    ch_names = ch_names + ['stim']
    ch_types = ch_types + ['stim']
    event_id = {ev: (ii + 1) for ii, ev in enumerate(run.classes)}
    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=eeg_data.T, info=info, verbose=verbose)
    raw.set_montage(montage)
    return raw, event_id
Ejemplo n.º 7
0
Archivo: bnci.py Proyecto: xkazm/moabb
def _convert_run_bbci(run, ch_types, verbose=None):
    """Convert one run to raw."""
    # parse eeg data
    montage = make_standard_montage('standard_1005')
    eeg_data = 1e-6 * run.X
    sfreq = run.fs

    ch_names = list(run.channels)

    trigger = np.zeros((len(eeg_data), 1))
    trigger[run.trial - 1, 0] = run.y
    event_id = {ev: (ii + 1) for ii, ev in enumerate(run.classes)}

    flash = np.zeros((len(eeg_data), 1))
    flash[run.trial - 1, 0] = run.y_stim + 2
    ev_fl = {'Stim%d' % (stim): (stim + 2) for stim in np.unique(run.y_stim)}
    event_id.update(ev_fl)

    eeg_data = np.c_[eeg_data, trigger, flash]
    ch_names = ch_names + ['Target', 'Flash']
    ch_types = ch_types + ['stim'] * 2

    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=eeg_data.T, info=info, verbose=verbose)
    raw.set_montage(montage)
    return raw, event_id
Ejemplo n.º 8
0
 def _convert_to_raw(self, data, s):
     fs = 500
     ch_names = [
         'Fp1', 'F5', 'F3', 'F1', 'Fz', 'FC5', 'FC3', 'FC1', 'FCz', 'C5',
         'C3', 'C1', 'Cz', 'CP5', 'CP3', 'CP1', 'CPz', 'P5', 'P3', 'P1',
         'Pz'
     ]
     ch_types = ['eeg'] * 21
     info = create_info(ch_names, fs, ch_types)
     info['description'] = 'PGHealthy'
     x = data['Signals'] * 1e-6
     raw = RawArray(x, info)
     epoch_start = np.array(data['Epoch_start']).T
     N = len(epoch_start)
     events = np.c_[epoch_start, np.zeros(N), np.ones(N) * (s + 1)]
     events = events.astype(np.int)
     raw.set_montage('standard_1005')
     mapping = {v: k for k, v in self.event_id.items()}
     onsets = events[:, 0] / raw.info['sfreq']
     durations = np.zeros_like(onsets)  # assumes instantaneous events
     descriptions = [mapping[ev_id] for ev_id in events[:, 2]]
     annot_from_events = Annotations(onset=onsets,
                                     duration=durations,
                                     description=descriptions)
     raw.notch_filter(50, verbose=False)
     return raw.set_annotations(annot_from_events)
Ejemplo n.º 9
0
Archivo: bnci.py Proyecto: xkazm/moabb
def _convert_run_epfl(run, verbose=None):
    """Convert one run to raw."""
    # parse eeg data
    event_id = {}

    montage = make_standard_montage('standard_1005')
    eeg_data = 1e-6 * run.eeg
    sfreq = run.header.SampleRate

    ch_names = list(run.header.Label[:-1])
    ch_types = ['eeg'] * len(ch_names)

    trigger = np.zeros((len(eeg_data), 1))

    for ii, typ in enumerate(run.header.EVENT.TYP):
        if typ in [6, 9]:  # Error
            trigger[run.header.EVENT.POS[ii] - 1, 0] = 2
        elif typ in [5, 10]:  # correct
            trigger[run.header.EVENT.POS[ii] - 1, 0] = 1

    eeg_data = np.c_[eeg_data, trigger]
    ch_names = ch_names + ['stim']
    ch_types = ch_types + ['stim']
    event_id = {'correct': 1, 'error': 2}

    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=eeg_data.T, info=info, verbose=verbose)
    raw.set_montage(montage)
    return raw, event_id
Ejemplo n.º 10
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        fnames = self.data_path(subject)
        sessions = {}

        for fpath in fnames:
            if self.code == "SSVEP MAMEM3":
                fnamed = os.path.basename(fpath)
                session_name = "session_" + fnamed[4]
                # Since the data for each session is saved in 2 files,
                # it is being saved in 2 runs
                run_number = len(fnamed) - 6
                run_name = "run_" + str(run_number)
            else:
                session_name = "session_" + fpath[-1]
                run_name = "run_0"

            record = wfdb.rdrecord(fpath)
            data = record.p_signal.T
            annots = wfdb.rdann(fpath, "win")
            # the number of samples isn't exactly equal in all the trials
            n_samples = record.sig_len
            stim_freq = np.array([float(e) for e in self.event_id.keys()])
            # aux_note are the exact frequencies, matched to nearest class
            events_label = [
                np.argmin(np.abs(stim_freq - float(f))) + 1
                for f in annots.aux_note
            ]
            raw_events = np.zeros([1, n_samples])
            #  annots.sample indicates the start of the trial
            # of class "events_label"
            for label, samploc in zip(events_label, annots.sample):
                raw_events[0, samploc] = label
            # append the data as another channel(stim) in the data
            data = np.concatenate((data, raw_events), axis=0)
            if self.code == "SSVEP MAMEM3":
                ch_names = record.sig_name
                sfreq = 128
                montage = make_standard_montage("standard_1020")
            else:
                ch_names = ["E{}".format(i + 1) for i in range(0, 256)]
                # ch_names = ["{}-{}".format(s, i) if s == "EEG" else s
                #             for i, s in enumerate(record.sig_name)]
                sfreq = 250
                montage = make_standard_montage("GSN-HydroCel-256")
            ch_types = ["eeg"] * len(ch_names) + ["stim"]
            ch_names.append("stim")

            info = create_info(ch_names, sfreq, ch_types)
            raw = RawArray(data, info, verbose=False)
            raw.set_montage(montage)
            if session_name not in sessions.keys():
                sessions[session_name] = {}
            if len(sessions[session_name]) == 0:
                sessions[session_name] = {run_name: raw}
            else:
                sessions[session_name][run_name] = raw
        return sessions
Ejemplo n.º 11
0
def load_openBCI_csv_as_raw(
        filename,
        sfreq=256.,
        ch_ind=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        stim_ind=16,
        replace_ch_names=None,
        verbose=1):
    """Load CSV files into a Raw object.

    Args:
        filename (list): paths to CSV files to load

    Keyword Args:
        subject_nb (int or str): subject number. If 'all', load all
            subjects.
        session_nb (int or str): session number. If 'all', load all
            sessions.
        sfreq (float): EEG sampling frequency
        ch_ind (list): indices of the EEG channels to keep
        stim_ind (int): index of the stim channel
        replace_ch_names (dict or None): dictionary containing a mapping to
            rename channels. Useful when an external electrode was used.

    Returns:
        (mne.io.array.array.RawArray): loaded EEG
        """
    n_channel = len(ch_ind)
    raw = []

    for fname in filename:

        # read the file
        data = pd.read_csv(fname, index_col=0)
        # name of each channels
        ch_names = list(data.columns)[0:n_channel] + ['Stim']
        if replace_ch_names is not None:
            ch_names = [
                c if c not in replace_ch_names.keys() else replace_ch_names[c]
                for c in ch_names
            ]
        # type of each channels
        ch_types = ['eeg'] * n_channel + ['stim']
        # get data and exclude Aux channel
        data = data.values[:, ch_ind + [stim_ind]].T
        # convert in Volts (from nanoVolts?)
        data[:-1] *= 1e-9
        montage = make_standard_montage('standard_1005')
        info = create_info(ch_names=ch_names,
                           ch_types=ch_types,
                           sfreq=sfreq,
                           verbose=verbose)
        rawi = RawArray(data=data, info=info, verbose=verbose)
        rawi.set_montage(montage, raise_if_subset=False, match_case=False)
        raw.append(rawi)
        # concatenate all raw objects
        raws = concatenate_raws(raw, verbose=verbose)
    return raws
Ejemplo n.º 12
0
Archivo: bnci.py Proyecto: xkazm/moabb
def _load_data_003_2015(subject,
                        path=None,
                        force_update=False,
                        update_path=None,
                        base_url=BNCI_URL,
                        verbose=None):
    """Load data for 003-2015 dataset."""
    if (subject < 1) or (subject > 10):
        raise ValueError("Subject must be between 1 and 12. Got %d." % subject)

    url = '{u}003-2015/s{s:d}.mat'.format(u=base_url, s=subject)
    filename = data_path(url, path, force_update, update_path)[0]

    from scipy.io import loadmat

    data = loadmat(filename, struct_as_record=False, squeeze_me=True)
    data = data['s%d' % subject]
    sfreq = 256.

    ch_names = [
        'Fz', 'Cz', 'P3', 'Pz', 'P4', 'PO7', 'Oz', 'PO8', 'Target', 'Flash'
    ]

    ch_types = ['eeg'] * 8 + ['stim'] * 2
    montage = make_standard_montage('standard_1005')

    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)

    sessions = {}
    sessions['session_0'] = {}
    for ri, run in enumerate([data.train, data.test]):
        # flash events on the channel 9
        flashs = run[9:10]
        ix_flash = flashs[0] > 0
        flashs[0, ix_flash] += 2  # add 2 to avoid overlapp on event id
        flash_code = np.unique(flashs[0, ix_flash])

        if len(flash_code) == 36:
            # char mode
            evd = {'Char%d' % ii: (ii + 2) for ii in range(1, 37)}
        else:
            # row / column mode
            evd = {'Col%d' % ii: (ii + 2) for ii in range(1, 7)}
            evd.update({'Row%d' % ii: (ii + 8) for ii in range(1, 7)})

        # target events are on channel 10
        targets = np.zeros_like(flashs)
        targets[0, ix_flash] = run[10, ix_flash] + 1

        eeg_data = np.r_[run[1:-2] * 1e-6, targets, flashs]
        raw = RawArray(data=eeg_data, info=info, verbose=verbose)
        raw.set_montage(montage)
        sessions['session_0']['run_' + str(ri)] = raw

    return sessions
Ejemplo n.º 13
0
def _load_data_003_2015(
    subject,
    path=None,
    force_update=False,
    update_path=None,
    base_url=BNCI_URL,
    verbose=None,
):
    """Load data for 003-2015 dataset."""
    if (subject < 1) or (subject > 10):
        raise ValueError("Subject must be between 1 and 12. Got %d." % subject)

    url = "{u}003-2015/s{s:d}.mat".format(u=base_url, s=subject)
    filename = data_path(url, path, force_update, update_path)[0]

    data = loadmat(filename, struct_as_record=False, squeeze_me=True)
    data = data["s%d" % subject]
    sfreq = 256.0

    ch_names = [
        "Fz", "Cz", "P3", "Pz", "P4", "PO7", "Oz", "PO8", "Target", "Flash"
    ]

    ch_types = ["eeg"] * 8 + ["stim"] * 2
    montage = make_standard_montage("standard_1005")

    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)

    sessions = {}
    sessions["session_0"] = {}
    for ri, run in enumerate([data.train, data.test]):
        # flash events on the channel 9
        flashs = run[9:10]
        ix_flash = flashs[0] > 0
        flashs[0, ix_flash] += 2  # add 2 to avoid overlapp on event id
        flash_code = np.unique(flashs[0, ix_flash])

        if len(flash_code) == 36:
            # char mode
            evd = {"Char%d" % ii: (ii + 2) for ii in range(1, 37)}
        else:
            # row / column mode
            evd = {"Col%d" % ii: (ii + 2) for ii in range(1, 7)}
            evd.update({"Row%d" % ii: (ii + 8) for ii in range(1, 7)})

        # target events are on channel 10
        targets = np.zeros_like(flashs)
        targets[0, ix_flash] = run[10, ix_flash] + 1

        eeg_data = np.r_[run[1:-2] * 1e-6, targets, flashs]
        raw = RawArray(data=eeg_data, info=info, verbose=verbose)
        raw.set_montage(montage)
        sessions["session_0"]["run_" + str(ri)] = raw

    return sessions
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
    def _get_single_subject_data(self, subject):
        """return data for a single subejct"""

        sessions = {}
        file_path_list = self.data_path(subject)

        for session in range(1, 3):
            data = loadmat(file_path_list[session - 1])

            # Create channel info and montage
            eeg_ch_names = data["EEG_MI_train"][0, 0][8][0]
            ch_names = [elem[0] for elem in eeg_ch_names] + ["stim"]
            ch_types = ["eeg"] * 62 + ["stim"]
            sfreq = data["EEG_MI_train"][0, 0][3][0, 0]
            info = create_info(ch_names=ch_names,
                               ch_types=ch_types,
                               sfreq=sfreq)
            montage = make_standard_montage("standard_1005")

            # Create raw_data
            raw_train_data = np.transpose(data["EEG_MI_train"][0, 0][0],
                                          (1, 2, 0))
            raw_test_data = np.transpose(data["EEG_MI_test"][0, 0][0],
                                         (1, 2, 0))
            raw_data = np.concatenate([raw_train_data, raw_test_data], axis=0)

            # Create raw_event
            train_event_id = data["EEG_MI_train"][0, 0][4].ravel()
            test_event_id = data["EEG_MI_test"][0, 0][4].ravel()
            event_id = np.concatenate([train_event_id, test_event_id], axis=0)
            raw_events = np.zeros((raw_data.shape[0], 1, raw_data.shape[2]))
            raw_events[:, 0, 0] = event_id

            # Zero pad the data
            data = np.concatenate([raw_data, raw_events], axis=1)
            zeroshape = (data.shape[0], data.shape[1], 50)
            data = np.concatenate(
                [np.zeros(zeroshape), data,
                 np.zeros(zeroshape)], axis=2)

            # Create RawArray
            raw = RawArray(data=np.concatenate(list(data), axis=1),
                           info=info,
                           verbose=False)
            raw.set_montage(montage)

            # add the data to sessions
            session_name = "session_{}".format(session)
            sessions[session_name] = {"run_1": raw}

        return sessions
Ejemplo n.º 16
0
    def _convert_one_session(self, data, mrk, session, trig_offset=0):
        eeg = data[session].x.T * 1e-6
        trig = np.zeros((1, eeg.shape[1]))
        idx = (mrk[session].time - 1) // 5
        trig[0, idx] = mrk[session].event.desc // 16 + trig_offset
        eeg = np.vstack([eeg, trig])
        ch_names = list(data[session].clab) + ['Stim']
        ch_types = ['eeg'] * 30 + ['eog'] * 2 + ['stim']

        montage = make_standard_montage('standard_1005')
        info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=200.)
        raw = RawArray(data=eeg, info=info, verbose=False)
        raw.set_montage(montage)
        return {'run_0': raw}
Ejemplo n.º 17
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        fnames = self.data_path(subject)
        filelist = fs_get_file_list(self.figshare_id)
        fsn = fs_get_file_name(filelist)
        sessions = {}

        for fpath in fnames:
            fnamed = fsn[osp.basename(fpath)]
            if fnamed[4] == "x":
                continue
            session_name = "session_" + fnamed[4]
            if self.code == "SSVEP MAMEM3":
                # Since the data for each session is saved in 2 files,
                # it is being saved in 2 runs
                run_number = len(fnamed) - 10
                run_name = "run_" + str(run_number)
            else:
                run_name = "run_0"

            if self.code == "SSVEP MAMEM3":
                m = loadmat(fpath)
                ch_names = [e[0] for e in m["info"][0, 0][9][0]]
                sfreq = 128
                montage = make_standard_montage("standard_1020")
                eeg = m["eeg"]
            else:
                m = loadmat(fpath, squeeze_me=True)
                ch_names = ["E{}".format(i + 1) for i in range(0, 256)]
                ch_names.append("stim")
                # ch_names = ["{}-{}".format(s, i) if s == "EEG" else s
                #             for i, s in enumerate(record.sig_name)]
                sfreq = 250
                if self.code == "SSVEP MAMEM2":
                    labels = m["labels"]
                else:
                    labels = None
                eeg = mamem_event(m["eeg"], m["DIN_1"], labels=labels)
                montage = make_standard_montage("GSN-HydroCel-256")
            ch_types = ["eeg"] * (len(ch_names) - 1) + ["stim"]
            info = create_info(ch_names, sfreq, ch_types)
            raw = RawArray(eeg, info, verbose=False)
            raw.set_montage(montage)
            if session_name not in sessions.keys():
                sessions[session_name] = {}
            if len(sessions[session_name]) == 0:
                sessions[session_name] = {run_name: raw}
            else:
                sessions[session_name][run_name] = raw
        return sessions
Ejemplo n.º 18
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        fname = self.data_path(subject)

        data = loadmat(
            fname,
            squeeze_me=True,
            struct_as_record=False,
            verify_compressed_data_integrity=False,
        )["eeg"]

        # fmt: off
        eeg_ch_names = [
            "Fp1", "AF7", "AF3", "F1", "F3", "F5", "F7", "FT7", "FC5", "FC3", "FC1",
            "C1", "C3", "C5", "T7", "TP7", "CP5", "CP3", "CP1", "P1", "P3", "P5", "P7",
            "P9", "PO7", "PO3", "O1", "Iz", "Oz", "POz", "Pz", "CPz", "Fpz", "Fp2",
            "AF8", "AF4", "AFz", "Fz", "F2", "F4", "F6", "F8", "FT8", "FC6", "FC4",
            "FC2", "FCz", "Cz", "C2", "C4", "C6", "T8", "TP8", "CP6", "CP4", "CP2",
            "P2", "P4", "P6", "P8", "P10", "PO8", "PO4", "O2",
        ]
        # fmt: on
        emg_ch_names = ["EMG1", "EMG2", "EMG3", "EMG4"]
        ch_names = eeg_ch_names + emg_ch_names + ["Stim"]
        ch_types = ["eeg"] * 64 + ["emg"] * 4 + ["stim"]
        montage = make_standard_montage("standard_1005")
        imagery_left = data.imagery_left - data.imagery_left.mean(axis=1, keepdims=True)
        imagery_right = data.imagery_right - data.imagery_right.mean(
            axis=1, keepdims=True
        )

        eeg_data_l = np.vstack([imagery_left * 1e-6, data.imagery_event])
        eeg_data_r = np.vstack([imagery_right * 1e-6, data.imagery_event * 2])

        # trials are already non continuous. edge artifact can appears but
        # are likely to be present during rest / inter-trial activity
        eeg_data = np.hstack(
            [eeg_data_l, np.zeros((eeg_data_l.shape[0], 500)), eeg_data_r]
        )
        log.warning(
            "Trials demeaned and stacked with zero buffer to create "
            "continuous data -- edge effects present"
        )

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

        return {"session_0": {"run_0": raw}}
Ejemplo n.º 19
0
def test_pick_types_csd():
    """Test pick_types(csd=True)."""
    # info with laplacian/CSD channels at indices 1, 2
    names = ['F1', 'F2', 'C1', 'C2', 'A1', 'A2', 'misc1', 'CSD1']
    info1 = create_info(
        names, 256, ["eeg", "eeg", "eeg", "eeg", "mag", "mag", 'misc', 'csd'])
    raw = RawArray(np.zeros((8, 512)), info1)
    raw.set_montage(make_standard_montage('standard_1020'), verbose='error')
    raw_csd = compute_current_source_density(raw, verbose='error')

    assert_array_equal(pick_types(info1, csd=True), [7])

    # pick from the raw object
    assert raw_csd.copy().pick_types(csd=True).ch_names == [
        'F1', 'F2', 'C1', 'C2', 'CSD1'
    ]
Ejemplo n.º 20
0
Archivo: bnci.py Proyecto: xkazm/moabb
def _convert_run_p300_sl(run, verbose=None):
    """Convert one p300 run from santa lucia file format."""
    montage = make_standard_montage('standard_1005')
    eeg_data = 1e-6 * run.X
    sfreq = 256
    ch_names = list(run.channels) + ['Target stim', 'Flash stim']
    ch_types = ['eeg'] * len(run.channels) + ['stim'] * 2

    flash_stim = run.y_stim
    flash_stim[flash_stim > 0] += 2
    eeg_data = np.c_[eeg_data, run.y, flash_stim]
    event_id = {ev: (ii + 1) for ii, ev in enumerate(run.classes)}
    event_id.update({ev: (ii + 3) for ii, ev in enumerate(run.classes_stim)})
    info = create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
    raw = RawArray(data=eeg_data.T, info=info, verbose=verbose)
    raw.set_montage(montage)
    return raw, event_id
Ejemplo n.º 21
0
    def _get_single_subject_data(self, subject):
        """return data for a single subject"""
        fname = self.data_path(subject)

        data = loadmat(fname,
                       squeeze_me=True,
                       struct_as_record=False,
                       verify_compressed_data_integrity=False)['eeg']

        eeg_ch_names = [
            'Fp1', 'AF7', 'AF3', 'F1', 'F3', 'F5', 'F7', 'FT7', 'FC5', 'FC3',
            'FC1', 'C1', 'C3', 'C5', 'T7', 'TP7', 'CP5', 'CP3', 'CP1', 'P1',
            'P3', 'P5', 'P7', 'P9', 'PO7', 'PO3', 'O1', 'Iz', 'Oz', 'POz',
            'Pz', 'CPz', 'Fpz', 'Fp2', 'AF8', 'AF4', 'AFz', 'Fz', 'F2', 'F4',
            'F6', 'F8', 'FT8', 'FC6', 'FC4', 'FC2', 'FCz', 'Cz', 'C2', 'C4',
            'C6', 'T8', 'TP8', 'CP6', 'CP4', 'CP2', 'P2', 'P4', 'P6', 'P8',
            'P10', 'PO8', 'PO4', 'O2'
        ]
        emg_ch_names = ['EMG1', 'EMG2', 'EMG3', 'EMG4']
        ch_names = eeg_ch_names + emg_ch_names + ['Stim']
        ch_types = ['eeg'] * 64 + ['emg'] * 4 + ['stim']
        montage = make_standard_montage('standard_1005')
        imagery_left = data.imagery_left - \
            data.imagery_left.mean(axis=1, keepdims=True)
        imagery_right = data.imagery_right - \
            data.imagery_right.mean(axis=1, keepdims=True)

        eeg_data_l = np.vstack([imagery_left * 1e-6, data.imagery_event])
        eeg_data_r = np.vstack([imagery_right * 1e-6, data.imagery_event * 2])

        # trials are already non continuous. edge artifact can appears but
        # are likely to be present during rest / inter-trial activity
        eeg_data = np.hstack(
            [eeg_data_l,
             np.zeros((eeg_data_l.shape[0], 500)), eeg_data_r])
        log.warning("Trials demeaned and stacked with zero buffer to create "
                    "continuous data -- edge effects present")

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

        return {'session_0': {'run_0': raw}}
Ejemplo n.º 22
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
Ejemplo n.º 23
0
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)
    raw = RawArray(np.zeros((1, 1000)), 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])
    raw.set_montage(mon)
    with pytest.raises(ValueError, match='match_case=False as 1 montage name'):
        raw.set_montage(mon, match_case=False)
Ejemplo n.º 24
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
Ejemplo n.º 25
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
Ejemplo n.º 26
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}}
Ejemplo n.º 27
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
Ejemplo n.º 28
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
Ejemplo n.º 29
0
def create_raw_with_noise(raw_without_noise, gaussian_distribution=None):
    '''
    [!] FUNCIÓN para hacer una copia de un Raw Data, aplicarle ruido y devolverlo como estructura Raw.
    '''
    data = raw_without_noise.get_data()
    stim = raw_without_noise.get_data(picks=['Stim'])
    '''
    Se crean muestras parametrizadas de una distribución normal (gaussiana) para generar ruido en la señal
    '''
    if len(data) == len(gaussian_distribution):
        print("Aplicando ruido a la señal...")
        data = data + gaussian_distribution
        data[-1] = stim
    else:
        print(
            "Error en la aplicación de ruido. Estructuras de datos con tamaños distintos."
        )
        return

    raw = RawArray(data=data, info=raw_without_noise.info)
    montage = 'standard_1020'
    raw.set_montage(montage)

    return raw
Ejemplo n.º 30
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