-
Notifications
You must be signed in to change notification settings - Fork 3
/
2_preprocessing_AEC_ortho.m
1241 lines (1070 loc) · 53.1 KB
/
2_preprocessing_AEC_ortho.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
%% == License ==========================================================
% This file is part of the project megFingerprinting. All of
% megFingerprinting code 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 3 of the License, or (at your option) any later version.
% megFingerprinting 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 megFingerprinting.
% If not, see <https://www.gnu.org/licenses/>.
%% == omMachina: OMEGA Preprocessing ==================================
% Based on OMEGA's preprocessing script by Guiomar Niso (26 May 2016)
% 1. Import BIDS dataset (will not work if we are not using this format!)
% 2. Import subject's anatomy
% 3. Prepare MEG and Noise files
% 4. Run PSD on sensors
% 5. Filtering: Line noise and high pass
% 6. SSP: EOG and ECG
% 7. postProcessing: PSD on sensors
% 8. SSP: Sacades and EMG
% 9. Preprocess empty room recordings
% 10. Separate into FOI's
% 11. Data/Noise Covariances
% 12. Compute head model
% 13. Inverse Modelling: Beamformers
% 14. Snapshot: Contact sheet of sources
% 15. Amplitude Envelope Correlation
% 16. Output CSV file
% 17. Save and ouput report
% 18. Delete intermediate files and save beamformer weights
%% == Initiate Brainstorm and protocol setup =============================
clc; clear;
cd './brainstorm3'
if ~brainstorm('status')
brainstorm nogui % If brainstorm ain't running, run it with no GUI
end
% Create protocol; if it already exists, load it
omProtocol.name = 'omMachina_3';
if exist('./brainstorm_db/omMachina_3', 'file') == 7
omProtocol.index = bst_get('Protocol', omProtocol.name);
bst_set('iProtocol', omProtocol.index);
else
gui_brainstorm('CreateProtocol', omProtocol.name, 0, 0);
end
%% == Parameters =========================================================
% MEG datasets storage
mydirMEG = './data/OMEGA_BIDS';
% Dir to save progress report
mydirBST = './output/reports';
% Dir of database
mydirDB = './data';
% Frequencies to filter with the noth (power line 60Hz and harmonics)
freqs_notch = [60, 120, 180, 240, 300, 360, 420, 480, 540, 600];
% Filters
filt.highpass = 0.3;
filt.lowpass = 0.; % 0: no filter
filter_low.deltaLow = 1.;
filter_high.deltaHigh = 4.;
filter_low.thetaLow = 4.;
filter_high.thetaHigh = 8.;
filter_low.alphaLow = 8.;
filter_high.alphaHigh = 13.;
filter_low.betaLow = 13.;
filter_high.betaHigh = 30.;
filter_low.gammaLow = 30.;
filter_high.gammaHigh = 50.;
filter_low.hgammaLow = 50.;
filter_high.hgammaHigh = 150.;
% Window length and overlap for PSD Welch method
win_length = 2; % sec
win_overlap = 50; % percentage
% .mat files include variables to arrange the atlas into Yeo's RSN
load('./dependencies/desikan_scale33.mat');
load('./dependencies/rsn_mapping_yeo.mat');
%% == 1) Import BIDS dataset =============================================
% Import BIDS dataset - This will import all subjects in the file!
sFiles = process_import_bids('ImportBidsDataset', mydirMEG, 15000, 0 , 1)
% 15000 vertices
% 0 = non-interactive
% 1 = allign sensors with head points
sSubjects = bst_get('ProtocolSubjects');
SubjectNames = {sSubjects.Subject.Name}';
%% == 2) Import subject's anatomy =======================================
% Because I am using OMEGA reconstructed anatomy (from the preprocessed
% version), we need to copy the files manually to the database (these are
% downloaded with the bash script). I start at the end because when using
% the delete_subject brainstorm function this updates automatically the
% database, so starting at the end will not fuck up the indexes of the
% subjects even when deleting some of them
for iSubject=(numel(SubjectNames)-1):-1:1
fold_bool = exist(['./data/OMEGA_BIDS/' SubjectNames{iSubject} '/ses-0001/anat']);
anat_file_bool = exist(['./data/OMEGA_BIDS/' SubjectNames{iSubject} '/ses-0001/anat/subjectimage_T1.mat']);
if fold_bool == 7 & anat_file_bool == 2
source = ['./data/OMEGA_BIDS/' SubjectNames{iSubject} '/ses-0001/anat'];
destination = ['./brainstorm_db/omMachina_3/anat/' SubjectNames{iSubject}];
copyfile(source, destination);
else
fprintf([SubjectNames{iSubject} ' has no processed anatomy and will be deleted!'])
db_delete_subjects(iSubject)
end
end
db_reload_database('current')
%% == 3) Prepare MEG & Noise files =======================================
% Process: Select file names with tag: noise
sNoise = bst_process('CallProcess', 'process_select_files_data',...
[], [], ...
'subjectname', 'sub-emptyroom', ...
'condition', '', ...
'tag', '', ...
'includebad', 0, ...
'includeintra', 0, ...
'includecommon', 0);
% Get cell aray with emtpy room recording dates
noiseDates = squeeze(zeros(numel(sNoise), 1));
for i=1:numel(sNoise)
noiseDates(i) = str2num(sNoise(i).FileName(37:44));
end
noiseDates = datetime(num2str(noiseDates), 'InputFormat','yyyyMMdd');
%% Prepare iteration variables so the parfor can run
sSubjects = bst_get('ProtocolSubjects');
SubjectNames = {sSubjects.Subject.Name}';
nSubjects = (numel(SubjectNames)-1);
for iSubject=20:30
tic
% Start a new report
reportName = [SubjectNames{iSubject} '_report'];
bst_report('Start', reportName);
sessions = dir([mydirMEG '/' SubjectNames{iSubject}]);
sessions = sessions(3:end); % Start from 3, because Linux
nSessions = numel(sessions);
% for iSession = 1:nSessions % Only analyzing session 1 for everyone!
fprintf(['Now processing: ' SubjectNames{iSubject} '\n'])
% Process: select data
sData = bst_process('CallProcess', 'process_select_files_data', ...
[], [], 'subjectname', SubjectNames{iSubject});
sData = bst_process('CallProcess', 'process_select_tag', ...
sData, [], ...
'tag', 'baselineresting', ...
'search', 1, ...
'select', 1); % Select only the files with the tag
% Process: If there is no baseline resting, analyze post-experiment
% baseline
if isempty(sData)
sData = bst_process('CallProcess', 'process_select_files_data', ...
[], [], 'subjectname', SubjectNames{iSubject});
sData = bst_process('CallProcess', 'process_select_tag', ...
sData, [], ...
'tag', 'restingaftertask', ...
'search', 1, ...
'select', 1); % Select only the files with the tag
sData = sData(1);
else
sData = sData(1);
end
% Process: Convert to continuous (CTF): Continuous
cont_bool = load(file_fullpath(sData.FileName), 'F');
time_bool = load(file_fullpath(sData.FileName), 'Time');
if ~(strcmp(cont_bool.F.format, 'CTF-CONTINUOUS'))
sData = bst_process('CallProcess', 'process_ctf_convert', ...
sData, [], 'rectype', 2);
end
% Sometimes the files are not continous but they only contain one long
% epoch. This bit controls for that
if isempty(sData)
if time_bool.Time(2) > 2
% Process: select data
sData = bst_process('CallProcess', 'process_select_files_data', ...
[], [], 'subjectname', SubjectNames{iSubject});
sData = bst_process('CallProcess', 'process_select_tag', ...
sData, [], ...
'tag', 'baselineresting', ...
'search', 1, ...
'select', 1); % Select only the files with the tag
end
end
% Process: If there is no baseline resting, analyze post-experiment
% baseline
if isempty(sData)
sData = bst_process('CallProcess', 'process_select_files_data', ...
[], [], 'subjectname', SubjectNames{iSubject});
sData = bst_process('CallProcess', 'process_select_tag', ...
sData, [], ...
'tag', 'restingaftertask', ...
'search', 1, ...
'select', 1); % Select only the files with the tag
sData = sData(1);
else
sData = sData(1);
end
% Process: Refine registration
sRefined = bst_process('CallProcess', ...
'process_headpoints_refine', sData, []);
% Process: Select file names with tag: rest
sFilesR = bst_process('CallProcess', 'process_select_tag', ...
sRefined, [], ...
'tag', 'baselineresting', ... % Differentiate from other files
'search', 1, ... % 1: Filename, 2: Comments
'select', 1); % Select only the files with the tag
% Process: If there is no baseline resting, analyze post-experiment
% baseline
if isempty(sFilesR)
sFilesR = bst_process('CallProcess', 'process_select_tag', ...
sRefined, [], ...
'tag', 'restingaftertask', ... % Differentiate from other files
'search', 1, ... % 1: Filename, 2: Comments
'select', 1); % Select only the files with the tag
sFilesR = sFilesR(1);
else
sFilesR = sFilesR(1);
end
% Process: Snapshot of Sensors/MRI registration (goes into report)
bst_process('CallProcess', 'process_snapshot', ...
sFilesR, [], ...
'target', 1, ... % Sensors/MRI registration
'modality', 1, ...% MEG (All)
'orient', 1, ... % left
'time', 0, ...
'contact_time', [0, 0.1], ...
'contact_nimage', 12, ...
'threshold', 30, ...
'comment', '');
%% == 4) preProcessing PSD on sensors ============================
% Process: Power spectrum density (Welch) pre-filtering
sFilesPSDpre = bst_process('CallProcess', 'process_psd', ...
sFilesR, [], ...
'timewindow', [], ...
'win_length', win_length, ...
'win_overlap', win_overlap, ...
'sensortypes', 'MEG, EEG', ...
'edit', struct(...
'Comment', 'Power', ...
'TimeBands', [], ...
'Freqs', [], ...
'ClusterFuncTime', 'none', ...
'Measure', 'power', ...
'Output', 'all', ...
'SaveKernel', 0));
% Process: Snapshot of Frequency spectrum prefiltering (goes into report))
bst_process('CallProcess', 'process_snapshot', ...
sFilesPSDpre, [], ...
'target', 10, ... % Frequency spectrum
'modality', 1, ... % MEG (All)
'orient', 1, ... % left
'time', 0, ...
'contact_time', [0, 0.1], ...
'contact_nimage', 12, ...
'threshold', 30, ...
'comment', 'prePreprocessing');
%% == 5) Filtering: Line noise and high pass =====================
% Process: Notch filter(60Hz + 10 Harmonics)
sFilesNotch = bst_process('CallProcess', 'process_notch', ...
sFilesR, [], ...
'freqlist', freqs_notch, ...
'sensortypes', 'MEG, EEG', ...
'read_all', 0);
% Process: High-pass:0.3Hz
sFilesMEG = bst_process('CallProcess', 'process_bandpass', ...
sFilesNotch, [], ...
'highpass', filt.highpass, ...
'lowpass', filt.lowpass, ...
'mirror', 0, ...
'sensortypes', 'MEG, EEG', ...
'read_all', 0);
% Delete intermediate files (Notch)
for iRun=1:numel(sFilesNotch)
% Process: Delete data files
bst_process('CallProcess', 'process_delete', ...
sFilesNotch(iRun).FileName, [], ...
'target', 2); % Delete conditions
end
%% == 6) SSP: EOG and ECG ========================================
% Process: Select file names with tag: resting
sFilesRESTING = bst_process('CallProcess', 'process_select_tag', ...
sFilesMEG, [], ...
'tag', 'baselineresting', ...
'search', 1, ...
'select', 1); % Select only the files with the tag
% Process: If there is no baseline resting, analyze post-experiment
% baseline
if isempty(sFilesRESTING)
sFilesRESTING = bst_process('CallProcess', 'process_select_tag', ...
sFilesMEG, [], ...
'tag', 'restingaftertask', ... % Differentiate from other files
'search', 1, ... % 1: Filename, 2: Comments
'select', 1); % Select only the files with the tag
sFilesRESTING = sFilesRESTING(1);
else
sFilesRESTING = sFilesRESTING(1);
end
% SSP detect and remove blinks per run
for iRun=1:numel(sFilesRESTING)
% Read the channel file
ChannelMat = in_bst_channel(sFilesRESTING(iRun).ChannelFile);
% Look for ECG channel
iChannelECG = channel_find(ChannelMat.Channel, 'ECG');
% Look for EOG channel
iChannelVEOG = channel_find(ChannelMat.Channel, 'VEOG');
% Process: Detect heartbeats
if ~isempty(iChannelECG)
bst_process('CallProcess', 'process_evt_detect_ecg', ...
sFilesRESTING(iRun), [], ...
'channelname', ChannelMat.Channel(iChannelECG).Name,...
'timewindow', [], ...
'eventname', 'cardiac');
else
disp('No ECG channel found!')
end
% Process: Detect eye blinks
if ~isempty(iChannelVEOG)
bst_process('CallProcess', 'process_evt_detect_eog', ...
sFilesRESTING(iRun), [], ...
'channelname', ChannelMat.Channel(iChannelVEOG).Name, ...
'timewindow', [], ...
'eventname', 'blink');
else
disp('No EOG channel found!')
end
end
% Process: Remove simultaneous (keep blinks over heart beats)
bst_process('CallProcess', 'process_evt_remove_simult', ...
sFilesRESTING, [], ...
'remove', 'cardiac', ...
'target', 'blink', ...
'dt', 0.25, ...
'rename', 0);
% Process: SSP ECG (cardiac) force remove 1st component
bst_process('CallProcess', 'process_ssp_ecg', ...
sFilesRESTING, [], ...
'eventname', 'cardiac', ...
'sensortypes', 'MEG', ...
'usessp', 1, ...
'select', 1);
% Process: SSP EOG (blink) force remove 1st component
bst_process('CallProcess', 'process_ssp_eog', ...
sFilesRESTING, [], ...
'eventname', 'blink', ...
'sensortypes', 'MEG', ...
'usessp', 1, ...
'select', 1);
% Process: Snapshot: SSP projectors
bst_process('CallProcess', 'process_snapshot', ...
sFilesRESTING, [], ...
'target', 2, ... % SSP projectors
'modality', 1, ... % MEG (All)
'orient', 1, ... % left
'time', 0, ...
'contact_time', [0, 0.1], ...
'contact_nimage', 12, ...
'threshold', 30, ...
'comment', '');
%% == 7) postProcessing PSD on sensors ===========================
% Process: Power spectrum density (Welch)
sFilesPSDpost = bst_process('CallProcess', 'process_psd', ...
sFilesRESTING, [], ...
'timewindow', [], ...
'win_length', win_length, ...
'win_overlap', win_overlap, ...
'sensortypes', 'MEG, EEG', ...
'edit', struct(...
'Comment', 'Power', ...
'TimeBands', [], ...
'Freqs', [], ...
'ClusterFuncTime', 'none', ...
'Measure', 'power', ...
'Output', 'all', ...
'SaveKernel', 0));
% Process: Snapshot: Frequency spectrum
bst_process('CallProcess', 'process_snapshot', ...
sFilesPSDpost, [], ...
'target', 10, ... % Frequency spectrum
'modality', 1, ... % MEG (All)
'orient', 1, ... % left
'time', 0, ...
'contact_time', [0, 0.1], ...
'contact_nimage', 12, ...
'threshold', 30, ...
'comment', 'After filtering and EOG/ECG SSP');
%% == 8) SSP: Sacades and EMG ====================================
% Process: Detect other artifacts (mark noisy segments)
bst_process('CallProcess', 'process_evt_detect_badsegment', ...
sFilesRESTING, [], ...
'timewindow', [], ...
'sensortypes', 'MEG, EEG', ...
'threshold', 3, ... % 3
'isLowFreq', 1, ...
'isHighFreq', 1);
% Process: SSP for low frequencies (saccades) 1 - 7 Hz (remove 1st)
bst_process('CallProcess', 'process_ssp', ...
sFilesRESTING, [], ...
'timewindow', [], ...
'eventname', '1-7Hz', ...
'eventtime', [], ...
'bandpass', [1, 7], ...
'sensortypes', 'MEG', ...
'usessp', 1, ...
'saveerp', 0, ...
'method', 1, ... % PCA: One component per sensor
'select', 1);
% Process: SSP for high frequencies (muscle) 40 - 400 Hz (remove 1st)
bst_process('CallProcess', 'process_ssp', ...
sFilesRESTING, [], ...
'timewindow', [], ...
'eventname', '', ...
'eventtime', [], ...
'bandpass', [40, 400], ...
'sensortypes', 'MEG', ...
'usessp', 1, ...
'saveerp', 0, ...
'method', 1, ... % PCA: One component per sensor
'select', 1);
%% == 9) Preprocess empty room recordings ========================
% Process: find the empty room recordings closest to this date
temp_date = load(['./brainstorm_db/omMachina_3/data/' sData.FileName]);
sub_date = [datetime(temp_date.F.header.res4.data_date, 'InputFormat', 'dd-MM-yyyy')];
[~, ind1] = min(abs(datenum(noiseDates) - datenum(sub_date)));
sub_noise = noiseDates(ind1, :);
sub_noise = string(datestr(sub_noise, 'yyyymmdd'));
% Process: Select noise recordings closest to participants testing date
sSubNoise = bst_process('CallProcess', 'process_select_tag', ...
sNoise, [], ...
'tag', sub_noise, ...
'search', 1, ...
'select', 1); % Select only the files with the tag
if ~(numel(sSubNoise) == 1)
sSubNoise = sSubNoise(1);
end
% Preprocess empty room recording!
% Process: Convert to continuous (CTF): Continuous
cont_bool = load(file_fullpath(sSubNoise.FileName), 'F');
time_bool = load(file_fullpath(sSubNoise.FileName), 'Time');
if ~(strcmp(cont_bool.F.format, 'CTF-CONTINUOUS'))
sSubNoise = bst_process('CallProcess', 'process_ctf_convert', ...
sSubNoise, [], 'rectype', 2);
end
% Sometimes the files are not continous but they only contain one long
% epoch. This bit controls for that
if isempty(sSubNoise)
if time_bool.Time(2) > 2
sSubNoise = bst_process('CallProcess', 'process_select_tag', ...
sNoise, [], ...
'tag', sub_noise, ...
'search', 1, ...
'select', 1); % Select only the files with the tag
end
end
% Process: Notch filter line noise
sNoiseFilesNotch = bst_process('CallProcess', 'process_notch', ...
sSubNoise, [], ...
'freqlist', freqs_notch, ...
'sensortypes', 'MEG, EEG', ...
'read_all', 1);
% Process: High-pass:0.3Hz
sFilesMEGNoise = bst_process('CallProcess', 'process_bandpass', ...
sNoiseFilesNotch, [], ...
'highpass', filt.highpass, ...
'lowpass', filt.lowpass, ...
'mirror', 0, ...
'sensortypes', 'MEG, EEG', ...
'read_all', 1);
%% == 10) Separate into FOI's =====================================
sFOI = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
sNoiseFOI = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
sFOI_names = fieldnames(sFOI);
filtL_names = fieldnames(filter_low);
filtH_names = fieldnames(filter_high);
nFOI = numel(sFOI_names);
for iFOI = 1:nFOI
sFOI.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_bandpass', ...
sFilesRESTING, [], ...
'highpass', filter_low.(filtL_names{iFOI}), ...
'lowpass', filter_high.(filtH_names{iFOI}), ...
'attenuation', 'strict', ... % 60dB
'sensortypes', 'MEG',...
'mirror', 0, ...
'read_all', 1, ... % Channels have SSP projections, read it all
'Method', 'bst-hfilter'); % This implements a Kaiser window FIR
sFOI.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_add_tag', ...
sFOI.(sFOI_names{iFOI}), [], ...
'tag', sFOI_names{iFOI}, ...
'output', 2); % Add to file name
% Process: Power spectrum density (Welch)
sFilesPSDpost = bst_process('CallProcess', 'process_psd', ...
sFOI.(sFOI_names{iFOI}), [], ...
'timewindow', [], ...
'win_length', win_length, ...
'win_overlap', win_overlap, ...
'sensortypes', 'MEG', ...
'edit', struct(...
'Comment', 'Power', ...
'TimeBands', [], ...
'Freqs', [], ...
'ClusterFuncTime', 'none', ...
'Measure', 'power', ...
'Output', 'all', ...
'SaveKernel', 0));
% Process: Snapshot: Frequency spectrum
bst_process('CallProcess', 'process_snapshot', ...
sFilesPSDpost, [], ...
'target', 10, ... % Frequency spectrum
'modality', 1, ... % MEG (All)
'orient', 1, ... % left
'time', 0, ...
'contact_time', [0, 0.1], ...
'contact_nimage', 12, ...
'threshold', 30, ...
'comment', sFOI_names{iFOI});
% Noise recording
sNoiseFOI.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_bandpass', ...
sFilesMEGNoise, [], ...
'highpass', filter_low.(filtL_names{iFOI}), ...
'lowpass', filter_high.(filtH_names{iFOI}), ...
'attenuation', 'strict', ... % 60dB
'sensortypes', 'MEG',...
'mirror', 0, ...
'read_all', 1, ...
'Method', 'bst-hfilter'); % This implements a Kaiser window FIR
sNoiseFOI.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_add_tag', ...
sNoiseFOI.(sFOI_names{iFOI}), [], ...
'tag', sFOI_names{iFOI}, ...
'output', 2); % Add to file name
end
% Brainstorm gets confused when you do things with scripting, so
% I'm reloading the database just in case
db_reload_database('current')
%% == 11) Data/Noise Covariance ==================================
for iFOI = 1:nFOI
% Import both files into the database
sFOI.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_import_data_time', ...
sFOI.(sFOI_names{iFOI}).FileName, [], ...
'subjectname', SubjectNames{iSubject}, ...
'condition', ['meg_' sFOI_names{iFOI}], ...
'timewindow', [], ...
'split', 0, ...
'ignoreshort', 0, ...
'usectfcomp', 1, ...
'usessp', 1, ...
'freq', [], ...
'baseline', []);
sNoiseFOI.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_import_data_time', ...
sNoiseFOI.(sFOI_names{iFOI}), [], ...
'subjectname', SubjectNames{iSubject}, ...
'condition', ['emptyroom_' sFOI_names{iFOI}], ...
'timewindow', [], ...
'split', 0, ...
'ignoreshort', 0, ...
'usectfcomp', 1, ...
'usessp', 1, ...
'freq', [], ...
'baseline', []);
% Standardize the number of channels
sFilesTEMP = bst_process('CallProcess', 'process_stdchan', ...
{sFOI.(sFOI_names{iFOI}).FileName, ...
sNoiseFOI.(sFOI_names{iFOI}).FileName}, [], ...
'method', 1); % Keep only the common channel names=> Remove all the others
sFOI.(sFOI_names{iFOI}) = sFilesTEMP(1);
sNoiseFOI.(sFOI_names{iFOI}) = sFilesTEMP(2);
% Compute the data covariance
sTime = load(file_fullpath(sFOI.(sFOI_names{iFOI}).FileName), 'Time');
bst_process('CallProcess', 'process_noisecov', ...
sFOI.(sFOI_names{iFOI}), [], ...
'baseline', [sTime.Time(1) sTime.Time(end)], ...
'datatimewindow', [sTime.Time(1) sTime.Time(end)], ...
'sensortypes', 'MEG', ...
'target', 2, ... % Data covariance
'dcoffset', 1, ... % Block by block
'identity', 0, ...
'copycond', 0, ...
'copysubj', 0, ...
'copymatch', 0, ...
'replacefile', 1); % Replace
% Compute the noise covariance
bst_process('CallProcess', 'process_noisecov', ...
sNoiseFOI.(sFOI_names{iFOI}), [], ...
'baseline', [], ...
'datatimewindow', [], ...
'sensortypes', 'MEG', ...
'target', 1, ... % Noise covariance
'dcoffset', 1, ... % Block by block
'identity', 0, ...
'copycond', 0, ...
'copysubj', 0, ...
'copymatch', 0, ...
'replacefile', 1); % Replace
% Copy subject's noise covariance
source = ['./brainstorm_db/omMachina_3/data/' SubjectNames{iSubject} '/emptyroom_' sFOI_names{iFOI} '/noisecov_full.mat'];
destination = ['./brainstorm_db/omMachina_3/data/' SubjectNames{iSubject} '/meg_' sFOI_names{iFOI} '/'];
copyfile(source, destination);
end
% Brainstorm gets confused when you do things with scripting, so
% I'm reloading the database just in case
db_reload_database('current')
%% == 12) Compute head model =====================================
for iFOI = 1:nFOI
bst_process('CallProcess', 'process_headmodel',...
sFOI.(sFOI_names{iFOI}), [], ...
'Comment', '', ...
'sourcespace', 1, ... % Cortex surface
'volumegrid', struct(...
'Method', 'isotropic', ...
'nLayers', 17, ...
'Reduction', 3, ...
'nVerticesInit', 4000, ...
'Resolution', 0.005, ...
'FileName', ''), ...
'meg', 3, ... % Overlapping spheres
'eeg', 1, ... %
'ecog', 1, ... %
'seeg', 1, ... %
'openmeeg', struct(...
'BemFiles', {{}}, ...
'BemNames', {{'Scalp', 'Skull', 'Brain'}}, ...
'BemCond', [1, 0.0125, 1], ...
'BemSelect', [1, 1, 1], ...
'isAdjoint', 0, ...
'isAdaptative', 1, ...
'isSplit', 0, ...
'SplitLength', 4000));
end
%% == 13) Inverse Modelling: Beamformers =========================
for iFOI = 1:nFOI
bst_process('CallProcess', 'process_inverse_2016',...
sFOI.(sFOI_names{iFOI}), [], ...
'output', 1, ... % Kernel only: shared
'inverse', struct(...
'Comment', 'PNAI: MEG', ...
'InverseMethod', 'lcmv', ...
'InverseMeasure', 'nai', ...
'SourceOrient', {{'fixed'}}, ...
'Loose', 0.2, ...
'UseDepth', 1, ...
'WeightExp', 0.5, ...
'WeightLimit', 10, ...
'NoiseMethod', 'median', ...
'NoiseReg', 0.1, ...
'SnrMethod', 'rms', ...
'SnrRms', 1e-06, ...
'SnrFixed', 3, ...
'ComputeKernel', 1, ...
'DataTypes', {{'MEG'}}));
end
%% == 14) Snapshot: Contact sheet of sources =========================
sSources = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
'beta', ' ', 'gamma', ' ', 'hgamma', ' ', 'validation', ' ', ...
'training', '');
sSources.training = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
sSources.validation = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
% sSources.training1 = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
% 'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
% sSources.training2 = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
% 'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
% sSources.training3 = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
% 'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
% sSources.training4 = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
% 'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
% sSources.validation = struct('delta', ' ', 'theta', ' ', 'alpha', ' ', ...
% 'beta', ' ', 'gamma', ' ', 'hgamma', ' ');
for iFOI = 1:nFOI
sSources.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_select_files_results', ...
[], [], ...
'subjectname', SubjectNames{iSubject}, ...
'condition', ['meg_' (sFOI_names{iFOI})], ...
'tag', '', ...
'includebad', 0, ...
'includeintra', 0, ...
'includecommon', 0);
bst_process('CallProcess', 'process_snapshot', ...
sSources.(sFOI_names{iFOI}), [], ...
'target', 9, ... % Sources (contact sheet)
'modality', 1, ... % MEG (All)
'orient', 1, ... % left
'time', [], ...
'contact_time', [sTime.Time(1) sTime.Time(end)], ...
'contact_nimage', 16, ...
'threshold', 15, ...
'Comment', sFOI_names{iFOI});
end
%% == 15) Amplitude Envelope Correlation =============================
sMatrix = struct('training', ' ', 'validation', ' ');
sMatrix.training = cell(27744, 4);
sMatrix.validation = cell(27744, 4);
for iFOI = 1:nFOI
% Get the output from the command line
diary off
diaryFileName = ['./output/pca_output/' SubjectNames{iSubject} '_' sFOI_names{iFOI} '_pca_output.txt' ];
diary(diaryFileName)
% Process: AEC NxN for training set
sSources.training.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_aec1n', ...
sSources.(sFOI_names{iFOI}).FileName, [], ...
'timewindow', [(5), (floor((sTime.Time(end))/2))], ...
'scouts', {'Desikan-Killiany', {'bankssts L', 'bankssts R', 'caudalanteriorcingulate L', 'caudalanteriorcingulate R', 'caudalmiddlefrontal L', 'caudalmiddlefrontal R', 'cuneus L', 'cuneus R', 'entorhinal L', 'entorhinal R', 'frontalpole L', 'frontalpole R', 'fusiform L', 'fusiform R', 'inferiorparietal L', 'inferiorparietal R', 'inferiortemporal L', 'inferiortemporal R', 'insula L', 'insula R', 'isthmuscingulate L', 'isthmuscingulate R', 'lateraloccipital L', 'lateraloccipital R', 'lateralorbitofrontal L', 'lateralorbitofrontal R', 'lingual L', 'lingual R', 'medialorbitofrontal L', 'medialorbitofrontal R', 'middletemporal L', 'middletemporal R', 'paracentral L', 'paracentral R', 'parahippocampal L', 'parahippocampal R', 'parsopercularis L', 'parsopercularis R', 'parsorbitalis L', 'parsorbitalis R', 'parstriangularis L', 'parstriangularis R', 'pericalcarine L', 'pericalcarine R', 'postcentral L', 'postcentral R', 'posteriorcingulate L', 'posteriorcingulate R', 'precentral L', 'precentral R', 'precuneus L', 'precuneus R', 'rostralanteriorcingulate L', 'rostralanteriorcingulate R', 'rostralmiddlefrontal L', 'rostralmiddlefrontal R', 'superiorfrontal L', 'superiorfrontal R', 'superiorparietal L', 'superiorparietal R', 'superiortemporal L', 'superiortemporal R', 'supramarginal L', 'supramarginal R', 'temporalpole L', 'temporalpole R', 'transversetemporal L', 'transversetemporal R'}}, ...
'scoutfunc', 3, ... % PCA
'scouttime', 1, ... % Before
'freqbands', {sFOI_names{iFOI}, [num2str(filter_low.([sFOI_names{iFOI} 'Low'])) ',' num2str(filter_high.([sFOI_names{iFOI} 'High']))], 'mean'}, ...
'isorth', 0, ...
'outputmode', 1); % Save individual results (one file per input file)
% Process: Add tag
sSources.training.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_add_tag', ...
sSources.training.(sFOI_names{iFOI}).FileName, [], ...
'tag', ['training_' sFOI_names{iFOI}], ...
'output', 2); % Add to file name
% Load Training Matrix
tMatrix = load(file_fullpath(sSources.training.(sFOI_names{iFOI}).FileName));
% Unload values unto big matrix file
n = 1;
for iSource=1:numel(tMatrix.RowNames)
for iTarget=1:numel(tMatrix.RowNames)
sMatrix.training{n + (iFOI-1)*(4624), 1} = tMatrix.RowNames(iSource);
sMatrix.training{n + (iFOI-1)*(4624), 2} = tMatrix.RowNames(iTarget);
sMatrix.training{n + (iFOI-1)*(4624), 3} = tMatrix.TF(n);
sMatrix.training{n + (iFOI-1)*(4624), 4} = sFOI_names{iFOI};
n = n+1;
end
end
% Copy the matrix to outputs
source = file_fullpath(sSources.training.(sFOI_names{iFOI}).FileName);
destination = ['./output/bst_matrices/' SubjectNames{iSubject} '_aecMatrix_training_' sFOI_names{iFOI} '.mat']
copyfile(source, destination)
% Process: AEC NxN for validation set
sSources.validation.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_aec1n', ...
sSources.(sFOI_names{iFOI}).FileName, [], ...
'timewindow', [ceil((sTime.Time(end))/2), (sTime.Time(end) - 5)], ...
'scouts', {'Desikan-Killiany', {'bankssts L', 'bankssts R', 'caudalanteriorcingulate L', 'caudalanteriorcingulate R', 'caudalmiddlefrontal L', 'caudalmiddlefrontal R', 'cuneus L', 'cuneus R', 'entorhinal L', 'entorhinal R', 'frontalpole L', 'frontalpole R', 'fusiform L', 'fusiform R', 'inferiorparietal L', 'inferiorparietal R', 'inferiortemporal L', 'inferiortemporal R', 'insula L', 'insula R', 'isthmuscingulate L', 'isthmuscingulate R', 'lateraloccipital L', 'lateraloccipital R', 'lateralorbitofrontal L', 'lateralorbitofrontal R', 'lingual L', 'lingual R', 'medialorbitofrontal L', 'medialorbitofrontal R', 'middletemporal L', 'middletemporal R', 'paracentral L', 'paracentral R', 'parahippocampal L', 'parahippocampal R', 'parsopercularis L', 'parsopercularis R', 'parsorbitalis L', 'parsorbitalis R', 'parstriangularis L', 'parstriangularis R', 'pericalcarine L', 'pericalcarine R', 'postcentral L', 'postcentral R', 'posteriorcingulate L', 'posteriorcingulate R', 'precentral L', 'precentral R', 'precuneus L', 'precuneus R', 'rostralanteriorcingulate L', 'rostralanteriorcingulate R', 'rostralmiddlefrontal L', 'rostralmiddlefrontal R', 'superiorfrontal L', 'superiorfrontal R', 'superiorparietal L', 'superiorparietal R', 'superiortemporal L', 'superiortemporal R', 'supramarginal L', 'supramarginal R', 'temporalpole L', 'temporalpole R', 'transversetemporal L', 'transversetemporal R'}}, ...
'scoutfunc', 3, ... % PCA
'scouttime', 1, ... % Before
'freqbands', {sFOI_names{iFOI}, [num2str(filter_low.([sFOI_names{iFOI} 'Low'])) ',' num2str(filter_high.([sFOI_names{iFOI} 'High']))], 'mean'}, ...
'isorth', 0, ...
'outputmode', 1); % Save individual results (one file per input file)
% Stop output of Command Window
diary off
% Process: Add tag
sSources.validation.(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_add_tag', ...
sSources.validation.(sFOI_names{iFOI}).FileName, [], ...
'tag', ['validation_' sFOI_names{iFOI}], ...
'output', 2); % Add to file name
% Load Validation Matrix
vMatrix = load(file_fullpath(sSources.validation.(sFOI_names{iFOI}).FileName))
% Unload values unto big matrix file
n = 1;
for iSource=1:numel(vMatrix.RowNames)
for iTarget=1:numel(vMatrix.RowNames)
sMatrix.validation{n + (iFOI-1)*(4624), 1} = vMatrix.RowNames(iSource);
sMatrix.validation{n + (iFOI-1)*(4624), 2} = vMatrix.RowNames(iTarget);
sMatrix.validation{n + (iFOI-1)*(4624), 3} = vMatrix.TF(n);
sMatrix.validation{n + (iFOI-1)*(4624), 4} = sFOI_names{iFOI};
n = n+1;
end
end
% Copy the matrix to outputs
source = file_fullpath(sSources.validation.(sFOI_names{iFOI}).FileName);
destination = ['./output/bst_matrices/' SubjectNames{iSubject} '_aecMatrix_validation_' sFOI_names{iFOI} '.mat']
copyfile(source, destination)
end
db_reload_database('current')
%% == 16) Output CSV file ====================
% Training set
datei = fopen(['./output/csv_matrices' SubjectNames{iSubject} '_aecMatrix_training.csv'], 'w');
for z=1:size(sMatrix.training, 1)
for s=1:size(sMatrix.training, 2)
var = sMatrix.training{z,s};
% If cell, get the contents
if iscell(var)
var = var{1};
end
% If zero, then empty cell
if size(var, 1) == 0
var = 0;
end
% If numeric -> String
if isnumeric(var)
var = num2str(var);
end
% OUTPUT value
fprintf(datei, '%s', var);
% OUTPUT separator
if s ~= size(sMatrix.training, 2)
fprintf(datei, ',');
end
end
if z ~= size(sMatrix.training, 1) % prevent a empty line at EOF
% OUTPUT newline
fprintf(datei, '\n');
end
end
% Closing file
fclose(datei);
%% Validation set
datei = fopen(['./output/csv_matrices' SubjectNames{iSubject} '_aecMatrix_validation.csv'], 'w');
for z=1:size(sMatrix.validation, 1)
for s=1:size(sMatrix.validation, 2)
var = sMatrix.validation{z,s};
% If cell, get the contents
if iscell(var)
var = var{1};
end
% If zero, then empty cell
if size(var, 1) == 0
var = 0;
end
% If numeric -> String
if isnumeric(var)
var = num2str(var);
end
% OUTPUT value
fprintf(datei, '%s', var);
% OUTPUT separator
if s ~= size(sMatrix.validation, 2)
fprintf(datei, ',');
end
end
if z ~= size(sMatrix.validation, 1) % prevent a empty line at EOF
% OUTPUT newline
fprintf(datei, '\n');
end
end
% Closing file
fclose(datei);
%% == Uncomment the next section to get 30s chunks instead of 2:30
%{
%% == 15) Amplitude Envelope Correlation =============================
sMatrix = struct('training1', ' ', 'training2', ' ', 'training3', ' ', ...
'training4', ' ','validation', ' ');
sMatrix.training1 = cell(27744, 4);
sMatrix.training2 = cell(27744, 4);
sMatrix.validation = cell(27744, 4);
sTrain = {'training1', 'training2', 'validation'}
% Get the output from the command line
diary off
diaryFileName = ['/home/labuser/data/megFingerprinting/output/pca_output/' SubjectNames{iSubject} '_pca_output.txt' ];
diary(diaryFileName)
times_start = [5, 35, sTime.Time(end) - 40];
times_end = [35, 65,sTime.Time(end) - 10];
for iTrainMatrix = 1:2
for iFOI = 1:nFOI
fprintf(['Now calculating matrix for training set ' num2str(iTrainMatrix) ' at ' sFOI_names{iFOI} ' frequency band\n']);
% Process: AEC NxN for training sets
sSources.(sTrain{iTrainMatrix}).(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_aec1n', ...
sSources.(sFOI_names{iFOI}).FileName, [], ...
'timewindow', [times_start(iTrainMatrix), times_end(iTrainMatrix)], ...
'scouts', {'Desikan-Killiany', {'bankssts L', 'bankssts R', 'caudalanteriorcingulate L', 'caudalanteriorcingulate R', 'caudalmiddlefrontal L', 'caudalmiddlefrontal R', 'cuneus L', 'cuneus R', 'entorhinal L', 'entorhinal R', 'frontalpole L', 'frontalpole R', 'fusiform L', 'fusiform R', 'inferiorparietal L', 'inferiorparietal R', 'inferiortemporal L', 'inferiortemporal R', 'insula L', 'insula R', 'isthmuscingulate L', 'isthmuscingulate R', 'lateraloccipital L', 'lateraloccipital R', 'lateralorbitofrontal L', 'lateralorbitofrontal R', 'lingual L', 'lingual R', 'medialorbitofrontal L', 'medialorbitofrontal R', 'middletemporal L', 'middletemporal R', 'paracentral L', 'paracentral R', 'parahippocampal L', 'parahippocampal R', 'parsopercularis L', 'parsopercularis R', 'parsorbitalis L', 'parsorbitalis R', 'parstriangularis L', 'parstriangularis R', 'pericalcarine L', 'pericalcarine R', 'postcentral L', 'postcentral R', 'posteriorcingulate L', 'posteriorcingulate R', 'precentral L', 'precentral R', 'precuneus L', 'precuneus R', 'rostralanteriorcingulate L', 'rostralanteriorcingulate R', 'rostralmiddlefrontal L', 'rostralmiddlefrontal R', 'superiorfrontal L', 'superiorfrontal R', 'superiorparietal L', 'superiorparietal R', 'superiortemporal L', 'superiortemporal R', 'supramarginal L', 'supramarginal R', 'temporalpole L', 'temporalpole R', 'transversetemporal L', 'transversetemporal R'}}, ...
'scoutfunc', 3, ... % PCA
'scouttime', 1, ... % Before
'freqbands', {sFOI_names{iFOI}, [num2str(filter_low.([sFOI_names{iFOI} 'Low'])) ',' num2str(filter_high.([sFOI_names{iFOI} 'High']))], 'mean'}, ...
'isorth', 0, ...
'outputmode', 1); % Save individual results (one file per input file)
% Process: Add tag
sSources.(sTrain{iTrainMatrix}).(sFOI_names{iFOI}) = bst_process('CallProcess', 'process_add_tag', ...
sSources.(sTrain{iTrainMatrix}).(sFOI_names{iFOI}).FileName , [], ...
'tag', ['training' num2str(iTrainMatrix) '_' sFOI_names{iFOI}], ...
'output', 2); % Add to file name
% Load Training Matrix
tMatrix = load(file_fullpath(sSources.(sTrain{iTrainMatrix}).(sFOI_names{iFOI}).FileName));
% Unload values unto big matrix file
n = 1;
for iSource=1:numel(tMatrix.RowNames)
for iTarget=1:numel(tMatrix.RowNames)
sMatrix.(sTrain{iTrainMatrix}){n + (iFOI-1)*(4624), 1} = tMatrix.RowNames(iSource);
sMatrix.(sTrain{iTrainMatrix}){n + (iFOI-1)*(4624), 2} = tMatrix.RowNames(iTarget);