How to use the mne.io.pick.pick_types function in mne

To help you get started, we’ve selected a few mne examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mne-tools / mne-python / mne / simulation / raw.py View on Github external
src, mri_head_t, info, bem, mindist, n_jobs, allow_bem_none=True,
            verbose=False)
    del (src, mindist)

    if forward is None:
        eegfwd = _compute_forwards(rr, bem, [eegels], [None],
                                   [None], ['eeg'], n_jobs, verbose=False)[0]
        eegfwd = _to_forward_dict(eegfwd, eegnames)
    else:
        if len(eegnames) > 0:
            eegfwd = pick_channels_forward(forward, eegnames, verbose=False)
        else:
            eegfwd = None

    # short circuit here if there are no MEG channels (don't need to iterate)
    if len(pick_types(info, meg=True)) == 0:
        eegfwd.update(**update_kwargs)
        for _ in dev_head_ts:
            yield eegfwd
        yield eegfwd
        return

    coord_frame = FIFF.FIFFV_COORD_HEAD
    if bem is not None and not bem['is_sphere']:
        idx = np.where(np.array([s['id'] for s in bem['surfs']]) ==
                       FIFF.FIFFV_BEM_SURF_ID_BRAIN)[0]
        assert len(idx) == 1
        # make a copy so it isn't mangled in use
        bem_surf = transform_surface_to(bem['surfs'][idx[0]], coord_frame,
                                        mri_head_t, copy=True)
    for ti, dev_head_t in enumerate(dev_head_ts):
        # Could be *slightly* more efficient not to do this N times,
github mne-tools / mne-python / mne / channels / channels.py View on Github external
%(verbose_meth)s

        Returns
        -------
        inst : instance of Raw, Epochs, or Evoked
            The modified instance.

        See Also
        --------
        pick_channels

        Notes
        -----
        .. versionadded:: 0.9.0
        """
        idx = pick_types(
            self.info, meg=meg, eeg=eeg, stim=stim, eog=eog, ecg=ecg, emg=emg,
            ref_meg=ref_meg, misc=misc, resp=resp, chpi=chpi, exci=exci,
            ias=ias, syst=syst, seeg=seeg, dipole=dipole, gof=gof, bio=bio,
            ecog=ecog, fnirs=fnirs, include=include, exclude=exclude,
            selection=selection)
        return self._pick_drop_channels(idx)
github mne-tools / mne-python / mne / forward / _make_forward.py View on Github external
-------
    megcoils : list of dict
        Information for each prepped MEG coil
    compcoils : list of dict
        Information for each prepped MEG coil
    megnames : list of str
        Name of each prepped MEG coil
    meginfo : instance of Info
        Information subselected for just the set of MEG coils
    """
    accuracy = 'accurate' if accurate else 'normal'
    info_extra = 'info'
    megnames, megcoils, compcoils = [], [], []

    # Find MEG channels
    picks = pick_types(info, meg=True, eeg=False, ref_meg=False,
                       exclude=exclude)

    # Make sure MEG coils exist
    nmeg = len(picks)
    if nmeg <= 0:
        raise RuntimeError('Could not find any MEG channels')

    # Get channel info and names for MEG channels
    megchs = [info['chs'][pick] for pick in picks]
    megnames = [info['ch_names'][p] for p in picks]
    logger.info('Read %3d MEG channels from %s'
                % (len(picks), info_extra))

    # Get MEG compensation channels
    if not ignore_ref:
        picks = pick_types(info, meg=False, ref_meg=True, exclude=exclude)
github mne-tools / mne-python / mne / preprocessing / maxwell.py View on Github external
ref = not ignore_ref
    meg_picks = pick_types(info, meg=True, ref_meg=ref, exclude=[])
    meg_info = pick_info(_simplify_info(info), meg_picks)
    del info
    good_picks = pick_types(meg_info, meg=True, ref_meg=ref, exclude='bads')
    n_bases = _get_n_moments([int_order, ext_order]).sum()
    if n_bases > len(good_picks):
        raise ValueError('Number of requested bases (%s) exceeds number of '
                         'good sensors (%s)' % (str(n_bases), len(good_picks)))
    recons = [ch for ch in meg_info['bads']]
    if len(recons) > 0:
        logger.info('    Bad MEG channels being reconstructed: %s' % recons)
    else:
        logger.info('    No bad MEG channels')
    ref_meg = False if ignore_ref else 'mag'
    mag_picks = pick_types(meg_info, meg='mag', ref_meg=ref_meg, exclude=[])
    ref_meg = False if ignore_ref else 'grad'
    grad_picks = pick_types(meg_info, meg='grad', ref_meg=ref_meg, exclude=[])
    assert len(mag_picks) + len(grad_picks) == len(meg_info['ch_names'])
    # Determine which are magnetometers for external basis purposes
    mag_or_fine = np.zeros(len(meg_picks), bool)
    mag_or_fine[mag_picks] = True
    # KIT gradiometers are marked as having units T, not T/M (argh)
    # We need a separate variable for this because KIT grads should be
    # treated mostly like magnetometers (e.g., scaled by 100) for reg
    coil_types = np.array([ch['coil_type'] for ch in meg_info['chs']])
    mag_or_fine[(coil_types & 0xFFFF) == FIFF.FIFFV_COIL_KIT_GRAD] = False
    # The same thing goes for CTF gradiometers...
    ctf_grads = [FIFF.FIFFV_COIL_CTF_GRAD,
                 FIFF.FIFFV_COIL_CTF_REF_GRAD,
                 FIFF.FIFFV_COIL_CTF_OFFDIAG_REF_GRAD]
    mag_or_fine[np.in1d(coil_types, ctf_grads)] = False
github mne-tools / mne-python / mne / simulation / raw.py View on Github external
# activation times with intervals drawn from a uniform distribution
        # based on activation rates between 40 and 80 beats per minute
        cardiac_idx = np.cumsum(rng.uniform(60. / 80., 60. / 40., max_beats) *
                                info['sfreq']).astype(int)
        cardiac_idx = cardiac_idx[cardiac_idx < len(times)]
        cardiac_data = np.zeros(len(times))
        cardiac_data[cardiac_idx] = 1
        # kernel is the sum of three hanning windows
        cardiac_kernel = np.concatenate([
            2 * np.hanning(int(0.04 * info['sfreq'])),
            -0.3 * np.hanning(int(0.05 * info['sfreq'])),
            0.2 * np.hanning(int(0.26 * info['sfreq']))], axis=-1)
        exg_data = np.convolve(cardiac_data, cardiac_kernel,
                               'same')[np.newaxis, :] * 15e-8
        # Add rescaled noisy data to ECG ch
        ch = pick_types(info, meg=False, eeg=False, ecg=True)
        picks = meg_picks
        del cardiac_data, cardiac_kernel, max_beats, cardiac_idx
    del meg_picks, meeg_picks
    noise = rng.standard_normal(exg_data.shape[1]) * 5e-6
    if len(ch) >= 1:
        ch = ch[-1]
        data[ch, :] = exg_data * 1e3 + noise
    else:
        ch = None
    nn = np.zeros_like(exg_rr)
    nn[:, 2] = 1
    src = setup_volume_source_space(pos=dict(rr=exg_rr, nn=nn),
                                    sphere_units='mm')
    _log_ch('%s simulated and trace' % kind, info, ch)
    del ch, nn, noise
github mne-tools / mne-python / mne / io / reference.py View on Github external
# reference-able channel type.
    possible_types = ['eeg', 'ecog', 'seeg']
    if ch_type == 'auto':
        for type_ in possible_types:
            if type_ in inst:
                ch_type = type_
                logger.info('%s channel type selected for '
                            're-referencing' % DEFAULTS['titles'][type_])
                break
        # if auto comes up empty, or the user specifies a bad ch_type.
        else:
            raise ValueError('No EEG, ECoG or sEEG channels found '
                             'to rereference.')

    ch_dict = {ch_type: True, 'meg': False, 'ref_meg': False}
    eeg_idx = pick_types(inst.info, **ch_dict)
    ch_sel = [inst.ch_names[i] for i in eeg_idx]

    if ref_channels == 'average' and not projection:  # apply average reference
        logger.info('Applying average reference.')
        ref_channels = ch_sel

    if ref_channels == []:
        logger.info('EEG data marked as already having the desired reference. '
                    'Preventing automatic future re-referencing to an average '
                    'reference.')
    else:
        logger.info('Applying a custom %s '
                    'reference.' % DEFAULTS['titles'][type_])

    return _apply_reference(inst, ref_channels, ch_sel)
github mne-tools / mne-python / mne / proj.py View on Github external
def _compute_proj(data, info, n_grad, n_mag, n_eeg, desc_prefix,
                  meg='separate', verbose=None):
    grad_ind = pick_types(info, meg='grad', ref_meg=False, exclude='bads')
    mag_ind = pick_types(info, meg='mag', ref_meg=False, exclude='bads')
    eeg_ind = pick_types(info, meg=False, eeg=True, ref_meg=False,
                         exclude='bads')

    _check_option('meg', meg, ['separate', 'combined'])
    if meg == 'combined':
        _get_rank_sss(info, msg='meg="combined" can only be used with '
                      'Maxfiltered data', verbose=False)
        if n_grad != n_mag:
            raise ValueError('n_grad (%d) must be equal to n_mag (%d) when '
                             'using meg="combined"')
        kinds = ['meg', '', 'eeg']
        n_mag = 0
        grad_ind = pick_types(info, meg=True, ref_meg=False, exclude='bads')
        if (n_grad > 0) and len(grad_ind) == 0:
            logger.info("No MEG channels found for joint estimation. "
                        "Forcing n_grad=n_mag=0")
            n_grad = 0
github mne-tools / mne-python / mne / viz / ica.py View on Github external
def _plot_sources_epochs(ica, epochs, picks, exclude, start, stop, show,
                         title, block, show_scrollbars):
    """Plot the components as epochs."""
    data = ica._transform_epochs(epochs, concatenate=True)
    eog_chs = pick_types(epochs.info, meg=False, eog=True, ref_meg=False)
    ecg_chs = pick_types(epochs.info, meg=False, ecg=True, ref_meg=False)
    c_names = list(ica._ica_names)
    ch_types = np.repeat('misc', ica.n_components_)
    for eog_idx in eog_chs:
        c_names.append(epochs.ch_names[eog_idx])
        ch_types = np.append(ch_types, 'eog')
    for ecg_idx in ecg_chs:
        c_names.append(epochs.ch_names[ecg_idx])
        ch_types = np.append(ch_types, 'ecg')
    extra_picks = np.append(eog_chs, ecg_chs).astype(int)
    if len(extra_picks) > 0:
        eog_ecg_data = np.concatenate(epochs.get_data()[:, extra_picks],
                                      axis=1)
        data = np.append(data, eog_ecg_data, axis=0)
    scalings = _handle_default('scalings_plot_raw')
    scalings['misc'] = 5.0
github mne-tools / mne-python / mne / preprocessing / ica.py View on Github external
def _pre_whiten(self, data, info, picks):
        """Aux function."""
        has_pre_whitener = hasattr(self, 'pre_whitener_')
        if not has_pre_whitener and self.noise_cov is None:
            # use standardization as whitener
            # Scale (z-score) the data by channel type
            info = pick_info(info, picks)
            pre_whitener = np.empty([len(data), 1])
            for ch_type in _DATA_CH_TYPES_SPLIT + ('eog', "ref_meg"):
                if _contains_ch_type(info, ch_type):
                    if ch_type == 'seeg':
                        this_picks = pick_types(info, meg=False, seeg=True)
                    elif ch_type == 'ecog':
                        this_picks = pick_types(info, meg=False, ecog=True)
                    elif ch_type == 'eeg':
                        this_picks = pick_types(info, meg=False, eeg=True)
                    elif ch_type in ('mag', 'grad'):
                        this_picks = pick_types(info, meg=ch_type)
                    elif ch_type == 'eog':
                        this_picks = pick_types(info, meg=False, eog=True)
                    elif ch_type in ('hbo', 'hbr'):
                        this_picks = pick_types(info, meg=False, fnirs=ch_type)
                    elif ch_type == 'ref_meg':
                        this_picks = pick_types(info, meg=False, ref_meg=True)
                    else:
                        raise RuntimeError('Should not be reached.'
                                           'Unsupported channel {}'
                                           .format(ch_type))
                    pre_whitener[this_picks] = np.std(data[this_picks])
            data /= pre_whitener
        elif not has_pre_whitener and self.noise_cov is not None:
            pre_whitener, _ = compute_whitener(self.noise_cov, info, picks)
github autoreject / autoreject / autoreject / viz.py View on Github external
def _handle_picks_viz(epochs):
    """Aux function to handle picks."""
    if any('ICA' in k for k in epochs.ch_names):
        picks = pick_types(epochs.info, misc=True, ref_meg=False,
                           exclude=[])
    else:
        picks = pick_types(epochs.info, meg=True, eeg=True, eog=True, ecg=True,
                           seeg=True, ecog=True, ref_meg=False, exclude=[])
    return picks