How to use the mne.find_events 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 / examples / time_frequency / plot_source_space_time_frequency.py View on Github external
from mne import io
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_band_induced_power

print(__doc__)

###############################################################################
# Set parameters
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)

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
events = events[:10]  # take 10 events to keep the computation time low
# 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)
github alphacsc / alphacsc / alphacsc / datasets / hcp.py View on Github external
f"hcp_path={HCP_DIR}")
    raw = hcp.read_raw(subject, data_type=data_type, run_index=run_index,
                       hcp_path=HCP_DIR, verbose=0)
    raw.load_data()
    hcp.preprocessing.map_ch_coords_to_mne(raw)
    raw.pick_types(meg='mag', eog=False, stim=True)

    # filter the electrical and low frequency components
    raw.notch_filter([60, 120], n_jobs=n_jobs)
    raw.filter(*filter_params, n_jobs=n_jobs)

    # Resample to the requested sfreq
    if sfreq is not None:
        raw.resample(sfreq=sfreq, n_jobs=n_jobs)

    events = mne.find_events(raw)
    raw.pick_types(meg='mag', stim=False)
    events[:, 0] -= raw.first_samp

    # Deep copy before modifying info to avoid issues when saving EvokedArray
    info = deepcopy(raw.info)
    info['events'] = events
    info['event_id'] = np.unique(events[:, 2])

    # Return the data
    return raw.get_data(), info
github mne-tools / mne-python / tutorials / source-modeling / plot_compute_covariance.py View on Github external
[pp.copy() for pp in raw.info['projs'] if 'EEG' not in pp['desc']])

noise_cov = mne.compute_raw_covariance(
    raw_empty_room, tmin=0, tmax=None)

###############################################################################
# Now that you have the covariance matrix in an MNE-Python object you can
# save it to a file with :func:`mne.write_cov`. Later you can read it back
# using :func:`mne.read_cov`.
#
# You can also use the pre-stimulus baseline to estimate the noise covariance.
# First we have to construct the epochs. When computing the covariance, you
# should use baseline correction when constructing the epochs. Otherwise the
# covariance matrix will be inaccurate. In MNE this is done by default, but
# just to be sure, we define it here manually.
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-0.2, tmax=0.5,
                    baseline=(-0.2, 0.0), decim=3,  # we'll decimate for speed
                    verbose='error')  # and ignore the warning about aliasing

###############################################################################
# Note that this method also attenuates any activity in your
# source estimates that resemble the baseline, if you like it or not.
noise_cov_baseline = mne.compute_covariance(epochs, tmax=0)

###############################################################################
# Plot the covariance matrices
# ----------------------------
#
# Try setting proj to False to see the effect. Notice that the projectors in
# epochs are already applied, so ``proj`` parameter has no effect.
noise_cov.plot(raw_empty_room.info, proj=True)
github mne-tools / mne-python / examples / time_frequency / plot_time_frequency_global_field_power.py View on Github external
('Theta', 4, 7),
    ('Alpha', 8, 12),
    ('Beta', 13, 25),
    ('Gamma', 30, 45)
]

###############################################################################
# We create average power time courses for each frequency band

# set epoching parameters
event_id, tmin, tmax = 1, -1., 3.
baseline = None

# get the header to extract events
raw = mne.io.read_raw_fif(raw_fname)
events = mne.find_events(raw, stim_channel='STI 014')

frequency_map = list()

for band, fmin, fmax in iter_freqs:
    # (re)load the data to save memory
    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    raw.pick_types(meg='grad', eog=True)  # we just look at gradiometers

    # bandpass filter
    raw.filter(fmin, fmax, n_jobs=1,  # use more jobs to speed up.
               l_trans_bandwidth=1,  # make sure filter params are the same
               h_trans_bandwidth=1)  # in each band and skip "auto" option.

    # epoch
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, baseline=baseline,
                        reject=dict(grad=4000e-13, eog=350e-6),
github mne-tools / mne-python / examples / time_frequency / plot_source_label_time_frequency.py View on Github external
print(__doc__)

###############################################################################
# Set parameters
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'
label_name = 'Aud-rh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name

tmin, tmax, event_id = -0.2, 0.5, 2

# 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)

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

# Picks MEG channels
picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True,
                       stim=False, include=include, exclude='bads')
reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6)

# Load epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=(None, 0), reject=reject,
                    preload=True)

# Compute a source estimate per frequency band including and excluding the
github autoreject / autoreject / examples / plot_visualize_bad_epochs.py View on Github external
import mne  # noqa

epochs = list()
for run in range(3, 7):
    run_fname = os.path.join(base_path, 'ds117', 'sub%03d' % subject_id, 'MEG',
                             'run_%02d_raw.fif' % run)
    raw = mne.io.read_raw_fif(run_fname, preload=True)
    raw.pick_types(eeg=True, meg=False, stim=True)  # less memory + computation
    raw.filter(1., 40., l_trans_bandwidth=0.5, n_jobs=1, verbose='INFO')

    raw.set_channel_types({'EEG061': 'eog', 'EEG062': 'eog',
                           'EEG063': 'ecg', 'EEG064': 'misc'})
    raw.rename_channels({'EEG061': 'EOG061', 'EEG062': 'EOG062',
                         'EEG063': 'ECG063', 'EEG064': 'MISC'})

    events = mne.find_events(raw, stim_channel='STI101',
                             consecutive='increasing',
                             min_duration=0.003, verbose=True)
    # Read epochs
    mne.io.set_eeg_reference(raw)

    epoch = mne.Epochs(raw, events, events_id, tmin, tmax, proj=True,
                       baseline=None,
                       preload=False, reject=None, decim=4)
    epochs.append(epoch)

    # Same `dev_head_t` for all runs so that we can concatenate them.
    epoch.info['dev_head_t'] = epochs[0].info['dev_head_t']


epochs = mne.epochs.concatenate_epochs(epochs)
###############################################################################
github mne-tools / mne-python / examples / simulation / plot_source_simulator.py View on Github external
# Create simulated source activity. Here we use a SourceSimulator whose
# add_data method is key. It specified where (label), what
# (source_time_series), and when (events) an event type will occur.
source_simulator = mne.simulation.SourceSimulator(src, tstep=tstep)
source_simulator.add_data(label, source_time_series, events)

# Project the source time series to sensor space and add some noise. The source
# simulator can be given directly to the simulate_raw function.
raw = mne.simulation.simulate_raw(info, source_simulator, forward=fwd)
cov = mne.make_ad_hoc_cov(raw.info)
mne.simulation.add_noise(raw, cov, iir_filter=[0.2, -0.2, 0.04])
raw.plot()

# Plot evoked data to get another view of the simulated raw data.
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, 1, tmin=-0.05, tmax=0.2)
evoked = epochs.average()
evoked.plot()
github mne-tools / mne-python / examples / time_frequency / plot_time_frequency_multitaper_sensors.py View on Github external
from mne import io
from mne.time_frequency import tfr_multitaper
from mne.datasets import somato

print(__doc__)

###############################################################################
# Load real somatosensory sample data.
data_path = somato.data_path()
raw_fname = data_path + '/MEG/somato/sef_raw_sss.fif'
event_id, tmin, tmax = 1, -1., 3.

# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
baseline = (None, 0)
events = mne.find_events(raw, stim_channel='STI 014')

# Pick a good channel for somatosensory responses.
picks = [raw.info['ch_names'].index('MEG 1142'), ]

epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=baseline, reject=dict(grad=4000e-13))

###############################################################################
# Calculate power

freqs = np.arange(5., 50., 2.)  # define frequencies of interest
n_cycles = freqs / 2.  # 0.5 second time windows for all frequencies

# Choose time x (full) bandwidth product
time_bandwidth = 4.0  # With 0.5 s time windows, this gives 8 Hz smoothing
github mne-tools / mne-python / examples / plot_extract_events_from_raw.py View on Github external
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.io import Raw

print(__doc__)

data_path = sample.data_path()
fname = data_path + '/MEG/sample/sample_audvis_raw.fif'

# Reading events
raw = Raw(fname)

events = mne.find_events(raw, stim_channel='STI 014')

# Writing events
mne.write_events('sample_audvis_raw-eve.fif', events)

for ind, before, after in events[:5]:
    print("At sample %d stim channel went from %d to %d"
          % (ind, before, after))

# Plot the events to get an idea of the paradigm
# Specify colors and an event_id dictionary for the legend.
event_id = {'aud_l': 1, 'aud_r': 2, 'vis_l': 3, 'vis_r': 4, 'smiley': 5,
            'button': 32}
color = {1: 'green', 2: 'yellow', 3: 'red', 4: 'c', 5: 'black', 32: 'blue'}

mne.viz.plot_events(events, raw.info['sfreq'], raw.first_samp, color=color,
                    event_id=event_id)
github pactools / pactools / examples / plot_mne_epoch_masking.py View on Github external
raw.plot_psd(fmax=60)
epochs = mne.Epochs(raw, events, tmin=-3, tmax=3)
epochs.average().plot()

###############################################################################
# Let's save the raw object out for input/output demonstration purposes

root = mne.utils._TempDir()
raw.save(op.join(root, 'pac_example-raw.fif'))

###############################################################################
# Here we define how to build the epochs: which channels will be selected, and
# on which time window around each event.

raw = mne.io.Raw(op.join(root, 'pac_example-raw.fif'))
events = mne.find_events(raw)

# select the time interval around the events
tmin, tmax = mu - 3 * sigma, mu + 3 * sigma
# select the channels (phase_channel, amplitude_channel)
ixs = (0, 0)

###############################################################################
# Then, we create the inputs with the function raw_to_mask, which creates the
# input arrays and the mask arrays. These arrays are then given to a
# comodulogram instance with the `fit` method, and the `plot` method draws the
# results.

# create the input array for Comodulogram.fit

low_sig, high_sig, mask = raw_to_mask(raw, ixs=ixs, events=events, tmin=tmin,
                                      tmax=tmax)