adding a random event trigger


I would like to add a random trigger by adding random numbers to my existing event onsets. Using the “add_event” method provided by the raw nirx object did not work, because no specific stim channel was used that could be found or specified. Alternatively, i tried to change the onsets & description within the annotations object. This worked fine, but setting the durations for the extended list of events did not work (and also when going on with the analysis, other functions like conversion to OD didn’t work), because the old size of the Annotations object was not updated. Any experiences about how to adjust the size of the annotations object? Or add additional triggers in general?


An easy way to add events is to work with the matrix produced by mne.find_events. Here is an example on the MNE-Sample dataset:

import numpy as np
import mne

data_path = mne.datasets.sample.data_path()
raw ='{data_path}/MEG/sample/sample_audvis_raw.fif')
events = mne.find_events(raw)

# `events` is a matrix of integer numbers that has 3 columns: onset, duration, event_code.
# Let's add 100 random event onsets. Onsets are given in terms of sample index.
# Little gotcha here: samples don't start at 0! They start at `raw.first_samp`
n_random_events = 100
random_onsets = np.random.randint(raw.first_samp, raw.first_samp + len(raw.times), size=n_random_events)

# Let's make sure the event onsets are in increasing order
random_onsets = np.sort(random_onsets)

# Now let's fill out the events matrix. The random events need a duration and an event_code.
# I'm doing to use a duration of 3 samples (you could also generate these randomly of course)
# and an event_code of 42 (of course, you can pick any code you want).
random_events = np.vstack((
    3 * np.ones(n_random_events, int),  # durations
    42 * np.ones(n_random_events, int),  # event_code
)).T  # vstack made the matrix (3 x n_random_events), so we transpose with .T to get (n_random_events x 3)

Now you can use the events matrix to cut epochs:

epochs = mne.Epochs(raw, random_events, event_id={'Random event': 42}, tmin=-0.1, tmax=0.5)
1 Like

Thank you Marijn.Unfortunately my fNIRS data has no stim channel defined, which is apparently needed for the mne.find_events function (ValueError: No stim channels found, but the raw object has annotations. Consider using mne.events_from_annotations to convert these to events).

Nevertheless, adding random onsets to annotations.onsets and then applying mne-events_from_annotations.
and feed it back to annotation by doing the reverse mne_annotation_from_events with a new event_dict did the trick in the end.