forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathannotations.py
1744 lines (1504 loc) · 62.9 KB
/
annotations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Authors: Jaakko Leppakangas <[email protected]>
# Robert Luke <[email protected]>
#
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import json
import os.path as op
import re
import warnings
from collections import Counter, OrderedDict
from collections.abc import Iterable
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from itertools import takewhile
from textwrap import shorten
import numpy as np
from scipy.io import loadmat
from ._fiff.constants import FIFF
from ._fiff.open import fiff_open
from ._fiff.tag import read_tag
from ._fiff.tree import dir_tree_find
from ._fiff.write import (
_safe_name_list,
end_block,
start_and_end_file,
start_block,
write_double,
write_float,
write_name_list_sanitized,
write_string,
)
from .utils import (
_check_dict_keys,
_check_dt,
_check_fname,
_check_option,
_check_pandas_installed,
_check_time_format,
_convert_times,
_DefaultEventParser,
_dt_to_stamp,
_is_numeric,
_mask_to_onsets_offsets,
_on_missing,
_pl,
_stamp_to_dt,
_validate_type,
check_fname,
fill_doc,
int_like,
logger,
verbose,
warn,
)
# For testing windows_like_datetime, we monkeypatch "datetime" in this module.
# Keep the true datetime object around for _validate_type use.
_datetime = datetime
def _check_o_d_s_c(onset, duration, description, ch_names):
onset = np.atleast_1d(np.array(onset, dtype=float))
if onset.ndim != 1:
raise ValueError(
f"Onset must be a one dimensional array, got {onset.ndim} (shape "
f"{onset.shape})."
)
duration = np.array(duration, dtype=float)
if duration.ndim == 0 or duration.shape == (1,):
duration = np.repeat(duration, len(onset))
if duration.ndim != 1:
raise ValueError(
f"Duration must be a one dimensional array, got {duration.ndim}."
)
description = np.array(description, dtype=str)
if description.ndim == 0 or description.shape == (1,):
description = np.repeat(description, len(onset))
if description.ndim != 1:
raise ValueError(
f"Description must be a one dimensional array, got {description.ndim}."
)
_safe_name_list(description, "write", "description")
# ch_names: convert to ndarray of tuples
_validate_type(ch_names, (None, tuple, list, np.ndarray), "ch_names")
if ch_names is None:
ch_names = [()] * len(onset)
ch_names = list(ch_names)
for ai, ch in enumerate(ch_names):
_validate_type(ch, (list, tuple, np.ndarray), f"ch_names[{ai}]")
ch_names[ai] = tuple(ch)
for ci, name in enumerate(ch_names[ai]):
_validate_type(name, str, f"ch_names[{ai}][{ci}]")
ch_names = _ndarray_ch_names(ch_names)
if not (len(onset) == len(duration) == len(description) == len(ch_names)):
raise ValueError(
"Onset, duration, description, and ch_names must be "
f"equal in sizes, got {len(onset)}, {len(duration)}, "
f"{len(description)}, and {len(ch_names)}."
)
return onset, duration, description, ch_names
def _ndarray_ch_names(ch_names):
# np.array(..., dtype=object) if all entries are empty will give
# an empty array of shape (n_entries, 0) which is not helpful. So let's
# force it to give us an array of shape (n_entries,) full of empty
# tuples
out = np.empty(len(ch_names), dtype=object)
out[:] = ch_names
return out
@fill_doc
class Annotations:
"""Annotation object for annotating segments of raw data.
.. note::
To convert events to `~mne.Annotations`, use
`~mne.annotations_from_events`. To convert existing `~mne.Annotations`
to events, use `~mne.events_from_annotations`.
Parameters
----------
onset : array of float, shape (n_annotations,)
The starting time of annotations in seconds after ``orig_time``.
duration : array of float, shape (n_annotations,) | float
Durations of the annotations in seconds. If a float, all the
annotations are given the same duration.
description : array of str, shape (n_annotations,) | str
Array of strings containing description for each annotation. If a
string, all the annotations are given the same description. To reject
epochs, use description starting with keyword 'bad'. See example above.
orig_time : float | str | datetime | tuple of int | None
A POSIX Timestamp, datetime or a tuple containing the timestamp as the
first element and microseconds as the second element. Determines the
starting time of annotation acquisition. If None (default),
starting time is determined from beginning of raw data acquisition.
In general, ``raw.info['meas_date']`` (or None) can be used for syncing
the annotations with raw data if their acquisition is started at the
same time. If it is a string, it should conform to the ISO8601 format.
More precisely to this '%%Y-%%m-%%d %%H:%%M:%%S.%%f' particular case of
the ISO8601 format where the delimiter between date and time is ' '.
%(ch_names_annot)s
.. versionadded:: 0.23
See Also
--------
mne.annotations_from_events
mne.events_from_annotations
Notes
-----
Annotations are added to instance of :class:`mne.io.Raw` as the attribute
:attr:`raw.annotations <mne.io.Raw.annotations>`.
To reject bad epochs using annotations, use
annotation description starting with 'bad' keyword. The epochs with
overlapping bad segments are then rejected automatically by default.
To remove epochs with blinks you can do:
>>> eog_events = mne.preprocessing.find_eog_events(raw) # doctest: +SKIP
>>> n_blinks = len(eog_events) # doctest: +SKIP
>>> onset = eog_events[:, 0] / raw.info['sfreq'] - 0.25 # doctest: +SKIP
>>> duration = np.repeat(0.5, n_blinks) # doctest: +SKIP
>>> description = ['bad blink'] * n_blinks # doctest: +SKIP
>>> annotations = mne.Annotations(onset, duration, description) # doctest: +SKIP
>>> raw.set_annotations(annotations) # doctest: +SKIP
>>> epochs = mne.Epochs(raw, events, event_id, tmin, tmax) # doctest: +SKIP
**ch_names**
Specifying channel names allows the creation of channel-specific
annotations. Once the annotations are assigned to a raw instance with
:meth:`mne.io.Raw.set_annotations`, if channels are renamed by the raw
instance, the annotation channels also get renamed. If channels are dropped
from the raw instance, any channel-specific annotation that has no channels
left in the raw instance will also be removed.
**orig_time**
If ``orig_time`` is None, the annotations are synced to the start of the
data (0 seconds). Otherwise the annotations are synced to sample 0 and
``raw.first_samp`` is taken into account the same way as with events.
When setting annotations, the following alignments
between ``raw.info['meas_date']`` and ``annotation.orig_time`` take place:
::
----------- meas_date=XX, orig_time=YY -----------------------------
| +------------------+
|______________| RAW |
| | |
| +------------------+
meas_date first_samp
.
. | +------+
. |_________| ANOT |
. | | |
. | +------+
. orig_time onset[0]
.
| +------+
|___________________| |
| | |
| +------+
orig_time onset[0]'
----------- meas_date=XX, orig_time=None ---------------------------
| +------------------+
|______________| RAW |
| | |
| +------------------+
. N +------+
. o_________| ANOT |
. n | |
. e +------+
.
| +------+
|________________________| |
| | |
| +------+
orig_time onset[0]'
----------- meas_date=None, orig_time=YY ---------------------------
N +------------------+
o______________| RAW |
n | |
e +------------------+
| +------+
|_________| ANOT |
| | |
| +------+
[[[ CRASH ]]]
----------- meas_date=None, orig_time=None -------------------------
N +------------------+
o______________| RAW |
n | |
e +------------------+
. N +------+
. o_________| ANOT |
. n | |
. e +------+
.
N +------+
o________________________| |
n | |
e +------+
orig_time onset[0]'
.. warning::
This means that when ``raw.info['meas_date'] is None``, doing
``raw.set_annotations(raw.annotations)`` will not alter ``raw`` if and
only if ``raw.first_samp == 0``. When it's non-zero,
``raw.set_annotations`` will assume that the "new" annotations refer to
the original data (with ``first_samp==0``), and will be re-referenced to
the new time offset!
**Specific annotation**
``BAD_ACQ_SKIP`` annotation leads to specific reading/writing file
behaviours. See :meth:`mne.io.read_raw_fif` and
:meth:`Raw.save() <mne.io.Raw.save>` notes for details.
""" # noqa: E501
def __init__(self, onset, duration, description, orig_time=None, ch_names=None):
self._orig_time = _handle_meas_date(orig_time)
self.onset, self.duration, self.description, self.ch_names = _check_o_d_s_c(
onset, duration, description, ch_names
)
self._sort() # ensure we're sorted
@property
def orig_time(self):
"""The time base of the Annotations."""
return self._orig_time
def __eq__(self, other):
"""Compare to another Annotations instance."""
if not isinstance(other, Annotations):
return False
return (
np.array_equal(self.onset, other.onset)
and np.array_equal(self.duration, other.duration)
and np.array_equal(self.description, other.description)
and np.array_equal(self.ch_names, other.ch_names)
and self.orig_time == other.orig_time
)
def __repr__(self):
"""Show the representation."""
counter = Counter(self.description)
kinds = ", ".join(["{} ({})".format(*k) for k in sorted(counter.items())])
kinds = (": " if len(kinds) > 0 else "") + kinds
ch_specific = ", channel-specific" if self._any_ch_names() else ""
s = (
f"Annotations | {len(self.onset)} segment"
f"{_pl(len(self.onset))}{ch_specific}{kinds}"
)
return "<" + shorten(s, width=77, placeholder=" ...") + ">"
def __len__(self):
"""Return the number of annotations.
Returns
-------
n_annot : int
The number of annotations.
"""
return len(self.duration)
def __add__(self, other):
"""Add (concatencate) two Annotation objects."""
out = self.copy()
out += other
return out
def __iadd__(self, other):
"""Add (concatencate) two Annotation objects in-place.
Both annotations must have the same orig_time
"""
if len(self) == 0:
self._orig_time = other.orig_time
if self.orig_time != other.orig_time:
raise ValueError(
"orig_time should be the same to add/concatenate 2 annotations (got "
f"{self.orig_time} != {other.orig_time})"
)
return self.append(
other.onset, other.duration, other.description, other.ch_names
)
def __iter__(self):
"""Iterate over the annotations."""
# Figure this out once ahead of time for consistency and speed (for
# thousands of annotations)
with_ch_names = self._any_ch_names()
for idx in range(len(self.onset)):
yield self.__getitem__(idx, with_ch_names=with_ch_names)
def __getitem__(self, key, *, with_ch_names=None):
"""Propagate indexing and slicing to the underlying numpy structure."""
if isinstance(key, int_like):
out_keys = ("onset", "duration", "description", "orig_time")
out_vals = (
self.onset[key],
self.duration[key],
self.description[key],
self.orig_time,
)
if with_ch_names or (with_ch_names is None and self._any_ch_names()):
out_keys += ("ch_names",)
out_vals += (self.ch_names[key],)
return OrderedDict(zip(out_keys, out_vals))
else:
key = list(key) if isinstance(key, tuple) else key
return Annotations(
onset=self.onset[key],
duration=self.duration[key],
description=self.description[key],
orig_time=self.orig_time,
ch_names=self.ch_names[key],
)
@fill_doc
def append(self, onset, duration, description, ch_names=None):
"""Add an annotated segment. Operates inplace.
Parameters
----------
onset : float | array-like
Annotation time onset from the beginning of the recording in
seconds.
duration : float | array-like
Duration of the annotation in seconds.
description : str | array-like
Description for the annotation. To reject epochs, use description
starting with keyword 'bad'.
%(ch_names_annot)s
.. versionadded:: 0.23
Returns
-------
self : mne.Annotations
The modified Annotations object.
Notes
-----
The array-like support for arguments allows this to be used similarly
to not only ``list.append``, but also
`list.extend <https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types>`__.
""" # noqa: E501
onset, duration, description, ch_names = _check_o_d_s_c(
onset, duration, description, ch_names
)
self.onset = np.append(self.onset, onset)
self.duration = np.append(self.duration, duration)
self.description = np.append(self.description, description)
self.ch_names = np.append(self.ch_names, ch_names)
self._sort()
return self
def copy(self):
"""Return a copy of the Annotations.
Returns
-------
inst : instance of Annotations
A copy of the object.
"""
return deepcopy(self)
def delete(self, idx):
"""Remove an annotation. Operates inplace.
Parameters
----------
idx : int | array-like of int
Index of the annotation to remove. Can be array-like to
remove multiple indices.
"""
self.onset = np.delete(self.onset, idx)
self.duration = np.delete(self.duration, idx)
self.description = np.delete(self.description, idx)
self.ch_names = np.delete(self.ch_names, idx)
@fill_doc
def to_data_frame(self, time_format="datetime"):
"""Export annotations in tabular structure as a pandas DataFrame.
Parameters
----------
%(time_format_df_raw)s
.. versionadded:: 1.7
Returns
-------
result : pandas.DataFrame
Returns a pandas DataFrame with onset, duration, and
description columns. A column named ch_names is added if any
annotations are channel-specific.
"""
pd = _check_pandas_installed(strict=True)
valid_time_formats = ["ms", "timedelta", "datetime"]
dt = _handle_meas_date(self.orig_time)
if dt is None:
dt = _handle_meas_date(0)
time_format = _check_time_format(time_format, valid_time_formats, dt)
dt = dt.replace(tzinfo=None)
times = _convert_times(self.onset, time_format, dt)
df = dict(onset=times, duration=self.duration, description=self.description)
if self._any_ch_names():
df.update(ch_names=self.ch_names)
df = pd.DataFrame(df)
return df
def count(self):
"""Count annotations.
Returns
-------
counts : dict
A dictionary containing unique annotation descriptions as keys with their
counts as values.
"""
return count_annotations(self)
def _any_ch_names(self):
return any(len(ch) for ch in self.ch_names)
def _prune_ch_names(self, info, on_missing):
# this prunes channel names and if a given channel-specific annotation
# no longer has any channels left, it gets dropped
keep = set(info["ch_names"])
ch_names = self.ch_names
warned = False
drop_idx = list()
for ci, ch in enumerate(ch_names):
if len(ch):
names = list()
for name in ch:
if name not in keep:
if not warned:
_on_missing(
on_missing,
"At least one channel name in "
f"annotations missing from info: {name}",
)
warned = True
else:
names.append(name)
ch_names[ci] = tuple(names)
if not len(ch_names[ci]):
drop_idx.append(ci)
if len(drop_idx):
self.delete(drop_idx)
return self
@verbose
def save(self, fname, *, overwrite=False, verbose=None):
"""Save annotations to FIF, CSV or TXT.
Typically annotations get saved in the FIF file for raw data
(e.g., as ``raw.annotations``), but this offers the possibility
to also save them to disk separately in different file formats
which are easier to share between packages.
Parameters
----------
fname : path-like
The filename to use.
%(overwrite)s
.. versionadded:: 0.23
%(verbose)s
Notes
-----
The format of the information stored in the saved annotation objects
depends on the chosen file format. :file:`.csv` files store the onset
as timestamps (e.g., ``2002-12-03 19:01:56.676071``),
whereas :file:`.txt` files store onset as seconds since start of the
recording (e.g., ``45.95597082905339``).
"""
check_fname(
fname,
"annotations",
(
"-annot.fif",
"-annot.fif.gz",
"_annot.fif",
"_annot.fif.gz",
".txt",
".csv",
),
)
fname = _check_fname(fname, overwrite=overwrite)
if fname.suffix == ".txt":
_write_annotations_txt(fname, self)
elif fname.suffix == ".csv":
_write_annotations_csv(fname, self)
else:
with start_and_end_file(fname) as fid:
_write_annotations(fid, self)
def _sort(self):
"""Sort in place."""
# instead of argsort here we use sorted so that it gives us
# the onset-then-duration hierarchy
vals = sorted(zip(self.onset, self.duration, range(len(self))))
order = list(list(zip(*vals))[-1]) if len(vals) else []
self.onset = self.onset[order]
self.duration = self.duration[order]
self.description = self.description[order]
self.ch_names = self.ch_names[order]
@verbose
def crop(
self, tmin=None, tmax=None, emit_warning=False, use_orig_time=True, verbose=None
):
"""Remove all annotation that are outside of [tmin, tmax].
The method operates inplace.
Parameters
----------
tmin : float | datetime | None
Start time of selection in seconds.
tmax : float | datetime | None
End time of selection in seconds.
emit_warning : bool
Whether to emit warnings when limiting or omitting annotations.
Defaults to False.
use_orig_time : bool
Whether to use orig_time as an offset.
Defaults to True.
%(verbose)s
Returns
-------
self : instance of Annotations
The cropped Annotations object.
"""
if len(self) == 0:
return self # no annotations, nothing to do
if not use_orig_time or self.orig_time is None:
offset = _handle_meas_date(0)
else:
offset = self.orig_time
if tmin is None:
tmin = timedelta(seconds=self.onset.min()) + offset
if tmax is None:
tmax = timedelta(seconds=(self.onset + self.duration).max()) + offset
for key, val in [("tmin", tmin), ("tmax", tmax)]:
_validate_type(
val, ("numeric", _datetime), key, "numeric, datetime, or None"
)
absolute_tmin = _handle_meas_date(tmin)
absolute_tmax = _handle_meas_date(tmax)
del tmin, tmax
if absolute_tmin > absolute_tmax:
raise ValueError(
f"tmax should be greater than or equal to tmin ({absolute_tmin} < "
f"{absolute_tmax})."
)
logger.debug(f"Cropping annotations {absolute_tmin} - {absolute_tmax}")
onsets, durations, descriptions, ch_names = [], [], [], []
out_of_bounds, clip_left_elem, clip_right_elem = [], [], []
for idx, (onset, duration, description, ch) in enumerate(
zip(self.onset, self.duration, self.description, self.ch_names)
):
# if duration is NaN behave like a zero
if np.isnan(duration):
duration = 0.0
# convert to absolute times
absolute_onset = timedelta(seconds=onset) + offset
absolute_offset = absolute_onset + timedelta(seconds=duration)
out_of_bounds.append(
absolute_onset > absolute_tmax or absolute_offset < absolute_tmin
)
if out_of_bounds[-1]:
clip_left_elem.append(False)
clip_right_elem.append(False)
logger.debug(
f" [{idx}] Dropping "
f"({absolute_onset} - {absolute_offset}: {description})"
)
else:
# clip the left side
clip_left_elem.append(absolute_onset < absolute_tmin)
if clip_left_elem[-1]:
absolute_onset = absolute_tmin
clip_right_elem.append(absolute_offset > absolute_tmax)
if clip_right_elem[-1]:
absolute_offset = absolute_tmax
if clip_left_elem[-1] or clip_right_elem[-1]:
durations.append((absolute_offset - absolute_onset).total_seconds())
else:
durations.append(duration)
onsets.append((absolute_onset - offset).total_seconds())
logger.debug(
f" [{idx}] Keeping "
f"({absolute_onset} - {absolute_offset} -> "
f"{onset} - {onset + duration})"
)
descriptions.append(description)
ch_names.append(ch)
logger.debug(f"Cropping complete (kept {len(onsets)})")
self.onset = np.array(onsets, float)
self.duration = np.array(durations, float)
assert (self.duration >= 0).all()
self.description = np.array(descriptions, dtype=str)
self.ch_names = _ndarray_ch_names(ch_names)
if emit_warning:
omitted = np.array(out_of_bounds).sum()
if omitted > 0:
warn(f"Omitted {omitted} annotation(s) that were outside data range.")
limited = (np.array(clip_left_elem) | np.array(clip_right_elem)).sum()
if limited > 0:
warn(
f"Limited {limited} annotation(s) that were expanding outside the"
" data range."
)
return self
@verbose
def set_durations(self, mapping, verbose=None):
"""Set annotation duration(s). Operates inplace.
Parameters
----------
mapping : dict | float
A dictionary mapping the annotation description to a duration in
seconds e.g. ``{'ShortStimulus' : 3, 'LongStimulus' : 12}``.
Alternatively, if a number is provided, then all annotations
durations are set to the single provided value.
%(verbose)s
Returns
-------
self : mne.Annotations
The modified Annotations object.
Notes
-----
.. versionadded:: 0.24.0
"""
_validate_type(mapping, (int, float, dict))
if isinstance(mapping, dict):
_check_dict_keys(
mapping,
self.description,
valid_key_source="data",
key_description="Annotation description(s)",
)
for stim in mapping:
map_idx = [desc == stim for desc in self.description]
self.duration[map_idx] = mapping[stim]
elif _is_numeric(mapping):
self.duration = np.ones(self.description.shape) * mapping
else:
raise ValueError(
"Setting durations requires the mapping of "
"descriptions to times to be provided as a dict. "
f"Instead {type(mapping)} was provided."
)
return self
@verbose
def rename(self, mapping, verbose=None):
"""Rename annotation description(s). Operates inplace.
Parameters
----------
mapping : dict
A dictionary mapping the old description to a new description,
e.g. {'1.0' : 'Control', '2.0' : 'Stimulus'}.
%(verbose)s
Returns
-------
self : mne.Annotations
The modified Annotations object.
Notes
-----
.. versionadded:: 0.24.0
"""
_validate_type(mapping, dict)
_check_dict_keys(
mapping,
self.description,
valid_key_source="data",
key_description="Annotation description(s)",
)
self.description = np.array([str(mapping.get(d, d)) for d in self.description])
return self
class EpochAnnotationsMixin:
"""Mixin class for Annotations in Epochs."""
@property
def annotations(self): # noqa: D102
return self._annotations
@verbose
def set_annotations(self, annotations, on_missing="raise", *, verbose=None):
"""Setter for Epoch annotations from Raw.
This method does not handle offsetting the times based
on first_samp or measurement dates, since that is expected
to occur in Raw.set_annotations().
Parameters
----------
annotations : instance of mne.Annotations | None
Annotations to set.
%(on_missing_ch_names)s
%(verbose)s
Returns
-------
self : instance of Epochs
The epochs object with annotations.
Notes
-----
Annotation onsets and offsets are stored as time in seconds (not as
sample numbers).
If you have an ``-epo.fif`` file saved to disk created before 1.0,
annotations can be added correctly only if no decimation or
resampling was performed. We thus suggest to regenerate your
:class:`mne.Epochs` from raw and re-save to disk with 1.0+ if you
want to safely work with :class:`~mne.Annotations` in epochs.
Since this method does not handle offsetting the times based
on first_samp or measurement dates, the recommended way to add
Annotations is::
raw.set_annotations(annotations)
annotations = raw.annotations
epochs.set_annotations(annotations)
.. versionadded:: 1.0
"""
_validate_type(annotations, (Annotations, None), "annotations")
if annotations is None:
self._annotations = None
else:
if getattr(self, "_unsafe_annot_add", False):
warn(
"Adding annotations to Epochs created (and saved to disk) before "
"1.0 will yield incorrect results if decimation or resampling was "
"performed on the instance, we recommend regenerating the Epochs "
"and re-saving them to disk."
)
new_annotations = annotations.copy()
new_annotations._prune_ch_names(self.info, on_missing)
self._annotations = new_annotations
return self
def get_annotations_per_epoch(self):
"""Get a list of annotations that occur during each epoch.
Returns
-------
epoch_annots : list
A list of lists (with length equal to number of epochs) where each
inner list contains any annotations that overlap the corresponding
epoch. Annotations are stored as a :class:`tuple` of onset,
duration, description (not as a :class:`~mne.Annotations` object),
where the onset is now relative to time=0 of the epoch, rather than
time=0 of the original continuous (raw) data.
"""
# create a list of annotations for each epoch
epoch_annot_list = [[] for _ in range(len(self.events))]
# check if annotations exist
if self.annotations is None:
return epoch_annot_list
# when each epoch and annotation starts/stops
# no need to account for first_samp here...
epoch_tzeros = self.events[:, 0] / self._raw_sfreq
epoch_starts, epoch_stops = (
np.atleast_2d(epoch_tzeros) + np.atleast_2d(self.times[[0, -1]]).T
)
# ... because first_samp isn't accounted for here either
annot_starts = self._annotations.onset
annot_stops = annot_starts + self._annotations.duration
# the first two cases (annot_straddles_epoch_{start|end}) will both
# (redundantly) capture cases where an annotation fully encompasses
# an epoch (e.g., annot from 1-4s, epoch from 2-3s). The redundancy
# doesn't matter because results are summed and then cast to bool (all
# we care about is presence/absence of overlap).
annot_straddles_epoch_start = np.logical_and(
np.atleast_2d(epoch_starts) >= np.atleast_2d(annot_starts).T,
np.atleast_2d(epoch_starts) < np.atleast_2d(annot_stops).T,
)
annot_straddles_epoch_end = np.logical_and(
np.atleast_2d(epoch_stops) > np.atleast_2d(annot_starts).T,
np.atleast_2d(epoch_stops) <= np.atleast_2d(annot_stops).T,
)
# this captures the only remaining case we care about: annotations
# fully contained within an epoch (or exactly coextensive with it).
annot_fully_within_epoch = np.logical_and(
np.atleast_2d(epoch_starts) <= np.atleast_2d(annot_starts).T,
np.atleast_2d(epoch_stops) >= np.atleast_2d(annot_stops).T,
)
# combine all cases to get array of shape (n_annotations, n_epochs).
# Nonzero entries indicate overlap between the corresponding
# annotation (row index) and epoch (column index).
all_cases = (
annot_straddles_epoch_start
+ annot_straddles_epoch_end
+ annot_fully_within_epoch
)
# for each Epoch-Annotation overlap occurrence:
for annot_ix, epo_ix in zip(*np.nonzero(all_cases)):
this_annot = self._annotations[annot_ix]
this_tzero = epoch_tzeros[epo_ix]
# adjust annotation onset to be relative to epoch tzero...
annot = (
this_annot["onset"] - this_tzero,
this_annot["duration"],
this_annot["description"],
)
# ...then add it to the correct sublist of `epoch_annot_list`
epoch_annot_list[epo_ix].append(annot)
return epoch_annot_list
def add_annotations_to_metadata(self, overwrite=False):
"""Add raw annotations into the Epochs metadata data frame.
Adds three columns to the ``metadata`` consisting of a list
in each row:
- ``annot_onset``: the onset of each Annotation within
the Epoch relative to the start time of the Epoch (in seconds).
- ``annot_duration``: the duration of each Annotation
within the Epoch in seconds.
- ``annot_description``: the free-form text description of each
Annotation.
Parameters
----------
overwrite : bool
Whether to overwrite existing columns in metadata or not.
Default is False.
Returns
-------
self : instance of Epochs
The modified instance (instance is also modified inplace).
Notes
-----
.. versionadded:: 1.0
"""
pd = _check_pandas_installed()
# check if annotations exist
if self.annotations is None:
warn(
f"There were no Annotations stored in {self}, so "
"metadata was not modified."
)
return self
# get existing metadata DataFrame or instantiate an empty one
if self._metadata is not None:
metadata = self._metadata
else:
data = np.empty((len(self.events), 0))
metadata = pd.DataFrame(data=data)
if (
any(
name in metadata.columns
for name in ["annot_onset", "annot_duration", "annot_description"]
)
and not overwrite
):
raise RuntimeError(
"Metadata for Epochs already contains columns "
'"annot_onset", "annot_duration", or "annot_description".'
)
# get the Epoch annotations, then convert to separate lists for
# onsets, durations, and descriptions
epoch_annot_list = self.get_annotations_per_epoch()
onset, duration, description = [], [], []
for epoch_annot in epoch_annot_list:
for ix, annot_prop in enumerate((onset, duration, description)):
entry = [annot[ix] for annot in epoch_annot]
# round onset and duration to avoid IO round trip mismatch
if ix < 2:
entry = np.round(entry, decimals=12).tolist()
annot_prop.append(entry)
# Create a new Annotations column that is instantiated as an empty
# list per Epoch.
metadata["annot_onset"] = pd.Series(onset)
metadata["annot_duration"] = pd.Series(duration)
metadata["annot_description"] = pd.Series(description)
# reset the metadata
self.metadata = metadata
return self
def _combine_annotations(
one, two, one_n_samples, one_first_samp, two_first_samp, sfreq
):
"""Combine a tuple of annotations."""
assert one is not None
assert two is not None
shift = one_n_samples / sfreq # to the right by the number of samples
shift += one_first_samp / sfreq # to the right by the offset
shift -= two_first_samp / sfreq # undo its offset
onset = np.concatenate([one.onset, two.onset + shift])
duration = np.concatenate([one.duration, two.duration])
description = np.concatenate([one.description, two.description])
ch_names = np.concatenate([one.ch_names, two.ch_names])
return Annotations(onset, duration, description, one.orig_time, ch_names)
def _handle_meas_date(meas_date):