-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathtest_spectral.py
1817 lines (1637 loc) · 61.9 KB
/
test_spectral.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
import os
import numpy as np
import pandas as pd
import pytest
from mne import EpochsArray, SourceEstimate, create_info
from mne.filter import filter_data
from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_less
from mne_connectivity import (
SpectralConnectivity,
read_connectivity,
spectral_connectivity_epochs,
spectral_connectivity_time,
)
from mne_connectivity.spectral.epochs import (
_compute_freq_mask,
_compute_freqs,
_get_n_epochs,
)
from mne_connectivity.spectral.epochs_bivariate import _CohEst
def create_test_dataset(
sfreq, n_signals, n_epochs, n_times, tmin, tmax, fstart, fend, trans_bandwidth=2.0
):
"""Create test dataset with no spurious correlations.
Parameters
----------
sfreq : float
The simulated data sampling rate.
n_signals : int
The number of channels/signals to simulate.
n_epochs : int
The number of Epochs to simulate.
n_times : int
The number of time points at which the Epoch data is "sampled".
tmin : int
The start time of the Epoch data.
tmax : int
The end time of the Epoch data.
fstart : int
The frequency at which connectivity starts. The lower end of the
spectral connectivity.
fend : int
The frequency at which connectivity ends. The upper end of the
spectral connectivity.
trans_bandwidth : int, optional
The bandwidth of the filtering operation, by default 2.
Returns
-------
data : np.ndarray of shape (n_epochs, n_signals, n_times)
The epoched dataset.
times_data : np.ndarray of shape (n_times, )
The times at which each sample of the ``data`` occurs at.
"""
# Use a case known to have no spurious correlations (it would bad if
# tests could randomly fail):
rng = np.random.RandomState(0)
data = rng.randn(n_signals, n_epochs * n_times)
times_data = np.linspace(tmin, tmax, n_times)
# simulate connectivity from fstart to fend
data[1, :] = filter_data(
data[0, :],
sfreq,
fstart,
fend,
filter_length="auto",
fir_design="firwin2",
l_trans_bandwidth=trans_bandwidth,
h_trans_bandwidth=trans_bandwidth,
)
# add some noise, so the spectrum is not exactly zero
data[1, :] += 1e-2 * rng.randn(n_times * n_epochs)
data = data.reshape(n_signals, n_epochs, n_times)
data = np.transpose(data, [1, 0, 2])
return data, times_data
def _stc_gen(data, sfreq, tmin, combo=False):
"""Simulate a SourceEstimate generator."""
vertices = [np.arange(data.shape[1]), np.empty(0)]
for d in data:
if not combo:
stc = SourceEstimate(
data=d, vertices=vertices, tmin=tmin, tstep=1 / float(sfreq)
)
yield stc
else:
# simulate a combination of array and source estimate
arr = d[0]
stc = SourceEstimate(
data=d[1:], vertices=vertices, tmin=tmin, tstep=1 / float(sfreq)
)
yield (arr, stc)
@pytest.mark.parametrize("method", ["coh", "cohy", "imcoh", "plv"])
@pytest.mark.parametrize("mode", ["multitaper", "fourier", "cwt_morlet"])
def test_spectral_connectivity_parallel(method, mode, tmp_path):
"""Test saving spectral connectivity with parallel functions."""
# Use a case known to have no spurious correlations (it would bad if
# tests could randomly fail):
rng = np.random.RandomState(0)
trans_bandwidth = 2.0
sfreq = 50.0
n_signals = 3
n_epochs = 8
n_times = 256
n_jobs = 2 # test with parallelization
data = rng.randn(n_signals, n_epochs * n_times)
# simulate connectivity from 5Hz..15Hz
fstart, fend = 5.0, 15.0
data[1, :] = filter_data(
data[0, :],
sfreq,
fstart,
fend,
filter_length="auto",
fir_design="firwin2",
l_trans_bandwidth=trans_bandwidth,
h_trans_bandwidth=trans_bandwidth,
)
# add some noise, so the spectrum is not exactly zero
data[1, :] += 1e-2 * rng.randn(n_times * n_epochs)
data = data.reshape(n_signals, n_epochs, n_times)
data = np.transpose(data, [1, 0, 2])
# define some frequencies for cwt
cwt_freqs = np.arange(3, 24.5, 1)
if method == "coh" and mode == "multitaper":
# only check adaptive estimation for coh to reduce test time
check_adaptive = [False, True]
else:
check_adaptive = [False]
if method == "coh" and mode == "cwt_morlet":
# so we also test using an array for num cycles
cwt_n_cycles = 7.0 * np.ones(len(cwt_freqs))
else:
cwt_n_cycles = 7.0
for adaptive in check_adaptive:
if adaptive:
mt_bandwidth = 1.0
else:
mt_bandwidth = None
con = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=None,
sfreq=sfreq,
mt_adaptive=adaptive,
mt_low_bias=True,
mt_bandwidth=mt_bandwidth,
cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles,
n_jobs=n_jobs,
)
tmp_file = tmp_path / "temp_file.nc"
con.save(tmp_file)
read_con = read_connectivity(tmp_file)
assert_array_almost_equal(con.get_data(), read_con.get_data())
# split `repr` before the file size (`~23 kB` for example)
a = repr(con).split("~")[0]
b = repr(read_con).split("~")[0]
assert a == b
@pytest.mark.parametrize(
"method",
[
"coh",
"cohy",
"imcoh",
"plv",
[
"ciplv",
"ppc",
"pli",
"pli2_unbiased",
"dpli",
"wpli",
"wpli2_debiased",
"coh",
],
],
)
@pytest.mark.parametrize("mode", ["multitaper", "fourier", "cwt_morlet"])
def test_spectral_connectivity(method, mode):
"""Test frequency-domain connectivity methods."""
sfreq = 50.0
n_signals = 3
n_epochs = 8
n_times = 256
trans_bandwidth = 2.0
tmin = 0.0
tmax = (n_times - 1) / sfreq
# 5Hz..15Hz
fstart, fend = 5.0, 15.0
data, times_data = create_test_dataset(
sfreq,
n_signals=n_signals,
n_epochs=n_epochs,
n_times=n_times,
tmin=tmin,
tmax=tmax,
fstart=fstart,
fend=fend,
trans_bandwidth=trans_bandwidth,
)
# First we test some invalid parameters:
pytest.raises(ValueError, spectral_connectivity_epochs, data, method="notamethod")
pytest.raises(ValueError, spectral_connectivity_epochs, data, mode="notamode")
# test invalid fmin fmax settings
pytest.raises(
ValueError,
spectral_connectivity_epochs,
data,
fmin=10,
fmax=10 + 0.5 * (sfreq / float(n_times)),
)
pytest.raises(ValueError, spectral_connectivity_epochs, data, fmin=10, fmax=5)
pytest.raises(
ValueError, spectral_connectivity_epochs, data, fmin=(0, 11), fmax=(5, 10)
)
pytest.raises(
ValueError, spectral_connectivity_epochs, data, fmin=(11,), fmax=(12, 15)
)
# define some frequencies for cwt
cwt_freqs = np.arange(3, 24.5, 1)
if method == "coh" and mode == "multitaper":
# only check adaptive estimation for coh to reduce test time
check_adaptive = [False, True]
else:
check_adaptive = [False]
if method == "coh" and mode == "cwt_morlet":
# so we also test using an array for num cycles
cwt_n_cycles = 7.0 * np.ones(len(cwt_freqs))
else:
cwt_n_cycles = 7.0
for adaptive in check_adaptive:
if adaptive:
mt_bandwidth = 1.0
else:
mt_bandwidth = None
con = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=None,
sfreq=sfreq,
mt_adaptive=adaptive,
mt_low_bias=True,
mt_bandwidth=mt_bandwidth,
cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles,
)
if isinstance(method, list):
this_con = con[0]
else:
this_con = con
freqs = this_con.attrs.get("freqs_used")
n = this_con.n_epochs_used
if isinstance(this_con, SpectralConnectivity):
times = this_con.attrs.get("times_used")
else:
times = this_con.times
assert n == n_epochs
assert_array_almost_equal(times_data, times)
if mode == "multitaper":
upper_t = 0.95
lower_t = 0.5
else: # mode == 'fourier' or mode == 'cwt_morlet'
# other estimates have higher variance
upper_t = 0.8
lower_t = 0.75
# test the simulated signal
gidx = np.searchsorted(freqs, (fstart, fend))
bidx = np.searchsorted(
freqs, (fstart - trans_bandwidth * 2, fend + trans_bandwidth * 2)
)
if method == "coh":
assert np.all(
con.get_data(output="dense")[1, 0, gidx[0] : gidx[1]] > upper_t
), con.get_data()[1, 0, gidx[0] : gidx[1]].min()
# we see something for zero-lag
assert_array_less(con.get_data(output="dense")[1, 0, : bidx[0]], lower_t)
assert np.all(
con.get_data(output="dense")[1, 0, bidx[1] :] < lower_t
), con.get_data()[1, 0, bidx[1:]].max()
elif method == "cohy":
# imaginary coh will be zero
check = np.imag(con.get_data(output="dense")[1, 0, gidx[0] : gidx[1]])
assert np.all(check < lower_t), check.max()
# we see something for zero-lag
assert_array_less(
upper_t, np.abs(con.get_data(output="dense")[1, 0, gidx[0] : gidx[1]])
)
assert_array_less(
np.abs(con.get_data(output="dense")[1, 0, : bidx[0]]), lower_t
)
assert_array_less(
np.abs(con.get_data(output="dense")[1, 0, bidx[1] :]), lower_t
)
elif method == "imcoh":
# imaginary coh will be zero
assert_array_less(
con.get_data(output="dense")[1, 0, gidx[0] : gidx[1]], lower_t
)
assert_array_less(con.get_data(output="dense")[1, 0, : bidx[0]], lower_t)
assert_array_less(con.get_data(output="dense")[1, 0, bidx[1] :], lower_t),
assert np.all(
con.get_data(output="dense")[1, 0, bidx[1] :] < lower_t
), con.get_data()[1, 0, bidx[1] :].max()
# compute a subset of connections using indices and 2 jobs
indices = (np.array([2, 1]), np.array([0, 0]))
if not isinstance(method, list):
test_methods = (method, _CohEst)
else:
test_methods = method
stc_data = _stc_gen(data, sfreq, tmin)
con2 = spectral_connectivity_epochs(
stc_data,
method=test_methods,
mode=mode,
indices=indices,
sfreq=sfreq,
mt_adaptive=adaptive,
mt_low_bias=True,
mt_bandwidth=mt_bandwidth,
tmin=tmin,
tmax=tmax,
cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles,
)
assert isinstance(con2, list)
assert len(con2) == len(test_methods)
freqs2 = con2[0].attrs.get("freqs_used")
if "times" in con2[0].dims:
times2 = con2[0].times
else:
times2 = con2[0].attrs.get("times_used")
n2 = con2[0].n_epochs_used
if method == "coh":
assert_array_almost_equal(con2[0].get_data(), con2[1].get_data())
if not isinstance(method, list):
con2 = con2[0] # only keep the first method
# we get the same result for the probed connections
assert_array_almost_equal(freqs, freqs2)
# "con2" is a raveled array already, so
# simulate setting indices on the full output in "con"
assert_array_almost_equal(
con.get_data(output="dense")[indices], con2.get_data()
)
assert n == n2
assert_array_almost_equal(times_data, times2)
else:
# we get the same result for the probed connections
assert len(con) == len(con2)
for c, c2 in zip(con, con2):
assert_array_almost_equal(freqs, freqs2)
assert_array_almost_equal(
c.get_data(output="dense")[indices], c2.get_data()
)
assert n == n2
assert_array_almost_equal(times_data, times2)
# Test with faverage
# compute same connections for two bands, fskip=1, and f. avg.
fmin = (5.0, 15.0)
fmax = (15.0, 30.0)
con3 = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
fmin=fmin,
fmax=fmax,
fskip=1,
faverage=True,
mt_adaptive=adaptive,
mt_low_bias=True,
mt_bandwidth=mt_bandwidth,
cwt_freqs=cwt_freqs,
cwt_n_cycles=cwt_n_cycles,
)
if isinstance(method, list):
freqs3 = con3[0].attrs.get("freqs_used")
else:
freqs3 = con3.attrs.get("freqs_used")
assert isinstance(freqs3, list)
assert len(freqs3) == len(fmin)
for i in range(len(freqs3)):
_fmin = max(fmin[i], min(cwt_freqs))
_fmax = min(fmax[i], max(cwt_freqs))
assert_allclose(freqs3[i][0], _fmin, atol=1)
assert_allclose(freqs3[i][1], _fmax, atol=1)
# average con2 "manually" and we get the same result
fskip = 1
if not isinstance(method, list):
for i in range(len(freqs3)):
# now we want to get the frequency indices
# create a frequency mask for all bands
n_times = len(con2.attrs.get("times_used"))
# compute frequencies to analyze based on number of samples,
# sampling rate, specified wavelet frequencies and mode
freqs = _compute_freqs(n_times, sfreq, cwt_freqs, mode)
# compute the mask based on specified min/max and decim factor
freq_mask = _compute_freq_mask(freqs, [fmin[i]], [fmax[i]], fskip)
freqs = freqs[freq_mask]
freqs_idx = np.searchsorted(freqs2, freqs)
con2_avg = np.mean(con2.get_data()[:, freqs_idx], axis=1)
assert_array_almost_equal(con2_avg, con3.get_data()[:, i])
else:
for j in range(len(con2)):
for i in range(len(freqs3)):
# now we want to get the frequency indices
# create a frequency mask for all bands
n_times = len(con2[0].attrs.get("times_used"))
# compute frequencies to analyze based on number of
# samples, sampling rate, specified wavelet frequencies
# and mode
freqs = _compute_freqs(n_times, sfreq, cwt_freqs, mode)
# compute the mask based on specified min/max and
# decim factor
freq_mask = _compute_freq_mask(freqs, [fmin[i]], [fmax[i]], fskip)
freqs = freqs[freq_mask]
freqs_idx = np.searchsorted(freqs2, freqs)
con2_avg = np.mean(con2[j].get_data()[:, freqs_idx], axis=1)
assert_array_almost_equal(con2_avg, con3[j].get_data()[:, i])
# test _get_n_epochs
full_list = list(range(10))
out_lens = np.array([len(x) for x in _get_n_epochs(full_list, 4)])
assert (out_lens == np.array([4, 4, 2])).all()
out_lens = np.array([len(x) for x in _get_n_epochs(full_list, 11)])
assert len(out_lens) > 0
assert out_lens[0] == 10
@pytest.mark.parametrize("method", ["cacoh", "mic", "mim", "gc"])
def test_spectral_connectivity_epochs_multivariate(method):
"""Test over-epoch multivariate connectivity methods."""
mode = "multitaper" # stick with single mode in interest of time
sfreq = 100.0 # Hz
n_signals = 4 # should be even!
n_seeds = n_signals // 2
n_epochs = 10
n_times = 200 # samples
trans_bandwidth = 2.0 # Hz
delay = 10 # samples (non-zero delay needed for ImCoh and GC to be >> 0)
indices = (
np.arange(n_seeds)[np.newaxis, :],
np.arange(n_seeds)[np.newaxis, :] + n_seeds,
)
n_targets = n_seeds
# 15-25 Hz connectivity
fstart, fend = 15.0, 25.0
rng = np.random.RandomState(0)
data = rng.randn(n_signals, n_epochs * n_times + delay)
# simulate connectivity from fstart to fend
data[n_seeds:, :] = filter_data(
data[:n_seeds, :],
sfreq,
fstart,
fend,
filter_length="auto",
fir_design="firwin2",
l_trans_bandwidth=trans_bandwidth,
h_trans_bandwidth=trans_bandwidth,
)
# add some noise, so the spectrum is not exactly zero
data[n_seeds:, :] += 1e-2 * rng.randn(n_seeds, n_times * n_epochs + delay)
# shift the seeds to that the targets are a delayed version of them
data[:n_seeds, : n_epochs * n_times] = data[:n_seeds, delay:]
data = data[:, : n_times * n_epochs]
data = data.reshape(n_signals, n_epochs, n_times)
data = np.transpose(data, [1, 0, 2])
con = spectral_connectivity_epochs(
data, method=method, mode=mode, indices=indices, sfreq=sfreq, gc_n_lags=20
)
freqs = con.freqs
gidx = (freqs.index(fstart), freqs.index(fend) + 1)
bidx = (
freqs.index(fstart - trans_bandwidth * 2),
freqs.index(fend + trans_bandwidth * 2) + 1,
)
if method in ["cacoh", "mic", "mim"]:
lower_t = 0.2
upper_t = 0.5
assert np.abs(con.get_data())[0, gidx[0] : gidx[1]].mean() > upper_t
assert np.abs(con.get_data())[0, : bidx[0]].mean() < lower_t
assert np.abs(con.get_data())[0, bidx[1] :].mean() < lower_t
elif method == "gc":
lower_t = 0.2
upper_t = 0.8
assert con.get_data()[0, gidx[0] : gidx[1]].mean() > upper_t
assert con.get_data()[0, : bidx[0]].mean() < lower_t
assert con.get_data()[0, bidx[1] :].mean() < lower_t
# check that target -> seed connectivity is low
indices_ts = (indices[1], indices[0])
con_ts = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices_ts,
sfreq=sfreq,
gc_n_lags=20,
)
assert con_ts.get_data()[0, gidx[0] : gidx[1]].mean() < lower_t
# check that TRGC is positive (i.e. net seed -> target connectivity not
# due to noise)
con_tr = spectral_connectivity_epochs(
data, method="gc_tr", mode=mode, indices=indices, sfreq=sfreq, gc_n_lags=20
)
con_ts_tr = spectral_connectivity_epochs(
data,
method="gc_tr",
mode=mode,
indices=indices_ts,
sfreq=sfreq,
gc_n_lags=20,
)
trgc = (con.get_data() - con_ts.get_data()) - (
con_tr.get_data() - con_ts_tr.get_data()
)
# checks that TRGC is positive and >> 0 (for 15-25 Hz)
assert np.all(trgc[0, gidx[0] : gidx[1]] > 0)
assert np.all(trgc[0, gidx[0] : gidx[1]] > upper_t)
# checks that TRGC is ~ 0 for other frequencies
assert np.allclose(trgc[0, : bidx[0]].mean(), 0, atol=lower_t)
assert np.allclose(trgc[0, bidx[1] :].mean(), 0, atol=lower_t)
# check all-to-all conn. computed for CaCoh/MIC/MIM when no indices given
if method in ["cacoh", "mic", "mim"]:
con = spectral_connectivity_epochs(
data, method=method, mode=mode, indices=None, sfreq=sfreq
)
assert con.indices is None
assert con.n_nodes == n_signals
if method in ["cacoh", "mic"]:
assert np.array(con.attrs["patterns"]).shape[2] == n_signals
# check ragged indices padded correctly
ragged_indices = ([[0]], [[1, 2]])
con = spectral_connectivity_epochs(
data, method=method, mode=mode, indices=ragged_indices, sfreq=sfreq
)
assert np.all(np.array(con.indices) == np.array([[[0, -1]], [[1, 2]]]))
# check shape of CaCoh/MIC patterns
if method in ["cacoh", "mic"]:
for mode in ["multitaper", "cwt_morlet"]:
con = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
fmin=10,
fmax=25,
cwt_freqs=np.arange(10, 25),
faverage=True,
)
if mode == "cwt_morlet":
patterns_shape = (
(n_seeds, len(con.freqs), len(con.times)),
(n_targets, len(con.freqs), len(con.times)),
)
else:
patterns_shape = (
(n_seeds, len(con.freqs)),
(n_targets, len(con.freqs)),
)
assert np.shape(con.attrs["patterns"][0][0]) == patterns_shape[0]
assert np.shape(con.attrs["patterns"][1][0]) == patterns_shape[1]
# only check these once for speed
if mode == "multitaper":
# check patterns averaged over freqs
fmin = (5.0, 15.0)
fmax = (15.0, 30.0)
con = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
fmin=fmin,
fmax=fmax,
faverage=True,
)
assert np.shape(con.attrs["patterns"][0][0])[1] == len(fmin)
assert np.shape(con.attrs["patterns"][1][0])[1] == len(fmin)
# check patterns shape matches input data, not rank
rank = ([1], [1])
con = spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=rank,
)
assert np.shape(con.attrs["patterns"][0][0])[0] == n_seeds
assert np.shape(con.attrs["patterns"][1][0])[0] == n_targets
# check patterns padded correctly
ragged_indices = ([[0]], [[1, 2]])
con = spectral_connectivity_epochs(
data, method=method, mode=mode, indices=ragged_indices, sfreq=sfreq
)
patterns = np.array(con.attrs["patterns"])
patterns_shape = (
(n_seeds, len(con.freqs)),
(n_targets, len(con.freqs)),
)
assert patterns[0, 0].shape == patterns_shape[0]
assert patterns[1, 0].shape == patterns_shape[1]
assert not np.any(np.isnan(patterns[0, 0, 0]))
assert np.all(np.isnan(patterns[0, 0, 1]))
assert not np.any(np.isnan(patterns[1, 0]))
def test_multivariate_spectral_connectivity_epochs_regression():
"""Test multivar. spectral connectivity over epochs for regression.
The multivariate methods were originally implemented in MATLAB by their
respective authors. To show that this Python implementation is identical
and to avoid any future regressions, we compare the results of the Python
and MATLAB implementations on some example data (randomly generated).
As the MNE code for computing the cross-spectral density matrix is not
available in MATLAB, the CSD matrix was computed using MNE and then loaded
into MATLAB to compute the connectivity from the original implementations
using the same processing settings in MATLAB and Python.
It is therefore important that no changes are made to the settings for
computing the CSD or the final connectivity scores!
"""
fpath = os.path.dirname(os.path.realpath(__file__))
data = pd.read_pickle(os.path.join(fpath, "data", "example_multivariate_data.pkl"))
sfreq = 100
indices = ([[0, 1]], [[2, 3]])
methods = ["cacoh", "mic", "mim", "gc", "gc_tr"]
con = spectral_connectivity_epochs(
data,
method=methods,
indices=indices,
mode="multitaper",
sfreq=sfreq,
fskip=0,
faverage=False,
tmin=0,
tmax=None,
mt_bandwidth=4,
mt_low_bias=True,
mt_adaptive=False,
gc_n_lags=20,
rank=tuple([[2], [2]]),
n_jobs=1,
)
mne_results = {}
for this_con in con:
# must take the absolute of the MIC scores, as the MATLAB
# implementation returns the absolute values.
if this_con.method == "mic":
mne_results[this_con.method] = np.abs(this_con.get_data())
else:
mne_results[this_con.method] = this_con.get_data()
matlab_results = pd.read_pickle(
os.path.join(fpath, "data", "example_multivariate_matlab_results.pkl")
)
for method in methods:
assert_allclose(matlab_results[method], mne_results[method], 1e-5)
@pytest.mark.parametrize(
"method",
["cacoh", "mic", "mim", "gc", "gc_tr", ["cacoh", "mic", "mim", "gc", "gc_tr"]],
)
@pytest.mark.parametrize("mode", ["multitaper", "fourier", "cwt_morlet"])
def test_multivar_spectral_connectivity_epochs_error_catch(method, mode):
"""Test error catching for multivar. freq.-domain connectivity methods."""
sfreq = 50.0
n_signals = 4 # Do not change!
n_epochs = 8
n_times = 256
rng = np.random.RandomState(0)
data = rng.randn(n_epochs, n_signals, n_times)
indices = ([[0, 1]], [[2, 3]])
cwt_freqs = np.arange(10, 25 + 1)
# check bad indices without nested array caught
with pytest.raises(
TypeError, match="multivariate indices must contain array-likes"
):
non_nested_indices = ([0, 1], [2, 3])
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=non_nested_indices,
sfreq=sfreq,
gc_n_lags=10,
)
# check bad indices with repeated channels caught
with pytest.raises(
ValueError, match="multivariate indices cannot contain repeated"
):
repeated_indices = ([[0, 1, 1]], [[2, 2, 3]])
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=repeated_indices,
sfreq=sfreq,
gc_n_lags=10,
)
# check mixed methods caught
with pytest.raises(ValueError, match="bivariate and multivariate connectivity"):
if isinstance(method, str):
mixed_methods = [method, "coh"]
elif isinstance(method, list):
mixed_methods = [*method, "coh"]
spectral_connectivity_epochs(
data,
method=mixed_methods,
mode=mode,
indices=indices,
sfreq=sfreq,
cwt_freqs=cwt_freqs,
)
# check bad rank args caught
too_low_rank = ([0], [0])
with pytest.raises(ValueError, match="ranks for seeds and targets must be"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=too_low_rank,
cwt_freqs=cwt_freqs,
)
too_high_rank = ([3], [3])
with pytest.raises(ValueError, match="ranks for seeds and targets must be"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=too_high_rank,
cwt_freqs=cwt_freqs,
)
too_few_rank = ([], [])
with pytest.raises(ValueError, match="rank argument must have shape"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=too_few_rank,
cwt_freqs=cwt_freqs,
)
too_much_rank = ([2, 2], [2, 2])
with pytest.raises(ValueError, match="rank argument must have shape"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=too_much_rank,
cwt_freqs=cwt_freqs,
)
# check rank-deficient data caught
bad_data = data.copy()
bad_data[:, 1] = bad_data[:, 0]
bad_data[:, 3] = bad_data[:, 2]
assert np.all(np.linalg.matrix_rank(bad_data[:, (0, 1), :]) == 1)
assert np.all(np.linalg.matrix_rank(bad_data[:, (2, 3), :]) == 1)
if isinstance(method, str):
rank_con = spectral_connectivity_epochs(
bad_data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
gc_n_lags=10,
cwt_freqs=cwt_freqs,
)
assert rank_con.attrs["rank"] == ([1], [1])
if method in ["cacoh", "mic", "mim"]:
# check rank-deficient transformation matrix caught
with pytest.raises(RuntimeError, match="the transformation matrix"):
spectral_connectivity_epochs(
bad_data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=([2], [2]),
cwt_freqs=cwt_freqs,
)
# only check these once (e.g. only with multitaper) for speed
if method == "gc" and mode == "multitaper":
# check bad n_lags caught
frange = (5, 10)
n_lags = 200 # will be far too high
with pytest.raises(ValueError, match="the number of lags"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
fmin=frange[0],
fmax=frange[1],
gc_n_lags=n_lags,
cwt_freqs=cwt_freqs,
)
# check no indices caught
with pytest.raises(ValueError, match="indices must be specified"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=None,
sfreq=sfreq,
cwt_freqs=cwt_freqs,
)
# check intersecting indices caught
bad_indices = ([[0, 1]], [[0, 2]])
with pytest.raises(
ValueError, match="seed and target indices must not intersect"
):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=bad_indices,
sfreq=sfreq,
cwt_freqs=cwt_freqs,
)
# check bad fmin/fmax caught
with pytest.raises(ValueError, match="computing Granger causality on multiple"):
spectral_connectivity_epochs(
data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
fmin=(10.0, 15.0),
fmax=(15.0, 20.0),
cwt_freqs=cwt_freqs,
)
# check rank-deficient autocovariance caught
with pytest.raises(RuntimeError, match="the autocovariance matrix is singular"):
spectral_connectivity_epochs(
bad_data,
method=method,
mode=mode,
indices=indices,
sfreq=sfreq,
rank=([2], [2]),
cwt_freqs=cwt_freqs,
)
@pytest.mark.parametrize("method", ["cacoh", "mic", "mim", "gc", "gc_tr"])
def test_multivar_spectral_connectivity_parallel(method):
"""Test multivar. freq.-domain connectivity methods run in parallel."""
sfreq = 50.0
n_signals = 4 # Do not change!
n_epochs = 8
n_times = 256
rng = np.random.RandomState(0)
data = rng.randn(n_epochs, n_signals, n_times)
indices = ([[0, 1]], [[2, 3]])
spectral_connectivity_epochs(
data,
method=method,
mode="multitaper",
indices=indices,
sfreq=sfreq,
gc_n_lags=10,
n_jobs=2,
)
spectral_connectivity_time(
data,
freqs=np.arange(10, 25),
method=method,
mode="multitaper",
indices=indices,
sfreq=sfreq,
gc_n_lags=10,
n_jobs=2,
)
def test_multivar_spectral_connectivity_flipped_indices():
"""Test multivar. indices structure maintained by connectivity methods."""
sfreq = 50.0
n_signals = 4
n_epochs = 8
n_times = 256
rng = np.random.RandomState(0)
data = rng.randn(n_epochs, n_signals, n_times)
freqs = np.arange(10, 20)
# if we're not careful, when finding the channels we need to compute the
# CSD for, we might accidentally reorder the connectivity indices
indices = ([[0, 1]], [[2, 3]])
flipped_indices = ([[2, 3]], [[0, 1]])
concat_indices = ([[0, 1], [2, 3]], [[2, 3], [0, 1]])
# we test on GC since this is a directed connectivity measure
method = "gc"
con_st = spectral_connectivity_epochs( # seed -> target
data, method=method, indices=indices, sfreq=sfreq, gc_n_lags=10
)
con_ts = spectral_connectivity_epochs( # target -> seed
data, method=method, indices=flipped_indices, sfreq=sfreq, gc_n_lags=10
)
con_st_ts = spectral_connectivity_epochs( # seed -> target; target -> seed
data, method=method, indices=concat_indices, sfreq=sfreq, gc_n_lags=10
)
assert not np.all(con_st.get_data() == con_ts.get_data())
assert np.all(con_st.get_data()[0] == con_st_ts.get_data()[0])
assert np.all(con_ts.get_data()[0] == con_st_ts.get_data()[1])