-
Notifications
You must be signed in to change notification settings - Fork 1
/
MAIN.m
1681 lines (1428 loc) · 72.5 KB
/
MAIN.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
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
%%------------------------------RESTINGLAB-------------------------------%%
% Version 0.63
% Developped by <Corentin Wicht>
% 19.04.2021
% Author: Corentin Wicht ([email protected])
% Contributor: Christian Mancini ([email protected])
%-------------------------------------------------------------------------%
% The script allows the user to perform semi-automatic artifact rejection
% including ICA on BioSemi resting-state EEG recordings. If ICA is computed
% the script runs a second time through all files to enable the user to
% reject components which will be pre-selected with dedicated algorithms.
% ENJOY %
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MAIN SCRIPT FOR PREPROCESSING AND ANALYSES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MAIN(App,CurrentPWD,Date_Start,SavePath)
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GLOBAL VARIABLES DEFINITION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get time
time_start = datestr(now);
% Hide warning messages
warning off MATLAB:subscripting:noSubscriptsSpecified
% Find folder in Functions containing "eeglab" (may change name if update)
Files = dir([CurrentPWD '\Functions\']);
dirFlags = [Files.isdir];
OnlyFolders = Files(dirFlags);
Idx = contains(lower({OnlyFolders.name}),'eeglab');
EEGLABFolder = [OnlyFolders(Idx).folder '\' OnlyFolders(Idx).name];
% Adding path to dependencies
addpath(EEGLABFolder);
addpath([CurrentPWD '\Functions\']);
addpath(genpath([CurrentPWD '\Functions\Dependencies']));
addpath([CurrentPWD '\Functions\EEGInterp']);
%-------------------------------------------------------------------------%
% LOADING GUI MATRICES
%-------------------------------------------------------------------------%
% Retrieving the list of all matrices
ParametersPath=dir([SavePath '\Parameters\' Date_Start '\']);
ParametersPath=ParametersPath(~cell2mat({ParametersPath.isdir}));
% Loading the matrices stored with the GUI
for k=1:length(ParametersPath)
load([ParametersPath(k).folder '\' ParametersPath(k).name])
end
%-------------------------------------------------------------------------%
% INSTALL MPICH2 for AMICA plugin
%-------------------------------------------------------------------------%
% Installing additionnal softwares for AMICA
ComputerType = computer;
% Determining the number and letters of harddrives
F = getdrives('-nofloppy');
% Finding out whether it's already installed or not
Result = 0;
for k=1:length(F)
if exist([F{k} 'Program Files\MPICH2'],'dir') || ...
exist([F{k} 'Program Files (x86)\MPICH2'],'dir')
Result = 1;
end
end
if ispc && ~Result && strcmpi(ICA,'yes')
% Temporary folder to delete
mkdir([CurrentPWD '\Mpich2_1.4']);
% AMICA
% https://sccn.ucsd.edu/~jason/amica_web.html
% Saving data from web & installing
if str2double(cell2mat(regexp(ComputerType,'\d*','Match')))==64
if ~exist([CurrentPWD '\Mpich2_1.4\mpich2-1.4-win-x86-64.msi'],'file')
websave([CurrentPWD '\Mpich2_1.4\mpich2-1.4-win-x86-64.msi'],...
'http://www.mpich.org/static/downloads/1.4/mpich2-1.4-win-x86-64.msi');
end
system([CurrentPWD '"\Mpich2_1.4\mpich2-1.4-win-x86-64.msi"']);
elseif str2double(cell2mat(regexp(ComputerType,'\d*','Match')))==32
if ~exist([CurrentPWD '\Mpich2_1.4\mpich2-1.4-win-ia32.msi'],'file')
websave([CurrentPWD '\Mpich2_1.4\mpich2-1.4-win-ia32.msi'],...
'http://www.mpich.org/static/downloads/1.4/mpich2-1.4-win-ia32.msi');
end
system([CurrentPWD '\Mpich2_1.4\mpich2-1.4-win-ia32.msi'])
end
% Delete temporary directory
cd(CurrentPWD)
rmdir('Mpich2_1.4','s')
end
%% DESIGN / EEG PARAMETERS
% Between-subject factor(s)
BetweenFactors=BetweenFactors(~cellfun('isempty',BetweenFactors));
if ~isempty(BetweenFactors)
for k=1:length(BetweenFactors)
Groups_Names(:,k) = strrep(BetweenLevels(k,~cellfun('isempty',BetweenLevels(k,:))),' ','');
end
else
Groups_Names = strsplit(FilesPath{1},'\') ;
Groups_Names = Groups_Names(end);
end
% Within-subject factor(s)
WithinFactors=WithinFactors(~cellfun('isempty',WithinFactors));
if ~isempty(WithinFactors)
for k=1:length(WithinFactors)
Conditions_Names(:,k) = WithinLevels(k,~cellfun('isempty',WithinLevels(k,:)));
Conditions=1:length(Conditions_Names);
end
else
Conditions = 1;
end
% EEG data
Channels=str2num(Channels);
if exist('FreqData','var')
FreqNames = FreqData(~cellfun('isempty',FreqData(:,1)),1);
FreqRanges = cell2mat(cellfun(@(x) str2num(x), FreqData(:,2),'UniformOutput',0));
Frequency_export = cellfun(@(x) ['S%d_' x '_'],FreqNames,'UniformOutput',false);
else
FreqNames = '';
FreqRanges = [];
end
if max(Channels)<128
DirectoryTemp = dir(['**/*' '.locs']);
FolderTemp = DirectoryTemp(contains({DirectoryTemp.folder},'ChanLocs')).folder;
Channel_load = [FolderTemp '\biosemi64.locs'];
else
DirectoryTemp = dir(['**/*' '.xyz']);
FolderTemp = DirectoryTemp(contains({DirectoryTemp.folder},'ChanLocs')).folder;
Channel_load=[FolderTemp '\biosemi128.xyz'];
end
% Plugins settings (if user pressed cancel the settings will be empty)
if isempty(AnswerCleanLine)
CleanLineParam = {'50 100','0.01','2','4','4','100','2'}; % Default
end
if isempty(AnswerASR)
AnswerASR = {'10',''}; % Default
else
if isempty(AnswerASR{1})
AnswerASR{1} = '-1';
end
if isempty(AnswerASR{2})
AnswerASR{2} = '-1';
end
end
if strcmpi(ICA,'Yes') && isempty(AnswerICA)
AnswerICA = {'2000'}; % Default
end
if str2double(AnswerBLINKER{1}) == 1
AnswerBLINKER = 'reject';
else
AnswerBLINKER = 'interp';
end
% Decision if doing basic analyses
if exist('AnalysesSwitch','var')
Analysis = 1;
% List of electrode groups
if strcmpi(AnalysesSwitch{2,end},'Yes')
AreasList = AreasList(cellfun(@(x) ~isempty(x),AreasList));
SplitHeaders = strsplit(AreasList{1},' ');
for k = 2:length(AreasList)
if ~isempty(str2num(AreasList{k})) % If user entered numbers
SplitChans=str2num(AreasList{k});
NewAreasList.(SplitHeaders{k-1})=SplitChans';
else
Delimiter = '\t';FormatSpec = '%q%q%q%[^\n\r]';
FileID = fopen(Channel_load,'r');
ChanList = textscan(FileID, FormatSpec, 'Delimiter', Delimiter,'EndOfLine', '\r\n');
ChanList = ChanList{end};
fclose(FileID);
SplitChans = strsplit(AreasList{k},' ');
for t=1:length(SplitChans)
Idx = find(ismember(lower(ChanList),lower(SplitChans{t})));
NewAreasList.(SplitHeaders{k-1})(t)=Idx;
end
end
end
end
end
%% DIRECTORIES
% If save path different than CurrentPWD
if sum(~SavePath)<1
% Excel directory
% mkdir([SavePath '\Excel\' Date_Start])
ExcelDirectory=[SavePath '\Excel\' Date_Start '\'];
% Exports directory
StatsDirectory=[SavePath '\Exports\' Date_Start '\SourceLocalisation\'];
TopoplotsDirectory=[SavePath '\Exports\' Date_Start '\Topoplots\'];
% Finds out if all folder for source localisation
StatsFolders=dir(StatsDirectory);
StatsFolders=StatsFolders([StatsFolders.isdir]);
for k=1:length(FreqNames)
if ~ismember(FreqNames{k},{StatsFolders.name})
% Create missing directories
mkdir([StatsDirectory FreqNames{k}])
end
end
% Additionnal directories
TopoDipFitDirectory=[SavePath '\Exports\' Date_Start '\TopoplotsDipFit\'];
else
% If save path same as CurrentPWD
% Excel directory
ExcelDirectory=[pwd '\Excel\' Date_Start '\'];
% Exports directory
StatsDirectory=[pwd '\Exports\SourceLocalisation\' Date_Start '\'];
TopoplotsDirectory=[pwd '\Exports\Topoplots\' Date_Start '\'];
% Finds out if all folder for source localisation
StatsFolders=dir(StatsDirectory);
StatsFolders=StatsFolders([StatsFolders.isdir]);
for k=1:length(FreqNames)
if ~ismember(FreqNames{k},{StatsFolders.name})
% Create missing directories
mkdir([StatsDirectory FreqNames{k}])
end
end
% Additionnal directories
TopoDipFitDirectory=[pwd '\TopoplotsDipFit\' Date_Start '\'];
end
% Datasets templates (Adding the subject number before)
Dataset_filtCleaned = ['%s' FileNames '%d_filtered'];
Dataset_interp = ['%s' FileNames '%d_filtered_cleaned'];
Dataset_filtCleaned_ICAed = ['%s' FileNames '%d_filtered_cleaned_ICAed'];
Dataset_filtCleaned_ICAedRejected = ['%s' FileNames '%d_filtered_cleaned_ICAedRejected'];
PreprocessedEEG=['%s' FileNames '%d_Preprocessed.bdf'];
PSDEEG=['%s' FileNames '%d_PowerSpectDensity.mat'];
%% SUBJECTS TEMPLATES
Conditions_Order=readtable([DirectoryCond FileCond]);
Conditions_OrderCell=table2cell(Conditions_Order(:,2:end));
if isempty(BetweenFactors)
Conditions_Labels = Conditions_Order.Properties.VariableNames(2:end);
else
Conditions_Labels = Conditions_Order.Properties.VariableNames(2:end-1);
end
TempSubjectslist = table2cell(Conditions_Order(:,1));
% If only 1 condition
if Conditions<2
Conditions_Names = {FileNames};
end
% Only keeping subjects selected for analysis
j=1;t=1;
if isnumeric(TempSubjectslist{1})
TempSubjectslist=cell2mat(TempSubjectslist);
else; TempSubjectslist=cellfun(@(x) str2double(x),TempSubjectslist);
end
for k=1:length(TempSubjectslist)
for l=1:size(ProcessData,2) % Number of sessions
if ProcessData{k,l}
Subjectslist(j) = TempSubjectslist(k);
j=j+1;
break
end
% Scan the ProcessData line to remplace empty fields by 0
ProcessData(k,cellfun(@(x) isempty(x),ProcessData(k,:))) = {false};
% This will detect files for which there is no data to analyze
if sum(cell2mat(ProcessData(k,:)))<1
SubjectsRemovedIdx(t) = k;
t=t+1;
break
end
end
end
% Removing lines from Conditions_Order (if completely excluded)
if exist('SubjectsRemovedIdx','var')
Conditions_OrderCell(SubjectsRemovedIdx,:)=[];
end
% Building the subjects selection list based on GUI data
SubjectsIncluded = [num2cell(TempSubjectslist) ProcessData];
FilesToProcess = 0;
% No idea where it comes from but sometimes it is loaded
if exist('Participant_load','var')
clear Participant_load
end
% Participants group directory
for k=1:length(FilesPath)
% Path of the folders containing the datasets for each group
FileList = dir([FilesPath{k} '\**/*' lower(Extension)]);
% Removing unnecessary files:
% 1) Removing Preprocessed.bdf files if preprocessing selected
FileList = FileList(~contains({FileList.name},'Preprocessed'));
% 2) If loading .set, remove unused file versions
if strcmpi(Extension,'.set')
% non-ICA files
IdxNonICA = contains({FileList.name}','filtered_cleaned');
% ICA files
IdxICA = contains({FileList.name}','filtered_cleaned_ICAedRejected');
% Grouping indexes and removing unused files
IdxRem = or(IdxNonICA,IdxICA);
FileList = FileList(IdxRem);
end
% If save path different than CurrentPWD
if sum(~SavePath)<1
% Creating folder templates for each subject
SplitTemp = strsplit(FilesPath{k},'\');
FoldPath = SplitTemp{end};
mkdir(SavePath,FoldPath);
for p=1:length(FileList)
SplitTemp=strsplit(FileList(p).folder,'\');
mkdir([SavePath '\' FoldPath],SplitTemp{end})
end
end
% Only keeping the ones containg the common name
FileList = FileList(contains({FileList.name},FileNames));
% List of all folders in the group
GroupFoldersTemp = {FileList(contains({FileList.folder},FilesPath{k})).folder};
UniqueFoldersTemp = sort_nat(unique(GroupFoldersTemp));
for j=1:length(UniqueFoldersTemp)
SplitFileTemp = strsplit(UniqueFoldersTemp{j},'\');
% UniqueNamesTemp = unique({FileList.name});
% Position of files
Pos = 1;
% Current subject
CurrentSubj = str2num(cell2mat(regexp(SplitFileTemp{end},'\d*','Match')));
% Number of files for the current subject
NumofFiles = find(strcmpi({FileList.folder},UniqueFoldersTemp{j}));
% For each unique file (for each participant/folder)
for l=1:length(NumofFiles)
CurrentFile = {FileList(NumofFiles(l)).name};
CurrentFileSplit = strsplit(CurrentFile{:},'.');
% Position in excel files
TempFilePos = cellfun(@(x) x==CurrentSubj, SubjectsIncluded(:,1)); % Subject
% Preallocating array
Condname_i = zeros([size(Conditions_Labels,2) 1]); Inverted = 0;
% For each condition, see if we find it in the name or subpath
if length(Conditions) > 1
for r=1:length(Condname_i)
Condname_i(r) = contains(CurrentFileSplit{1},Conditions_Labels{r},'IgnoreCase',true);
end
% In case of multiple positives, take the lengthier condition name
if sum(Condname_i) > 1
[~,CondPos] = max(cellfun('length',Conditions_Labels) .* Condname_i);
elseif sum(Condname_i) == 1
CondPos = find(Condname_i == 1);
else % Case where the header and the data in columns are inverted
for s=1:length(Condname_i)
Condname_i(l) = contains(CurrentFileSplit{1},Conditions_OrderCell{TempFilePos,s},'IgnoreCase',true);
end
CondPos = find(Condname_i == 1); Inverted = 1;
end
else; CondPos = 1;
end
% Only including data that was selected in the GUI
if cell2mat(SubjectsIncluded(TempFilePos,CondPos+1)) == 1 % initially str2double
% HERE WRITE FOR THE LOG !
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).Path = UniqueFoldersTemp(j);
% Create the folder list content structure called FileList
if Inverted
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).FileList(CondPos) = CurrentFile;
else
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).FileList(Pos) = CurrentFile;
end
% Retrieving the conditions assignement values
if length(Conditions_Names)>1
if Inverted
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).CondAssign(Pos) = ...
Conditions_Names(l);
else
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).CondAssign(Pos) = ...
Conditions_OrderCell(TempFilePos,l);
end
else
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).CondAssign(Pos) = ...
Conditions_Names(l);
end
% Writting the export path
if sum(~SavePath)<1
SplitFile = strsplit(UniqueFoldersTemp{j},'\');
splitFolder = strsplit(FilesPath{k},'\');
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).ExportPath =...
[SavePath '\' splitFolder{end} '\' SplitFile{end}];
else
Participant_load.(Groups_Names{k}).(SplitFileTemp{end}).ExportPath = UniqueFoldersTemp(j);
end
% Count the number of files to process below
FilesToProcess = FilesToProcess + 1; Pos = Pos + 1;
end
end
end
end
%% Excel templates
try
% If save path different than CurrentPWD
if sum(~SavePath)<1
ExcelPath = [SavePath '\Excel\' Date_Start];
ExcelFiles=dir([ExcelPath '\**/*' '.xlsx']);
% Creating excel templates if they do not exist
if length(ExcelFiles)<=1
CreateTemplates(num2cell(TempSubjectslist),Conditions_Names,FreqNames,Channels,[SavePath '\Excel\' Date_Start '\'],ExcelFiles);
end
else
Temp=what('Excel');
ExcelPath = [Temp.path '\' Date_Start];
ExcelFiles=dir([ExcelPath '\**/*' '.xlsx']);
% Creating excel templates if they do not exist
if isempty(ExcelFiles)
CreateTemplates(num2cell(TempSubjectslist),Conditions_Names,FreqNames,Channels,[Temp.path '\' Date_Start '\'],ExcelFiles);
end
end
catch
warning(['Since excel templates already exist and you just changed the FileName, the script crashed.',...
newline 'To avoid this, please remove all previously generated templates from the following folder and re-run the script:', ...
newline ExcelPath])
end
% LOADING THE TEMPLATES
SleepNoSleepTable=readtable(backslash([ExcelDirectory 'AsleepAwakeTrials.xlsx']));
for m=1:size(FreqRanges,1)
% Importing areas amplitude templates
AreaAmpTable.(FreqNames{m})=readtable(backslash([ExcelDirectory ['AreaAmplitude' FreqNames{m} '.xlsx']]));
for n=1:length(Conditions)
% Temporary sheet name
TempSheetsName = [FreqNames{m} '_' lower(Conditions_Names{n})];
% sheets name longer than or equal to 31 characters will crash
if length(TempSheetsName) >= 31
TempSheetsName = TempSheetsName(1:30);
end
% Importing Global Power Spectra templates
GPS.(FreqNames{m}).(Conditions_Names{n})=readtable(backslash([ExcelDirectory ['GPS_' FreqNames{m} '.xlsx']]),...
'Sheet',TempSheetsName);
end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PREPROCESSING
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Epitome of UI
WaitBarApp = uiprogressdlg(App.MainGUIUIFigure,'Title','Progress Bar',...
'Message','','Cancelable','on');
File = 0;
% If the extension is .set, only the analyses are performed
if ~strcmpi(Extension,'.set') && strcmpi(Steps,'Preprocessing') || strcmpi(Steps,'Both')
% Participants loop
for g=1:length(Subjectslist)
% Current Subject
ParticipantNumber = Subjectslist(g);
% Position of the current subject in the subject list
Pos = find(Subjectslist == ParticipantNumber);
% Retrieving current subject information
FolderTemplate = regexp(SplitFileTemp{end},'\D*','Match');
if length(FilesPath)>1
CurrentFile = Participant_load.(Conditions_OrderCell{Pos,end}). ...
([FolderTemplate{:} num2str(ParticipantNumber)]);
else
CurrentFile = Participant_load.(Groups_Names{1}). ...
([FolderTemplate{:} num2str(ParticipantNumber)]);
end
% Conditions loop
for h=1:length(CurrentFile.FileList)
%-----------------------------------------------------------------%
% Loading directory and templates
%-----------------------------------------------------------------%
% Finding current condition number
WhichCond = find(contains(lower(Conditions_Names),...
lower(CurrentFile.CondAssign{h})));
% Selecting appropriate groups folder
Dir_load = backslash(CurrentFile.Path{:});
Subj_load = [Dir_load backslash(['\' CurrentFile.FileList{h}])];
% If save path different than CurrentPWD
if ~isempty(SavePath)
Dir_save = backslash(CurrentFile.ExportPath);
else
Dir_save = Dir_load;
end
% Update progress, report current estimate
File = File + 1;
WaitBarApp.Value = File/FilesToProcess;
WaitBarApp.Title = '1. PREPROCESSING: Loading data';
WaitBarApp.Message = sprintf('Sbj %d/%d : %s',g,...
length(Subjectslist),CurrentFile.CondAssign{WhichCond});
% Check for Cancel button press
if WaitBarApp.CancelRequested
return
end
%% IMPORT
% Creating first dataset
[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
close gcf
% set double-precision parameter
pop_editoptions('option_single', 0,'option_computeica',1);
% Import the .bdf file
% SHOULD NEVER SPECIFY A REF CHAN FOR BIOSEMI (since BioSemi uses CMS-DRL which cannot be imported)
% https://sccn.ucsd.edu/pipermail/eeglablist/2014/007822.html
% https://blricrex.hypotheses.org/files/2015/03/Pr%C3%A9sentationCREx_EEGLAB-corrig%C3%A9.pdf
EEG = pop_biosig(Subj_load, 'channels', Channels);
% Loading BioSemi channel location
try
EEG=pop_chanedit(EEG, 'load',{Channel_load 'filetype' 'loc'});
catch
warning(['There seems to be no channels location file in this directory:',...
newline Channel_load])
end
%% RESTRICTING DATA LENGTH (optional)
if End~=0
EEG = pop_select( EEG,'time',[Beginning ...
End]);
end
%% Changing events structure (double to strings)
EventFields={'event','urevent'};
for t = 1:length(EventFields)
if ~isempty(EEG.(EventFields{t}))
TempEvents = {EEG.(EventFields{t}).type};
for f=1:length(TempEvents)
if isa(TempEvents{f},'double')
EEG.(EventFields{t})(f).type = num2str(EEG.(EventFields{t})(f).type);
end
end
end
end
%% FILTERING
% Waitbar updating
WaitBarApp.Title = '1. PREPROCESSING: Filtering';
% Sampling rate
if EEG.srate>SamplingRate
EEG = pop_resample(EEG, SamplingRate);
end
% High-pass/Low-pass filter
EEG = pop_eegfiltnew(EEG,HighPass,LowPass);
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ARTIFACTS REJECTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Waitbar updating
WaitBarApp.Title = '1. PREPROCESSING: CleanLine';
% CLEANLINE
% CleanLine sinusoidal stationary noise removal
% (http://www.antillipsi.net/research/software#TOC-Cleanline)
PromptCleanLine=cellfun(@(x) str2num(x),AnswerCleanLine,'UniformOutput',false);
EEG = pop_cleanline(EEG,'bandwidth',PromptCleanLine{3},'chanlist',1:EEG.nbchan ,...
'computepower',0,'linefreqs',PromptCleanLine{1},'normSpectrum',0,'p',PromptCleanLine{2},...
'pad',PromptCleanLine{7},'plotfigures',0,'scanforlines',1,'sigtype','Channels',...
'tau',PromptCleanLine{6},'verb',1,'winsize',PromptCleanLine{5},'winstep',PromptCleanLine{4});
close gcf;
% Finding current subject export name
Temp = strsplit(CurrentFile.Path{:},'\');
SubjName = [Temp{end} '_'];
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INTERPOLATION/CHANNELS REJECTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%n%%%%%%%%%%%%
% Temporary save the original EEG (non-robust averaged)
OriginalEEG = EEG;
% Waitbar updating
WaitBarApp.Title = '1. PREPROCESSING: Channels interpolation';
% Detection of bad channels
ErrorArtifacts = {};
r = 1;
try
% Function from the PrepPipeline to perform 1) Bad Channels
% Detection and rejection
% Parameters
InterpChanStruct = getReferenceStructure();
defaults = getPrepDefaults(EEG, 'reference');
InterpChanStruct = checkDefaults(struct(), InterpChanStruct, defaults);
defaults = getPrepDefaults(EEG, 'detrend');
InterpChanStruct = checkDefaults(struct(), InterpChanStruct, defaults);
InterpChanStruct.rereferencedChannels = sort(InterpChanStruct.rereferencedChannels);
InterpChanStruct.referenceChannels = sort(InterpChanStruct.referenceChannels);
InterpChanStruct.evaluationChannels = sort(InterpChanStruct.evaluationChannels);
% Bad channels identification by robust reference
InterpChanStruct.referenceSignalOriginal = ...
nanmean(EEG.data(InterpChanStruct.referenceChannels, :), 1);
InterpChanStruct = robustReference(EEG, InterpChanStruct);
% Saving the bad channels data to reintroduce them later
% Saving the bad channels data to reintroduce them later
EEG.BadChans.chanlocs = EEG.chanlocs;
EEG.BadChans.nbchan = EEG.nbchan;
EEG.BadChans.data = EEG.data(InterpChanStruct.badChannels.all,:);
EEG.BadChans.InterpChans = InterpChanStruct.badChannels.all;
% Removing the bad channels
EEG = pop_select(EEG,'nochannel',InterpChanStruct.badChannels.all);
catch
% Write error to the LOG
ErrorArtifacts{r} = [SubjName FileNames num2str(WhichCond)];
r = r+1;
break
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NON-SINUSOIDAL NOISE REMOVAL
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%n%%%%%%%%%%%%
% Saving data for visual comparision below
OriginalEEG = EEG;
% Waitbar updating
WaitBarApp.Title = '1. PREPROCESSING: ASR';
% ARTIFACT SUBSPACE RECONSTRUCTION (ASR)
% Automated bad channels detection and non-stationary noise removal
% Christian's method (http://sccn.ucsd.edu/eeglab/plugins/ASR.pdf)
% Non-stationary artifacts removal
% Fixing the maximum available memory enhances reproducibility
MaxMemory = round(hlp_memfree()/2000000,-3);
if strcmpi(ASR,'Yes')
% ASR
EEG = clean_rawdata(EEG, -1, -1, -1, -1, str2double(AnswerASR{1}),...
str2double(AnswerASR{2}));
% Removing the events that were created by ASR
EEG = RemovEvents(EEG,'EventTypes',{'X','boundary'});
% Allows for visual inspection of old/new EEG (Optional)
if strcmpi(Automaticity,'Yes')
vis_artifacts(EEG,OriginalEEG);
disp('Ignore errors above !!');
% Holds the figure until inspection is over
Fig=msgbox('THE CODE WILL CONTINUE ONCE YOU PRESS OK','WAIT','warn');
uiwait(Fig);
close gcf
end
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% EYE BLINKS ARTIFACTS REJECTION/INTERPOLATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%n%%%%%%%%%%%%
% BLINKER: EYE BLINKS REMOVAL
if strcmpi(BLINKER,'Yes')
% Waitbar updating
WaitBarApp.Title = '1. PREPROCESSING: BLINKER';
% Setting parameters
Params = checkBlinkerDefaults(struct(), getBlinkerDefaults(EEG));
Params.fileName = [Dir_save '\\' sprintf(Dataset_filtCleaned, SubjName, WhichCond)];
Params.blinkerSaveFile = [Dir_save '\\' sprintf(Dataset_filtCleaned, SubjName, WhichCond) '_blinks.mat'];
Params.showMaxDistribution = true;
Params.verbose = false;
Params.fieldList = {'leftBase','rightBase'};
% Run BLINKER algorithm
try
[EEG, ~, ~, blinkFits,~] = pop_blinker(EEG, Params);
close gcf;fprintf('%d blinks identified by BLINKER\n',length(blinkFits));
catch
disp('0 blink identified by BLINKER\n');
end
% Retrieve blinks latency
for m=1:length(blinkFits)
AbsLatency(m,:) = [blinkFits(m).leftBase blinkFits(m).rightBase];
end
if strcmpi(AnswerBLINKER,'reject') && ~isempty(blinkFits)
% Removing the data containing blinks
EEG = eeg_eegrej(EEG, AbsLatency);
end
% Removing the events that were created by eeg_eegrej()
EEG = RemovEvents(EEG,'EventTypes',{'boundary'});
end
% if strcmpi(BLINKER,'Yes') && strcmpi(AnswerBLINKER,'interp') ...
% && ~isempty(blinkFits)
%
% % THIS IS CURRENTLY NOT WORKING!!! I CANNOT FORCE TO
% % INTERPOLATE ALL THE SIGNAL I AM PROVIDING IT!!!!
% % SHIT....
%
% % 1) ASR 1st run
% % ASR settings
% asr_windowlen = max(0.5,1.5*EEG.nbchan/EEG.srate);
% BurstCriterion = str2double(AnswerASR{1});asr_stepsize = 4;
% maxdims = 1;usegpu = false;
%
% % Creating a clean reference section
% EEGCleanRef = clean_windows(EEG,0.075,[-3.5 5.5],1);
%
% % Building the Blink EEG dataset
% BlinkEEG = EEG; TempEEG = EEG;
% BlinkEEG.data = []; BlinkEEG.event = []; Pos = 1;
% for p=1:size(AbsLatency,1)
% % BlinkEEG.data(:,AbsLatency(p,1):AbsLatency(p,2)) = ...
% % EEG.data(:,AbsLatency(p,1):AbsLatency(p,2));
% BlinkEEG.data = [BlinkEEG.data EEG.data(:,AbsLatency(p,1):AbsLatency(p,2))];
% BlinkEEG.event(Pos).type = 'leftBase';
% if p>1
% BlinkEEG.event(Pos).latency = BlinkEEG.event(Pos-1).latency+1;
% else
% BlinkEEG.event(Pos).latency = 1;
% end
% Pos = Pos + 1;
% BlinkEEG.event(Pos).type = 'rightBase';
% BlinkEEG.event(Pos).latency = BlinkEEG.event(Pos-1).latency + (AbsLatency(p,2)-AbsLatency(p,1));
% Pos = Pos + 1;
% end
%
% % Calibrate on the reference data
% state = asr_calibrate_r(EEGCleanRef.data, EEGCleanRef.srate,...
% BurstCriterion, [], [], [], [], [], [], []);
%
% % Extrapolate last few samples of the signal
% sig = [BlinkEEG.data bsxfun(@minus,2*BlinkEEG.data(:,end),...
% BlinkEEG.data(:,(end-1):-1:end-round(asr_windowlen/2*BlinkEEG.srate)))];
%
% % Process signal using ASR
% [BlinkEEG.data,state] = asr_process_r(sig,BlinkEEG.srate,state,...
% asr_windowlen,asr_windowlen/2,asr_stepsize,maxdims,MaxMemory,usegpu);
%
% % Shift signal content back (to compensate for processing delay)
% BlinkEEG.data(:,1:size(state.carry,2)) = [];
%
% % Replace original data with the Blink corrected data
% NEWEEG = EEG; Pos = 1:2:size(AbsLatency,1)*2;
% for p=1:size(AbsLatency,1)
% NEWEEG.data(:,AbsLatency(p,1):AbsLatency(p,2)) = ...
% BlinkEEG.data(:,BlinkEEG.event(Pos(p)).latency:...
% BlinkEEG.event(Pos(p)+1).latency);
% end
%
% % Allows for visual inspection of old/new EEG (Optional)
% if strcmpi(Automaticity,'Yes')
% vis_artifacts(NEWEEG,EEG);
% disp('Ignore errors above !!');
% % Holds the figure until inspection is over
% Fig=msgbox('THE CODE WILL CONTINUE ONCE YOU PRESS OK','WAIT','warn');
% uiwait(Fig);
% close gcf
% end
%
% % Replace artifact data
% EEG.data = NEWEEG.data;
% end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SLEEP / NO SLEEP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmpi(Sleep, 'Yes')
% TO CONTINUE:
% TESTING THE NEW ALGORITHM:
% https://github.com/alexander-malafeev/feature-based-sleep-scoring
% % Channel to use
% SleepChan = ismember({EEG.chanlocs.labels},'C1'); % GUI!!
% LOCChan = ismember({EEG.chanlocs.labels},'Fp1');
% ROCChan = ismember({EEG.chanlocs.labels},'Fp2');
%
% % Main electrode data
% EEGSleep = squeeze(EEG.data(SleepChan,:));
%
% % truncate signals, i.e. it should contain integer number of epochs
% EpochsTF = SecondsEpoch*EEG.srate;
% MaxExp=floor(size(EEG.data,2)/EpochsTF); % how many X second epochs are in our file
% EEGSleep = EEGSleep(1,1:MaxExp*EpochsTF);
%
% % Additional electrodes
% EOG = zeros(1,size(EEGSleep,2));
% EMG = zeros(1,size(EEGSleep,2));
% LOC = squeeze(EEG.data(LOCChan,:));
% LOC = LOC(1,1:MaxExp*EpochsTF);
% ROC = squeeze(EEG.data(ROCChan,:));
% ROC = LOC(1,1:MaxExp*EpochsTF);
%
% % Channel power spectra
% FreqResol = 5; % GUI!!
% SamplingRate = EEG.srate;
% Spect = spectopo(EEGSleep,0,EEG.srate,'freqfac',FreqResol,'plot','off');
%
% % Extracting sleep-related features on 1 EEG channel
% [ X, FeaturesNames] = extractFeatures(Spect', EEGSleep, EOG, EMG,...
% SecondsEpoch, SamplingRate, FreqResol, LOC, ROC);
%%
% % Temporary epoching the file
% EEG = eeg_regepochs(EEG, SecondsEpoch);
%
% % WAVELET MORLET DECOMPOSITION
% % composed or real and imaginery numbers : Gaussian and complex sine wave
% % see : https://jallen.faculty.arizona.edu/sites/jallen.faculty.arizona.edu/files/Chapter_13_Complex_Morlet_Wavelets_Power_Phase.pdf
% % and : http://www.mikexcohen.com/left_toc.html
%
% % Waitbar updating
% WaitBarApp.Title = '1. PREPROCESSING: Sleep rejection';
%
% % Preallocation
% WTData.Morlet=[];
% SleepNoSleep=zeros(size(EEG.data,3),1);
%
% % Looping over epochs
% for j=1:size(EEG.data,3)
% % Computing Wavelet Morlet Decomposition
% [WTData.Morlet(:,:,j), Freq]=wt(EEG.data(:,:,j),EEG.srate,'fmin',2.6,'fmax',...
% 48,'Preprocess','on','Wavelet','Morlet','Padding',0,'plot','off','Display','off','f0',0.1);
% end
%
% % Calculating Power of complex number (i.e. absolute value)
% WTData.Absolute.All=abs(WTData.Morlet);
%
% % Calculating EEG bandpass filtered (i.e. only taking real number)
% % WTData.Absolute.All=real(WTData.Morlet);
% % Calculating Phase of complex number (arctan(imag/real))
% % WTData.Absolute.All=arctan(imag(WTData.Morlet)/real(WTData.Morlet));
%
% % Looking for indexes for Theta and Alpha bands
% Index.Theta=find(Freq>=5 & Freq<=7);
% Index.Alpha=find(Freq>=8 & Freq<=12);
%
% % Computing average WTdata for Theta and Alpha indexes
% WTData.Absolute.Theta=mean(WTData.Absolute.All(Index.Theta,:,:),1);
% WTData.Absolute.Alpha=mean(WTData.Absolute.All(Index.Alpha,:,:),1);
% WTData.Absolute.Theta=squeeze(mean(WTData.Absolute.Theta,2));
% WTData.Absolute.Alpha=squeeze(mean(WTData.Absolute.Alpha,2));
%
% % Plotting the amplitude values (absolute)
% figure
% plot(1:length(WTData.Absolute.Theta),WTData.Absolute.Theta)
% hold on
% plot(1:length(WTData.Absolute.Alpha),WTData.Absolute.Alpha)
% title('Morlet Wavelet Decomposition')
% xlabel('Epochs')
% ylabel('Amplitude (absolute values)')
% legend('Theta','Alpha')
%
% % Exporting SleepNoSleep figures
% if sum(~SavePath)<1
% SaveFigures(gcf,[SavePath '\Exports\' Date_Start '\SleepNoSleep\'...
% sprintf('WaveletMorletSleep_%d_%s',ParticipantNumber,...
% Conditions_OrderCell{Pos,WhichCond})],'w','bmp');
% else
% SaveFigures(gcf,[CurrentPWD '\Exports\' Date_Start '\SleepNoSleep\'...
% sprintf('WaveletMorletSleep_%d_%s',ParticipantNumber,...
% Conditions_OrderCell{Pos,WhichCond})],'w','bmp');
% end
%
% % Statistical decision if asleep or not
% % If = 1 means asleep / = 0 means awake
% for i=1:size(EEG.data,3)
% if WTData.Absolute.Alpha(i)<WTData.Absolute.Theta(i)
% SleepNoSleep(i)=1;
% else
% SleepNoSleep(i)=0;
% end
% end
%
% % Preparing list of trials in Awake/Asleep states
% TrialsAwake=[];
% TrialsAsleep=[];
% i=1;
% j=1;
% for n=1:length(SleepNoSleep)
% if SleepNoSleep(n)==0
% TrialsAwake(i)=n;
% i=i+1;
% else
% TrialsAsleep(j)=n;
% j=j+1;
% end
% end
%
% % EEG will only contain the trials corresponding to AWAKE state
% if ~isempty(TrialsAsleep)
% EEG = pop_select(EEG, 'trial', TrialsAwake);
% end
%
% % Indexes to store data in correct columns
% TempIndex = find(contains(lower(SleepNoSleepTable.Properties.VariableNames),...
% lower(Conditions_Names{WhichCond})));
%
% % Filling the SleepNoSleep table
% SleepNoSleepTable(Pos,TempIndex(1))={length(TrialsAsleep)};
% SleepNoSleepTable(Pos,TempIndex(2))={length(TrialsAwake)};
%
% % Unepoching the file
% % Epoching was only temporary to perform Wavelet Morlet Conv
% EEG = eeg_epoch2continuous(EEG);
%
% % Removing the events that were created by Epoching
% EventFields={'event','urevent'};
% for t=1:length(EventFields)
% IdxX = contains({EEG.(EventFields{t}).type},'X');
% IdxBound = contains({EEG.(EventFields{t}).type},'boundary');
% EEG.(EventFields{t})(or(IdxX,IdxBound))=[];
% end
end
% Save DATASET 1 - FILTERED
if strcmpi(ExpFilt,'Yes')
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, CURRENTSET,'setname',...
sprintf(Dataset_filtCleaned, SubjName,WhichCond)...
,'gui','off', 'savenew', [Dir_save '\\' sprintf(Dataset_filtCleaned, SubjName, WhichCond)]);
end
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BAD CHANNELS INTERPOLATION AND AVERAGE REFERENCING
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Reintroduce the bad channels data
Temp = zeros(length(Channels),size(EEG.data,2)); PosGood = 1; PosBad = 1;
for m=Channels
if ~ismember(m,EEG.BadChans.InterpChans)
Temp(m,:) = EEG.data(PosGood,:); PosGood = PosGood + 1;
else
% Restricting channel data length since EEG.data
% size might have changed with artifact rejection
Temp(m,:) = EEG.BadChans.data(PosBad,1:size(EEG.data,2));PosBad = PosBad + 1;
end