Modifying annotations in-place

I was working with someone new to MNE the other day and realized that I often get tripped up when trying to modify annotations in my raw object:

import mne
import numpy as np

data = np.ones((10, 1000))
ch_names = [f"EEG{num}" for num in np.arange(1, 11, 1)]
sfreq = 100
ch_types = "eeg"
info = mne.create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)

raw = mne.io.RawArray(data, info)

onsets = [2, 4, 6]
durs = 0
descs = "stim"
my_annots = mne.Annotations(onset=onsets, duration=durs, description=descs)
raw.set_annotations(my_annots)

As the documentation points out, iterating/slicing/indexing annotations within an Annotations object returns a copy. Admittedly I often forget this.

# This does not modify annotations in-place

for this_annot in raw.annotations:
    this_annot["duration"] += 1
np.testing.assert_array_equal(raw.annotations.duration, [1, 1, 1])

But this does operate in-place:

# This operates in place

raw.annotations.duration += 1
np.testing.assert_array_equal(raw.annotations.duration, [1, 1, 1])

Does anyone know if this latter code-snippet the β€œsuggested” way to modify annotations in a raw object? If this design was intentional, should it be documented?

I am not 100% sure myself, but I always thought the idea was to not modify annotations in place (which may bypass potential checks), but instead create a new annotations object and set it to raw via set_annotations.

2 Likes

Thanks @sappelhoff that makes sense. So maybe my example of changing annotations in-place ( via raw.annotaitons.duration += 1) is an unintended coincidence :slightly_smiling_face:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.