-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
test_epochs.py
5173 lines (4565 loc) · 183 KB
/
test_epochs.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
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import pickle
from copy import deepcopy
from datetime import timedelta
from functools import partial
from io import BytesIO
from pathlib import Path
import numpy as np
import pytest
import scipy.signal
from numpy.fft import rfft, rfftfreq
from numpy.testing import (
assert_allclose,
assert_array_almost_equal,
assert_array_equal,
assert_array_less,
assert_equal,
)
import mne
from mne import (
Annotations,
Epochs,
combine_evoked,
create_info,
equalize_channels,
make_fixed_length_epochs,
make_fixed_length_events,
pick_channels,
pick_events,
pick_types,
read_epochs,
read_events,
read_evokeds,
write_evokeds,
)
from mne._fiff.constants import FIFF
from mne._fiff.proj import _has_eeg_average_ref_proj
from mne._fiff.write import INT32_MAX, _get_split_size, write_float, write_int
from mne.annotations import _handle_meas_date
from mne.baseline import rescale
from mne.chpi import head_pos_to_trans_rot_t, read_head_pos
from mne.datasets import testing
from mne.epochs import (
BaseEpochs,
EpochsArray,
_handle_event_repeated,
average_movements,
bootstrap,
combine_event_ids,
concatenate_epochs,
equalize_epoch_counts,
make_metadata,
)
from mne.event import merge_events
from mne.io import RawArray, read_raw_fif
from mne.preprocessing import maxwell_filter
from mne.utils import (
_dt_to_stamp,
_record_warnings,
assert_meg_snr,
catch_logging,
object_diff,
use_log_level,
)
data_path = testing.data_path(download=False)
fname_raw_testing = data_path / "MEG" / "sample" / "sample_audvis_trunc_raw.fif"
fname_raw_move = data_path / "SSS" / "test_move_anon_raw.fif"
fname_raw_movecomp_sss = data_path / "SSS" / "test_move_anon_movecomp_raw_sss.fif"
fname_raw_move_pos = data_path / "SSS" / "test_move_anon_raw.pos"
base_dir = Path(__file__).parents[1] / "io" / "tests" / "data"
raw_fname = base_dir / "test_raw.fif"
event_name = base_dir / "test-eve.fif"
evoked_nf_name = base_dir / "test-nf-ave.fif"
event_id, tmin, tmax = 1, -0.2, 0.5
event_id_2 = np.int64(2) # to test non Python int types
rng = np.random.RandomState(42)
pytestmark = [
pytest.mark.filterwarnings(
"ignore:The current default of copy=False will change to copy=.*:FutureWarning",
),
]
def _create_epochs_with_annotations():
"""Create test dataset of Epochs with Annotations."""
# set up a test dataset
data = rng.randn(1, 600)
sfreq = 100.0
info = create_info(ch_names=["MEG1"], ch_types=["grad"], sfreq=sfreq)
raw = RawArray(data, info)
# epoch onsets will be at 0.5, 2.5, 4.5s and will be one second long
events = np.zeros((3, 3), dtype=int)
events[:, 0] = (np.array([0.5, 2.5, 4.5]) * sfreq).astype(int)
# make annotations to test various kinds of overlap
# onset dur descr
annots = [
(0.3, 0.0, "no_overlap"),
(0.4, 0.1, "coincident_onset"), # only edge coincides
(0.4, 0.2, "straddles_onset"),
(1.4, 0.2, "straddles_offset"),
(1.5, 0.0, "coincident_offset"), # only edge coincides, zero-dur
(2.6, 0.0, "within_epoch"),
(4.4, 1.2, "surround_epoch"),
(3.4, 1.2, "multiple"),
]
annots = Annotations(*zip(*annots))
raw.set_annotations(annots)
epochs = Epochs(raw, events=events, tmin=0, tmax=1, baseline=None)
return epochs, raw, events
def test_event_repeated():
"""Test epochs takes into account repeated events."""
n_samples = 100
n_channels = 2
ch_names = ["chan%i" % i for i in range(n_channels)]
info = mne.create_info(ch_names=ch_names, sfreq=1000.0)
data = np.zeros((n_channels, n_samples))
raw = mne.io.RawArray(data, info)
events = np.array([[10, 0, 1], [10, 0, 2]])
epochs = mne.Epochs(raw, events, event_repeated="drop")
assert epochs.drop_log == ((), ("DROP DUPLICATE",))
assert_array_equal(epochs.selection, [0])
epochs = mne.Epochs(raw, events, event_repeated="merge")
assert epochs.drop_log == ((), ("MERGE DUPLICATE",))
assert_array_equal(epochs.selection, [0])
def test_handle_event_repeated():
"""Test handling of repeated events."""
# A general test case
EVENT_ID = {"aud": 1, "vis": 2, "foo": 3}
EVENTS = np.array(
[
[0, 0, 1],
[0, 0, 2],
[3, 0, 2],
[3, 0, 1],
[5, 0, 2],
[5, 0, 1],
[5, 0, 3],
[7, 0, 1],
]
)
SELECTION = np.arange(len(EVENTS))
DROP_LOG = ((),) * len(EVENTS)
with pytest.raises(RuntimeError, match="Event time samples were not uniq"):
_handle_event_repeated(
EVENTS,
EVENT_ID,
event_repeated="error",
selection=SELECTION,
drop_log=DROP_LOG,
)
events, event_id, selection, drop_log = _handle_event_repeated(
EVENTS, EVENT_ID, "drop", SELECTION, DROP_LOG
)
assert_array_equal(events, [[0, 0, 1], [3, 0, 2], [5, 0, 2], [7, 0, 1]])
assert_array_equal(events, EVENTS[selection])
unselection = np.setdiff1d(SELECTION, selection)
assert all(drop_log[k] == ("DROP DUPLICATE",) for k in unselection)
assert event_id == {"aud": 1, "vis": 2}
events, event_id, selection, drop_log = _handle_event_repeated(
EVENTS, EVENT_ID, "merge", SELECTION, DROP_LOG
)
assert_array_equal(events[0][-1], events[1][-1])
assert_array_equal(events, [[0, 0, 4], [3, 0, 4], [5, 0, 5], [7, 0, 1]])
assert_array_equal(events[:, :2], EVENTS[selection][:, :2])
unselection = np.setdiff1d(SELECTION, selection)
assert all(drop_log[k] == ("MERGE DUPLICATE",) for k in unselection)
assert set(event_id.keys()) == set(["aud", "aud/vis", "aud/foo/vis"])
assert event_id["aud/vis"] == 4
# Test early return with no changes: no error for wrong event_repeated arg
fine_events = np.array([[0, 0, 1], [1, 0, 2]])
events, event_id, selection, drop_log = _handle_event_repeated(
fine_events, EVENT_ID, "no", [0, 2], DROP_LOG
)
assert event_id == EVENT_ID
assert_array_equal(selection, [0, 2])
assert drop_log == DROP_LOG
assert_array_equal(events, fine_events)
del fine_events
# Test falling back on 0 for heterogeneous "prior-to-event" codes
# order of third column does not determine new event_id key, we always
# take components, sort, and join on "/"
# should make new event_id value: 5 (because 1,2,3,4 are taken)
heterogeneous_events = np.array([[0, 3, 2], [0, 4, 1]])
events, event_id, selection, drop_log = _handle_event_repeated(
heterogeneous_events, EVENT_ID, "merge", [0, 1], deepcopy(DROP_LOG)
)
assert set(event_id.keys()) == set(["aud/vis"])
assert event_id["aud/vis"] == 5
assert_array_equal(selection, [0])
assert drop_log[1] == ("MERGE DUPLICATE",)
assert_array_equal(
events,
np.array(
[
[0, 0, 5],
]
),
)
del heterogeneous_events
# Test keeping a homogeneous "prior-to-event" code (=events[:, 1])
homogeneous_events = np.array([[0, 99, 1], [0, 99, 2], [1, 0, 1], [2, 0, 2]])
events, event_id, selection, drop_log = _handle_event_repeated(
homogeneous_events, EVENT_ID, "merge", [1, 3, 4, 7], deepcopy(DROP_LOG)
)
assert set(event_id.keys()) == set(["aud", "vis", "aud/vis"])
assert_array_equal(events, np.array([[0, 99, 4], [1, 0, 1], [2, 0, 2]]))
assert_array_equal(selection, [1, 4, 7])
assert drop_log[3] == ("MERGE DUPLICATE",)
del homogeneous_events
# Test dropping instead of merging, if event_codes to be merged are equal
equal_events = np.array([[0, 0, 1], [0, 0, 1]])
events, event_id, selection, drop_log = _handle_event_repeated(
equal_events, EVENT_ID, "merge", [3, 5], deepcopy(DROP_LOG)
)
assert_array_equal(
events,
np.array(
[
[0, 0, 1],
]
),
)
assert_array_equal(selection, [3])
assert drop_log[5] == ("MERGE DUPLICATE",)
assert set(event_id.keys()) == set(["aud"])
# new numbers
for vals, want in (((1, 3), 2), ((2, 3), 1), ((1, 2), 3)):
events = np.zeros((2, 3), int)
events[:, 2] = vals
event_id = {str(v): v for v in events[:, 2]}
selection = np.arange(len(events))
drop_log = [tuple() for _ in range(len(events))]
events, event_id, selection, drop_log = _handle_event_repeated(
events, event_id, "merge", selection, drop_log
)
want = np.array([[0, 0, want]])
assert_array_equal(events, want)
def _get_data(preload=False):
"""Get data."""
raw = read_raw_fif(raw_fname, preload=preload, verbose="warning")
events = read_events(event_name)
picks = pick_types(
raw.info,
meg=True,
eeg=True,
stim=True,
ecg=True,
eog=True,
include=["STI 014"],
exclude="bads",
)
return raw, events, picks
reject = dict(grad=1000e-12, mag=4e-12, eeg=80e-6, eog=150e-6)
flat = dict(grad=1e-15, mag=1e-15)
def test_get_data_copy():
"""Test the .get_data() method."""
raw, events, picks = _get_data()
event_id = {"a/1": 1, "a/2": 2, "b/1": 3, "b/2": 4}
epochs = Epochs(raw, events, event_id, preload=True)
# Testing with respect to units param
# more tests in mne/io/tests/test_raw.py::test_get_data_units
# EEG is already in V, so no conversion should take place
d1 = epochs.get_data(picks="eeg", units=None)
d2 = epochs.get_data(picks="eeg", units="V")
assert_array_equal(d1, d2)
with pytest.raises(ValueError, match="is not a valid unit for eeg"):
epochs.get_data(picks="eeg", units="")
with pytest.raises(ValueError, match="cannot be str if there is more"):
epochs.get_data(picks=["eeg", "meg"], units="V")
# Check combination of units with item param, scale only one ch_type
d3 = epochs.get_data(item=[1, 2, 3], units={"grad": "fT/cm"})
assert d3.shape[0] == 3
grad_idxs = np.array([i == "grad" for i in epochs.get_channel_types()])
eeg_idxs = np.array([i == "eeg" for i in epochs.get_channel_types()])
assert_array_equal(
d3[:, grad_idxs, :],
epochs.get_data("grad", item=[1, 2, 3]) * 1e13, # T/m to fT/cm
)
assert_array_equal(d3[:, eeg_idxs, :], epochs.get_data("eeg", item=[1, 2, 3]))
# Test tmin/tmax
data = epochs.get_data(tmin=0)
assert np.all(
data.shape[-1] == epochs._data.shape[-1] - np.nonzero(epochs.times == 0)[0]
)
assert epochs.get_data(tmin=0, tmax=0).size == 0
with pytest.raises(TypeError, match="tmin .* float, None"):
epochs.get_data(tmin=[1], tmax=1)
with pytest.raises(TypeError, match="tmax .* float, None"):
epochs.get_data(tmin=1, tmax=np.ones(5))
# Test copy
data = epochs.get_data(copy=True)
assert not np.shares_memory(data, epochs._data)
with pytest.warns(FutureWarning, match="The current default of copy=False will"):
data = epochs.get_data(verbose="debug")
assert np.shares_memory(data, epochs._data)
assert data is epochs._data
data_orig = data.copy()
# picks, item, and units must be None
data = epochs.get_data(copy=False, picks=[1])
assert not np.shares_memory(data, epochs._data)
data = epochs.get_data(copy=False, item=[0])
assert not np.shares_memory(data, epochs._data)
data = epochs.get_data(copy=False, units=dict(eeg="uV"))
assert not np.shares_memory(data, epochs._data)
# Make sure we didn't mess up our values
assert_allclose(data_orig, epochs._data)
def test_hierarchical():
"""Test hierarchical access."""
raw, events, picks = _get_data()
event_id = {"a/1": 1, "a/2": 2, "b/1": 3, "b/2": 4}
epochs = Epochs(raw, events, event_id, preload=True)
epochs_a1 = epochs["a/1"]
epochs_a2 = epochs["a/2"]
epochs_b1 = epochs["b/1"]
epochs_b2 = epochs["b/2"]
epochs_a = epochs["a"]
assert_equal(len(epochs_a), len(epochs_a1) + len(epochs_a2))
epochs_b = epochs["b"]
assert_equal(len(epochs_b), len(epochs_b1) + len(epochs_b2))
epochs_1 = epochs["1"]
assert_equal(len(epochs_1), len(epochs_a1) + len(epochs_b1))
epochs_2 = epochs["2"]
assert_equal(len(epochs_2), len(epochs_a2) + len(epochs_b2))
epochs_all = epochs[("1", "2")]
assert_equal(len(epochs), len(epochs_all))
assert_array_equal(epochs.get_data(), epochs_all.get_data())
@pytest.mark.slowtest
@testing.requires_testing_data
def test_average_movements():
"""Test movement averaging algorithm."""
# usable data
crop = 0.0, 10.0
origin = (0.0, 0.0, 0.04)
raw = read_raw_fif(fname_raw_move, allow_maxshield="yes")
raw.info["bads"] += ["MEG2443"] # mark some bad MEG channel
raw.crop(*crop).load_data()
raw.filter(None, 20, fir_design="firwin")
events = make_fixed_length_events(raw, event_id)
picks = pick_types(
raw.info, meg=True, eeg=True, stim=True, ecg=True, eog=True, exclude=()
)
epochs = Epochs(
raw, events, event_id, tmin, tmax, picks=picks, proj=False, preload=True
)
with pytest.warns(RuntimeWarning, match="were dropped"):
epochs_proj = Epochs(
raw, events[:1], event_id, tmin, tmax, picks=picks, proj=True, preload=True
)
raw_sss_stat = maxwell_filter(
raw, origin=origin, regularize=None, bad_condition="ignore"
)
del raw
epochs_sss_stat = Epochs(
raw_sss_stat, events, event_id, tmin, tmax, picks=picks, proj=False
)
evoked_sss_stat = epochs_sss_stat.average()
del raw_sss_stat, epochs_sss_stat
head_pos = read_head_pos(fname_raw_move_pos)
trans = epochs.info["dev_head_t"]["trans"]
head_pos_stat = (
np.array([trans[:3, 3]]),
np.array([trans[:3, :3]]),
np.array([0.0]),
)
# SSS-based
pytest.raises(TypeError, average_movements, epochs, None)
evoked_move_non = average_movements(
epochs, head_pos=head_pos, weight_all=False, origin=origin
)
evoked_move_all = average_movements(
epochs, head_pos=head_pos, weight_all=True, origin=origin
)
evoked_stat_all = average_movements(
epochs, head_pos=head_pos_stat, weight_all=True, origin=origin
)
evoked_std = epochs.average()
for ev in (evoked_move_non, evoked_move_all, evoked_stat_all):
assert_equal(ev.nave, evoked_std.nave)
assert_equal(len(ev.info["bads"]), 0)
# substantial changes to MEG data
for ev in (evoked_move_non, evoked_stat_all):
assert_meg_snr(ev, evoked_std, 0.0, 0.1)
pytest.raises(AssertionError, assert_meg_snr, ev, evoked_std, 1.0, 1.0)
meg_picks = pick_types(evoked_std.info, meg=True, exclude=())
assert_allclose(
evoked_move_non.data[meg_picks], evoked_move_all.data[meg_picks], atol=1e-20
)
# compare to averaged movecomp version (should be fairly similar)
raw_sss = read_raw_fif(fname_raw_movecomp_sss)
raw_sss.crop(*crop).load_data()
raw_sss.filter(None, 20, fir_design="firwin")
picks_sss = pick_types(
raw_sss.info, meg=True, eeg=True, stim=True, ecg=True, eog=True, exclude=()
)
assert_array_equal(picks, picks_sss)
epochs_sss = Epochs(
raw_sss, events, event_id, tmin, tmax, picks=picks_sss, proj=False
)
evoked_sss = epochs_sss.average()
assert_equal(evoked_std.nave, evoked_sss.nave)
# this should break the non-MEG channels
pytest.raises(AssertionError, assert_meg_snr, evoked_sss, evoked_move_all, 0.0, 0.0)
assert_meg_snr(evoked_sss, evoked_move_non, 0.02, 2.6)
assert_meg_snr(evoked_sss, evoked_stat_all, 0.05, 3.2)
# these should be close to numerical precision
assert_allclose(evoked_sss_stat.data, evoked_stat_all.data, atol=1e-20)
# pos[0] > epochs.events[0] uses dev_head_t, so make it equivalent
destination = deepcopy(epochs.info["dev_head_t"])
x = head_pos_to_trans_rot_t(head_pos[1])
epochs.info["dev_head_t"]["trans"][:3, :3] = x[1]
epochs.info["dev_head_t"]["trans"][:3, 3] = x[0]
pytest.raises(
AssertionError,
assert_allclose,
epochs.info["dev_head_t"]["trans"],
destination["trans"],
)
evoked_miss = average_movements(
epochs, head_pos=head_pos[2:], origin=origin, destination=destination
)
assert_allclose(evoked_miss.data, evoked_move_all.data, atol=1e-20)
assert_allclose(evoked_miss.info["dev_head_t"]["trans"], destination["trans"])
# degenerate cases
destination["to"] = destination["from"] # bad dest
pytest.raises(
RuntimeError,
average_movements,
epochs,
head_pos,
origin=origin,
destination=destination,
)
pytest.raises(TypeError, average_movements, "foo", head_pos=head_pos)
pytest.raises(
RuntimeError, average_movements, epochs_proj, head_pos=head_pos
) # prj
def _assert_drop_log_types(drop_log):
__tracebackhide__ = True
assert isinstance(drop_log, tuple), "drop_log should be tuple"
assert all(
isinstance(log, tuple) for log in drop_log
), "drop_log[ii] should be tuple"
assert all(
isinstance(s, str) for log in drop_log for s in log
), "drop_log[ii][jj] should be str"
def test_reject():
"""Test epochs rejection."""
raw, events, _ = _get_data()
names = raw.ch_names[::5]
assert "MEG 2443" in names
raw.pick(names).load_data()
assert "eog" in raw
raw.info.normalize_proj()
picks = np.arange(len(raw.ch_names))
# cull the list just to contain the relevant event
events = events[events[:, 2] == event_id, :]
assert len(events) == 7
selection = np.arange(3)
drop_log = ((),) * 3 + (("MEG 2443",),) * 4
_assert_drop_log_types(drop_log)
pytest.raises(TypeError, pick_types, raw)
picks_meg = pick_types(raw.info, meg=True, eeg=False)
pytest.raises(
TypeError,
Epochs,
raw,
events,
event_id,
tmin,
tmax,
picks=picks,
preload=False,
reject="foo",
)
pytest.raises(
ValueError,
Epochs,
raw,
events,
event_id,
tmin,
tmax,
picks=picks_meg,
preload=False,
reject=dict(eeg=1.0),
)
# this one is okay because it's not actually requesting rejection
Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=picks_meg,
preload=False,
reject=dict(eeg=np.inf),
)
# Good function
def my_reject_1(epoch_data):
bad_idxs = np.where(np.percentile(epoch_data, 90, axis=1) > 1e-35)
reasons = "a" * len(bad_idxs[0])
return len(bad_idxs) > 0, reasons
# Bad function
def my_reject_2(epoch_data):
bad_idxs = np.where(np.percentile(epoch_data, 90, axis=1) > 1e-35)
reasons = "a" * len(bad_idxs[0])
return len(bad_idxs), reasons
for val in (-1, -2): # protect against older MNE-C types
for kwarg in ("reject", "flat"):
pytest.raises(
ValueError,
Epochs,
raw,
events,
event_id,
tmin,
tmax,
picks=picks_meg,
preload=False,
**{kwarg: dict(grad=val)},
)
# Check that reject and flat in constructor are not callables
val = my_reject_1
for kwarg in ("reject", "flat"):
with pytest.raises(
TypeError,
match=r".* must be an instance of numeric, got <class 'function'> instead.",
):
Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=picks_meg,
preload=False,
**{kwarg: dict(grad=val)},
)
# Check if callable returns a tuple with reasons
bad_types = [my_reject_2, ("Hi" "Hi"), (1, 1), None]
for val in bad_types: # protect against bad types
for kwarg in ("reject", "flat"):
with pytest.raises(
TypeError,
match=r".* must be an instance of .* got <class '.*'> instead.",
):
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=picks_meg,
preload=True,
)
epochs.drop_bad(**{kwarg: dict(grad=val)})
pytest.raises(
KeyError,
Epochs,
raw,
events,
event_id,
tmin,
tmax,
picks=picks,
preload=False,
reject=dict(foo=1.0),
)
data_7 = dict()
keep_idx = [0, 1, 2]
for preload in (True, False):
for proj in (True, False, "delayed"):
# no rejection
epochs = Epochs(
raw, events, event_id, tmin, tmax, picks=picks, preload=preload
)
_assert_drop_log_types(epochs.drop_log)
pytest.raises(ValueError, epochs.drop_bad, reject="foo")
epochs.drop_bad()
assert_equal(len(epochs), len(events))
assert_array_equal(epochs.selection, np.arange(len(events)))
assert epochs.drop_log == ((),) * 7
if proj not in data_7:
data_7[proj] = epochs.get_data()
assert_array_equal(epochs.get_data(), data_7[proj])
# with rejection
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=picks,
reject=reject,
preload=preload,
)
_assert_drop_log_types(epochs.drop_log)
epochs.drop_bad()
_assert_drop_log_types(epochs.drop_log)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.selection, selection)
assert epochs.drop_log == drop_log
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# rejection post-hoc
epochs = Epochs(
raw, events, event_id, tmin, tmax, picks=picks, preload=preload
)
epochs.drop_bad()
assert_equal(len(epochs), len(events))
assert_array_equal(epochs.get_data(), data_7[proj])
epochs.drop_bad(reject)
assert_equal(len(epochs), len(events) - 4)
assert_equal(len(epochs), len(epochs.get_data()))
assert_array_equal(epochs.selection, selection)
assert epochs.drop_log == drop_log
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# rejection twice
reject_part = dict(grad=1100e-12, mag=4e-12, eeg=80e-6, eog=150e-6)
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=picks,
reject=reject_part,
preload=preload,
)
epochs.drop_bad()
assert_equal(len(epochs), len(events) - 1)
epochs.drop_bad(reject)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.selection, selection)
assert epochs.drop_log == drop_log
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# ensure that thresholds must become more stringent, not less
pytest.raises(ValueError, epochs.drop_bad, reject_part)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
with pytest.warns(RuntimeWarning, match="were dropped"):
epochs.drop_bad(flat=dict(mag=1.0))
assert_equal(len(epochs), 0)
pytest.raises(ValueError, epochs.drop_bad, flat=dict(mag=0.0))
# rejection of subset of trials (ensure array ownership)
reject_part = dict(grad=1100e-12, mag=4e-12, eeg=80e-6, eog=150e-6)
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=picks,
reject=None,
preload=preload,
)
epochs = epochs[:-1]
epochs.drop_bad(reject=reject)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# rejection on annotations
sfreq = raw.info["sfreq"]
onsets = [(event[0] - raw.first_samp) / sfreq for event in events[::2][:3]]
onsets[0] = onsets[0] + tmin - 0.499 # tmin < 0
onsets[1] = onsets[1] + tmax - 0.001
stamp = _dt_to_stamp(raw.info["meas_date"])
first_time = stamp[0] + stamp[1] * 1e-6 + raw.first_samp / sfreq
for orig_time in [None, first_time]:
annot = Annotations(onsets, [0.5, 0.5, 0.5], "BAD", orig_time)
raw.set_annotations(annot)
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=[0],
reject=None,
preload=preload,
)
epochs.drop_bad()
assert_equal(len(events) - 3, len(epochs.events))
assert_equal(epochs.drop_log[0][0], "BAD")
assert_equal(epochs.drop_log[2][0], "BAD")
assert_equal(epochs.drop_log[4][0], "BAD")
raw.set_annotations(None)
# rejection with all None / False arguments: no loading / dropping
epochs = Epochs(
raw,
events,
event_id,
tmin,
tmax,
picks=[0],
reject=None,
flat=None,
reject_by_annotation=False,
reject_tmin=None,
reject_tmax=None,
)
with catch_logging() as log:
epochs.drop_bad(verbose="debug")
log = log.getvalue()
assert "is a noop" in log
def test_reject_by_annotations_reject_tmin_reject_tmax():
"""Test reject_by_annotations with reject_tmin and reject_tmax defined."""
# 10 seconds of data, event at 2s, bad segment from 1s to 1.5s
info = mne.create_info(ch_names=["test_a"], sfreq=1000, ch_types="eeg")
raw = mne.io.RawArray(np.atleast_2d(np.arange(0, 10, 1 / 1000)), info=info)
events = np.array([[2000, 0, 1]])
raw.set_annotations(mne.Annotations(1, 0.5, "BAD"))
# Make the epoch based on the event at 2s, so from 1s to 3s ... assert it
# is rejected due to bad segment overlap from 1s to 1.5s
with pytest.warns(RuntimeWarning, match="were dropped"):
epochs = mne.Epochs(
raw, events, tmin=-1, tmax=1, preload=True, reject_by_annotation=True
)
assert len(epochs) == 0
# Setting `reject_tmin` to prevent rejection of epoch.
epochs = mne.Epochs(
raw,
events,
tmin=-1,
tmax=1,
reject_tmin=-0.2,
preload=True,
reject_by_annotation=True,
)
assert len(epochs) == 1
# Same check but bad segment overlapping from 2.5s to 3s: use `reject_tmax`
raw.set_annotations(mne.Annotations(2.5, 0.5, "BAD"))
epochs = mne.Epochs(
raw,
events,
tmin=-1,
tmax=1,
reject_tmax=0.4,
preload=True,
reject_by_annotation=True,
)
assert len(epochs) == 1
def test_own_data():
"""Test for epochs data ownership (gh-5346)."""
raw, events = _get_data()[:2]
n_epochs = 10
events = events[:n_epochs]
epochs = mne.Epochs(raw, events, preload=True)
assert epochs._data.flags["C_CONTIGUOUS"]
assert epochs._data.flags["OWNDATA"]
epochs.crop(tmin=-0.1, tmax=0.4)
assert len(epochs) == epochs._data.shape[0] == len(epochs.events)
assert len(epochs) == n_epochs
assert not epochs._data.flags["OWNDATA"]
# data ownership value error
epochs.drop_bad(flat=dict(eeg=8e-6))
n_now = len(epochs)
assert 5 < n_now < n_epochs
assert len(epochs) == epochs._data.shape[0] == len(epochs.events)
good_chan = epochs.copy().pick([epochs.ch_names[0]])
good_chan.rename_channels({good_chan.ch_names[0]: "good"})
epochs.add_channels([good_chan])
# "ValueError: resize only works on single-segment arrays"
epochs.drop_bad(flat=dict(eeg=10e-6))
assert 1 < len(epochs) < n_now
def test_decim():
"""Test epochs decimation."""
# First with EpochsArray
dec_1, dec_2 = 2, 3
decim = dec_1 * dec_2
n_epochs, n_channels, n_times = 5, 10, 20
sfreq = 1000.0
sfreq_new = sfreq / decim
data = rng.randn(n_epochs, n_channels, n_times)
events = np.array([np.arange(n_epochs), [0] * n_epochs, [1] * n_epochs]).T
info = create_info(n_channels, sfreq, "eeg")
with info._unlock():
info["lowpass"] = sfreq_new / float(decim)
epochs = EpochsArray(data, info, events)
data_epochs = epochs.copy().decimate(decim).get_data()
data_epochs_2 = epochs.copy().decimate(decim, offset=1).get_data()
data_epochs_3 = epochs.decimate(dec_1).decimate(dec_2).get_data()
assert_array_equal(data_epochs, data[:, :, ::decim])
assert_array_equal(data_epochs_2, data[:, :, 1::decim])
assert_array_equal(data_epochs, data_epochs_3)
# Now let's do it with some real data
raw, events, picks = _get_data()
events = events[events[:, 2] == 1][:2]
raw.load_data().pick([raw.ch_names[pick] for pick in picks[::30]])
raw.info.normalize_proj()
del picks
sfreq_new = raw.info["sfreq"] / decim
with raw.info._unlock():
raw.info["lowpass"] = sfreq_new / 12.0 # suppress aliasing warnings
pytest.raises(ValueError, epochs.decimate, -1)
pytest.raises(ValueError, epochs.decimate, 2, offset=-1)
pytest.raises(ValueError, epochs.decimate, 2, offset=2)
for this_offset in range(decim):
epochs = Epochs(
raw,
events,
event_id,
tmin=-this_offset / raw.info["sfreq"],
tmax=tmax,
baseline=None,
)
idx_offsets = np.arange(decim) + this_offset
for offset, idx_offset in zip(np.arange(decim), idx_offsets):
expected_times = epochs.times[idx_offset::decim]
expected_data = epochs.get_data()[:, :, idx_offset::decim]
must_have = offset / float(epochs.info["sfreq"])
assert np.isclose(must_have, expected_times).any()
ep_decim = epochs.copy().decimate(decim, offset)
assert np.isclose(must_have, ep_decim.times).any()
assert_allclose(ep_decim.times, expected_times)
assert_allclose(ep_decim.get_data(), expected_data)
assert_equal(ep_decim.info["sfreq"], sfreq_new)
# More complicated cases
epochs = Epochs(raw, events, event_id, tmin, tmax)
expected_data = epochs.get_data()[:, :, ::decim]
expected_times = epochs.times[::decim]
for preload in (True, False):
# at init
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=decim, preload=preload)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# split between init and afterward
epochs = Epochs(
raw, events, event_id, tmin, tmax, decim=dec_1, preload=preload
).decimate(dec_2)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
epochs = Epochs(
raw, events, event_id, tmin, tmax, decim=dec_2, preload=preload
).decimate(dec_1)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# split between init and afterward, with preload in between
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=dec_1, preload=preload)
epochs.load_data()
epochs = epochs.decimate(dec_2)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=dec_2, preload=preload)
epochs.load_data()
epochs = epochs.decimate(dec_1)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# decimate afterward
epochs = Epochs(raw, events, event_id, tmin, tmax, preload=preload).decimate(
decim
)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# decimate afterward, with preload in between
epochs = Epochs(raw, events, event_id, tmin, tmax, preload=preload)
epochs.load_data()
epochs.decimate(decim)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info["sfreq"], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# test picks when getting data
picks = [3, 4, 7]
d1 = epochs.get_data(picks=picks)
d2 = epochs.get_data()[:, picks]
assert_array_equal(d1, d2)
def test_base_epochs():
"""Test base epochs class."""
raw = _get_data()[0]
epochs = BaseEpochs(raw.info, None, np.ones((1, 3), int), event_id, tmin, tmax)
pytest.raises(NotImplementedError, epochs.get_data)
# events have wrong dtype (float)
with pytest.raises(TypeError, match="events should be a NumPy array"):
BaseEpochs(raw.info, None, np.ones((1, 3), float), event_id, tmin, tmax)
# events have wrong shape
with pytest.raises(ValueError, match="events must be of shape"):
BaseEpochs(raw.info, None, np.ones((1, 3, 2), int), event_id, tmin, tmax)
# events are tuple (like returned by mne.events_from_annotations)
with pytest.raises(TypeError, match="events should be a NumPy array"):
BaseEpochs(raw.info, None, (np.ones((1, 3), int), {"foo": 1}))
def test_savgol_filter():
"""Test savgol filtering."""
h_freq = 20.0
raw, events = _get_data()[:2]
epochs = Epochs(raw, events, event_id, tmin, tmax)
pytest.raises(RuntimeError, epochs.savgol_filter, 10.0)
epochs = Epochs(raw, events, event_id, tmin, tmax, preload=True)
epochs.pick(picks="grad")
freqs = rfftfreq(len(epochs.times), 1.0 / epochs.info["sfreq"])
data = np.abs(rfft(epochs.get_data()))
pass_mask = freqs <= h_freq / 2.0 - 5.0
stop_mask = freqs >= h_freq * 2 + 5.0
epochs.savgol_filter(h_freq)
data_filt = np.abs(rfft(epochs.get_data()))
# decent in pass-band
assert_allclose(
np.mean(data[:, :, pass_mask], 0),
np.mean(data_filt[:, :, pass_mask], 0),