From b228b1555b375d562972fc55820dc4f3350b20ef Mon Sep 17 00:00:00 2001 From: Ishaan Maheshwari Date: Thu, 19 Nov 2026 03:37:23 +0530 Subject: [PATCH 1/2] ENH: Support EpochsTFR in concatenate_epochs --- doc/changes/dev/newfeature.rst | 1 + mne/epochs.py | 67 +++++++++++++++++++--------- mne/time_frequency/tests/test_tfr.py | 27 +++++++++++ mne/time_frequency/tfr.py | 4 +- 4 files changed, 78 insertions(+), 21 deletions(-) create mode 100644 doc/changes/dev/newfeature.rst diff --git a/doc/changes/dev/newfeature.rst b/doc/changes/dev/newfeature.rst new file mode 100644 index 00000000000..be8f581c7f3 --- /dev/null +++ b/doc/changes/dev/newfeature.rst @@ -0,0 +1 @@ +Allow :func:`mne.concatenate_epochs` to concatenate :class:`~mne.time_frequency.EpochsTFR` instances, by `Aman Srivastava`_ and `Ishaan Maheshwari`_. diff --git a/mne/epochs.py b/mne/epochs.py index 96570d6f775..78d63e0e24b 100644 --- a/mne/epochs.py +++ b/mne/epochs.py @@ -6418,17 +6418,23 @@ def _concatenate_epochs( epochs_list, *, with_data=True, add_offset=True, on_mismatch="raise" ): """Auxiliary function for concatenating epochs.""" + from .time_frequency.tfr import EpochsTFR + if not isinstance(epochs_list, list | tuple): raise TypeError(f"epochs_list must be a list or tuple, got {type(epochs_list)}") + out = epochs_list[0] + is_tfr = isinstance(out, EpochsTFR) # to make warning messages only occur once during concatenation warned = False for ei, epochs in enumerate(epochs_list): - if not isinstance(epochs, BaseEpochs): - raise TypeError( - f"epochs_list[{ei}] must be an instance of Epochs, got {type(epochs)}" - ) + _validate_type( + epochs, + EpochsTFR if is_tfr else BaseEpochs, + f"epochs_list[{ei}]", + "EpochsTFR" if is_tfr else "Epochs", + ) if ( getattr(epochs, "annotations", None) is not None @@ -6445,23 +6451,25 @@ def _concatenate_epochs( # from the original object epochs = epochs.copy() epochs.set_annotations(None) - out = epochs_list[0] offsets = [0] - if with_data: + if with_data and not is_tfr: out.drop_bad() offsets.append(len(out)) events = [out.events] metadata = [out.metadata] - baseline, tmin, tmax = out.baseline, out.tmin, out.tmax - raw_sfreq = out._raw_sfreq + baseline = out.baseline + if is_tfr: + tmin = tmax = raw_sfreq = None + shift = len(out.times) + else: + tmin, tmax, raw_sfreq = out.tmin, out.tmax, out._raw_sfreq + shift = np.int64((10 + tmax) * out.info["sfreq"]) info = deepcopy(out.info) drop_log = out.drop_log event_id = deepcopy(out.event_id) selection = out.selection - # offset is the last epoch + tmax + 10 second - shift = np.int64((10 + tmax) * out.info["sfreq"]) # Allow reading empty epochs (ToDo: Maybe not anymore in the future) - if out._allow_empty: + if not len(out.events) or (not is_tfr and out._allow_empty): events_offset = 0 else: events_offset = int(np.max(events[0][:, 0])) + shift @@ -6470,13 +6478,20 @@ def _concatenate_epochs( warned = False for ii, epochs in enumerate(epochs_list[1:], 1): _ensure_infos_match(epochs.info, info, f"epochs[{ii}]", on_mismatch=on_mismatch) + if is_tfr: + if not np.array_equal(epochs.freqs, out.freqs): + raise ValueError("TFR frequencies must match") + if epochs.method != out.method or epochs._data_type != out._data_type: + raise ValueError("TFR method and data type must match") + if not np.array_equal(epochs.weights, out.weights): + raise ValueError("TFR taper weights must match") if not np.allclose(epochs.times, epochs_list[0].times): raise ValueError("Epochs must have same times") if epochs.baseline != baseline: raise ValueError("Baseline must be same for all epochs") - if epochs._raw_sfreq != raw_sfreq and not warned: + if not is_tfr and epochs._raw_sfreq != raw_sfreq and not warned: warned = True warn( "The original raw sampling rate of the Epochs does not " @@ -6505,7 +6520,7 @@ def _concatenate_epochs( f"in epochs_list[0] and to {b[k_v]} in epochs_list[{ii}]." ) - if with_data: + if with_data and not is_tfr: epochs.drop_bad() offsets.append(len(epochs)) evs = epochs.events.copy() @@ -6526,7 +6541,9 @@ def _concatenate_epochs( events_overflow = True add_offset = False # we no longer need to add offset events.append(evs) - selection = np.concatenate((selection, epochs.selection)) + selection = np.concatenate( + (selection, epochs.selection + (len(drop_log) if is_tfr else 0)) + ) drop_log = drop_log + epochs.drop_log event_id.update(epochs.event_id) metadata.append(epochs.metadata) @@ -6550,9 +6567,10 @@ def _concatenate_epochs( metadata = pd.concat(metadata) else: # dict of dicts metadata = sum(metadata, list()) - assert len(offsets) == (len(epochs_list) if with_data else 0) + 1 data = None - if with_data: + if is_tfr: + data = np.concatenate([epochs.data for epochs in epochs_list]) + elif with_data: offsets = np.cumsum(offsets) for start, stop, epochs in zip(offsets[:-1], offsets[1:], epochs_list): this_data = epochs.get_data(copy=False) @@ -6584,8 +6602,8 @@ def concatenate_epochs( *, on_mismatch: Literal["raise", "warn", "ignore"] = "raise", verbose: bool | str | int | None = None, -) -> EpochsArray: - """Concatenate a list of `~mne.Epochs` into one `~mne.Epochs` object. +) -> "EpochsArray | EpochsTFR": + """Concatenate epochs or epoched time-frequency data. .. note:: Unlike `~mne.concatenate_raws`, this function does **not** modify any of the input data. @@ -6593,7 +6611,8 @@ def concatenate_epochs( Parameters ---------- epochs_list : list - List of `~mne.Epochs` instances to concatenate (in that order). + List of `~mne.Epochs` or `~mne.time_frequency.EpochsTFR` instances + of the same kind to concatenate in order. add_offset : bool If True, a fixed offset is added to the event times from different Epochs sets, such that they are easy to distinguish after the @@ -6616,7 +6635,7 @@ def concatenate_epochs( Returns ------- - epochs : instance of EpochsArray + epochs : instance of EpochsArray or EpochsTFR The result of the concatenation. All data will be loaded into memory. Notes @@ -6641,6 +6660,14 @@ def concatenate_epochs( add_offset=add_offset, on_mismatch=on_mismatch, ) + first = epochs_list[0] + if not isinstance(first, BaseEpochs): + # Avoid copying the input data again when preserving TFR attributes. + out = deepcopy(first, {id(first.data): data, id(first.info): info}) + out.events, out.event_id = events, event_id + out.selection, out.drop_log = selection.copy(), drop_log + out.metadata = metadata + return out selection = np.where([len(d) == 0 for d in drop_log])[0] out = EpochsArray( data=data, diff --git a/mne/time_frequency/tests/test_tfr.py b/mne/time_frequency/tests/test_tfr.py index b4556f61833..7c95887e0bc 100644 --- a/mne/time_frequency/tests/test_tfr.py +++ b/mne/time_frequency/tests/test_tfr.py @@ -1330,6 +1330,27 @@ def test_epochstfr_getitem(epochs_full, n_drop, as_tfr_array): tfr = EpochsTFRArray( info=tfr.info, data=tfr.data, times=tfr.times, freqs=tfr.freqs ) + first, second = tfr[:2], tfr[2:] + joined = mne.concatenate_epochs([first, second], add_offset=False) + assert_array_equal(mne.concatenate_epochs([tfr[[]], tfr]).data, tfr.data) + assert isinstance(joined, EpochsTFR) + assert_array_equal(joined.data, tfr.data) + assert_array_equal(joined.events, tfr.events) + assert_array_equal( + joined.selection, np.r_[first.selection, second.selection + len(first.drop_log)] + ) + assert joined.drop_log == first.drop_log + second.drop_log + if tfr.metadata is not None: + assert_frame_equal( + joined.metadata.reset_index(drop=True), tfr.metadata.reset_index(drop=True) + ) + shifted = mne.concatenate_epochs([first, second]) + offset = first.events[:, 0].max() + len(tfr.times) + assert_array_equal(shifted.events[2:, 0], second.events[:, 0] + offset) + with pytest.raises(ValueError, match="times"): + mne.concatenate_epochs([first, second.copy().shift_time(0.1)]) + with pytest.raises(ValueError, match="Baseline"): + mne.concatenate_epochs([first, second.copy().apply_baseline((None, 0))]) # test integer and slice subset_ints = tfr[[0, 1, 2]] subset_slice = tfr[:3] @@ -1666,6 +1687,12 @@ def test_epochs_compute_tfr_multitaper_complex_phase(epochs, output): tfr = epochs.compute_tfr("multitaper", freqs_linspace, output=output) assert len(tfr.shape) == 5 # epoch x channel x taper x freq x time assert tfr.weights.shape == tfr.shape[2:4] # check weights and coeffs shapes match + other = tfr[:1] + joined = mne.concatenate_epochs([tfr, other]) + assert_array_equal(joined.data, np.concatenate([tfr.data, other.data])) + other.weights[:] *= 2 + with pytest.raises(ValueError, match="weights"): + mne.concatenate_epochs([tfr, other]) @pytest.mark.parametrize("copy", (False, True)) diff --git a/mne/time_frequency/tfr.py b/mne/time_frequency/tfr.py index 3c66fad5942..9540c853752 100644 --- a/mne/time_frequency/tfr.py +++ b/mne/time_frequency/tfr.py @@ -4569,7 +4569,9 @@ def __setstate__(self, state): "drop_log", tuple( () if k in self.selection else ("IGNORED",) - for k in range(max(len(self.events), max(self.selection) + 1)) + for k in range( + max(len(self.events), max(self.selection, default=-1) + 1) + ) ), ) self._bad_dropped = True # always true, need for `equalize_event_counts()` From 8de6d72be2819fc50933d57ecdd9f20f58fa456e Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:12:00 +0000 Subject: [PATCH 2/2] [autofix.ci] apply automated fixes --- doc/changes/dev/{newfeature.rst => 14565.newfeature.rst} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename doc/changes/dev/{newfeature.rst => 14565.newfeature.rst} (100%) diff --git a/doc/changes/dev/newfeature.rst b/doc/changes/dev/14565.newfeature.rst similarity index 100% rename from doc/changes/dev/newfeature.rst rename to doc/changes/dev/14565.newfeature.rst