How to merge two epochs trial by trial

Hi:

Now I have an EEG raw file, and I need to cut out epochs and set the baseline. However, the position of the baseline relative to the cut-out epochs is uncertain, so I need to cut out the required epochs and baseline separately, and then merge them trial by trial. I noticed the mne.concatenate_epochs method, but it seems to directly stack two epochs together rather than concatenating them trial by trial. My current solution is as follows.


I would like to know if this is correct and if there is a direct method provided. Thank you.

Cheng.

Hello @Zyaire and welcome to the forum!

Could you please share your code as text (using the Preformatted text button in the toolbar)? Working with screenshots is really difficult for some users here, and it doesn’t allow us to easily copy and quote the code.

Thanks,
Richard

def cut_epoch_two_part(raw, events, tmin=-0.7, tmax=1, event_id=19):
    """
    Concatenate the EEG segment of interest with a 0.5s segment before event_id=1.

    :param raw: Raw EEG data (mne.io.Raw)
    :param events: Event information (array, shape: n_events x 3)
    :param tmin: Minimum time after the event (default: -0.7s)
    :param tmax: Maximum time after the event (default: 1s)
    :param event_id: Event ID to extract (default: 19)
    :return: Concatenated epochs (mne.Epochs)
    """

    # 1. Extract target event (event_id=19) epochs
    epochs_main = mne.Epochs(raw, events, event_id=event_id, tmin=tmin, tmax=tmax,
                             baseline=None, preload=True)

    baseline_tmin = -0.5  # Take 0.5s before event_id=1
    baseline_tmax = 0  # Event onset time

    # 3. Extract baseline epochs
    epochs_baseline = mne.Epochs(raw, events, event_id=event_id+5, tmin=baseline_tmin, tmax=baseline_tmax,
                                 baseline=None, preload=True)

    # Ensure the number of trials in both epochs matches
    print("len(epochs_main): ", len(epochs_main))
    print("len(epochs_baseline): ", len(epochs_baseline))

    if len(epochs_main) != len(epochs_baseline):
        raise ValueError("The lengths of epochs_main and epochs_baseline are different, merging is not possible")

    # 4. Concatenate trials one by one
    combined_data = np.concatenate([epochs_baseline.get_data(),
                                    epochs_main.get_data()], axis=-1)

    # 5. Generate new epochs
    new_info = epochs_main.info  # Inherit the original epochs' info
    combined_epochs = mne.EpochsArray(combined_data, new_info, tmin=baseline_tmin,
                                      events=epochs_main.events)

    return combined_epochs

Okay, this is my code.