From 4fcf3b5314da73bf7d884d2e840cc21686e68362 Mon Sep 17 00:00:00 2001 From: Ishaan Maheshwari Date: Thu, 19 Nov 2026 00:15:10 +0530 Subject: [PATCH 1/5] ENH: Support EpochsSpectrum in concatenate_epochs --- doc/changes/dev/newfeature.rst | 1 + mne/epochs.py | 93 ++++++++++++++++------- mne/tests/test_epochs.py | 24 ++++++ mne/time_frequency/tests/test_spectrum.py | 6 ++ 4 files changed, 95 insertions(+), 29 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..976d9e9ab8e --- /dev/null +++ b/doc/changes/dev/newfeature.rst @@ -0,0 +1 @@ +Allow :func:`mne.concatenate_epochs` to concatenate :class:`~mne.time_frequency.EpochsSpectrum` instances, by `Ishaan Maheshwari`_. diff --git a/mne/epochs.py b/mne/epochs.py index 96570d6f775..9f492b2632e 100644 --- a/mne/epochs.py +++ b/mne/epochs.py @@ -6421,14 +6421,19 @@ def _concatenate_epochs( 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] + spectrum = isinstance(out, EpochsSpectrum) + expected = EpochsSpectrum if spectrum else BaseEpochs # 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, + expected, + f"epochs_list[{ei}]", + "EpochsSpectrum" if spectrum else "Epochs", + ) if ( getattr(epochs, "annotations", None) is not None @@ -6445,38 +6450,52 @@ 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 spectrum: 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 = tmin = tmax = raw_sfreq = None + if not spectrum: + baseline, tmin, tmax = out.baseline, out.tmin, out.tmax + raw_sfreq = out._raw_sfreq info = deepcopy(out.info) drop_log = out.drop_log - event_id = deepcopy(out.event_id) + event_id = deepcopy(out.event_id) or {} selection = out.selection - # offset is the last epoch + tmax + 10 second - shift = np.int64((10 + tmax) * out.info["sfreq"]) + shift = len(out.freqs) if spectrum else np.int64((10 + tmax) * out.info["sfreq"]) # Allow reading empty epochs (ToDo: Maybe not anymore in the future) - if out._allow_empty: + if out.events is None or not len(out.events) or getattr(out, "_allow_empty", False): events_offset = 0 else: - events_offset = int(np.max(events[0][:, 0])) + shift + samples = out.events[:, 0] + events_offset = int(samples[-1] if spectrum else samples.max()) + shift events_offset = np.int64(events_offset) events_overflow = False 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 not np.allclose(epochs.times, epochs_list[0].times): + if spectrum: + if not np.array_equal(epochs.freqs, out.freqs): + raise ValueError("Spectra must have the same frequencies") + if epochs.method != out.method: + raise ValueError("Spectra must have the same method") + if ( + tuple(epochs._dims) != tuple(out._dims) + or epochs._data_type != out._data_type + or not np.array_equal(epochs.weights, out.weights) + ): + raise ValueError("Spectrum dimensions, type and weights must match") + if (epochs.events is None) != (out.events is None): + raise ValueError("Either all or none of the spectra must have events") + elif not np.allclose(epochs.times, out.times): raise ValueError("Epochs must have same times") - if epochs.baseline != baseline: + if not spectrum and epochs.baseline != baseline: raise ValueError("Baseline must be same for all epochs") - if epochs._raw_sfreq != raw_sfreq and not warned: + if not spectrum and epochs._raw_sfreq != raw_sfreq and not warned: warned = True warn( "The original raw sampling rate of the Epochs does not " @@ -6486,7 +6505,7 @@ def _concatenate_epochs( # compare event_id for kind in ("keys", "values"): a = event_id - b = epochs.event_id + b = epochs.event_id or {} if kind == "keys": other = "values" what = "maps to" @@ -6505,9 +6524,17 @@ 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 spectrum: epochs.drop_bad() offsets.append(len(epochs)) + selection = np.concatenate( + (selection, epochs.selection + (len(drop_log) if spectrum else 0)) + ) + drop_log = drop_log + epochs.drop_log + event_id.update(epochs.event_id or {}) + metadata.append(epochs.metadata) + if epochs.events is None: + continue evs = epochs.events.copy() if len(epochs.events) == 0: warn("One of the Epochs objects to concatenate was empty.") @@ -6526,11 +6553,7 @@ 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)) - drop_log = drop_log + epochs.drop_log - event_id.update(epochs.event_id) - metadata.append(epochs.metadata) - events = np.concatenate(events, axis=0) + events = None if out.events is None else np.concatenate(events, axis=0) # check to see if we exceeded our maximum event offset if events_overflow: events[:, 0] = np.arange(1, len(events) + 1) @@ -6550,9 +6573,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 spectrum: + 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 +6608,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 | EpochsSpectrum: + """Concatenate epochs or epoched spectra along the epoch dimension. .. note:: Unlike `~mne.concatenate_raws`, this function does **not** modify any of the input data. @@ -6593,7 +6617,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.EpochsSpectrum` 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 +6641,7 @@ def concatenate_epochs( Returns ------- - epochs : instance of EpochsArray + epochs : instance of EpochsArray or EpochsSpectrum The result of the concatenation. All data will be loaded into memory. Notes @@ -6641,6 +6666,16 @@ def concatenate_epochs( add_offset=add_offset, on_mismatch=on_mismatch, ) + if isinstance(epochs_list[0], EpochsSpectrum): + first = epochs_list[0] + # Reuse the concatenated data and copied info when copying spectral attributes. + out = deepcopy(first, {id(first.data): data, id(first.info): info}) + out.events = events + out.event_id = event_id or None + out.selection = selection.copy() + out.drop_log = 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/tests/test_epochs.py b/mne/tests/test_epochs.py index 1addef66681..6fcbba35167 100644 --- a/mne/tests/test_epochs.py +++ b/mne/tests/test_epochs.py @@ -3868,6 +3868,21 @@ def test_concatenate_epochs(): epochs = Epochs( raw=raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax, picks=picks ) + spectrum = epochs.compute_psd(method="welch", n_fft=64) + joined = concatenate_epochs([spectrum, spectrum]) + assert_array_equal(joined.data, np.concatenate([spectrum.data] * 2)) + assert_array_equal(joined.freqs, spectrum.freqs) + assert_array_equal(joined.events[:, 2], np.tile(spectrum.events[:, 2], 2)) + offset = spectrum.events[-1, 0] + len(spectrum.freqs) + assert_array_equal( + joined.events[len(spectrum.events) :, 0], spectrum.events[:, 0] + offset + ) + assert joined.drop_log == spectrum.drop_log * 2 + with pytest.raises(ValueError, match="frequencies"): + concatenate_epochs([spectrum, epochs.compute_psd(method="welch", n_fft=32)]) + with pytest.raises(TypeError, match="EpochsSpectrum"): + concatenate_epochs([spectrum, epochs]) + epochs2 = epochs.copy() epochs_list = [epochs, epochs2] epochs_conc = concatenate_epochs(epochs_list) @@ -4081,6 +4096,15 @@ def test_metadata(tmp_path, monkeypatch): epochs.metadata = meta log = log.getvalue().strip() assert log == "Replacing existing metadata with 2 columns", f"{log}" + spectrum = epochs.compute_psd(method="welch", picks="all") + joined = concatenate_epochs([spectrum[5:], spectrum[:5]], add_offset=False) + order = np.r_[5:10, :5] + assert_array_equal(joined.events, events[order]) + assert_array_equal(joined.metadata.to_numpy(), meta.iloc[order].to_numpy()) + assert_array_equal(joined.metadata.index, joined.selection) + assert_array_equal(joined.selection, np.arange(5, 15)) + assert joined.event_id == event_id + indices = np.arange(len(epochs)) # expected indices assert_array_equal(epochs.metadata.index, indices) diff --git a/mne/time_frequency/tests/test_spectrum.py b/mne/time_frequency/tests/test_spectrum.py index 0b8ad562456..e77643eca68 100644 --- a/mne/time_frequency/tests/test_spectrum.py +++ b/mne/time_frequency/tests/test_spectrum.py @@ -14,6 +14,7 @@ from mne import ( Annotations, BaseEpochs, + concatenate_epochs, create_info, grand_average, make_fixed_length_epochs, @@ -682,6 +683,11 @@ def test_spectrum_array(kind, method, output, average, tmp_path, request): dim_names=dim_names, weights=spectrum.weights, ) + if kind == "epochs": + joined = concatenate_epochs([spect_arr, spect_arr]) + assert_array_equal(joined.data, np.concatenate([data, data])) + assert_array_equal(joined.weights, spectrum.weights) + assert joined.events is None _check_spectrum_equivalent(spectrum, spect_arr, tmp_path) From 662458dfd05477de9774c03d0feae5defb016551 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:51:05 +0000 Subject: [PATCH 2/5] [autofix.ci] apply automated fixes --- doc/changes/dev/{newfeature.rst => 14564.newfeature.rst} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename doc/changes/dev/{newfeature.rst => 14564.newfeature.rst} (100%) diff --git a/doc/changes/dev/newfeature.rst b/doc/changes/dev/14564.newfeature.rst similarity index 100% rename from doc/changes/dev/newfeature.rst rename to doc/changes/dev/14564.newfeature.rst From c570290770cd9c85f1d63314b53e9630a9821950 Mon Sep 17 00:00:00 2001 From: Ishaan Maheshwari Date: Thu, 19 Nov 2026 03:05:33 +0530 Subject: [PATCH 3/5] MAINT: Address ty typing diagnostics in concatenate_epochs - Separate spectrum and standard epochs initialization to avoid None typing on tmax. - Guard events overflow indexing when events is None. - Credit Aman Srivastava as co-author for EpochsSpectrum concatenation in changelog. Co-authored-by: Aman Srivastava --- doc/changes/dev/14564.newfeature.rst | 2 +- mne/epochs.py | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/doc/changes/dev/14564.newfeature.rst b/doc/changes/dev/14564.newfeature.rst index 976d9e9ab8e..fcca9da6b87 100644 --- a/doc/changes/dev/14564.newfeature.rst +++ b/doc/changes/dev/14564.newfeature.rst @@ -1 +1 @@ -Allow :func:`mne.concatenate_epochs` to concatenate :class:`~mne.time_frequency.EpochsSpectrum` instances, by `Ishaan Maheshwari`_. +Allow :func:`mne.concatenate_epochs` to concatenate :class:`~mne.time_frequency.EpochsSpectrum` instances, by `Aman Srivastava`_ and `Ishaan Maheshwari`_. diff --git a/mne/epochs.py b/mne/epochs.py index 9f492b2632e..c55137eb6d3 100644 --- a/mne/epochs.py +++ b/mne/epochs.py @@ -6456,21 +6456,22 @@ def _concatenate_epochs( offsets.append(len(out)) events = [out.events] metadata = [out.metadata] - baseline = tmin = tmax = raw_sfreq = None - if not spectrum: + if spectrum: + baseline = tmin = tmax = raw_sfreq = None + shift = len(out.freqs) + else: baseline, tmin, tmax = out.baseline, out.tmin, out.tmax raw_sfreq = 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) or {} selection = out.selection - shift = len(out.freqs) if spectrum else np.int64((10 + tmax) * out.info["sfreq"]) # Allow reading empty epochs (ToDo: Maybe not anymore in the future) if out.events is None or not len(out.events) or getattr(out, "_allow_empty", False): events_offset = 0 else: - samples = out.events[:, 0] - events_offset = int(samples[-1] if spectrum else samples.max()) + shift + events_offset = int(out.events[:, 0].max()) + shift events_offset = np.int64(events_offset) events_overflow = False warned = False @@ -6555,7 +6556,7 @@ def _concatenate_epochs( events.append(evs) events = None if out.events is None else np.concatenate(events, axis=0) # check to see if we exceeded our maximum event offset - if events_overflow: + if events_overflow and events is not None: events[:, 0] = np.arange(1, len(events) + 1) # Create metadata object (or make it None) From 19df1af8f902ce8a82fe63390adf08d3c2328d8e Mon Sep 17 00:00:00 2001 From: Ishaan Maheshwari Date: Thu, 26 Nov 2026 01:33:47 +0530 Subject: [PATCH 4/5] TEST: Consolidate EpochsSpectrumArray concatenation into test_epochs.py --- mne/tests/test_epochs.py | 11 +++++++++++ mne/time_frequency/tests/test_spectrum.py | 6 ------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/mne/tests/test_epochs.py b/mne/tests/test_epochs.py index 6fcbba35167..8084dea2285 100644 --- a/mne/tests/test_epochs.py +++ b/mne/tests/test_epochs.py @@ -59,6 +59,7 @@ from mne.event import merge_events from mne.io import RawArray, read_raw_fif from mne.preprocessing import maxwell_filter +from mne.time_frequency import EpochsSpectrumArray from mne.utils import ( _dt_to_stamp, _record_warnings, @@ -3882,6 +3883,16 @@ def test_concatenate_epochs(): concatenate_epochs([spectrum, epochs.compute_psd(method="welch", n_fft=32)]) with pytest.raises(TypeError, match="EpochsSpectrum"): concatenate_epochs([spectrum, epochs]) + spect_arr = EpochsSpectrumArray( + data=spectrum.get_data(), + info=spectrum.info, + freqs=spectrum.freqs, + weights=spectrum.weights, + ) + joined = concatenate_epochs([spect_arr, spect_arr]) + assert_array_equal(joined.data, np.concatenate([spect_arr.data] * 2)) + assert_array_equal(joined.weights, spect_arr.weights) + assert joined.events is None epochs2 = epochs.copy() epochs_list = [epochs, epochs2] diff --git a/mne/time_frequency/tests/test_spectrum.py b/mne/time_frequency/tests/test_spectrum.py index e77643eca68..0b8ad562456 100644 --- a/mne/time_frequency/tests/test_spectrum.py +++ b/mne/time_frequency/tests/test_spectrum.py @@ -14,7 +14,6 @@ from mne import ( Annotations, BaseEpochs, - concatenate_epochs, create_info, grand_average, make_fixed_length_epochs, @@ -683,11 +682,6 @@ def test_spectrum_array(kind, method, output, average, tmp_path, request): dim_names=dim_names, weights=spectrum.weights, ) - if kind == "epochs": - joined = concatenate_epochs([spect_arr, spect_arr]) - assert_array_equal(joined.data, np.concatenate([data, data])) - assert_array_equal(joined.weights, spectrum.weights) - assert joined.events is None _check_spectrum_equivalent(spectrum, spect_arr, tmp_path) From 3f85f43e7468d22a0b65d4595b575fd151e560bf Mon Sep 17 00:00:00 2001 From: Ishaan Maheshwari Date: Sat, 28 Nov 2026 01:00:58 +0530 Subject: [PATCH 5/5] MAINT: Separate dimension, type, and weight checks in concatenate_epochs --- mne/epochs.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mne/epochs.py b/mne/epochs.py index c55137eb6d3..da494054276 100644 --- a/mne/epochs.py +++ b/mne/epochs.py @@ -6482,12 +6482,12 @@ def _concatenate_epochs( raise ValueError("Spectra must have the same frequencies") if epochs.method != out.method: raise ValueError("Spectra must have the same method") - if ( - tuple(epochs._dims) != tuple(out._dims) - or epochs._data_type != out._data_type - or not np.array_equal(epochs.weights, out.weights) - ): - raise ValueError("Spectrum dimensions, type and weights must match") + if tuple(epochs._dims) != tuple(out._dims): + raise ValueError("Spectra must have the same dimensions") + if epochs._data_type != out._data_type: + raise ValueError("Spectra must have the same data type") + if not np.array_equal(epochs.weights, out.weights): + raise ValueError("Spectra must have the same weights") if (epochs.events is None) != (out.events is None): raise ValueError("Either all or none of the spectra must have events") elif not np.allclose(epochs.times, out.times):