How to use the mne.Epochs 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 alexandrebarachant / pyRiemann / examples / stats / oneWay_Manova_ERP.py View on Github external
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0., 1
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)

# Setup for reading the raw data
raw = io.Raw(raw_fname, preload=True)
raw.filter(2, None, method='iir')  # replace baselining with high-pass
events = mne.read_events(event_fname)

raw.info['bads'] = ['MEG 2443']  # set bad channels
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=False,
                       exclude='bads')

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=False,
                    picks=picks, baseline=None, preload=True, verbose=False)

labels = epochs.events[::5, -1]

# get epochs
epochs_data = epochs.get_data()[::5]

n_perms = 100
###############################################################################
# Pairwise distance based permutation test
###############################################################################
t_init = time()
p_test = PermutationDistance(n_perms, metric='riemann', mode='pairwise',
                             estimator=XdawnCovariances(2))
p, F = p_test.test(epochs_data, labels)
duration = time() - t_init
github mne-tools / mne-python / examples / preprocessing / plot_run_ica.py View on Github external
# Read and preprocess the data. Preprocessing consists of:
#
# - MEG channel selection
# - 1-30 Hz band-pass filter
# - epoching -0.2 to 0.5 seconds with respect to events

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True)
raw.filter(1, 30, fir_design='firwin')

# longer + more epochs for more artifact exposure
events = mne.find_events(raw, stim_channel='STI 014')
epochs = mne.Epochs(raw, events, event_id=None, tmin=-0.2, tmax=0.5)

###############################################################################
# Fit ICA model using the FastICA algorithm, detect and plot components
# explaining ECG artifacts.

ica = ICA(n_components=0.95, method='fastica').fit(epochs)

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs)

ica.plot_components(ecg_inds)

###############################################################################
# Plot properties of ECG components:
ica.plot_properties(epochs, picks=ecg_inds)
github mne-tools / mne-python / tutorials / sample-datasets / plot_brainstorm_phantom_elekta.py View on Github external
raw.plot_psd(tmax=30., average=False)

###############################################################################
# Our phantom produces sinusoidal bursts at 20 Hz:

raw.plot(events=events)

###############################################################################
# Now we epoch our data, average it, and look at the first dipole response.
# The first peak appears around 3 ms. Because we low-passed at 40 Hz,
# we can also decimate our data to save memory.

tmin, tmax = -0.1, 0.1
bmax = -0.05  # Avoid capture filter ringing into baseline
event_id = list(range(1, 33))
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=(None, bmax),
                    preload=False)
epochs['1'].average().plot(time_unit='s')

###############################################################################
# .. _plt_brainstorm_phantom_elekta_eeg_sphere_geometry:
#
# Let's use a :ref:`sphere head geometry model `
# and let's see the coordinate alignment and the sphere location. The phantom
# is properly modeled by a single-shell sphere with origin (0., 0., 0.).
sphere = mne.make_sphere_model(r0=(0., 0., 0.), head_radius=0.08)

mne.viz.plot_alignment(epochs.info, subject=subject, show_axes=True,
                       bem=sphere, dig=True, surfaces='inner_skull')

###############################################################################
# Let's do some dipole fits. We first compute the noise covariance,
github mne-tools / mne-python / examples / preprocessing / plot_xdawn_denoising.py View on Github external
# Set parameters and read data
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
tmin, tmax = -0.1, 0.3
event_id = dict(vis_r=4)

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname, preload=True)
raw.filter(1, 20, fir_design='firwin')  # replace baselining with high-pass
events = read_events(event_fname)

raw.info['bads'] = ['MEG 2443']  # set bad channels
picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                   exclude='bads')
# Epoching
epochs = Epochs(raw, events, event_id, tmin, tmax, proj=False,
                picks=picks, baseline=None, preload=True,
                verbose=False)

# Plot image epoch before xdawn
plot_epochs_image(epochs['vis_r'], picks=[230], vmin=-500, vmax=500)

###############################################################################
# Now, we estimate a set of xDAWN filters for the epochs (which contain only
# the ``vis_r`` class).

# Estimates signal covariance
signal_cov = compute_raw_covariance(raw, picks=picks)

# Xdawn instance
xd = Xdawn(n_components=2, signal_cov=signal_cov)
github mne-tools / mne-python / tutorials / plot_spatio_temporal_cluster_stats_sensor.py View on Github external
event_id = {'Aud_L': 1, 'Aud_R': 2, 'Vis_L': 3, 'Vis_R': 4}
tmin = -0.2
tmax = 0.5

# Setup for reading the raw data
raw = mne.io.Raw(raw_fname, preload=True)
raw.filter(1, 30)
events = mne.read_events(event_fname)

###############################################################################
# Read epochs for the channel of interest

picks = mne.pick_types(raw.info, meg='mag', eog=True)

reject = dict(mag=4e-12, eog=150e-6)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=None, reject=reject, preload=True)

epochs.drop_channels(['EOG 061'])
epochs.equalize_event_counts(event_id, copy=False)

condition_names = 'Aud_L', 'Aud_R', 'Vis_L', 'Vis_R'
X = [epochs[k].get_data() for k in condition_names]  # as 3D matrix
X = [np.transpose(x, (0, 2, 1)) for x in X]  # transpose for clustering


###############################################################################
# load FieldTrip neighbor definition to setup sensor connectivity
connectivity, ch_names = read_ch_connectivity('neuromag306mag')

print(type(connectivity))  # it's a sparse matrix!
github mne-tools / mne-python / mne / proj.py View on Github external
Returns
    -------
    projs: list
        List of projection vectors.

    See Also
    --------
    compute_proj_epochs, compute_proj_evoked
    """
    if duration is not None:
        duration = np.round(duration * raw.info['sfreq']) / raw.info['sfreq']
        events = make_fixed_length_events(raw, 999, start, stop, duration)
        picks = pick_types(raw.info, meg=True, eeg=True, eog=True, ecg=True,
                           emg=True, exclude='bads')
        epochs = Epochs(raw, events, None, tmin=0.,
                        tmax=duration - 1. / raw.info['sfreq'],
                        picks=picks, reject=reject, flat=flat,
                        baseline=None, proj=False)
        data = _compute_cov_epochs(epochs, n_jobs)
        info = epochs.info
        if not stop:
            stop = raw.n_times / raw.info['sfreq']
    else:
        # convert to sample indices
        start = max(raw.time_as_index(start)[0], 0)
        stop = raw.time_as_index(stop)[0] if stop else raw.n_times
        stop = min(stop, raw.n_times)
        data, times = raw[:, start:stop]
        _check_n_samples(stop - start, data.shape[0])
        data = np.dot(data, data.T)  # compute data covariance
        info = raw.info
github dbdq / neurodecode / pycnbi / utils / epochs2txt.py View on Github external
sfreq = raw.info['sfreq']
    if REF_CH_NEW is not None:
        pu.rereference(raw, REF_CH_NEW, REF_CH_OLD)

    # pick channels
    if CHANNEL_PICKS is None:
        picks = [raw.ch_names.index(c) for c in raw.ch_names if c not in EXCLUDES]
    elif type(CHANNEL_PICKS[0]) == str:
        picks = [raw.ch_names.index(c) for c in CHANNEL_PICKS]
    else:
        assert type(CHANNEL_PICKS[0]) is int
        picks = CHANNEL_PICKS

    # do epoching
    for epname, epval in EPOCHS.items():
        epochs = mne.Epochs(raw, events, dict(epname=epval), tmin=TMIN, tmax=TMAX,
                            proj=False, picks=picks, baseline=None, preload=True)
        data = epochs.get_data()  # epochs x channels x times
        for i, ep_data in enumerate(data):
            fout = '%s/%s-%d.txt' % (out_path, epname, i + 1)
            with open(fout, 'w') as f:
                for t in range(ep_data.shape[1]):
                    f.write(qc.list2string(ep_data[:, t], '%.6f') + '\n')
            logger.info('Exported %s' % fout)
github mne-tools / mne-python / tutorials / sample-datasets / plot_brainstorm_auditory.py View on Github external
saccades_events = df[df['label'] == 'saccade'].values[:, :3].astype(int)

# Conversion from samples to times:
onsets = annotations_df['onset'].values / raw.info['sfreq']
durations = annotations_df['duration'].values / raw.info['sfreq']
descriptions = annotations_df['label'].values

annotations = mne.Annotations(onsets, durations, descriptions)
raw.set_annotations(annotations)
del onsets, durations, descriptions

###############################################################################
# Here we compute the saccade and EOG projectors for magnetometers and add
# them to the raw data. The projectors are added to both runs.
saccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,
                            baseline=(None, None),
                            reject_by_annotation=False)

projs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,
                                        desc_prefix='saccade')
if use_precomputed:
    proj_fname = op.join(data_path, 'MEG', 'bst_auditory',
                         'bst_auditory-eog-proj.fif')
    projs_eog = mne.read_proj(proj_fname)[0]
else:
    projs_eog, _ = mne.preprocessing.compute_proj_eog(raw.load_data(),
                                                      n_mag=1, n_eeg=0)
raw.add_proj(projs_saccade)
raw.add_proj(projs_eog)
del saccade_epochs, saccades_events, projs_eog, projs_saccade  # To save memory
github mne-tools / mne-python / examples / io / plot_elekta_epochs.py View on Github external
# mne.write_evokeds(fname_out, evokeds)

###############################################################################
# Make a new averaging category
newcat = dict()
newcat['comment'] = 'Visual lower left, longer epochs'
newcat['event'] = 3  # reference event
newcat['start'] = -.2  # epoch start rel. to ref. event (in seconds)
newcat['end'] = .7  # epoch end
newcat['reqevent'] = 0  # additional required event; 0 if none
newcat['reqwithin'] = .5  # ...required within .5 sec (before or after)
newcat['reqwhen'] = 2  # ...required before (1) or after (2) ref. event
newcat['index'] = 9  # can be set freely

cond = raw.acqparser.get_condition(raw, newcat)
epochs = mne.Epochs(raw, reject=raw.acqparser.reject,
                    flat=raw.acqparser.flat, **cond)
epochs.average().plot(time_unit='s')
github NeuroTechX / moabb / moabb / contexts / bnci_2014_002.py View on Github external
def _epochs(self, subjects, event_id):
        """epoch data"""
        raws = self.dataset.get_data(subjects=subjects)
        raws = raws[0]
        ep = []
        # we process each run independently
        for raw in raws:
            raw.filter(7., 35., method='iir')

            events = find_events(raw, shortest_event=0, verbose=False)

            picks = pick_types(raw.info, meg=False, eeg=True, stim=False,
                               eog=False, exclude='bads')
            epochs = Epochs(raw, events, event_id, self.tmin, self.tmax,
                            proj=False, picks=picks, baseline=None,
                            preload=True, verbose=False)
            ep.append(epochs)
        return ep