当前位置: 首页>>代码示例>>Python>>正文


Python mne.Epochs方法代码示例

本文整理汇总了Python中mne.Epochs方法的典型用法代码示例。如果您正苦于以下问题:Python mne.Epochs方法的具体用法?Python mne.Epochs怎么用?Python mne.Epochs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mne的用法示例。


在下文中一共展示了mne.Epochs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_viz

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def test_viz():
    """Test viz."""
    import matplotlib.pyplot as plt

    set_matplotlib_defaults(plt)

    events = mne.find_events(raw)
    picks = mne.pick_channels(raw.info['ch_names'],
                              ['MEG 2443', 'MEG 2442', 'MEG 2441'])
    epochs = mne.Epochs(raw, events, picks=picks, baseline=(None, 0),
                        reject=None, preload=True,
                        event_id={'1': 1, '2': 2, '3': 3, '4': 4})
    bad_epochs_idx = [0, 1, 3]
    n_epochs, n_channels, _ = epochs.get_data().shape
    bad_epochs = np.zeros(n_epochs, dtype=bool)
    bad_epochs[bad_epochs_idx] = True

    labels = np.zeros((n_epochs, n_channels))
    reject_log = autoreject.RejectLog(bad_epochs, labels, epochs.ch_names)
    reject_log.plot_epochs(epochs)
    reject_log.plot()
    reject_log.plot(orientation='horizontal')
    pytest.raises(ValueError, reject_log.plot_epochs, epochs[:2])
    pytest.raises(ValueError, reject_log.plot, 'down')
    plt.close('all') 
开发者ID:autoreject,项目名称:autoreject,代码行数:27,代码来源:test_viz.py

示例2: _vote_bad_epochs

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def _vote_bad_epochs(self, epochs, picks):
        """Each channel votes for an epoch as good or bad.

        Parameters
        ----------
        epochs : instance of mne.Epochs
            The epochs object for which bad epochs must be found.
        picks : array-like
            The indices of the channels to consider.
        """
        labels = np.zeros((len(epochs), len(epochs.ch_names)))
        labels.fill(np.nan)
        bad_sensor_counts = np.zeros((len(epochs),))

        this_ch_names = [epochs.ch_names[p] for p in picks]
        deltas = np.ptp(epochs.get_data()[:, picks], axis=-1).T
        threshes = [self.threshes_[ch_name] for ch_name in this_ch_names]
        for ch_idx, (delta, thresh) in enumerate(zip(deltas, threshes)):
            bad_epochs_idx = np.where(delta > thresh)[0]
            labels[:, picks[ch_idx]] = 0
            labels[bad_epochs_idx, picks[ch_idx]] = 1

        bad_sensor_counts = np.sum(labels == 1, axis=1)
        return labels, bad_sensor_counts 
开发者ID:autoreject,项目名称:autoreject,代码行数:26,代码来源:autoreject.py

示例3: fit_transform

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def fit_transform(self, epochs, return_log=False):
        """Estimate the rejection params and finds bad epochs.

        Parameters
        ----------
        epochs : instance of mne.Epochs
            The epochs object which must be cleaned.

        return_log : bool
            If true the rejection log is also returned.

        Returns
        -------
        epochs_clean : instance of mne.Epochs
            The cleaned epochs.

        reject_log : instance of autoreject.RejectLog
            The rejection log. Returned only of return_log is True.
        """
        return self.fit(epochs).transform(epochs, return_log=return_log) 
开发者ID:autoreject,项目名称:autoreject,代码行数:22,代码来源:autoreject.py

示例4: make_epochs

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def make_epochs(z_hat, info, t_lim, n_times_atom=1):
    """Make Epochs on the activations of atoms.
    n_splits, n_atoms, n_times_valid = z_hat.shape
    n_trials, n_atoms, n_times_epoch = z_hat_epoch.shape
    """
    n_splits, n_atoms, n_times_valid = z_hat.shape
    n_times = n_times_valid + n_times_atom - 1
    # pad with zeros
    padding = np.zeros((n_splits, n_atoms, n_times_atom - 1))
    z_hat = np.concatenate([z_hat, padding], axis=2)
    # reshape into an unique time-serie per atom
    z_hat = np.reshape(z_hat.swapaxes(0, 1), (n_atoms, n_splits * n_times))

    # create trials around the events, using mne
    new_info = mne.create_info(ch_names=n_atoms, sfreq=info['sfreq'])
    rawarray = mne.io.RawArray(data=z_hat, info=new_info, verbose=False)
    t_min, t_max = t_lim
    epochs = mne.Epochs(rawarray, info['events'], info['event_id'], t_min,
                        t_max, verbose=False)
    z_hat_epoched = epochs.get_data()
    return z_hat_epoched 
开发者ID:alphacsc,项目名称:alphacsc,代码行数:23,代码来源:epoch.py

示例5: calc_noise_epoches_from_empty_room

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def calc_noise_epoches_from_empty_room(events_id, data_raw_fname, empty_room_raw_fname, from_t, to_t,
        overwrite_epochs=False):
    from mne.event import make_fixed_length_events
    from mne.io import Raw

    epochs_noise_dic = {}
    epochs_noise_fnames = [get_cond_fname(EPO_NOISE, event) for event in events_id.keys()]
    if np.all([os.path.isfile(fname) for fname in epochs_noise_fnames]) and not overwrite_epochs:
        for event in events_id.keys():
            epochs_noise_dic[event] = mne.read_epochs(get_cond_fname(EPO_NOISE, event))
    else:
        raw = Raw(data_raw_fname)
        raw_noise = Raw(empty_room_raw_fname)
        # raw_noise.info['bads'] = ['MEG0321']  # 1 bad MEG channel
        picks = mne.pick_types(raw.info, meg=True)#, exclude='bads')
        events_noise = make_fixed_length_events(raw_noise, 1)
        epochs_noise = mne.Epochs(raw_noise, events_noise, 1, from_t,
            to_t, proj=True, picks=picks, baseline=None, preload=True)
        for event, event_id in events_id.items():
            # then make sure the number of epochs is the same
            epochs = mne.read_epochs(get_cond_fname(EPO, event))
            epochs_noise_dic[event] = epochs_noise[:len(epochs.events)]
            epochs_noise_dic[event].save(get_cond_fname(EPO_NOISE, event))
    return epochs_noise_dic 
开发者ID:pelednoam,项目名称:mmvt,代码行数:26,代码来源:beamformers_electrodes_tweak.py

示例6: clean_by_interp

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def clean_by_interp(inst, picks=None, verbose='progressbar'):
    """Clean epochs/evoked by LOOCV.

    Parameters
    ----------
    inst : instance of mne.Evoked or mne.Epochs
        The evoked or epochs object.
    picks : ndarray, shape(n_channels,) | None
        The channels to be considered for autoreject. If None, defaults
        to data channels {'meg', 'eeg'}.
    verbose : 'tqdm', 'tqdm_notebook', 'progressbar' or False
        The verbosity of progress messages.
        If `'progressbar'`, use `mne.utils.ProgressBar`.
        If `'tqdm'`, use `tqdm.tqdm`.
        If `'tqdm_notebook'`, use `tqdm.tqdm_notebook`.
        If False, suppress all output messages.

    Returns
    -------
    inst_clean : instance of mne.Evoked or mne.Epochs
        Instance after interpolation of bad channels.
    """
    return _clean_by_interp(inst, picks=picks, verbose=verbose) 
开发者ID:autoreject,项目名称:autoreject,代码行数:25,代码来源:utils.py

示例7: test_global_autoreject

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def test_global_autoreject():
    """Test global autoreject."""
    event_id = None
    tmin, tmax = -0.2, 0.5
    events = mne.find_events(raw)

    picks = mne.pick_types(raw.info, meg=True, eeg=True, stim=False,
                           eog=True, exclude=[])
    # raise error if preload is false
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        picks=picks, baseline=(None, 0),
                        reject=None, preload=False)

    # Test get_rejection_thresholds.
    reject1 = get_rejection_threshold(epochs, decim=1, random_state=42)
    reject2 = get_rejection_threshold(epochs, decim=1, random_state=42)
    reject3 = get_rejection_threshold(epochs, decim=2, random_state=42)
    tols = dict(eeg=5e-6, eog=5e-6, grad=10e-12, mag=5e-15)
    assert reject1, isinstance(reject1, dict)
    for key, value in list(reject1.items()):
        assert reject1[key] == reject2[key]
        assert abs(reject1[key] - reject3[key]) < tols[key]

    reject = get_rejection_threshold(epochs, decim=4, ch_types='eeg')
    assert 'eog' not in reject
    assert 'eeg' in reject
    pytest.raises(ValueError, get_rejection_threshold, epochs,
                  decim=4, ch_types=5) 
开发者ID:autoreject,项目名称:autoreject,代码行数:30,代码来源:test_autoreject.py

示例8: test_io

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def test_io():
    """Test IO functionality."""
    event_id = None
    tmin, tmax = -0.2, 0.5
    events = mne.find_events(raw)
    savedir = _TempDir()
    fname = op.join(savedir, 'autoreject.hdf5')

    include = [u'EEG %03d' % i for i in range(1, 45, 3)]
    picks = mne.pick_types(raw.info, meg=False, eeg=False, stim=False,
                           eog=True, include=include, exclude=[])

    # raise error if preload is false
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        picks=picks, baseline=(None, 0), decim=4,
                        reject=None, preload=True)[:10]
    ar = AutoReject(cv=2, random_state=42, n_interpolate=[1],
                    consensus=[0.5], verbose=False)
    ar.save(fname)  # save without fitting

    # check that fit after saving is the same as fit
    # without saving
    ar2 = read_auto_reject(fname)
    ar.fit(epochs)
    ar2.fit(epochs)
    assert np.sum([ar.threshes_[k] - ar2.threshes_[k]
                   for k in ar.threshes_.keys()]) == 0.

    pytest.raises(ValueError, ar.save, fname)
    ar.save(fname, overwrite=True)
    ar3 = read_auto_reject(fname)
    epochs_clean1, reject_log1 = ar.transform(epochs, return_log=True)
    epochs_clean2, reject_log2 = ar3.transform(epochs, return_log=True)
    assert_array_equal(epochs_clean1.get_data(), epochs_clean2.get_data())
    assert_array_equal(reject_log1.labels, reject_log2.labels) 
开发者ID:autoreject,项目名称:autoreject,代码行数:37,代码来源:test_autoreject.py

示例9: test_utils

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def test_utils():
    """Test utils."""
    event_id = {'Visual/Left': 3}
    tmin, tmax = -0.2, 0.5
    events = mne.find_events(raw)
    picks = mne.pick_channels(raw.info['ch_names'],
                              ['MEG 2443', 'MEG 2442', 'MEG 2441'])
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        picks=picks, baseline=(None, 0),
                        reject=None, preload=True)

    this_epoch = epochs.copy()
    epochs_clean = clean_by_interp(this_epoch)
    assert_array_equal(this_epoch.get_data(), epochs.get_data())
    pytest.raises(AssertionError, assert_array_equal, epochs_clean.get_data(),
                  this_epoch.get_data())

    picks_meg = mne.pick_types(evoked.info, meg='grad', eeg=False, exclude=[])
    picks_eeg = mne.pick_types(evoked.info, meg=False, eeg=True, exclude=[])
    picks_bad_meg = mne.pick_channels(evoked.ch_names, include=['MEG 2443'])
    picks_bad_eeg = mne.pick_channels(evoked.ch_names, include=['EEG 053'])
    evoked_orig = evoked.copy()
    for picks, picks_bad in zip([picks_meg, picks_eeg],
                                [picks_bad_meg, picks_bad_eeg]):
        evoked_autoreject = interpolate_bads(evoked, picks=picks,
                                             reset_bads=False)
        evoked.interpolate_bads(reset_bads=False)
        assert_array_equal(evoked.data[picks_bad],
                           evoked_autoreject.data[picks_bad])
        pytest.raises(AssertionError, assert_array_equal,
                      evoked_orig.data[picks_bad], evoked.data[picks_bad])

    # test that autoreject EEG interpolation code behaves the same as MNE
    evoked_ar = evoked_orig.copy()
    evoked_mne = evoked_orig.copy()

    origin = _check_origin('auto', evoked_ar.info)
    _interpolate_bads_eeg(evoked_ar, picks=None)
    mne.channels.interpolation._interpolate_bads_eeg(evoked_mne, origin=origin)
    assert_array_almost_equal(evoked_ar.data, evoked_mne.data) 
开发者ID:autoreject,项目名称:autoreject,代码行数:42,代码来源:test_utils.py

示例10: test_interpolate_bads

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def test_interpolate_bads():
    """Test interpolate bads."""
    event_id = None
    events = mne.find_events(raw)
    tmin, tmax = -0.2, 0.5
    for ii, ch_name in enumerate(raw.info['ch_names'][:14]):
        raw.set_channel_types({ch_name: 'bio'})
        raw.rename_channels({ch_name: 'BIO%02d' % ii})

    picks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=False)
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
                        baseline=(None, 0), decim=10,
                        reject=None, preload=True)[:10]
    epochs.info['bads'] = ['MEG 2212']
    interpolate_bads(epochs, picks) 
开发者ID:autoreject,项目名称:autoreject,代码行数:17,代码来源:test_utils.py

示例11: get_reject_log

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def get_reject_log(self, epochs, threshes=None, picks=None):
        """Get rejection logs from epochs.

        .. note::
           If multiple channel types are present, reject_log.bad_epochs
           reflects the union of bad epochs across channel types.

        Parameters
        ----------
        epochs : instance of mne.Epochs
            The epochs from which to get the drop logs.
        picks : np.ndarray, shape(n_channels, ) | list | None
            The channel indices to be used. If None, the .picks attribute
            will be used.

        Returns
        -------
        reject_log : instance of autoreject.RejectLog
            The rejection log.
        """
        picks = (self.picks_ if picks is None else picks)
        picks_by_type = _get_picks_by_type(picks=picks, info=epochs.info)
        assert len(picks_by_type) == 1
        ch_type, this_picks = picks_by_type[0]
        del picks

        labels, bad_sensor_counts = self._vote_bad_epochs(
            epochs, picks=this_picks)

        labels = self._get_epochs_interpolation(
            epochs, labels=labels, picks=this_picks,
            n_interpolate=self.n_interpolate_[ch_type])

        assert len(labels) == len(epochs)

        bad_epochs = self._get_bad_epochs(
            bad_sensor_counts, ch_type=ch_type, picks=this_picks)

        reject_log = RejectLog(labels=labels, bad_epochs=bad_epochs,
                               ch_names=epochs.ch_names)
        return reject_log 
开发者ID:autoreject,项目名称:autoreject,代码行数:43,代码来源:autoreject.py

示例12: transform

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def transform(self, epochs, return_log=False):
        """Fix and find the bad epochs.

        Parameters
        ----------
        epochs : instance of mne.Epochs
            The epochs object for which bad epochs must be found.

        return_log : bool
            If true the rejection log is also returned.

        Returns
        -------
        epochs_clean : instance of mne.Epochs
            The cleaned epochs.

        reject_log : instance of autoreject.RejectLog
            The rejection log. Returned only of return_log is True.
        """
        _check_data(epochs, picks=self.picks, verbose=self.verbose,
                    ch_constraint='data_channels')

        reject_log = self.get_reject_log(epochs, picks=None)
        if np.all(reject_log.bad_epochs):
            raise ValueError('All epochs are bad. Sorry.')

        epochs_clean = epochs.copy()
        # this one knows how to handle picks.
        _apply_interp(reject_log, self, epochs_clean, self.threshes_,
                      self.picks_, self.dots, self.verbose)

        _apply_drop(reject_log, self, epochs_clean, self.threshes_,
                    self.picks_, self.verbose)

        if return_log:
            return epochs_clean, reject_log
        else:
            return epochs_clean 
开发者ID:autoreject,项目名称:autoreject,代码行数:40,代码来源:autoreject.py

示例13: eeg_to_df

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def eeg_to_df(eeg, index=None, include="all", exclude=None, hemisphere="both", central=True):
    """
    Convert mne Raw or Epochs object to dataframe or dict of dataframes.

    DOCS INCOMPLETE :(
    """
    if isinstance(eeg, mne.Epochs):
        data = {}

        if index is None:
            index = range(len(eeg))

        for epoch_index, epoch in zip(index, eeg.get_data()):

            epoch = pd.DataFrame(epoch.T)
            epoch.columns = eeg.ch_names
            epoch.index = eeg.times

            selection = eeg_select_electrodes(eeg, include=include, exclude=exclude, hemisphere=hemisphere, central=central)

            data[epoch_index] = epoch[selection]

    else:  # it might be a Raw object
        data = eeg.get_data().T
        data = pd.DataFrame(data)
        data.columns = eeg.ch_names
        data.index = eeg.times

    return(data) 
开发者ID:neuropsychology,项目名称:NeuroKit.py,代码行数:31,代码来源:eeg_data.py

示例14: epoch_data

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def epoch_data(self, events, tmin, tmax, baseline):
        epochs = mne.Epochs(self.current["data"], self.current["events"],
                            event_id=events, tmin=tmin, tmax=tmax,
                            baseline=baseline, preload=True)
        self.history.append(f'data = mne.Epochs(data, events, '
                            f'event_id={events}, tmin={tmin}, tmax={tmax}, '
                            f'baseline={baseline}, preload=True)')
        self.current["data"] = epochs
        self.current["dtype"] = "epochs"
        self.current["events"] = self.current["data"].events
        self.current["name"] += " (epoched)" 
开发者ID:cbrnr,项目名称:mnelab,代码行数:13,代码来源:model.py

示例15: init_data

# 需要导入模块: import mne [as 别名]
# 或者: from mne import Epochs [as 别名]
def init_data():
    data_path = sample.data_path()
    raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
    fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
    tmin, tmax, event_id = -0.2, 0.5, 1

    # Setup for reading the raw data
    raw = io.read_raw_fif(raw_fname)
    events = mne.find_events(raw, stim_channel='STI 014')
    inverse_operator = read_inverse_operator(fname_inv)

    # Setting the label
    label = mne.read_label(data_path + '/MEG/sample/labels/Aud-lh.label')

    include = []
    raw.info['bads'] += ['MEG 2443', 'EEG 053']  # bads + 2 more

    # picks MEG gradiometers
    picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                           stim=False, include=include, exclude='bads')

    # Load condition 1
    event_id = 1
    # Use linear detrend to reduce any edge artifacts
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                        baseline=(None, 0), reject=dict(grad=4000e-13, eog=150e-6),
                        preload=True, detrend=1)
    return epochs, inverse_operator, label 
开发者ID:pelednoam,项目名称:mmvt,代码行数:30,代码来源:source_estimate_power.py


注:本文中的mne.Epochs方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。