Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changes/dev/14564.newfeature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow :func:`mne.concatenate_epochs` to concatenate :class:`~mne.time_frequency.EpochsSpectrum` instances, by `Aman Srivastava`_ and `Ishaan Maheshwari`_.
96 changes: 66 additions & 30 deletions mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -6445,38 +6450,53 @@ 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
if spectrum:
baseline = tmin = tmax = raw_sfreq = None
shift = len(out.freqs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defining a shift value for events here is tricky. I don't see a "correct" value, but in most cases this will probably be an offset of much fewer samples than the 'epoch end + 10 s' shift set for Epochs inputs. This could also lead to the first event of a concatenated object "starting" before the last one from the previous object should have ended.

I don't think there's anything in MNE that would complain about this. @drammock or @larsoner, do you think this might cause issues when working with the concatenated object, or it's irrelevant?

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)
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"])
# 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
events_offset = int(out.events[:, 0].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):
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):
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 "
Expand All @@ -6486,7 +6506,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"
Expand All @@ -6505,9 +6525,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.")
Expand All @@ -6526,13 +6554,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))
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:
if events_overflow and events is not None:
events[:, 0] = np.arange(1, len(events) + 1)

# Create metadata object (or make it None)
Expand All @@ -6550,9 +6574,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)
Expand Down Expand Up @@ -6584,16 +6609,17 @@ 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.

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
Expand All @@ -6616,7 +6642,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
Expand All @@ -6641,6 +6667,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,
Expand Down
35 changes: 35 additions & 0 deletions mne/tests/test_epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -3868,6 +3869,31 @@ 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])
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]
epochs_conc = concatenate_epochs(epochs_list)
Expand Down Expand Up @@ -4081,6 +4107,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)

Expand Down
Loading