Пример #1
0
def test_pick_channels_regexp():
    """Test pick with regular expression
    """
    ch_names = ["MEG 2331", "MEG 2332", "MEG 2333"]
    assert_array_equal(pick_channels_regexp(ch_names, "MEG ...1"), [0])
    assert_array_equal(pick_channels_regexp(ch_names, "MEG ...[2-3]"), [1, 2])
    assert_array_equal(pick_channels_regexp(ch_names, "MEG *"), [0, 1, 2])
Пример #2
0
def test_pick_channels_regexp():
    """Test pick with regular expression
    """
    ch_names = ['MEG 2331', 'MEG 2332', 'MEG 2333']
    assert_array_equal(pick_channels_regexp(ch_names, 'MEG ...1'), [0])
    assert_array_equal(pick_channels_regexp(ch_names, 'MEG ...[2-3]'), [1, 2])
    assert_array_equal(pick_channels_regexp(ch_names, 'MEG *'), [0, 1, 2])
Пример #3
0
def sort(EEG, montage, rename=False):
    """
    EEG mne raw data.
    montage str '10-20' or "BC"
    rename bool replace rename channel names if true
    Return mne data 
    """

    bool_index = np.zeros(len(EEG.ch_names))
    if montage == "10-20":
        setup = ten_twenty()
    elif montage == "BC":
        setup = BC()
    else:
        raise NameError('Invalid montage')

    for channel in setup:
        index = mne.pick_channels_regexp(EEG.ch_names, regexp="EEG " +
                                         channel)  #May need extra debugging

        if index == []:
            #IF someone want to gennerate missing channels thoug interpolation this is the place.
            raise NameError(f"Channel {channel} is not in dataset")

        index = index[0]
        if rename == True:
            EEG.ch_names[index] = channel

        bool_index[index] = True
    EEG_new = EEG.drop_channels(np.array(EEG.ch_names)[bool_index == False])
    return EEG_new
Пример #4
0
def test_ica_labels():
    """Test ICA labels."""
    # The CTF data are uniquely well suited to testing the ICA.find_bads_
    # methods
    raw = read_raw_ctf(ctf_fname, preload=True)

    # set the appropriate EEG channels to EOG and ECG
    raw.set_channel_types({'EEG057': 'eog', 'EEG058': 'eog', 'EEG059': 'ecg'})
    ica = ICA(n_components=4, random_state=0, max_iter=2, method='fastica',
              allow_ref_meg=True)
    with pytest.warns(UserWarning, match='did not converge'):
        ica.fit(raw)
    _assert_ica_attributes(ica)

    ica.find_bads_eog(raw, l_freq=None, h_freq=None)
    picks = list(pick_types(raw.info, meg=False, eog=True))
    for idx, ch in enumerate(picks):
        assert '{}/{}/{}'.format('eog', idx, raw.ch_names[ch]) in ica.labels_
    assert 'eog' in ica.labels_
    for key in ('ecg', 'ref_meg', 'ecg/ECG-MAG'):
        assert key not in ica.labels_

    ica.find_bads_ecg(raw, l_freq=None, h_freq=None, method='correlation',
                      threshold='auto')
    picks = list(pick_types(raw.info, meg=False, ecg=True))
    for idx, ch in enumerate(picks):
        assert '{}/{}/{}'.format('ecg', idx, raw.ch_names[ch]) in ica.labels_
    for key in ('ecg', 'eog'):
        assert key in ica.labels_
    for key in ('ref_meg', 'ecg/ECG-MAG'):
        assert key not in ica.labels_

    # derive reference ICA components and append them to raw
    ica_rf = ICA(n_components=2, random_state=0, max_iter=2,
                 allow_ref_meg=True)
    with pytest.warns(UserWarning, match='did not converge'):
        ica_rf.fit(raw.copy().pick_types(meg=False, ref_meg=True))
    icacomps = ica_rf.get_sources(raw)
    # rename components so they are auto-detected by find_bads_ref
    icacomps.rename_channels({c: 'REF_' + c for c in icacomps.ch_names})
    # and add them to raw
    raw.add_channels([icacomps])
    ica.find_bads_ref(raw, l_freq=None, h_freq=None, method="separate")
    picks = pick_channels_regexp(raw.ch_names, 'REF_ICA*')
    for idx, ch in enumerate(picks):
        assert '{}/{}/{}'.format('ref_meg', idx,
                                 raw.ch_names[ch]) in ica.labels_
    ica.find_bads_ref(raw, l_freq=None, h_freq=None, method="together")
    assert 'ref_meg' in ica.labels_

    for key in ('ecg', 'eog', 'ref_meg'):
        assert key in ica.labels_
    assert 'ecg/ECG-MAG' not in ica.labels_

    ica.find_bads_ecg(raw, l_freq=None, h_freq=None, threshold='auto')
    for key in ('ecg', 'eog', 'ref_meg', 'ecg/ECG-MAG'):
        assert key in ica.labels_
Пример #5
0
def bids_preprocess_raw(raw, bids_path, montage):
    """Preprocess raw channel names and types."""
    # acquisition in EZTrack is encoded for eeg,ecog,seeg
    acquisition = bids_path.acquisition
    datatype = bids_path.datatype

    # set channel types
    if acquisition in ["seeg", "ecog", "eeg"]:
        logger.info(f"Setting channel types to: {acquisition}")
        raw.set_channel_types(
            {raw.ch_names[i]: acquisition for i in mne.pick_types(raw.info, eeg=True)}
        )

    # reformat channel text if necessary
    raw = _channel_text_scrub(raw)

    # set DC channels -> MISC for now
    picks = mne.pick_channels_regexp(raw.ch_names, regexp="DC|[$]")
    raw.set_channel_types(
        {raw.ch_names[pick]: "misc" for pick in picks}
    )

    # set bio channels (e.g. EKG, EMG, EOG)
    picks = mne.pick_channels_regexp(raw.ch_names, regexp="EKG|ECG")
    raw.set_channel_types(
        {raw.ch_names[pick]: "ecg" for pick in picks}
    )
    picks = mne.pick_channels_regexp(raw.ch_names, regexp="EMG")
    raw.set_channel_types(
        {raw.ch_names[pick]: "emg" for pick in picks}
    )
    picks = mne.pick_channels_regexp(raw.ch_names, regexp="EOG")
    raw.set_channel_types(
        {raw.ch_names[pick]: "eog" for pick in picks}
    )

    if datatype == "eeg" and montage == "standard_1020":
        ref_chs = ["A1", "A2", "M1", "M2"]
        for ch in ref_chs:
            if ch in raw.ch_names:
                raw.set_channel_types({ch: "misc"})
    return raw
Пример #6
0
def test_ica_labels():
    """Test ICA labels."""
    # The CTF data are uniquely well suited to testing the ICA.find_bads_
    # methods
    raw = read_raw_ctf(ctf_fname, preload=True)
    # derive reference ICA components and append them to raw
    icarf = ICA(n_components=2, random_state=0, max_iter=2, allow_ref_meg=True)
    with pytest.warns(UserWarning, match='did not converge'):
        icarf.fit(raw.copy().pick_types(meg=False, ref_meg=True))
    icacomps = icarf.get_sources(raw)
    # rename components so they are auto-detected by find_bads_ref
    icacomps.rename_channels({c: 'REF_' + c for c in icacomps.ch_names})
    # and add them to raw
    raw.add_channels([icacomps])
    # set the appropriate EEG channels to EOG and ECG
    raw.set_channel_types({'EEG057': 'eog', 'EEG058': 'eog', 'EEG059': 'ecg'})
    ica = ICA(n_components=4, random_state=0, max_iter=2, method='fastica')
    with pytest.warns(UserWarning, match='did not converge'):
        ica.fit(raw)

    ica.find_bads_eog(raw, l_freq=None, h_freq=None)
    picks = list(pick_types(raw.info, meg=False, eog=True))
    for idx, ch in enumerate(picks):
        assert '{}/{}/{}'.format('eog', idx, raw.ch_names[ch]) in ica.labels_
    assert 'eog' in ica.labels_
    for key in ('ecg', 'ref_meg', 'ecg/ECG-MAG'):
        assert key not in ica.labels_

    ica.find_bads_ecg(raw, l_freq=None, h_freq=None, method='correlation')
    picks = list(pick_types(raw.info, meg=False, ecg=True))
    for idx, ch in enumerate(picks):
        assert '{}/{}/{}'.format('ecg', idx, raw.ch_names[ch]) in ica.labels_
    for key in ('ecg', 'eog'):
        assert key in ica.labels_
    for key in ('ref_meg', 'ecg/ECG-MAG'):
        assert key not in ica.labels_

    ica.find_bads_ref(raw, l_freq=None, h_freq=None)
    picks = pick_channels_regexp(raw.ch_names, 'REF_ICA*')
    for idx, ch in enumerate(picks):
        assert '{}/{}/{}'.format('ref_meg', idx,
                                 raw.ch_names[ch]) in ica.labels_
    for key in ('ecg', 'eog', 'ref_meg'):
        assert key in ica.labels_
    assert 'ecg/ECG-MAG' not in ica.labels_

    ica.find_bads_ecg(raw, l_freq=None, h_freq=None)
    for key in ('ecg', 'eog', 'ref_meg', 'ecg/ECG-MAG'):
        assert key in ica.labels_
Пример #7
0
def channel_indices_from_list(fulllist, findlist, excllist=None):
    """Get indices of matching channel names from list

    Parameters
    ----------
    fulllist: list of channel names
    findlist: list of (regexp) names to find
              regexp are resolved using mne.pick_channels_regexp()
    excllist: list of channel names to exclude,
              e.g., raw.info.get('bads')

    Returns
    -------
    chnpick: array with indices
    """
    chnpick = []
    for ir in xrange(len(findlist)):
        if findlist[ir].translate(None, ' ').isalnum():
            try:
                chnpicktmp = ([fulllist.index(findlist[ir])])
                chnpick = np.array(np.concatenate((chnpick, chnpicktmp),
                                                  axis=1),
                                   dtype=int)
            except:
                print ">>>>> Channel '%s' not found." % findlist[ir]
        else:
            chnpicktmp = (mne.pick_channels_regexp(fulllist, findlist[ir]))
            if len(chnpicktmp) == 0:
                print ">>>>> '%s' does not match any channel name." % findlist[
                    ir]
            else:
                chnpick = np.array(np.concatenate((chnpick, chnpicktmp),
                                                  axis=1),
                                   dtype=int)
    if len(chnpick) > 1:
        # Remove duplicates:
        chnpick = np.sort(np.array(list(set(np.sort(chnpick)))))

    if excllist is not None and len(excllist) > 0:
        exclinds = [
            fulllist.index(excllist[ie]) for ie in xrange(len(excllist))
        ]
        chnpick = list(np.setdiff1d(chnpick, exclinds))
    return chnpick
Пример #8
0
def channel_indices_from_list(fulllist, findlist, excllist=None):
    """Get indices of matching channel names from list

    Parameters
    ----------
    fulllist: list of channel names
    findlist: list of (regexp) names to find
              regexp are resolved using mne.pick_channels_regexp()
    excllist: list of channel names to exclude,
              e.g., raw.info.get('bads')

    Returns
    -------
    chnpick: array with indices
    """
    chnpick = []
    for ir in xrange(len(findlist)):
        if findlist[ir].translate(None, ' ').isalnum():
            try:
                chnpicktmp = ([fulllist.index(findlist[ir])])
                chnpick = np.array(np.concatenate((chnpick, chnpicktmp)), dtype=int)
            except:
                print ">>>>> Channel '%s' not found." % findlist[ir]
        else:
            chnpicktmp = (mne.pick_channels_regexp(fulllist, findlist[ir]))
            if len(chnpicktmp) == 0:
                print ">>>>> '%s' does not match any channel name." % findlist[ir]
            else:
                chnpick = np.array(np.concatenate((chnpick, chnpicktmp)), dtype=int)
    if len(chnpick) > 1:
        # Remove duplicates:
        chnpick = np.sort(np.array(list(set(np.sort(chnpick)))))

    if excllist is not None and len(excllist) > 0:
        exclinds = [fulllist.index(excllist[ie]) for ie in xrange(len(excllist))]
        chnpick = list(np.setdiff1d(chnpick, exclinds))
    return chnpick
Пример #9
0
print(mne.pick_types(info, meg=False, eeg=True, exclude=[]))

###############################################################################
# Note that the ``meg`` and ``fnirs`` parameters of :func:`~mne.pick_types`
# accept strings as well as boolean values, to allow selecting only
# magnetometer or gradiometer channels (via ``meg='mag'`` or ``meg='grad'``) or
# to pick only oxyhemoglobin or deoxyhemoglobin channels (via ``fnirs='hbo'``
# or ``fnirs='hbr'``, respectively).
#
# A third way to pick channels from an :class:`~mne.Info` object is to apply
# `regular expression`_ matching to the channel names using
# :func:`mne.pick_channels_regexp`. Here the ``^`` represents the beginning of
# the string and ``.`` character matches any single character, so both EEG and
# EOG channels will be selected:

print(mne.pick_channels_regexp(info['ch_names'], '^E.G'))

###############################################################################
# :func:`~mne.pick_channels_regexp` can be especially useful for channels named
# according to the `10-20 <ten-twenty_>`_ system (e.g., to select all channels
# ending in "z" to get the midline, or all channels beginning with "O" to get
# the occipital channels). Note that :func:`~mne.pick_channels_regexp` uses the
# Python standard module :mod:`re` to perform regular expression matching; see
# the documentation of the :mod:`re` module for implementation details.
#
# .. warning::
#    Both :func:`~mne.pick_channels` and :func:`~mne.pick_channels_regexp`
#    operate on lists of channel names, so they are unaware of which channels
#    (if any) have been marked as "bad" in ``info['bads']``. Use caution to
#    avoid accidentally selecting bad channels.
#
Пример #10
0
###############################################################################
# .. _picking_channels:
#
# Obtaining subsets of channels
# -----------------------------
#
# There are a number of convenience functions to obtain channel indices, given
# an :class:`mne.Info` object.

###############################################################################
# Get channel indices by name
channel_indices = mne.pick_channels(info['ch_names'], ['MEG 0312', 'EEG 005'])

###############################################################################
# Get channel indices by regular expression
channel_indices = mne.pick_channels_regexp(info['ch_names'], 'MEG *')

###############################################################################
# Get channel indices by type
channel_indices = mne.pick_types(info, meg=True)  # MEG only
channel_indices = mne.pick_types(info, eeg=True)  # EEG only

###############################################################################
# MEG gradiometers and EEG channels
channel_indices = mne.pick_types(info, meg='grad', eeg=True)

###############################################################################
# Get a dictionary of channel indices, grouped by channel type
channel_indices_by_type = mne.io.pick.channel_indices_by_type(info)
print('The first three magnetometers:', channel_indices_by_type['mag'][:3])
bands = [[1, 4], [4, 8], [8, 13], [13, 30], [30, 55], [65, 100]]
window_length = 13.65  # sec
fifs_dir = home + '/data/meg/rest/'  # '/mnt/neuro/MEG_data/fifs/rest/'
weights_dir = home + '/data/meg/sam_narrow_8mm/'
out_dir = home + '/data/meg/rois_spheres/'
vox_fname = home + '/data/fmri_full_grid/rois_spheres/' + \
                   'spheresIdxInYeo_888r4.txt'
fid = open(vox_fname, 'r')
vox = np.array([int(line.rstrip()) for line in fid])
fid.close()
markers_fname = home + '/data/meg/marker_data_clean.npy'
markers = np.load(markers_fname)[()]

raw_fname = fifs_dir + '/%s_rest_LP100_CP3_DS300_raw.fif' % s
raw = mne.io.Raw(raw_fname, preload=True, compensation=3)
picks = mne.pick_channels_regexp(raw.info['ch_names'], 'M..-*')
data, time = raw[picks, :]
events = fg.get_good_events(markers[s], time, window_length)
epochs = mne.Epochs(raw, events, None, 0, window_length, preload=True,
                    baseline=None, detrend=0, picks=picks)

epoch_data = epochs.get_data()
nepochs, nsensors, ntimes = epoch_data.shape
epoch_data = epoch_data.swapaxes(1, 0)
sensor_data = np.resize(epoch_data, [epoch_data.shape[0], -1])

# correlation matrices stored here
all_data = {}
# For each subject, we use the weight matrix to compute virtual electrodes
for band in bands:
    print band
Пример #12
0
# List all information about the first data channel
print(info['chs'][0])

###############################################################################
# Obtaining subsets of channels
# -----------------------------
#
# There are a number of convenience functions to obtain channel indices, given
# an :class:`mne.io.meas_info.Info` object.

# Get channel indices by name
channel_indices = mne.pick_channels(info['ch_names'], ['MEG 0312', 'EEG 005'])

# Get channel indices by regular expression
channel_indices = mne.pick_channels_regexp(info['ch_names'], 'MEG *')

# Get channel indices by type
channel_indices = mne.pick_types(info, meg=True)  # MEG only
channel_indices = mne.pick_types(info, eeg=True)  # EEG only
# MEG gradiometers and EEG channels
channel_indices = mne.pick_types(info, meg='grad', eeg=True)

# Get a dictionary of channel indices, grouped by channel type
channel_indices_by_type = mne.io.pick.channel_indices_by_type(info)
print('The first three magnetometers:', channel_indices_by_type['mag'][:3])

###############################################################################
# Obtaining information about channels
# ------------------------------------
Пример #13
0
        cbar_kws=dict(label='Score'),
        ax=ax[1])
    ax[1].set_title('Scores > Limit', fontweight='bold')

    # The figure title should not overlap with the subplots.
    fig.tight_layout(rect=[0, 0.03, 1, 0.95])
    return fig


manual_inspection(raw)
# The channel 2043 seems very noisy.
# And the channels 0933, 1212, 2023 are suspicous. Better not let pass anything.

# %%
# Check of channel 2043 and 2023
picks = mne.pick_channels_regexp(raw.ch_names, regexp='MEG20.')
raw.plot(order=picks, n_channels=len(picks))

# %%
# Check of channels 1212 and 0933
picks = mne.pick_channels_regexp(raw.ch_names, regexp='MEG121.|MEG093.')
raw.plot(order=picks, n_channels=len(picks))

# %%
# from manual inspection
raw.info['bads'] += ['MEG2043', 'MEG0933', 'MEG1212', 'MEG2023']

# %%
# Manual Inspection of bad Channels in the Empty room ############
##################################################################
Пример #14
0
def plot_artifacts(art_raw, thresholds=dict(), axs=None):

    if axs is None:
        fig, axs = plt.subplots(4, 1, sharex=True, figsize=(12.83, 4.66))
    elif len(axs) != 4:
        raise ValueError('please supply 4 axis for plotting')

    _TICKm = np.array([0, 0.5, 1])

    art_data = art_raw.get_data()
    annot = art_raw.annotations

    # plot gfp_normed
    sel = pick_channels(art_raw.ch_names, ['gfp_normed'])
    if len(sel) == 1:
        if annot is not None:
            for on, dur, desc in zip(annot.onset, annot.duration,
                                     annot.description):
                if 'gfp' in desc.lower():
                    axs[0].axvspan(on, on + dur, color='r', alpha=0.2)
        axs[0].plot(art_raw.times, art_data[sel, :].T)
        if thresholds.get('gfp_thresh', None) is not None:
            axs[0].axhline(thresholds['gfp_thresh'], color='r')
            axs[0].set_ylim(top=1.5 * thresholds['gfp_thresh'])
            new_ticks = np.round(_TICKm * thresholds['gfp_thresh'], decimals=2)
            axs[0].set_yticks(new_ticks)
        axs[0].set_ylabel('GFP/median')

    # plot displacements...
    sel = pick_channels_regexp(art_raw.ch_names, 'HPI\d+_disp_pos')
    # sel = pick_channels(art_raw.ch_names, ['LPA_disp_pos', 'NAS_disp_pos', 'RPA_disp_pos'])
    if len(sel) >= 1:
        if annot is not None:
            for on, dur, desc in zip(annot.onset, annot.duration,
                                     annot.description):
                if 'motion-dist' in desc.lower():
                    axs[1].axvspan(on, on + dur, color='r', alpha=0.2)
        axs[1].plot(art_raw.times, 100 * art_data[sel, :].T)
        if thresholds.get('motion_disp_thresh', None) is not None:
            axs[1].axhline(100 * thresholds['motion_disp_thresh'], color='r')
            axs[1].set_ylim(top=1.5 * 100 * thresholds['motion_disp_thresh'])
            new_ticks = np.round(_TICKm * 100 *
                                 thresholds['motion_disp_thresh'],
                                 decimals=2)
            axs[1].set_yticks(new_ticks)
        axs[1].set_ylabel('hpi disp (cm)')
        # axs[1].legend([art_raw.ch_names[k] for k in sel], loc=1)

    # plot velocities...
    sel = pick_channels_regexp(art_raw.ch_names, 'HPI\d+_velo_pos')
    # sel = pick_channels(art_raw.ch_names, ['LPA_velo_pos', 'NAS_velo_pos', 'RPA_velo_pos'])
    if len(sel) >= 1:
        if annot is not None:
            for on, dur, desc in zip(annot.onset, annot.duration,
                                     annot.description):
                if 'motion-velo' in desc.lower():
                    axs[2].axvspan(on, on + dur, color='r', alpha=0.2)
        axs[2].plot(art_raw.times, 100 * art_data[sel, :].T)
        if thresholds.get('motion_velo_thresh', None) is not None:
            axs[2].axhline(100 * thresholds['motion_velo_thresh'], color='r')
            axs[2].set_ylim(top=1.5 * 100 * thresholds['motion_velo_thresh'])
            new_ticks = np.round(_TICKm * 100 *
                                 thresholds['motion_velo_thresh'],
                                 decimals=2)
            axs[2].set_yticks(new_ticks)
        axs[2].set_ylabel('hpi velo (cm/s)')
        # axs[2].legend([art_raw.ch_names[k] for k in sel], loc=1)

    # plot muscle...
    sel = pick_channels(art_raw.ch_names, ['mucsl_score'])
    if len(sel) == 1:
        if annot is not None:
            for on, dur, desc in zip(annot.onset, annot.duration,
                                     annot.description):
                if 'muscle' in desc.lower():
                    axs[3].axvspan(on, on + dur, color='r', alpha=0.2)
        axs[3].plot(art_raw.times, art_data[sel, :].T)
        if thresholds.get('muscle_thresh', None) is not None:
            axs[3].axhline(thresholds['muscle_thresh'], color='r')
            axs[3].set_ylim(top=1.5 * thresholds['muscle_thresh'])
            new_ticks = np.round(_TICKm * thresholds['muscle_thresh'],
                                 decimals=2)
            axs[3].set_yticks(new_ticks)

        axs[3].set_ylabel('Muscle Stat')
        axs[3].set_xlabel('Time (s)')

    for ax in axs:
        ax.set_xlim(art_raw.times[0], art_raw.times[-1])
# ``proj='reconstruct'``, which can reduce the signal bias introduced by
# projections (see :ref:`tut-artifact-ssp-reconstruction` below).
#
# Example: EOG and ECG artifact repair
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Visualizing the artifacts
# ~~~~~~~~~~~~~~~~~~~~~~~~~
#
# As mentioned in :ref:`the ICA tutorial <tut-artifact-ica>`, an important
# first step is visualizing the artifacts you want to repair. Here they are in
# the raw data:

# pick some channels that clearly show heartbeats and blinks
regexp = r'(MEG [12][45][123]1|EEG 00.)'
artifact_picks = mne.pick_channels_regexp(raw.ch_names, regexp=regexp)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks))

###############################################################################
# Repairing ECG artifacts with SSP
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# MNE-Python provides several functions for detecting and removing heartbeats
# from EEG and MEG data. As we saw in :ref:`tut-artifact-overview`,
# `~mne.preprocessing.create_ecg_epochs` can be used to both detect and
# extract heartbeat artifacts into an `~mne.Epochs` object, which can
# be used to visualize how the heartbeat artifacts manifest across the sensors:

ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.plot_joint()
Пример #16
0
print(raw.info['bads'])

# %%
# Here you can see that the :file:`.fif` file we loaded from disk must have
# been keeping track of channels marked as "bad" — which is good news, because
# it means any changes we make to the list of bad channels will be preserved if
# we save our data at intermediate stages and re-load it later. Since we saw
# above that ``EEG 053`` is one of the bad channels, let's look at it alongside
# some other EEG channels to see what's bad about it. We can do this using the
# standard :meth:`~mne.io.Raw.plot` method, and instead of listing the channel
# names one by one (``['EEG 050', 'EEG 051', ...]``) we'll use a `regular
# expression`_ to pick all the EEG channels between 050 and 059 with the
# :func:`~mne.pick_channels_regexp` function (the ``.`` is a wildcard
# character):

picks = mne.pick_channels_regexp(raw.ch_names, regexp='EEG 05.')
raw.plot(order=picks, n_channels=len(picks))

# %%
# We can do the same thing for the bad MEG channel (``MEG 2443``). Since we
# know that Neuromag systems (like the one used to record the example data) use
# the last digit of the MEG channel number to indicate sensor type, here our
# `regular expression`_ will pick all the channels that start with 2 and end
# with 3:

picks = mne.pick_channels_regexp(raw.ch_names, regexp='MEG 2..3')
raw.plot(order=picks, n_channels=len(picks))

# %%
# Notice first of all that the channels marked as "bad" are plotted in a light
# gray color in a layer behind the other channels, to make it easy to
    raw.info['bads'] = bad_EEG[nip]
    
    ###########################################################################
    ####################### Cycle across channel type #########################
    ########################################################################### 
    for ch_type, picks in picks_by_type(raw.info, meg_combined=True):
        
        # Load ICA  
        ica = read_ica(data_ica_directory + nip + '/' + nip + '_' + ch_type + '-ica.fif')
        reject = rejectDict[ch_type]

        #######################################################################
        ######################### Check EOG061 artifacts ######################
        #######################################################################
        # Choose good channels (ch_types + EOG061)
        eog_channels = mne.pick_channels_regexp(raw.info['ch_names'], 'EOG *')
        picks_eog1 = np.concatenate([picks, np.array([eog_channels[0]])]) # 382 = EOG061
        # Create eog-based epochs 
        eog_epochs = create_eog_epochs(raw, reject=reject, picks=picks_eog1, 
                                       baseline = (None, 0), ch_name='EOG061')
        eog_average = eog_epochs.average()

        if len(eog_epochs) > 0:        
            for bad_component in ica_rejects[nip][ch_type]['eog1']:
                # Plots                            
                report.add_figs_to_section(ica.plot_properties(eog_epochs, picks=[bad_component]), 
                                           captions=ch_type.upper() + ' - EOG061 - ICA n. ' + str(bad_component),
                                           section=nip)

                report.add_figs_to_section(ica.plot_overlay(eog_average, exclude=[bad_component]),
                                           captions=' ',
Пример #18
0
# we need the raw MEG data AND the ICs. The trick is how much we can keep in memory. Let's try to keep all the MEG data and the weights, and load the ICs as necessayr. We also only produce the virtual electrodes we need
data_dir = home + '/data/meg/fifs/rest/'
weights_dir = home + '/data/meg/sam_narrow_8mm/'
markers_fname = home + '/data/meg/marker_data_clean.npy'
nwindow = 13.65
freq_band = '8-13'
res_dir = home + '/tmp/'  # /data/results/graicar/meg/'

subjs = np.load(res_dir + 'group_' + freq_band + '_aligned.npz')['subjs']
sensor_data = {}
weights = {}
for subj in subjs:
    raw = mne.io.Raw(data_dir + subj + '_rest_LP100_CP3_DS300_raw.fif',
                     preload=True,
                     compensation=3)
    picks = mne.pick_channels_regexp(raw.info['ch_names'], 'M..-*')
    band = [int(i) for i in freq_band.split('-')]
    raw.filter(l_freq=band[0], h_freq=band[1], picks=picks)
    weights[subj] = np.load(weights_dir + subj + '_' + freq_band +
                            '_weights.npz')['weights']
    data, time = raw[picks, :]
    raw.apply_hilbert(picks, envelope=False)
    markers = np.load(markers_fname)[()]
    events = fg.get_good_events(markers[subj], time, nwindow)
    epochs = mne.Epochs(raw,
                        events,
                        None,
                        0,
                        nwindow,
                        preload=True,
                        baseline=None,
Пример #19
0
                f.info['bads'] = badchlist_upd
            elif badchans_SSS == 'recalc':
                subraw = f.copy()
                subraw.info['bads'] = []
                subraw.load_data()
                subraw.pick_types(meg=True)

                r = mne.preprocessing.find_bad_channels_maxwell(
                    subraw,
                    cross_talk=crosstalk_file,
                    calibration=fine_cal_file,
                    verbose=True,
                    coord_frame=frame_SSS,
                    origin=origin)

                meg_chnames = np.array(f.ch_names)[mne.pick_channels_regexp(
                    f.ch_names, 'MEG*')]

                # These are found after removing Jan's components
                bad_from_maxwell = r[0] + r[1]
                susp = set(bad_from_maxwell) - set(badchlist)
                missed_by_alg = set(badchlist) - set(bad_from_maxwell)
                print(
                    'Bad channels: missed by Jan {} missed by Maxwell alg {}'.
                    format(susp, missed_by_alg))
                f.info['bads'] = list(set(bad_from_maxwell + badchlist))

                np.savez(fname_bads_full, f.info['bads'])
                import scipy
                scipy.io.savemat(fname_bads_mat_full, {'bads': f.info['bads']})
            elif badchans_SSS == 'no':
                f.info['bads'] = badchlist