-
Notifications
You must be signed in to change notification settings - Fork 1
/
pac_man.m
760 lines (657 loc) · 35.4 KB
/
pac_man.m
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
% pac_man() - Computes phase-amplitude coupling measure. Requires inputs
% from pac_pop_main.
%
% Usage:
% >> EEG = pac_man(EEG, varargin);
% >> EEG = pac_man(EEG, 'lfoPhase', [1,4], 'hfoAmp', [80,300],...
% 'hfoTopRatio', 10, 'hfoPool', 1, 'whichMarker', 1,...
% 'windowLength', [], 'alpha', 0.05, 'numSurro', 500,...
% 'numPhaseBin', 30);
%
% Input arguments (ALL necessary):
% lfoPhase : Band-pass frequencies for low-frequency phase.
% hfoAmp : Band-pass frequencies for high-frequency oscillation
% (HFO) amplitude.
% hfoTopRatio : Highest amplitude rate in HFO (unit: percent)
% hfoPool : 1, each channel (default); 2, all channels; 3, use
% user-selected event markers generated by Mobilab-based
% single-channel event marking tool developed for
% Children's Hospital of Michigan (not generally available;
% if interested, please email Makoto Miyakoshi); 4, use
% user-selected event markers generated by EEGLAB. When
% this option is selected, phase-amplitude coupling is
% computed from the data points at windows centered at
% the preselected events. The surrogate statistics is
% calculated by using the same data points for the
% amplitude but different data points sampled from all
% the valid (i.e. not within +/- 1-s window from the
% 'boundary') data points.
% for the optimal automatic processes.
% whichMarker : When user-selected event marker is specified for 'hfoPool',
% select the type of event to use for event markers.
% Otherwise, can be left empty. The index of the event
% marker used can be identified by running
% eventTypes = unique({EEG.event.type}).
% windowLength : When user-selected event marker is specified for 'hfoPool',
% select the window length. Ex. 500 means a window of
% +/- 500 ms from the center of the event marker will be
% used for a window. Overlapped winodws are not counted
% only once.
% alpha : statistical significance level. Eg. 0.05 -> 5% level.
% numSurro : Number of iteration for surrogation test. This test
% method is explained in Canolty et al. (2006). For a
% preliminary test, use 200-500. For publication, use 2000-.
% numPhaseBin : Number of equidistant phase bins. Increasing this
% number results in increase of statistical power. Use
% 20-30 for start.
%
% Outputs: All outputs are located in EEG.pac.
% analyticEEG : Band-pass filterd low-frequency phase coupled with
% band-pass filtered high-frequency oscillation
% amplitude. Same size as EEG.data.
% hfoIndex : Data indices of selected highest amplitudes.
% angleMean : Mean angles of data selected with hfoIndex.
% vectLength : Resultant vector length of data selected with hfoIndex.
% vectLengthVar : Variance of the resultant vector length.
% histBinMax : Maximum values in histograms for drawing graphs.
% phaseProbability : Number of data count in each phase bins.
% phaseSrotedAmp : Mean amplitdes of each phase bins.
% phaseSortedAmpSe : Standard errors of amplitdes in each phase bins.
%
% When hfoPool==4 (i.e. event-related window-wise PAC), the following items are generated and stored.
% windowMeanAmp : Mean high-freq amp across selected widnows.
% windowStdAmp : Standard dev. of high-freq amp across selected widnows.
% windowMeanPhase : Circular-mean low-freq amp across selected widnows.
% windowStdPhase : Circular-std low-freq amp across selected widnows.
%
% These four structures contains results from different multiple comparison corrections.
% uncorrected : Channel-wise multiple comparison uncorrected.
% Bonferroni : Channel-wise multiple comparison with Bonferroni.
% BonfHolm : Channel-wise multiple comparison with Bonferroni-Holm.
% FDR : Channel-wise multiple comparison with false discovery rate.
%
% Each of the structure contains p-values from various tests:
% MIpval : Results from phase permutation on Modulation Index.
% phaseRayleighPval : Results from Rayleigh test on phase distribution.
% phaseOmniTestPval : Results from Omnibus test on phase distribution.
% phaseRaoSpacePval : Results from Rao's spacing test on phase distribution.
% This is currently not used for weired results.
% phaseChi2GofPval : Results from Chi-square goodness of fit test on phase distribution.
% phaseKstestPval : Results from Kolmogorov-Smirnov test on phase distribution.
% ampChi2GofPval : Results from Chi-square goodness of fit test on phase-bin-mean amplitude across phase bins.
% ampKstestPval : Results from Kolmogorov-Smirnov test on phase-bin-mean amplitude across phase bins.
%
% In the MIpval, the observed Modulation Index is tested against the null
% hypothesis that there is no phase-amplitude coupling in the observed data.
% In the phaseXXXPval, the phase distribution of the HFO-indexed data are tested
% against the null hypothesis that the observed phase distributions are uniform.
% In the ampXXXPval, the phase-bin-mean amplitudes are tested against the
% null hypothesis that the observed phase-bin-mean amplitudes are uniformly
% distributed.
%
% Note that all of these statistics except for MIpval are critically affected
% by numPhaseBin. If you set numPhaseBin to 10000 (suppose your data is longer
% than that), p-value will be ridiculously small (such as 1.616199e-35).
%
% External toolbox dependency:
% Berens (2009) circstat: A MATLAB toolbox for circular statistics. J stat softw. 31.
% History:
% 08/16/2024 Makoto and Henrico. Supported PAC-ERP visualization suggested by Henrioco Stam, Erasmus University.
% 08/14/2024 Makoto. Fixed whichMarker-1 to whichMarker. Rewrote the stats.
% 08/09/2024 Makoto. Fix request by Henrico. 'hfoPool', '4' is added.
% 01/13/2021 Makoto. Checked for moving to Github.
% 11/04/2020 Makoto. Removing 1-s data before and after data edges and boundaries to avoid filter's edge effect for window-rejected data.
% 07/24/2019 Makoto. 'binValue' size mismatch issue fixed again. Thanks Brian Kavanaugh!
% 05/10/2019 Makoto. 'binValue' size mismatch issue fixed. Thanks Brian Kavanaugh!
% 02/01/2017 ver 5.2 by Makoto. Abnormally low amplitude channel error added.
% 06/03/2014 ver 5.1 by Makoto. phasebin+1 changed.
% 06/21/2013 ver 5.0 by Makoto. Watson-Williams test added.
% 04/16/2013 ver 4.1 by Makoto. Confidence Interval option added.
% 12/26/2012 ver 4.0 by Makoto. Optimized for Matrix calculation. Statistics upgraded. Help written.
% 11/02/2012 ver 3.0 by Makoto. Statistics and AA added.
% 10/31/2012 ver 2.1 by Makoto. fixed EEG.pac.maskESC_N = pacAllChan4 < critical4N;
% 10/22/2012 ver 2.0 by Makoto. Made into a part of plugin.
% 09/18/2012 ver 1.1 by Makoto. More accurate window length. EEG.pac.
% 09/14/2012 ver 1.0 by Makoto. Prototype created.
% Copyright (C) 2012 Makoto Miyakoshi, JSPS/SCCN,INC,UCSD; Cincinnati Children's Hospital.
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function EEG = pac_man(EEG, varargin)
%%%%%%%%%%%%%%%%%%%
%%% input check %%%
%%%%%%%%%%%%%%%%%%%
if nargin < 18
help pac_man
return
end
result = finputcheck(varargin, {...
'lfoPhase' 'real' [0 Inf] []
'hfoAmp' 'real' [0 Inf] []
'hfoTopRatio' 'real' [0 100] []
'hfoPool' 'integer' [1 3] []
'whichMarker' 'integer' [1 Inf] []
'windowLength' 'integer' [1 Inf] []
'alpha' 'real' [0 100] []
'numSurro' 'integer' [1 Inf] []
'numPhaseBin' 'integer' [1 Inf] []});
if ischar(result), error(result); end
clear result
% Check dead channels
allChanStd = std(EEG.data, [], 2);
allChanStdRatio = allChanStd/median(allChanStd);
if any(allChanStdRatio<0.001)
badChanIdx = find(allChanStdRatio<0.001); % 06/19/2020 Makoto. Loosened.
for chIdx = 1:length(badChanIdx)
fprintf('Channel %.0f have abnormally low SD. Remove this channel from analysis.\n', badChanIdx(chIdx))
end
error('Use ''Edit''->''Select data'' to remove the channels above.')
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% remove existing pac %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(EEG, 'pac')
EEG = rmfield(EEG, 'pac');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% initial parameter setting %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lfoPhaseInput = vararginReader('lfoPhase', varargin);
hfoAmpInput = vararginReader('hfoAmp', varargin);
hfoTopRatioInput = vararginReader('hfoTopRatio', varargin);
hfoPoolInput = vararginReader('hfoPool', varargin);
whichMarkerInput = vararginReader('whichMarker', varargin);
windowLengthInput = vararginReader('windowLength', varargin);
alphaInput = vararginReader('alpha', varargin);
numSurroInput = vararginReader('numSurro', varargin);
numPhaseBinInput = vararginReader('numPhaseBin', varargin);
%%%%%%%%%%%%%%%%%%%%%%%%
%%% store parameters %%%
%%%%%%%%%%%%%%%%%%%%%%%%
EEG.pac.lfoPhase = lfoPhaseInput;
EEG.pac.hfoAmp = hfoAmpInput;
EEG.pac.hfoTopRatio = hfoTopRatioInput;
EEG.pac.hfoPool = hfoPoolInput;
EEG.pac.whichMarker = whichMarkerInput;
EEG.pac.windowLength = windowLengthInput;
EEG.pac.alpha = alphaInput;
EEG.pac.numSurro = numSurroInput;
EEG.pac.numPhaseBin = numPhaseBinInput;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% reserve memory for storing results %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
EEG.pac.analyticEEG = zeros(size(EEG.data));
%%%%%%%%%%%%%%%%%%
%%% DC removal %%%
%%%%%%%%%%%%%%%%%%
EEG.data = bsxfun(@minus, EEG.data, mean(EEG.data,2));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% compute analytic EEG %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Low-frequency instantaneous phase.
EEG_lowFreqPhase = pop_eegfiltnew(EEG, lfoPhaseInput(1), lfoPhaseInput(end));
lowFreqPhase_data = EEG_lowFreqPhase.data;
analyPhase = angle(hilbert(lowFreqPhase_data'))';
% High-frequency instantaneous amplitude.
EEG_highFreqAmp = pop_eegfiltnew(EEG, hfoAmpInput(1), hfoAmpInput(end));
highFreqAmp_data = EEG_highFreqAmp.data;
analyAmp = abs(hilbert(highFreqAmp_data'))';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Remove 1-s peri-boundary data points. %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is mainly for window-rejected data to avoid filter's edge effect (11/04/2020 Makoto. Added).
if ~isempty(EEG.event)
boundaryIdx = find(strcmp({EEG.event.type}, 'boundary'));
if ~isempty(boundaryIdx)
boundaryLatency = round([EEG.event(boundaryIdx).latency]);
periBoundaryIdx = [1:EEG.srate (1+EEG.pnts-EEG.srate):EEG.pnts]; % The first and the last 1-s by the edge effect.
for boundaryIdx = 1:length(boundaryLatency)
periBoundaryIdx = [periBoundaryIdx 1+boundaryLatency(boundaryIdx)-EEG.srate:boundaryLatency(boundaryIdx)+EEG.srate]; %#ok
end
periBoundaryIdx = unique(periBoundaryIdx);
% Trim indices outside the data range.
periBoundaryIdx(periBoundaryIdx<1) = [];
periBoundaryIdx(periBoundaryIdx>EEG.pnts) = [];
else
boundaryLatency = [];
periBoundaryIdx = [1:EEG.srate (1+EEG.pnts-EEG.srate):EEG.pnts]; % The first and the last 1-s by the edge effect.
end
else
boundaryLatency = [];
periBoundaryIdx = [1:EEG.srate (1+EEG.pnts-EEG.srate):EEG.pnts]; % The first and the last 1-s by the edge effect.
end
offTheBoundaryIdx = setdiff(1:EEG.pnts, periBoundaryIdx);
analyAmp_offTheBoundary = analyAmp( :,offTheBoundaryIdx);
analyPhase_offTheBoundary = analyPhase(:,offTheBoundaryIdx);
fprintf('\n\n%.0f boundaries found. %.1f s data will be removed.\n\n\n', length(boundaryLatency), length(periBoundaryIdx)/EEG.srate)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Combine the low-freq phase with the high-freq amp. %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
analyticEEG_PAC = analyAmp_offTheBoundary.*exp(1i*analyPhase_offTheBoundary);
EEG.pac.analyticEEG = analyticEEG_PAC;
clear EEG_*
switch hfoPoolInput
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Channel-wise pooling %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 1
analyAmpSort = sort(analyAmp_offTheBoundary, 2, 'descend');
critical = floor(length(analyAmpSort)*hfoTopRatioInput/100);
criticalValues = analyAmpSort(:, critical);
logicalHasMask = analyAmp_offTheBoundary >= repmat(criticalValues, [1 size(analyAmp_offTheBoundary,2)]);
for chIdx = 1:EEG.nbchan
EEG.pac.hfoIndex{chIdx,1} = find(logicalHasMask(chIdx,:));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Whole-data pooling %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
case 2
tmp = analyAmp_offTheBoundary(:);
tmpSort = sort(tmp, 'descend');
critical = tmpSort(floor(length(tmpSort)*EEG.pac.hfoTopRatio/100));
globalHfoIndex = tmp >= critical;
% obtain globalHFOmask
globalHFOmask = false(length(tmpSort),1);
globalHFOmask(globalHfoIndex) = 1;
globalHFOmask = reshape(globalHFOmask, size(EEG.data));
for chIdx = 1:EEG.nbchan
EEG.pac.hfoIndex{chIdx,1} = find(globalHFOmask(chIdx,:));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Handpicked window centers +/- halfWinLen, one event per channel (Mobilab-based event marking, depricated). %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 3 % handpicked
error('This option requires update of Mobilab. Email [email protected] if you want to use it.')
% % create a list that has channel and latency of the selected event
% eventTypes = unique({EEG.event.type});
% tmpMarker = eventTypes{whichMarker-1};
% hitIndex = strcmp({EEG.event.type}, tmpMarker);
% hitIndex = find(hitIndex);
% tmpChanList = cell2mat({EEG.event(1,hitIndex).channel})';
% tmpLatencyList = cell2mat({EEG.event(1,hitIndex).latency})';
% hfoList = cat(2, tmpChanList, tmpLatencyList);
%
% % create HFO index
% EEG.pac.hfoIndex{EEG.nbchan,1} = []; % prepare cell array
% for chIdx = 1:EEG.nbchan
% tmpHfoListIndex = hfoList(:,1)==chIdx;
% if any(tmpHfoListIndex)
% tmpHfoLatencyList = hfoList(tmpHfoListIndex, 2);
% tmpHfoListWin = zeros(1,length(tmpHfoLatencyList)*windowLength*2);
% for m = 1:length(tmpHfoLatencyList)
% tmpIndex = (m-1)*windowLength*2+1:m*windowLength*2;
% tmpHfoListWin(1,tmpIndex) = tmpHfoLatencyList(m)-windowLength:tmpHfoLatencyList(m)+windowLength-1;
% end
% tmpHfoListWin(tmpHfoListWin<1) =[]; % exclude negative latency
% tmpHfoListWin(tmpHfoListWin>EEG.pnts)=[]; % exclude out of range latency
% tmpHfoListWin = unique(tmpHfoListWin); % exclude overlap
% EEG.pac.hfoIndex{chIdx,1} = tmpHfoListWin;
% end
% end
%
% % create non-empty channel list
% nonEmptyChannelList = false(1,length(EEG.pac.hfoIndex));
% for chIdx = 1:length(EEG.pac.hfoIndex)
% nonEmptyChannelList(chIdx,1) = ~isempty(EEG.pac.hfoIndex{chIdx,1});
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% EEGLAB's event-based window selection defined by center +/- halfWinLen. %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 4 % Requested by Henrico Stam, Erasmus University.
% Obtain the target event times.
allEventTypes = unique({EEG.event.type});
%selectedEvent = allEventTypes{whichMarker-1};
selectedEvent = allEventTypes{whichMarkerInput};
eventIdx = find(strcmp({EEG.event.type}, selectedEvent));
latencyIdx = cell2mat({EEG.event(eventIdx).latency})';
% Obtain the target event window edges.
winddowLengthInFrame = round(windowLengthInput/(1000/EEG.srate));
selectedWindowEdges = [latencyIdx-winddowLengthInFrame latencyIdx+winddowLengthInFrame];
% Exclude out of data range windows.
outOfDataRangeWinIdx = selectedWindowEdges(:,1)<0 | selectedWindowEdges(:,2)>EEG.pnts;
selectedWindowEdges(outOfDataRangeWinIdx,:) = [];
% Obtain good window time indices in 1:EEG.pnts.
goodWindowIdx2D = zeros(winddowLengthInFrame*2, size(selectedWindowEdges,1));
for selectedWinIdx = 1:size(goodWindowIdx2D,2)
goodWindowIdx2D(:,selectedWinIdx) = selectedWindowEdges(selectedWinIdx,1)+1:selectedWindowEdges(selectedWinIdx,2);
end
periEventWindowIdx = goodWindowIdx2D(:);
% Obtain non-peri-boundary time indices in 1:EEG.pnts.
nonPeriBoundaryTimeIdx = setdiff(1:EEG.pnts, periBoundaryIdx);
% Obtain the inclusive mask.
[~, inclusiveMask] = intersect(nonPeriBoundaryTimeIdx, periEventWindowIdx);
fprintf('\n\n%.1f%% of data removed for being located within 1-s from a boundary.', 100*(1-length(inclusiveMask)/(size(goodWindowIdx2D,1)*size(goodWindowIdx2D,2))))
% Reshape the extractetd 3D tensor to 2D.
analyAmpSort = sort(analyAmp_offTheBoundary(:,inclusiveMask), 2, 'descend');
critical = floor(length(analyAmpSort)*hfoTopRatioInput/100);
criticalValues = analyAmpSort(:, critical);
logicalHasMask = analyAmp_offTheBoundary >= repmat(criticalValues, [1 size(analyAmp_offTheBoundary,2)]);
logicalHasMask(:,periBoundaryIdx) = false;
for chIdx = 1:EEG.nbchan
EEG.pac.hfoIndex{chIdx,1} = find(logicalHasMask(chIdx,:));
end
%% Another request for later visualization addressed here.
% Exclude peri-boundary windows.
periBoundaryWindowIdx = [];
for windowIdx = 1:size(selectedWindowEdges,1)
if any(intersect(periBoundaryIdx, selectedWindowEdges(windowIdx,1):selectedWindowEdges(windowIdx,2)))
periBoundaryWindowIdx = [periBoundaryWindowIdx; windowIdx]; %#ok
end
end
% Reject the windows.
fprintf('%d/%d windows rejected for being located within 1-s from boundaries.\n\n\n\n', length(periBoundaryWindowIdx), size(selectedWindowEdges,1))
winEdgesAfterRejection = selectedWindowEdges;
winEdgesAfterRejection(periBoundaryWindowIdx,:) = [];
windowLength = median(diff(winEdgesAfterRejection,1,2));
winAmpMatrix = zeros(EEG.nbchan, windowLength, size(winEdgesAfterRejection,1));
winPhaseMatrix = zeros(EEG.nbchan, windowLength, size(winEdgesAfterRejection,1));
for windowIdx = 1:size(winEdgesAfterRejection,1)
winAmpMatrix( :,:,windowIdx) = analyAmp( :, winEdgesAfterRejection(windowIdx,1)+1:winEdgesAfterRejection(windowIdx,2));
winPhaseMatrix(:,:,windowIdx) = analyPhase(:, winEdgesAfterRejection(windowIdx,1)+1:winEdgesAfterRejection(windowIdx,2));
end
meanAmp = mean(winAmpMatrix, 3);
stdAmp = std(winAmpMatrix, 0, 3);
meanPhase = circ_mean(winPhaseMatrix, [], 3);
stdPhase = circ_std( winPhaseMatrix, [], [], 3);
%{
figure
for chIdx = 1:32
subplot(5,7,chIdx)
plot(meanAmp(chIdx,:)); hold on; plot(meanPhase(chIdx,:))
end
%}
% Store the results.
EEG.pac.winEdgesAfterRejection = winEdgesAfterRejection;
EEG.pac.windowMeanAmp = meanAmp;
EEG.pac.windowStdAmp = stdAmp;
EEG.pac.windowMeanPhase = meanPhase;
EEG.pac.windowStdPhase = stdPhase;
end
%%%%%%%%%%%%%%%%%%%%%%%
%%% reserve results %%%
%%%%%%%%%%%%%%%%%%%%%%%
EEG.pac.angleMean = zeros(EEG.nbchan,1);
EEG.pac.angleStd = zeros(EEG.nbchan,1);
EEG.pac.vectLength = zeros(EEG.nbchan,1);
EEG.pac.vectLengthVar = zeros(EEG.nbchan,1);
EEG.pac.histBinMax = zeros(EEG.nbchan,1);
EEG.pac.mi = zeros(EEG.nbchan,1);
EEG.pac.moduInd95CI = zeros(EEG.nbchan,1);
EEG.pac.moduInd99CI = zeros(EEG.nbchan,1);
EEG.pac.phaseBinValues = zeros(EEG.nbchan, numPhaseBinInput+1); % 06/03/2014
EEG.pac.uncorrected.MIpval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.MIpval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.phaseRayleighPval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.phaseOmniTestPval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.phaseRaoSpacePval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.phaseWtsnWillPval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.ampChi2GofPval = ones(EEG.nbchan,1);
EEG.pac.uncorrected.ampKstestPval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.MIpval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.MIpval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.phaseRayleighPval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.phaseOmniTestPval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.phaseRaoSpacePval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.phaseWtsnWillPval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.ampChi2GofPval = ones(EEG.nbchan,1);
EEG.pac.Bonferroni.ampKstestPval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.MIpval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.MIpval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.phaseRayleighPval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.phaseOmniTestPval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.phaseRaoSpacePval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.phaseWtsnWillPval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.ampChi2GofPval = ones(EEG.nbchan,1);
EEG.pac.BonfHolm.ampKstestPval = ones(EEG.nbchan,1);
EEG.pac.FDR.MIpval = ones(EEG.nbchan,1);
EEG.pac.FDR.MIpval = ones(EEG.nbchan,1);
EEG.pac.FDR.phaseRayleighPval = ones(EEG.nbchan,1);
EEG.pac.FDR.phaseOmniTestPval = ones(EEG.nbchan,1);
EEG.pac.FDR.phaseRaoSpacePval = ones(EEG.nbchan,1);
EEG.pac.FDR.phaseWtsnWillPval = ones(EEG.nbchan,1);
EEG.pac.FDR.ampChi2GofPval = ones(EEG.nbchan,1);
EEG.pac.FDR.ampKstestPval = ones(EEG.nbchan,1);
EEG.pac.phaseProbability = cell(EEG.nbchan,1);
EEG.pac.phaseSortedAmp = cell(EEG.nbchan,1);
EEG.pac.phaseSortedAmpSe = cell(EEG.nbchan,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Compute PAC and perform statistics %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
waitBar = waitbar(0,'Computing start');
for chIdx = 1:EEG.nbchan
% update waitbar
waitbar(chIdx/EEG.nbchan, waitBar, ['Processing Channel ' num2str(chIdx)]);
hfoIndex = EEG.pac.hfoIndex{chIdx,1};
if isempty(hfoIndex)
disp(['Channel ' num2str(chIdx) ' has no HFO marker.'])
else
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Compute HFO-indexed data %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if hfoPoolInput == 1 || hfoPoolInput == 2
analyAmp_offTheBoundary_included = abs( EEG.pac.analyticEEG(chIdx,:));
analyPhase_offTheBoundary_included = angle(EEG.pac.analyticEEG(chIdx,:));
elseif hfoPoolInput == 4
analyAmp_offTheBoundary_included = analyAmp_offTheBoundary( chIdx, :);
analyPhase_offTheBoundary_included = analyPhase_offTheBoundary(chIdx, :);
end
hfoPreselectedAmp = analyAmp_offTheBoundary_included( hfoIndex);
hfoPreselectedPhase = analyPhase_offTheBoundary_included(hfoIndex);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Compute Modulation Index of this HFO %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
trueMI = abs(mean(hfoPreselectedAmp.*exp(1i*hfoPreselectedPhase)));
EEG.pac.mi(chIdx,1) = trueMI;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Compute descriptive statistics %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% vector length mean
EEG.pac.vectLength(chIdx,1) = circ_r(hfoPreselectedPhase');
% vector length variance
EEG.pac.vectLengthVar(chIdx,1) = circ_var(hfoPreselectedPhase');
% angle mean
tmpAngle = circ_mean(hfoPreselectedPhase');
% angle std
tmpAngleStd = circ_std(hfoPreselectedPhase');
% converting angle scale from -pi<x<pi to 0<x<2pi
if tmpAngle < 0
tmpAngle = 2*pi+tmpAngle;
end
% store results
EEG.pac.angleMean(chIdx,1) = tmpAngle;
EEG.pac.angleStd(chIdx,1) = tmpAngleStd;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Statistical test for MI %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
surroPhaseTensor = zeros(length(hfoIndex), numSurroInput);
for surroIterIdx = 1:numSurroInput
surroPhaseIdx = randperm(size(analyPhase_offTheBoundary,2), length(hfoIndex));
surroPhaseTensor(:,surroIterIdx) = analyPhase_offTheBoundary(chIdx, surroPhaseIdx);
end
trueAmpTensor = repmat(hfoPreselectedAmp', [1 numSurroInput]);
SurroMI = abs(mean(trueAmpTensor.*exp(1i*surroPhaseTensor), 1));
% 08/14/2024 Makoto.
% I found my previous approach does not make much sense. Why is the range of phase rotation limited to the length of hfoPhase, rather than to the entire valid data?
%{
minskip = 1;
maxskip = length(hfoPhase)-1;
skipIdx = ceil(length(hfoPhase).*rand(numSurro*3,1));
skipIdx(skipIdx>maxskip) = [];
skipIdx(skipIdx<minskip) = [];
skipIdx = skipIdx(1:numSurro,1);
surroPhase = zeros(length(hfoIndex), numSurro);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% run matrix computation (much faster) %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for surroIdx = 1:numSurro
tmpSurroPhase = [analyPhase(skipIdx(surroIdx):end) analyPhase(1:skipIdx(surroIdx)-1)]; % randomize phase instead of amp- consider circular shifts
surroPhase(:,surroIdx) = tmpSurroPhase(hfoIndex)';
end
%}
%%%%%%%%%%%%%%%
%%% p-value %%%
%%%%%%%%%%%%%%%
currentPval = stat_surrogate_pvals(SurroMI, trueMI, 'right');
%{
% Parametric statistics just for interest.
meanSurro = mean(SurroMI);
stdSurro = std(SurroMI);
Y = normpdf(double(trueMI), meanSurro, stdSurro)
%}
EEG.pac.uncorrected.MIpval(chIdx,1) = currentPval;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Confidence interval %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
EEG.pac.moduInd95CI(chIdx,1) = prctile(SurroMI, 95);
EEG.pac.moduInd99CI(chIdx,1) = prctile(SurroMI, 99);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Statistical test for circular distribution of HFO angles %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 07/23/2019 Makoto. Upon fix request by Brian Kavanaugh.
sortHfoPhase = sort(hfoPreselectedPhase);
binSize = length(hfoPreselectedPhase)/size(EEG.pac.phaseBinValues,2);
nonIntegerIdx = 1:binSize:length(hfoPreselectedPhase);
integerIdx = round(nonIntegerIdx);
binValue = sortHfoPhase(integerIdx);
% % Sample every N points. Note that 'binValue' must contain
% % sortHfoPhase(1) and sortHfoPhase(end), but the latter one can be
% % missed by this indexing -- fixed (05/10/2019 Makoto)
% binValue = sortHfoPhase(1:binSize:length(hfoPreselectedInstPhase));
% if length(binValue) == size(EEG.pac.phaseBinValues,2)-1
% binValue(end+1) = sortHfoPhase(end);
% end
% % I thought it is this kind of problem, but it is not (07/22/2019)
% minusPiToPiEdges = linspace(-pi, pi, size(EEG.pac.phaseBinValues,2));
% [binValue,EDGES] = histcounts(sortHfoPhase, minusPiToPiEdges);
% binSize = floor(length(hfoPreselectedInstPhase)/numPhaseBin);
% sortHfoPhase = sort(hfoPreselectedInstPhase);
% binValue = sortHfoPhase(1:binSize:length(hfoPreselectedInstPhase));
% if length(binValue) == size(EEG.pac.phaseBinValues,2)-1
% binValue(end+1) = sortHfoPhase(end);
% end
%
% % sample every N points
% binSize = floor(length(hfoPreselectedInstPhase)/numPhaseBin);
% sortHfoPhase = sort(hfoPreselectedInstPhase);
% binValue = sortHfoPhase(1:binSize:length(hfoPreselectedInstPhase));
% store bin values
EEG.pac.phaseBinValues(chIdx,:) = binValue';
% uniform distribution statistics (3 circular statistics)
EEG.pac.uncorrected.phaseRayleighPval(chIdx,1) = circ_rtest(binValue); % Rayleigh test
EEG.pac.uncorrected.phaseOmniTestPval(chIdx,1) = circ_otest(binValue); % omnibus or Hodges-Ajne test test
EEG.pac.uncorrected.phaseRaoSpacePval(chIdx,1) = circ_raotest(binValue); % Rao's spacing test
clear expectedCounts h p st tmpCdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Compute phase-sorted amplitude %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
edges = linspace(-pi,pi,numPhaseBinInput+1);
[phaseProbability, ~, binIndex] = histcounts(hfoPreselectedPhase, edges);
phaseSortedAmp = zeros(numPhaseBinInput,1);
phaseSortedAmpSe = zeros(numPhaseBinInput,1);
for binIdxIdx = 1:numPhaseBinInput
phaseSortedAmp(binIdxIdx,1) = mean(hfoPreselectedAmp(binIndex==binIdxIdx));
phaseSortedAmpSe(binIdxIdx,1) = std(hfoPreselectedAmp(binIndex==binIdxIdx))/sqrt(length(find(binIndex==binIdxIdx)));
end
% sort from 0 to 2pi
phaseSortOrder = [numPhaseBinInput/2+1:numPhaseBinInput 1:numPhaseBinInput/2];
EEG.pac.phaseProbability{chIdx,1} = phaseProbability(phaseSortOrder);
EEG.pac.phaseSortedAmp{chIdx,1} = phaseSortedAmp(phaseSortOrder);
EEG.pac.phaseSortedAmpSe{chIdx,1} = phaseSortedAmpSe(phaseSortOrder);
% statistics (chi-square test)
edges = linspace(min(phaseSortedAmp),max(phaseSortedAmp),numPhaseBinInput+1);
expectedCounts = repmat(numPhaseBinInput/(length(edges)-1), [1 length(edges)-1]);
[~,p] = chi2gof(phaseSortedAmp, 'edges', edges, 'expected', expectedCounts);
EEG.pac.uncorrected.ampChi2GofPval(chIdx,1) = p;
% statistics (kstest)
tmpCdf(:,1) = linspace(min(phaseSortedAmp), max(phaseSortedAmp), numPhaseBinInput);
tmpCdf(:,2) = linspace(0,1,numPhaseBinInput);
[~,p] = kstest(phaseSortedAmp, tmpCdf);
EEG.pac.uncorrected.ampKstestPval(chIdx,1) = p;
% keep record of max bin value
EEG.pac.histBinMax(chIdx,1) = max(phaseProbability);
end
end
%%%%%%%%%%%%%%%%%%
%%% Angle test %%%
%%%%%%%%%%%%%%%%%%
for chIdx = 1:EEG.nbchan
[EEG.pac.uncorrected.phaseWtsnWillPval(chIdx,1),~] = circ_wwtest(EEG.pac.phaseBinValues(chIdx,:), EEG.pac.angleMean);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Multiple comparisons %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Bonferroni
EEG.pac.Bonferroni.MIpval = EEG.pac.uncorrected.MIpval*EEG.nbchan;
EEG.pac.Bonferroni.phaseRayleighPval = EEG.pac.uncorrected.phaseRayleighPval*EEG.nbchan;
EEG.pac.Bonferroni.phaseOmniTestPval = EEG.pac.uncorrected.phaseOmniTestPval*EEG.nbchan;
EEG.pac.Bonferroni.phaseRaoSpacePval = EEG.pac.uncorrected.phaseRaoSpacePval*EEG.nbchan;
EEG.pac.Bonferroni.phaseWtsnWillPval = EEG.pac.uncorrected.phaseWtsnWillPval*EEG.nbchan;
EEG.pac.Bonferroni.ampChi2GofPval = EEG.pac.uncorrected.ampChi2GofPval*EEG.nbchan;
EEG.pac.Bonferroni.ampKstestPval = EEG.pac.uncorrected.ampKstestPval*EEG.nbchan;
% Bonferroni-Holm
EEG.pac.BonfHolm.MIpval = bonf_holm(EEG.pac.uncorrected.MIpval);
EEG.pac.BonfHolm.phaseRayleighPval = bonf_holm(EEG.pac.uncorrected.phaseRayleighPval);
EEG.pac.BonfHolm.phaseOmniTestPval = bonf_holm(EEG.pac.uncorrected.phaseOmniTestPval);
EEG.pac.BonfHolm.phaseRaoSpacePval = bonf_holm(EEG.pac.uncorrected.phaseRaoSpacePval);
EEG.pac.BonfHolm.phaseWtsnWillPval = bonf_holm(EEG.pac.uncorrected.phaseWtsnWillPval);
EEG.pac.BonfHolm.ampChi2GofPval = bonf_holm(EEG.pac.uncorrected.ampChi2GofPval);
EEG.pac.BonfHolm.ampKstestPval = bonf_holm(EEG.pac.uncorrected.ampKstestPval);
% False-discovery Rate
EEG.pac.FDR.MIpval = fdr(EEG.pac.uncorrected.MIpval);
EEG.pac.FDR.phaseRayleighPval = fdr(EEG.pac.uncorrected.phaseRayleighPval);
EEG.pac.FDR.phaseOmniTestPval = fdr(EEG.pac.uncorrected.phaseOmniTestPval);
EEG.pac.FDR.phaseRaoSpacePval = fdr(EEG.pac.uncorrected.phaseRaoSpacePval);
EEG.pac.FDR.phaseWtsnWillPval = fdr(EEG.pac.uncorrected.phaseWtsnWillPval);
EEG.pac.FDR.ampChi2GofPval = fdr(EEG.pac.uncorrected.ampChi2GofPval);
EEG.pac.FDR.ampKstestPval = fdr(EEG.pac.uncorrected.ampKstestPval);
% set default stats options
EEG.pac.phaseTestType = 1;
EEG.pac.multiCompType = 1;
% close waitber
close(waitBar)
%%%%%%%%%%%%%%%%%%%%%%%
%%% Display Pacman. %%%
%%%%%%%%%%%%%%%%%%%%%%%
disp(' %%%%%%%%% ');
disp(' %%%% %%%% ');
disp(' %%% %%% ');
disp(' %%% %%% %%% ');
disp(' %% %%% % % ');
disp(' % %%% %%%% ');
disp(' % %%%%% ');
disp(' % %%%% %%% %%% %%% ');
disp(' % %%% %%%%% %%%%% %%%%%');
disp(' % %%%% %%% %%% %%% ');
disp(' % %%%%% ');
disp(' %% %%%% ');
disp(' %%% % ');
disp(' %%% %%%% ');
disp(' %%%% %%%%% ');
disp(' %%%%%%%%% ');
disp(newline)
disp(' I computed them all! ');
disp(newline)
disp('PAC is computed and stored in EEG.pac')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%%%%%%%%%%%%%%%%%%%%
%%% Subfunctions %%%
%%%%%%%%%%%%%%%%%%%%
function output = vararginReader(strings,varargin)
varargin = varargin{1,1};
for n = 1:length(varargin)
if strcmp(varargin{1,n}, strings)
output = varargin{1,n+1};
end
end