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/14565.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.EpochsTFR` instances, by `Aman Srivastava`_ and `Ishaan Maheshwari`_.
67 changes: 47 additions & 20 deletions mne/epochs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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 "
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -6584,16 +6602,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 | EpochsTFR":
"""Concatenate epochs or epoched time-frequency data.

.. 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.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
Expand All @@ -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
Expand All @@ -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,
Expand Down
27 changes: 27 additions & 0 deletions mne/time_frequency/tests/test_tfr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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))
Expand Down
4 changes: 3 additions & 1 deletion mne/time_frequency/tfr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()`
Expand Down
Loading