-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathtest_tfr.py
More file actions
1995 lines (1778 loc) · 73 KB
/
test_tfr.py
File metadata and controls
1995 lines (1778 loc) · 73 KB
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: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import datetime
import re
from itertools import product
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pytest
from matplotlib.collections import PathCollection
from numpy.testing import (
assert_allclose,
assert_array_almost_equal,
assert_array_equal,
assert_equal,
)
import mne
from mne import (
Epochs,
EpochsArray,
create_info,
pick_types,
read_events,
)
from mne.epochs import equalize_epoch_counts
from mne.io import read_raw_fif
from mne.time_frequency import (
AverageTFR,
AverageTFRArray,
EpochsSpectrum,
EpochsTFR,
EpochsTFRArray,
RawTFR,
RawTFRArray,
tfr_array_morlet,
tfr_array_multitaper,
)
from mne.time_frequency.tfr import (
_compute_tfr,
_make_dpss,
combine_tfr,
cwt,
fwhm,
morlet,
read_tfrs,
tfr_morlet,
tfr_multitaper,
write_tfrs,
)
from mne.utils import _import_h5io_funcs, catch_logging, grand_average
from mne.utils._testing import _get_suptitle
from mne.viz.utils import (
_channel_type_prettyprint,
_fake_click,
_fake_keypress,
_fake_scroll,
)
from .test_spectrum import _get_inst
data_path = Path(__file__).parents[2] / "io" / "tests" / "data"
raw_fname = data_path / "test_raw.fif"
event_fname = data_path / "test-eve.fif"
raw_ctf_fname = data_path / "test_ctf_raw.fif"
freqs_linspace = np.linspace(20, 40, num=5)
freqs_unsorted_list = [26, 33, 41, 20]
mag_names = [f"MEG 01{n}1" for n in (1, 2, 3)]
parametrize_morlet_multitaper = pytest.mark.parametrize(
"method", ("morlet", "multitaper")
)
parametrize_power_phase_complex = pytest.mark.parametrize(
"output", ("power", "phase", "complex")
)
parametrize_inst_and_ch_type = pytest.mark.parametrize(
"inst,ch_type",
(
pytest.param("raw_tfr", "mag"),
pytest.param("raw_tfr", "grad"),
pytest.param("epochs_tfr", "mag"), # no grad pairs in epochs fixture
pytest.param("average_tfr", "mag"),
pytest.param("average_tfr", "grad"),
),
)
def test_tfr_ctf():
"""Test that TFRs can be calculated on CTF data."""
raw = read_raw_fif(raw_ctf_fname).crop(0, 1)
raw.apply_gradient_compensation(3)
events = mne.make_fixed_length_events(raw, duration=0.5)
epochs = mne.Epochs(raw, events)
for method in (tfr_multitaper, tfr_morlet):
method(epochs, [10], 1) # smoke test
# Copied from SciPy before it was removed
def _morlet2(M, s, w=5):
x = np.arange(0, M) - (M - 1.0) / 2
x = x / s
wavelet = np.exp(1j * w * x) * np.exp(-0.5 * x**2) * np.pi ** (-0.25)
output = np.sqrt(1 / s) * wavelet
return output
@pytest.mark.parametrize("sfreq", [1000.0, 100 + np.pi])
@pytest.mark.parametrize("freq", [10.0, np.pi])
@pytest.mark.parametrize("n_cycles", [7, 2])
def test_morlet(sfreq, freq, n_cycles):
"""Test morlet with and without zero mean."""
Wz = morlet(sfreq, freq, n_cycles, zero_mean=True)
W = morlet(sfreq, freq, n_cycles, zero_mean=False)
assert np.abs(np.mean(np.real(Wz))) < 1e-5
if n_cycles == 2:
assert np.abs(np.mean(np.real(W))) > 1e-3
else:
assert np.abs(np.mean(np.real(W))) < 1e-5
assert_allclose(np.linalg.norm(W), np.sqrt(2), atol=1e-6)
# Convert to SciPy nomenclature and compare
M = len(W)
w = n_cycles
s = w * sfreq / (2 * freq * np.pi) # from SciPy docs
Ws = _morlet2(M, s, w) * np.sqrt(2)
assert_allclose(W, Ws)
# Check FWHM
fwhm_formula = fwhm(freq, n_cycles)
half_max = np.abs(W).max() / 2.0
fwhm_empirical = (np.abs(W) >= half_max).sum() / sfreq
# Could be off by a few samples
assert_allclose(fwhm_formula, fwhm_empirical, atol=3 / sfreq)
def test_tfr_morlet():
"""Test time-frequency transform (PSD and ITC)."""
# Set parameters
event_id = 1
tmin = -0.2
tmax = 0.498 # Allows exhaustive decimation testing
# Setup for reading the raw data
raw = read_raw_fif(raw_fname)
events = read_events(event_fname)
include = []
exclude = raw.info["bads"] + ["MEG 2443", "EEG 053"] # bads + 2 more
# picks MEG gradiometers
picks = pick_types(
raw.info, meg="grad", eeg=False, stim=False, include=include, exclude=exclude
)
picks = picks[:2]
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks)
data = epochs.get_data()
times = epochs.times
nave = len(data)
epochs_nopicks = Epochs(raw, events, event_id, tmin, tmax)
freqs = np.arange(6, 20, 5) # define frequencies of interest
n_cycles = freqs / 4.0
# Test first with a single epoch
power, itc = tfr_morlet(
epochs[0], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True
)
# Now compute evoked
evoked = epochs.average()
with pytest.raises(ValueError, match="Inter-trial coherence is not supported with"):
tfr_morlet(evoked, freqs, n_cycles=1.0, return_itc=True)
power, itc = tfr_morlet(
epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True
)
power_, itc_ = tfr_morlet(
epochs,
freqs=freqs,
n_cycles=n_cycles,
use_fft=True,
return_itc=True,
decim=slice(0, 2),
)
# Test picks argument and average parameter
pytest.raises(
ValueError,
tfr_morlet,
epochs,
freqs=freqs,
n_cycles=n_cycles,
return_itc=True,
average=False,
)
power_picks, itc_picks = tfr_morlet(
epochs_nopicks,
freqs=freqs,
n_cycles=n_cycles,
use_fft=True,
return_itc=True,
picks=picks,
average=True,
)
epochs_power_picks = tfr_morlet(
epochs_nopicks,
freqs=freqs,
n_cycles=n_cycles,
use_fft=True,
return_itc=False,
picks=picks,
average=False,
)
assert_allclose(epochs_power_picks.data[0, 0, 0, 0], 9.130315e-23, rtol=1e-4)
power_picks_avg = epochs_power_picks.average()
# the actual data arrays here are equivalent, too...
assert_allclose(power.data, power_picks.data)
assert_allclose(power.data, power_picks_avg.data)
assert_allclose(itc.data, itc_picks.data)
# test on evoked
power_evoked = tfr_morlet(evoked, freqs, n_cycles, use_fft=True, return_itc=False)
# one is squared magnitude of the average (evoked) and
# the other is average of the squared magnitudes (epochs PSD)
# so values shouldn't match, but shapes should
assert_array_equal(power.data.shape, power_evoked.data.shape)
with pytest.raises(AssertionError, match="Not equal to tolerance"):
assert_allclose(power.data, power_evoked.data)
# complex output
with pytest.raises(ValueError, match='must be "power" if average=True'):
tfr_morlet(
epochs, freqs, n_cycles, return_itc=False, average=True, output="complex"
)
with pytest.raises(ValueError, match="Inter-trial coher.*average=False"):
tfr_morlet(
epochs, freqs, n_cycles, return_itc=True, average=False, output="complex"
)
epochs_power_complex = tfr_morlet(
epochs, freqs, n_cycles, return_itc=False, average=False, output="complex"
)
epochs_amplitude_2 = abs(epochs_power_complex)
epochs_amplitude_3 = epochs_amplitude_2.copy()
epochs_amplitude_3.data[:] = np.inf # test that it's actually copied
# test that the power computed via `complex` is equivalent to power
# computed within the method.
assert_allclose(epochs_amplitude_2.data**2, epochs_power_picks.data)
# test that aggregating power across tapers when multitaper with
# output='complex' gives the same as output='power'
epoch_data = epochs.get_data()
multitaper_power = tfr_array_multitaper(
epoch_data, epochs.info["sfreq"], freqs, n_cycles, output="power"
)
multitaper_complex, weights = tfr_array_multitaper(
epoch_data,
epochs.info["sfreq"],
freqs,
n_cycles,
output="complex",
return_weights=True,
)
weights = np.expand_dims(weights, axis=(0, 1, -1)) # match shape of complex data
tfr = weights * multitaper_complex
tfr = (tfr * tfr.conj()).real.sum(axis=2)
power_from_complex = tfr * (2 / (weights * weights.conj()).real.sum(axis=2))
assert_allclose(power_from_complex, multitaper_power)
print(itc) # test repr
print(itc.ch_names) # test property
itc += power # test add
itc -= power # test sub
ret = itc * 23 # test mult
itc = ret / 23 # test dic
power = power.apply_baseline(baseline=(-0.1, 0), mode="logratio")
assert power.baseline == (-0.1, 0)
assert "meg" in power
assert "grad" in power
assert "mag" not in power
assert "eeg" not in power
assert power.nave == nave
assert itc.nave == nave
assert power.data.shape == (len(picks), len(freqs), len(times))
assert power.data.shape == itc.data.shape
assert power_.data.shape == (len(picks), len(freqs), 2)
assert power_.data.shape == itc_.data.shape
assert np.sum(itc.data >= 1) == 0
assert np.sum(itc.data <= 0) == 0
# grand average
itc2 = itc.copy()
itc2.info["bads"] = [itc2.ch_names[0]] # test channel drop
gave = grand_average([itc2, itc])
assert gave.data.shape == (
itc2.data.shape[0] - 1,
itc2.data.shape[1],
itc2.data.shape[2],
)
assert itc2.ch_names[1:] == gave.ch_names
assert gave.nave == 2
itc2.drop_channels(itc2.info["bads"])
assert_allclose(gave.data, itc2.data)
itc2.data = np.ones(itc2.data.shape)
itc.data = np.zeros(itc.data.shape)
itc2.nave = 2
itc.nave = 1
itc.drop_channels([itc.ch_names[0]])
combined_itc = combine_tfr([itc2, itc])
assert_allclose(combined_itc.data, np.ones(combined_itc.data.shape) * 2 / 3)
# more tests
power, itc = tfr_morlet(
epochs, freqs=freqs, n_cycles=2, use_fft=False, return_itc=True
)
assert power.data.shape == (len(picks), len(freqs), len(times))
assert power.data.shape == itc.data.shape
assert np.sum(itc.data >= 1) == 0
assert np.sum(itc.data <= 0) == 0
tfr = tfr_morlet(
epochs[0], freqs, use_fft=True, n_cycles=2, average=False, return_itc=False
)
tfr_data = tfr.data[0]
assert tfr_data.shape == (len(picks), len(freqs), len(times))
tfr2 = tfr_morlet(
epochs[0],
freqs,
use_fft=True,
n_cycles=2,
decim=slice(0, 2),
average=False,
return_itc=False,
).data[0]
assert tfr2.shape == (len(picks), len(freqs), 2)
single_power = tfr_morlet(epochs, freqs, 2, average=False, return_itc=False).data
single_power2 = tfr_morlet(
epochs, freqs, 2, decim=slice(0, 2), average=False, return_itc=False
).data
single_power3 = tfr_morlet(
epochs, freqs, 2, decim=slice(1, 3), average=False, return_itc=False
).data
single_power4 = tfr_morlet(
epochs, freqs, 2, decim=slice(2, 4), average=False, return_itc=False
).data
assert_allclose(np.mean(single_power, axis=0), power.data)
assert_allclose(np.mean(single_power2, axis=0), power.data[:, :, :2])
assert_allclose(np.mean(single_power3, axis=0), power.data[:, :, 1:3])
assert_allclose(np.mean(single_power4, axis=0), power.data[:, :, 2:4])
power_pick = power.pick(power.ch_names[:10:2])
assert_equal(len(power_pick.ch_names), len(power.ch_names[:10:2]))
assert_equal(power_pick.data.shape[0], len(power.ch_names[:10:2]))
power_drop = power.drop_channels(power.ch_names[1:10:2])
assert_equal(power_drop.ch_names, power_pick.ch_names)
assert_equal(power_pick.data.shape[0], len(power_drop.ch_names))
power_pick, power_drop = mne.equalize_channels([power_pick, power_drop])
assert_equal(power_pick.ch_names, power_drop.ch_names)
assert_equal(power_pick.data.shape, power_drop.data.shape)
# Test decimation:
# 2: multiple of len(times) even
# 3: multiple odd
# 8: not multiple, even
# 9: not multiple, odd
for decim in [2, 3, 8, 9]:
for use_fft in [True, False]:
power, itc = tfr_morlet(
epochs,
freqs=freqs,
n_cycles=2,
use_fft=use_fft,
return_itc=True,
decim=decim,
)
assert_equal(power.data.shape[2], np.ceil(float(len(times)) / decim))
freqs = list(range(50, 55))
decim = 2
_, n_chan, n_time = data.shape
tfr = tfr_morlet(
epochs[0], freqs, 2.0, decim=decim, average=False, return_itc=False
).data[0]
assert_equal(tfr.shape, (n_chan, len(freqs), n_time // decim))
# Test cwt modes
Ws = morlet(512, [10, 20], n_cycles=2)
pytest.raises(ValueError, cwt, data[0, :, :], Ws, mode="foo")
for use_fft in [True, False]:
for mode in ["same", "valid", "full"]:
cwt(data[0], Ws, use_fft=use_fft, mode=mode)
# Test invalid frequency arguments
with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"):
tfr_morlet(epochs, freqs=np.arange(0, 3), n_cycles=7)
with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"):
tfr_morlet(epochs, freqs=np.arange(-4, -1), n_cycles=7)
# Test decim parameter checks
pytest.raises(
TypeError,
tfr_morlet,
epochs,
freqs=freqs,
n_cycles=n_cycles,
use_fft=True,
return_itc=True,
decim="decim",
)
# When convolving in time, wavelets must not be longer than the data
pytest.raises(ValueError, cwt, data[0, :, : Ws[0].size - 1], Ws, use_fft=False)
with pytest.warns(UserWarning, match="one of the wavelets.*is longer"):
cwt(data[0, :, : Ws[0].size - 1], Ws, use_fft=True)
# Check for off-by-one errors when using wavelets with an even number of
# samples
psd = cwt(data[0], [Ws[0][:-1]], use_fft=False, mode="full")
assert_equal(psd.shape, (2, 1, 420))
def test_dpsswavelet():
"""Test DPSS tapers."""
freqs = np.arange(5, 25, 3)
Ws, weights = _make_dpss(
1000,
freqs=freqs,
n_cycles=freqs / 2.0,
time_bandwidth=4.0,
zero_mean=True,
return_weights=True,
)
assert np.shape(Ws)[:2] == (3, len(freqs)) # 3 tapers expected
assert np.shape(Ws)[:2] == np.shape(weights) # weights of shape (tapers, freqs)
# Check that zero mean is true
assert np.abs(np.mean(np.real(Ws[0][0]))) < 1e-5
@pytest.mark.slowtest
def test_tfr_multitaper():
"""Test tfr_multitaper."""
sfreq = 200.0
ch_names = ["SIM0001", "SIM0002"]
ch_types = ["grad", "grad"]
info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types)
n_times = int(sfreq) # Second long epochs
n_epochs = 3
seed = 42
rng = np.random.RandomState(seed)
noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times)
t = np.arange(n_times, dtype=np.float64) / sfreq
signal = np.sin(np.pi * 2.0 * 50.0 * t) # 50 Hz sinusoid signal
signal[np.logical_or(t < 0.45, t > 0.55)] = 0.0 # Hard windowing
on_time = np.logical_and(t >= 0.45, t <= 0.55)
signal[on_time] *= np.hanning(on_time.sum()) # Ramping
dat = noise + signal
reject = dict(grad=4000.0)
events = np.empty((n_epochs, 3), int)
first_event_sample = 100
event_id = dict(sin50hz=1)
for k in range(n_epochs):
events[k, :] = first_event_sample + k * n_times, 0, event_id["sin50hz"]
epochs = EpochsArray(
data=dat, info=info, events=events, event_id=event_id, reject=reject
)
freqs = np.arange(35, 70, 5, dtype=np.float64)
power, itc = tfr_multitaper(
epochs, freqs=freqs, n_cycles=freqs / 2.0, time_bandwidth=4.0
)
power2, itc2 = tfr_multitaper(
epochs, freqs=freqs, n_cycles=freqs / 2.0, time_bandwidth=4.0, decim=slice(0, 2)
)
picks = np.arange(len(ch_names))
power_picks, itc_picks = tfr_multitaper(
epochs, freqs=freqs, n_cycles=freqs / 2.0, time_bandwidth=4.0, picks=picks
)
power_epochs = tfr_multitaper(
epochs,
freqs=freqs,
n_cycles=freqs / 2.0,
time_bandwidth=4.0,
return_itc=False,
average=False,
)
power_averaged = power_epochs.average()
power_evoked = tfr_multitaper(
epochs.average(),
freqs=freqs,
n_cycles=freqs / 2.0,
time_bandwidth=4.0,
return_itc=False,
average=False,
).average()
print(power_evoked) # test repr for EpochsTFR
# Test channel picking
power_epochs_picked = power_epochs.copy().drop_channels(["SIM0002"])
assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200))
assert_equal(power_epochs_picked.ch_names, ["SIM0001"])
pytest.raises(
ValueError,
tfr_multitaper,
epochs,
freqs=freqs,
n_cycles=freqs / 2.0,
return_itc=True,
average=False,
)
# test picks argument
assert_allclose(power.data, power_picks.data)
assert_allclose(power.data, power_averaged.data)
assert_allclose(power.times, power_epochs.times)
assert_allclose(power.times, power_averaged.times)
assert_equal(power.nave, power_averaged.nave)
assert_equal(power_epochs.data.shape, (3, 2, 7, 200))
assert_allclose(itc.data, itc_picks.data)
# one is squared magnitude of the average (evoked) and
# the other is average of the squared magnitudes (epochs PSD)
# so values shouldn't match, but shapes should
assert_array_equal(power.data.shape, power_evoked.data.shape)
pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data)
tmax = t[np.argmax(itc.data[0, freqs == 50, :])]
fmax = freqs[np.argmax(power.data[1, :, t == 0.5])]
assert tmax > 0.3 and tmax < 0.7
assert not np.any(itc.data < 0.0)
assert fmax > 40 and fmax < 60
assert power2.data.shape == (len(picks), len(freqs), 2)
assert power2.data.shape == itc2.data.shape
# Test decim parameter checks and compatibility between wavelets length
# and instance length in the time dimension.
pytest.raises(
TypeError,
tfr_multitaper,
epochs,
freqs=freqs,
n_cycles=freqs / 2.0,
time_bandwidth=4.0,
decim=(1,),
)
pytest.raises(
ValueError,
tfr_multitaper,
epochs,
freqs=freqs,
n_cycles=1000,
time_bandwidth=4.0,
)
# Test invalid frequency arguments
with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"):
tfr_multitaper(epochs, freqs=np.arange(0, 3), n_cycles=7)
with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"):
tfr_multitaper(epochs, freqs=np.arange(-4, -1), n_cycles=7)
@pytest.mark.parametrize(
"method,freqs",
(
pytest.param("morlet", freqs_linspace, id="morlet"),
pytest.param("multitaper", freqs_linspace, id="multitaper"),
pytest.param("stockwell", freqs_linspace[[0, -1]], id="stockwell"),
),
)
@pytest.mark.parametrize("decim", (4, slice(0, 200), slice(1, 200, 3)))
def test_tfr_decim_and_shift_time(epochs, method, freqs, decim):
"""Test TFR decimation; slices must be long-ish to be longer than the wavelets."""
tfr = epochs.compute_tfr(method, freqs=freqs, decim=decim)
if not isinstance(decim, slice):
decim = slice(None, None, decim)
# check n_times
want = len(range(*decim.indices(len(epochs.times))))
assert tfr.shape[-1] == want
# Check that decim changes sfreq
assert tfr.sfreq == epochs.info["sfreq"] / (decim.step or 1)
# check after-the-fact decimation. The mixin .decimate method doesn't allow slices
if isinstance(decim, int):
tfr2 = epochs.compute_tfr(method, freqs=freqs, decim=1)
tfr2.decimate(decim)
assert tfr == tfr2
# test .shift_time() too
shift = -0.137
data, times, freqs = tfr.get_data(return_times=True, return_freqs=True)
tfr.shift_time(shift, relative=True)
assert_allclose(times + shift, tfr.times, rtol=0, atol=0.5 / tfr.sfreq)
# shift time should only affect times:
assert_array_equal(data, tfr.get_data())
assert_array_equal(freqs, tfr.freqs)
@pytest.mark.slowtest
@pytest.mark.parametrize("inst", ("raw_tfr", "epochs_tfr", "average_tfr"))
def test_tfr_io(inst, average_tfr, request, tmp_path):
"""Test TFR I/O."""
pytest.importorskip("h5io")
pd = pytest.importorskip("pandas")
h5py = pytest.importorskip("h5py")
tfr = _get_inst(inst, request, average_tfr=average_tfr)
fname = tmp_path / "temp_tfr.hdf5"
# test .save() method
tfr.save(fname, overwrite=True)
assert read_tfrs(fname) == tfr
# test save single TFR with write_tfrs()
write_tfrs(fname, tfr, overwrite=True)
assert read_tfrs(fname) == tfr
# test save multiple TFRs with write_tfrs()
tfr2 = tfr.copy()
tfr2._data = np.zeros_like(tfr._data)
write_tfrs(fname, [tfr, tfr2], overwrite=True)
tfr_list = read_tfrs(fname)
assert tfr_list[0] == tfr
assert tfr_list[1] == tfr2
# test condition-related errors
if isinstance(tfr, AverageTFR):
# auto-generated keys: first TFR has comment, so `0` not assigned
tfr2.comment = None
write_tfrs(fname, [tfr, tfr2], overwrite=True)
with pytest.raises(ValueError, match='Cannot find condition "0" in this'):
read_tfrs(fname, condition=0)
# second TFR had no comment, so should get auto-comment `1` assigned
read_tfrs(fname, condition=1)
return
else:
with pytest.raises(NotImplementedError, match="condition is only supported"):
read_tfrs(fname, condition="foo")
# the rest we only do for EpochsTFR (no need to parametrize)
if isinstance(tfr, RawTFR):
return
# make sure everything still works if there's metadata
tfr.metadata = pd.DataFrame(dict(foo=range(tfr.shape[0])), index=tfr.selection)
# test old-style meas date
sec_microsec_tuple = (1, 2)
with tfr.info._unlock():
tfr.info["meas_date"] = sec_microsec_tuple
tfr.save(fname, overwrite=True)
tfr_loaded = read_tfrs(fname)
want = datetime.datetime(
year=1970,
month=1,
day=1,
hour=0,
minute=0,
second=sec_microsec_tuple[0],
microsecond=sec_microsec_tuple[1],
tzinfo=datetime.timezone.utc,
)
assert tfr_loaded.info["meas_date"] == want
with tfr.info._unlock():
tfr.info["meas_date"] = want
assert tfr_loaded == tfr
# test AverageTFR from EpochsTFR.average() can be read (gh-13521)
tfravg = tfr.average()
tfravg.save(fname, overwrite=True)
tfravg_loaded = read_tfrs(fname)
assert tfravg == tfravg_loaded
# test loading with old-style birthday format
fname_multi = tmp_path / "temp_multi_tfr.hdf5"
write_tfrs(fname_multi, tfr) # also check for multiple files from write_tfrs
fname_subject_info = tmp_path / "subject-info.hdf5"
_, write_hdf5 = _import_h5io_funcs()
write_hdf5(fname_subject_info, dict(birthday=(2000, 1, 1)), title="subject_info")
for this_fname in (fname, fname_multi):
with h5py.File(this_fname, "r+") as f:
if f.get("mnepython/key_info/key_subject_info"):
path = "mnepython/key_info/key_subject_info"
else: # multi-files on linux have different path to attrs
path = "mnepython/idx_0/idx_1/key_info/key_subject_info"
del f[path]
f[path] = h5py.ExternalLink(fname_subject_info, "subject_info")
tfr_loaded = read_tfrs(this_fname)
assert isinstance(tfr_loaded.info["subject_info"]["birthday"], datetime.date)
# test with taper dimension and weights
n_tapers = 3 # anything >= 1 should do
weights = np.ones((n_tapers, tfr.shape[2])) # tapers x freqs
state = tfr.__getstate__()
state["data"] = np.repeat(np.expand_dims(tfr.data, 2), n_tapers, axis=2) # add dim
state["weights"] = weights # add weights
state["dims"] = ("epoch", "channel", "taper", "freq", "time") # update dims
tfr = EpochsTFR(inst=state)
tfr.save(fname, overwrite=True)
tfr_loaded = read_tfrs(fname)
assert tfr_loaded == tfr
# test overwrite
with pytest.raises(OSError, match="Destination file exists."):
tfr.save(fname, overwrite=False)
def test_roundtrip_from_legacy_func(epochs, tmp_path):
"""Test save/load with TFRs generated by legacy method (gh-12512)."""
pytest.importorskip("h5io")
fname = tmp_path / "temp_tfr.hdf5"
tfr = tfr_morlet(
epochs, freqs=freqs_linspace, n_cycles=7, average=True, return_itc=False
)
tfr.save(fname, overwrite=True)
assert read_tfrs(fname) == tfr
def test_raw_tfr_init(raw):
"""Test the RawTFR and RawTFRArray constructors."""
one = RawTFR(inst=raw, method="morlet", freqs=freqs_linspace)
two = RawTFRArray(one.info, one.data, one.times, one.freqs, method="morlet")
# some attributes we know won't match:
for attr in ("_data_type", "_inst_type"):
assert getattr(one, attr) != getattr(two, attr)
delattr(one, attr)
delattr(two, attr)
assert one == two
# test RawTFR.__getitem__
data = one[:5]
assert data.shape == (5,) + one.shape[1:]
# test missing method/freqs
with pytest.raises(ValueError, match="RawTFR got unsupported parameter value"):
RawTFR(inst=raw)
def test_average_tfr_init(full_evoked):
"""Test the AverageTFR and AverageTFRArray constructors."""
one = AverageTFR(inst=full_evoked, method="morlet", freqs=freqs_linspace)
two = AverageTFRArray(
one.info,
one.data,
one.times,
one.freqs,
method="morlet",
comment=one.comment,
nave=one.nave,
)
# some attributes we know won't match, otherwise should be identical
assert one._data_type != two._data_type
one._data_type = two._data_type
assert one == two
# test missing method, bad freqs
with pytest.raises(ValueError, match="AverageTFR got unsupported parameter value"):
AverageTFR(inst=full_evoked)
with pytest.raises(ValueError, match='must be a length-2 iterable or "auto"'):
AverageTFR(inst=full_evoked, method="stockwell", freqs=freqs_linspace)
@pytest.mark.parametrize("inst", ("raw_tfr", "epochs_tfr", "average_tfr"))
def test_tfr_init_errors(inst, request, average_tfr):
"""Test __init__ for {Raw,Epochs,Average}TFR."""
# Load data
inst = _get_inst(inst, request, average_tfr=average_tfr)
state = inst.__getstate__()
# Prepare for TFRArray object instantiation
inst_name = inst.__class__.__name__
class_mapping = dict(RawTFR=RawTFR, EpochsTFR=EpochsTFR, AverageTFR=AverageTFR)
ndims_mapping = dict(
RawTFR=("3D or 4D"), EpochsTFR=("4D or 5D"), AverageTFR=("3D or 4D")
)
TFR = class_mapping[inst_name]
allowed_ndims = ndims_mapping[inst_name]
# Check errors caught
with pytest.raises(ValueError, match=f".*TFR data should be {allowed_ndims}"):
TFR(inst=state | dict(data=inst.data[..., 0]))
with pytest.raises(ValueError, match=f".*TFR data should be {allowed_ndims}"):
TFR(inst=state | dict(data=np.expand_dims(inst.data, axis=(0, 1))))
with pytest.raises(ValueError, match="Channel axis of data .* doesn't match info"):
TFR(inst=state | dict(data=inst.data[..., :-1, :, :]))
with pytest.raises(ValueError, match="Time axis of data.*doesn't match times attr"):
TFR(inst=state | dict(times=inst.times[:-1]))
with pytest.raises(ValueError, match="Frequency axis of.*doesn't match freqs attr"):
TFR(inst=state | dict(freqs=inst.freqs[:-1]))
@pytest.mark.parametrize(
"method,freqs,match",
(
("morlet", None, "EpochsTFR got unsupported parameter value freqs=None."),
(None, freqs_linspace, "got unsupported parameter value method=None."),
(None, None, "got unsupported parameter values method=None and freqs=None."),
),
)
def test_compute_tfr_init_errors(epochs, method, freqs, match):
"""Test that method and freqs are always passed (if not using __setstate__)."""
with pytest.raises(ValueError, match=match):
epochs.compute_tfr(method=method, freqs=freqs)
def test_equalize_epochs_tfr_counts(epochs_tfr):
"""Test equalize_epoch_counts for EpochsTFR."""
# make the fixture have 3 epochs instead of 1
epochs_tfr._data = np.vstack((epochs_tfr._data, epochs_tfr._data, epochs_tfr._data))
tfr2 = epochs_tfr.copy()
tfr2 = tfr2[:-1]
equalize_epoch_counts([epochs_tfr, tfr2])
assert epochs_tfr.shape == tfr2.shape
def test_dB_computation():
"""Test dB computation in plot methods (gh 11091)."""
ampl = 2.0
data = np.full((3, 2, 3), ampl**2) # already power
complex_data = np.full((3, 2, 3), ampl + 0j) # ampl → power when plotting
times = np.array([0.1, 0.2, 0.3])
freqs = np.array([0.10, 0.20])
info = mne.create_info(
["MEG 001", "MEG 002", "MEG 003"], 1000.0, ["mag", "mag", "mag"]
)
kwargs = dict(times=times, freqs=freqs, nave=20, comment="test", method="crazy-tfr")
tfr = AverageTFRArray(info=info, data=data, **kwargs)
complex_tfr = AverageTFRArray(info=info, data=complex_data, **kwargs)
plot_kwargs = dict(dB=True, combine="mean", vlim=(0, 7))
fig1 = tfr.plot(**plot_kwargs)[0]
fig2 = complex_tfr.plot(**plot_kwargs)[0]
# since we're fixing vmin/vmax, equal colors should mean ~equal input data
quadmesh1 = fig1.axes[0].collections[0]
quadmesh2 = fig2.axes[0].collections[0]
if hasattr(quadmesh1, "_mapped_colors"): # fails on compat/old
assert_array_equal(quadmesh1._mapped_colors, quadmesh2._mapped_colors)
def test_plot():
"""Test TFR plotting."""
data = np.zeros((3, 2, 3))
times = np.array([0.1, 0.2, 0.3])
freqs = np.array([0.10, 0.20])
info = mne.create_info(
["MEG 001", "MEG 002", "MEG 003"], 1000.0, ["mag", "mag", "mag"]
)
tfr = AverageTFRArray(
info=info,
data=data,
times=times,
freqs=freqs,
nave=20,
comment="test",
method="crazy-tfr",
)
# interactive mode on by default
fig = tfr.plot(picks=[1], cmap="RdBu_r")[0]
_fake_keypress(fig, "up")
_fake_keypress(fig, " ")
_fake_keypress(fig, "down")
_fake_keypress(fig, " ")
_fake_keypress(fig, "+")
_fake_keypress(fig, " ")
_fake_keypress(fig, "-")
_fake_keypress(fig, " ")
_fake_keypress(fig, "pageup")
_fake_keypress(fig, " ")
_fake_keypress(fig, "pagedown")
cbar = fig.get_axes()[0].CB # Fake dragging with mouse.
ax = cbar.cbar.ax
_fake_click(fig, ax, (0.1, 0.1))
_fake_click(fig, ax, (0.1, 0.2), kind="motion")
_fake_click(fig, ax, (0.1, 0.3), kind="release")
_fake_click(fig, ax, (0.1, 0.1), button=3)
_fake_click(fig, ax, (0.1, 0.2), button=3, kind="motion")
_fake_click(fig, ax, (0.1, 0.3), kind="release")
_fake_scroll(fig, 0.5, 0.5, -0.5) # scroll down
_fake_scroll(fig, 0.5, 0.5, 0.5) # scroll up
plt.close("all")
@pytest.mark.parametrize("output", ("complex", "phase"))
def test_plot_multitaper_complex_phase(output):
"""Test TFR plotting of data with a taper dimension."""
# Create example data with a taper dimension
n_chans, n_tapers, n_freqs, n_times = (3, 4, 2, 3)
data = np.random.rand(n_chans, n_tapers, n_freqs, n_times)
if output == "complex":
data = data + np.random.rand(*data.shape) * 1j # add imaginary data
times = np.arange(n_times)
freqs = np.arange(n_freqs)
weights = np.random.rand(n_tapers, n_freqs)
info = mne.create_info(n_chans, 1000.0, "eeg")
tfr = AverageTFRArray(
info=info, data=data, times=times, freqs=freqs, weights=weights
)
# Check that plotting works
tfr.plot()
@pytest.mark.parametrize(
"timefreqs,title,combine",
(
pytest.param(
{(0.33, 23): (0, 0), (0.25, 30): (0.1, 2)},
"0.25 ± 0.05 s,\n30.0 ± 1.0 Hz",
"mean",
id="dict,mean",
),
pytest.param([(0.25, 30)], "0.25 s,\n30.0 Hz", "rms", id="list,rms"),
pytest.param(None, None, lambda x: x.mean(axis=0), id="none,lambda"),
),
)
@parametrize_inst_and_ch_type
def test_tfr_plot_joint(
inst, ch_type, combine, timefreqs, title, full_average_tfr, request
):
"""Test {Raw,Epochs,Average}TFR.plot_joint()."""
tfr = _get_inst(inst, request, average_tfr=full_average_tfr)
with catch_logging() as log:
fig = tfr.plot_joint(
picks=ch_type,
timefreqs=timefreqs,
combine=combine,
topomap_args=dict(res=8, contours=0, sensors=False), # for speed
verbose="debug",
)
assert f"Plotting topomap for {ch_type} data" in log.getvalue()
# check for correct number of axes
n_topomaps = 1 if timefreqs is None else len(timefreqs)
assert len(fig.axes) == n_topomaps + 2 # n_topomaps + 1 image + 1 colorbar
# title varies by `ch_type` when `timefreqs=None`, so we don't test that here
if title is not None:
assert fig.axes[0].get_title() == title
# test interactivity
ax = [ax for ax in fig.axes if ax.get_xlabel() == "Time (s)"][0]
kw = dict(fig=fig, ax=ax, xform="ax")
_fake_click(**kw, kind="press", point=(0.4, 0.4))
_fake_click(**kw, kind="motion", point=(0.5, 0.5))
_fake_click(**kw, kind="release", point=(0.6, 0.6))
# make sure we actually got a pop-up figure, and it has a plausible title
fignums = plt.get_fignums()
assert len(fignums) == 2
popup_fig = plt.figure(fignums[-1])
assert re.match(
r"-?\d{1,2}\.\d{3} - -?\d{1,2}\.\d{3} s,\n\d{1,2}\.\d{2} - \d{1,2}\.\d{2} Hz",
_get_suptitle(popup_fig),
)
@pytest.mark.parametrize(
"match,timefreqs,topomap_args",
(
(r"Requested time point \(-88.000 s\) exceeds the range of", [(-88, 1)], None),
(r"Requested frequency \(99.0 Hz\) exceeds the range of", [(0.0, 99)], None),
("list of tuple pairs, or a dict of such tuple pairs, not 0", [0.0], None),
("does not match the channel type present in", None, dict(ch_type="eeg")),
),
)
def test_tfr_plot_joint_errors(full_average_tfr, match, timefreqs, topomap_args):
"""Test AverageTFR.plot_joint() error messages."""
with pytest.raises(ValueError, match=match):
full_average_tfr.plot_joint(timefreqs=timefreqs, topomap_args=topomap_args)
def test_tfr_plot_joint_doesnt_modify(full_average_tfr):
"""Test that the object is unchanged after plot_joint()."""
tfr = full_average_tfr.copy()
full_average_tfr.plot_joint()
assert tfr == full_average_tfr
def test_add_channels():
"""Test tfr splitting / re-appending channel types."""
data = np.zeros((6, 2, 3))
times = np.array([0.1, 0.2, 0.3])
freqs = np.array([0.10, 0.20])
info = mne.create_info(
["MEG 001", "MEG 002", "MEG 003", "EEG 001", "EEG 002", "STIM 001"],
1000.0,
["mag", "mag", "mag", "eeg", "eeg", "stim"],
)
tfr = AverageTFRArray(
info=info,
data=data,
times=times,
freqs=freqs,
nave=20,
comment="test",
method="crazy-tfr",
)
tfr_eeg = tfr.copy().pick(picks="eeg")