-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemOrder.m
2971 lines (2444 loc) · 121 KB
/
memOrder.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
classdef memOrder < handle
%% Properties
properties(SetAccess = private)
subID
folderDir
encode
sceneRecog
timeDiscrim
validTasks
validPhases
end
%% Methods
methods
%% Constructor
function obj = memOrder(folderDir)
%% Notes
%% Set folderDir and subID
obj.subID = extractBefore(extractAfter(folderDir,'Folder\'),'\');
obj.folderDir = folderDir;
%% Set the directories
behavDir = append(folderDir,'Behavioral_Data\Raw\');
eyeDir = append(folderDir,'Eye-tracking\Processed\eyeDATA\cleaned_eyeDATA\');
nwbDir = append(folderDir,'NWBProcessing\NWB_Data\');
%% Determine file IDs
info_file = dir(fullfile(folderDir,'*.xlsx'));
info_file = append(folderDir,info_file.name);
fileIDs = readtable(info_file);
%% Grab file names
nwb_names = fileIDs.File;
behav_names = fileIDs.Behav;
%% Grab eye file
eye_names = dir(fullfile(eyeDir,'*.mat'));
eye_names = {eye_names.name}';
%% Grab eye to use
eyes = fileIDs{:,end};
%% Grab GAZE file
I = contains(eye_names,'GAZE');
eye_name = eye_names{I,1};
%% Create logicals
encode = logical(fileIDs.Encode);
sceneRecog = logical(fileIDs.SceneRecognition);
timeDiscrim = logical(fileIDs.TimeDiscrimination);
%% Add to object if task was performed
if any(encode == 1)
obj.encode.nwb_fname = append(nwbDir,nwb_names{encode});
obj.encode.behave_fname = append(behavDir,behav_names{encode});
obj.encode.eye_fname = append(eyeDir,eye_name);
obj.encode.eyeToUse = string(eyes{encode,1});
end
if any(sceneRecog == 1)
obj.sceneRecog.nwb_fname = append(nwbDir,nwb_names{sceneRecog});
obj.sceneRecog.behave_fname = append(behavDir,behav_names{sceneRecog});
obj.sceneRecog.eye_fname = append(eyeDir,eye_name);
obj.sceneRecog.eyeToUse = string(eyes{sceneRecog,1});
end
if any(timeDiscrim == 1)
obj.timeDiscrim.nwb_fname = append(nwbDir,nwb_names{timeDiscrim});
obj.timeDiscrim.behave_fname = append(behavDir,behav_names{timeDiscrim});
obj.timeDiscrim.eye_fname = append(eyeDir,eye_name);
obj.timeDiscrim.eyeToUse = string(eyes{timeDiscrim,1});
end
%% Find the non-empty structures for dynamic indexing
fieldNames = fieldnames(obj);
matchedNames = cell(length(fieldNames),1);
for ii = 1:length(fieldNames)
if isstruct(obj.(fieldNames{ii,1}))
if ~isempty(obj.(fieldNames{ii,1}))
matchedNames{ii,1} = fieldNames{ii,1};
end
end
end
%% Remove empty matchedNames
matchedNames = matchedNames(~cellfun('isempty',matchedNames));
%% Add to object
obj.validTasks = matchedNames;
%% Add valid phases
obj.validPhases = {"fixation";"presentation";"question"};
%% Preallocate
tmpNames = cell(length(matchedNames),1);
count = 1;
%% Loop through and do the NWB processing
for ii = 1:length(matchedNames)
%% Compare names to identify times through the same file
if any(strcmp(obj.(matchedNames{ii,1}).nwb_fname,tmpNames))
count = count + 1;
else
count = 1;
end
%% Move the file name to tmpNames
tmpNames{ii,1} = obj.(matchedNames{ii,1}).nwb_fname;
%% Print
fprintf('Ephys data loaded for sub %s and task %s..\n',obj.subID,matchedNames{ii,1})
%% Load the data
tmp = nwbRead(obj.(matchedNames{ii}).nwb_fname);
%% Load the behavioral info here
obj.(matchedNames{ii}).behave_info = load(obj.(matchedNames{ii}).behave_fname);
%% Convert respmat vales from old (-3 to 3) to new (111 to 116)
%% Load macrowire time stamps
timestamps = tmp.processing.get('ecephys').nwbdatainterface.get...
('LFP').electricalseries.get('MacroWireSeries').timestamps.load;
%% Downsample time stamps
obj.(matchedNames{ii,1}).LFP_timestamps = downsample(timestamps,8);
%% Convert time stamps
obj.(matchedNames{ii,1}).LFP_converted_timestamps = (obj.(matchedNames{ii,1}).LFP_timestamps - obj.(matchedNames{ii,1}).LFP_timestamps(1,1))/(1e6);
%% Get the sampling frequency
LFP_sessionInfo = tmp.processing.get('ecephys').nwbdatainterface.get...
('LFP').electricalseries.get('MacroWireSeries');
obj.(matchedNames{ii,1}).fs = str2double(cell2mat(extractBetween(LFP_sessionInfo.description,'= ',':')));
%% Get voltage for macrowires and convert
obj.(matchedNames{ii,1}).LFP_data = (double(tmp.processing.get('ecephys').nwbdatainterface.get...
('LFP').electricalseries.get('MacroWireSeries').data.load)) .* LFP_sessionInfo.data_conversion;
%% Channel IDs
chanLabels = cellstr(tmp.general_extracellular_ephys_electrodes.vectordata.get('label').data.load()); %use MA only!
MAchan = find(contains(chanLabels,'MA_'));
chanID = cellstr(tmp.general_extracellular_ephys_electrodes.vectordata.get('location').data.load());
hemisphere = cellstr(tmp.general_extracellular_ephys_electrodes.vectordata.get('hemisph').data.load());
shortBnames = cellstr(tmp.general_extracellular_ephys_electrodes.vectordata.get('shortBAn').data.load());
wireID = tmp.general_extracellular_ephys_electrodes.vectordata.get('channID').data.load();
obj.(matchedNames{ii,1}).chanID = chanID(MAchan);
obj.(matchedNames{ii,1}).chanHemi = hemisphere(MAchan);
obj.(matchedNames{ii,1}).chanSname = shortBnames(MAchan);
obj.(matchedNames{ii,1}).wireID = wireID(MAchan);
%% Find unique brain regions and turn into a table
tmpBRegUni = unique(obj.(matchedNames{ii,1}).chanSname);
hemiTemp = cell(length(tmpBRegUni),1);
longName = cell(length(tmpBRegUni),1);
for ui = 1:length(tmpBRegUni)
tmpIND = find(matches(obj.(matchedNames{ii,1}).chanSname,tmpBRegUni{ui}),1,'first');
hemiTemp{ui} = obj.(matchedNames{ii,1}).chanHemi{tmpIND};
longName{ui} = obj.(matchedNames{ii,1}).chanID{tmpIND};
end
obj.(matchedNames{ii,1}).brTABLE = table(tmpBRegUni,hemiTemp,longName,'VariableNames',{'SEEGele',...
'Hemisphere','LongBRname'});
%% Assign LFP to each brain region
obj.(matchedNames{ii,1}).regionLFP = cell(length(obj.(matchedNames{ii,1}).brTABLE.SEEGele),1);
for k = 1:height(obj.(matchedNames{ii,1}).brTABLE)
reg = strcmp(obj.(matchedNames{ii,1}).brTABLE.SEEGele{k},obj.(matchedNames{ii,1}).chanSname);
obj.(matchedNames{ii,1}).regionLFP{k} = obj.(matchedNames{ii,1}).LFP_data(reg,:);
end
%% Extract event key
obj.(matchedNames{ii,1}).eventTimes = tmp.acquisition.get('events').timestamps.load();
temp_eventIDs = cellstr(tmp.acquisition.get('events').data.load());
%% Convert eventIDs from hexadecimal
I = contains(temp_eventIDs,'TTL');
obj.(matchedNames{ii,1}).eventTimes = obj.(matchedNames{ii,1}).eventTimes(I);
temp_eventIDs2 = temp_eventIDs(I);
TTL_task = extractBetween(temp_eventIDs2,'(',')');
obj.(matchedNames{ii,1}).eventIDs = cellfun(@(x) hex2dec(x),TTL_task,'UniformOutput',true);
%% Find task start and stop indices
x = find(obj.(matchedNames{ii,1}).eventIDs == 61); % task start
y = find(obj.(matchedNames{ii,1}).eventIDs == 60); % task end
%% Find the time in the recording that corresponds to the indices
for jj = 1:length(obj.(matchedNames{ii,1}).eventTimes)
[~,obj.(matchedNames{ii,1}).LFPIdx(jj,1)] = min(abs(obj.(matchedNames{ii,1}).eventTimes(jj,1) - obj.(matchedNames{ii,1}).LFP_timestamps));
end
%% Little fix for uneven indices if needed
if length(y) < length(x) % if no stop
a = length(x);
y(a,1) = length(obj.(matchedNames{ii,1}).eventIDs);
end
if length(x) < length(y) % if no start
x(1,1) = 1;
end
%% Reduce indices to those relevant to the task
obj.(matchedNames{ii,1}).eventIDs = obj.(matchedNames{ii,1}).eventIDs(x(count,1):y(count,1),1);
obj.(matchedNames{ii,1}).eventTimes = obj.(matchedNames{ii,1}).eventTimes(x(count,1):y(count,1),1);
obj.(matchedNames{ii,1}).LFPIdx = obj.(matchedNames{ii,1}).LFPIdx(x(count,1):y(count,1),1);
%% Reduce data to that of the individual task
obj.(matchedNames{ii,1}).LFP_timestamps = obj.(matchedNames{ii,1}).LFP_timestamps(obj.(matchedNames{ii,1}).LFPIdx(1,1):obj.(matchedNames{ii,1}).LFPIdx(end,1),:);
obj.(matchedNames{ii,1}).LFP_converted_timestamps = obj.(matchedNames{ii,1}).LFP_converted_timestamps(obj.(matchedNames{ii,1}).LFPIdx(1,1):obj.(matchedNames{ii,1}).LFPIdx(end,1),:);
obj.(matchedNames{ii,1}).LFP_data = obj.(matchedNames{ii,1}).LFP_data(:,obj.(matchedNames{ii,1}).LFPIdx(1,1):obj.(matchedNames{ii,1}).LFPIdx(end,1));
%% Calculate correction factor
obj.(matchedNames{ii,1}).correction_factor = obj.(matchedNames{ii,1}).LFPIdx(1,1) - 1;
obj.(matchedNames{ii,1}).LFPIdx = obj.(matchedNames{ii,1}).LFPIdx - obj.(matchedNames{ii,1}).correction_factor;
end
end
%% Load the eye data
function loadEyeData(obj)
%% Notes
% This function loads the processed eye folder and eye the
% eye data to the appropriate data field in the object.
%% Print
fprintf('Running function loadEyeData..\n')
%% Loop over valid tasks
for ii = 1:length(obj.validTasks)
%% Set the task
task = obj.validTasks{ii,1};
%% Load the eye data
if ~exist('outInfo','var')
outInfo = load(obj.(task).eye_fname);
outInfo = outInfo.outInfo;
end
%% Rename Encoding
if isfield(outInfo,'encoding')
outInfo.encode = outInfo.encoding;
outInfo = rmfield(outInfo,'encoding');
end
%% Get the eye data if the same fields exist
if isfield(outInfo,task)
obj.(task).eyeInfo = outInfo.(task);
end
end
end
%% Fix channel names
function fixChNames(obj)
%% Notes
% This function loops through valid tasks to find the channels
% of interest for the analysis.
%% Print
fprintf('Running function fixChNames..\n');
%% Loop through tasks and select channels
for ii = 1:length(obj.validTasks)
%% Get the task
task = obj.validTasks{ii,1};
%% Ch short names
short_names = obj.(task).brTABLE{:,1};
%% Loop to fix names
for jj = 1:length(short_names)
%% Grab the channels
I = strcmp(short_names{jj,1},obj.(task).chanSname);
tmpChNames = obj.(task).chanSname(I);
%% Loop over individual channels
for kk = length(tmpChNames):-1:1
tmpChNames(kk,1) = append(tmpChNames(kk,1),num2str(kk));
end
%% Write over channel names
obj.(task).chanSname(I) = tmpChNames;
clear tmpChNames
end
end
end
%% Identify bad channels
function identifyBads(obj)
%% Notes
% This function loops through valid tasks and find individual
% channels in each task that exceed a certain threshold. Those
% that do are replaced with NaN's and are not used in
% subsequent functions.
%% Print
fprintf('Running function identifyBads..\n');
%% Loop through tasks
for ii = 1:length(obj.validTasks)
%% Get the task
task = obj.validTasks{ii,1};
%% Preallocate
AmpIdx = NaN(length(obj.(task).chanSname),1);
kurtVal = NaN(length(obj.(task).chanSname),1);
chMean = NaN(length(obj.(task).chanSname),1);
chStd = NaN(length(obj.(task).chanSname),1);
chUpper = NaN(length(obj.(task).chanSname),1);
chLower = NaN(length(obj.(task).chanSname),1);
prctThr = NaN(length(obj.(task).chanSname),1);
%% Loop through channels to identify bads
for jj = 1:length(obj.(task).chanSname)
%% Calculate mean and standard deviation
ch_mean = mean(obj.(task).LFP_data(jj,:));
ch_std = std(obj.(task).LFP_data(jj,:));
%% Set thresholds
upper_th = ch_mean + 2*ch_std;
lower_th = ch_mean - 2*ch_std;
%% Compare channel to its thresholds
I = obj.(task).LFP_data(jj,:) >= upper_th | obj.(task).LFP_data(jj,:) <= lower_th;
chMean(jj,1) = ch_mean;
chStd(jj,1) = ch_std;
chUpper(jj,1) = upper_th;
chLower(jj,1) = lower_th;
prctThr(jj,1) = sum(I)/length(I);
if sum(I)/length(I) < 0.2 % 20% of total signal above or below the threshold
AmpIdx(jj,1) = 0;
else
AmpIdx(jj,1) = 1;
end
%% Calculate kurtosis value
kurtVal(jj,1) = kurtosis(obj.(task).LFP_data(jj,:));
%% Clear variables
clear ch_mean ch_std upper_th lower_th I
end
%% Find bad channels with kurtosis
kurtMAD = mad(kurtVal,1);
kurtMED = median(kurtVal);
kurtZ = ((kurtVal - kurtMED)./kurtMAD); % Z-scored kurtosis
I = kurtZ > 3 | kurtZ < -3;
%% Find bad channels identified by either method
AmpIdx = logical(AmpIdx);
keepIdx = NaN(length(AmpIdx),1);
for jj = 1:length(AmpIdx)
if I(jj,1) == 1 || AmpIdx(jj,1) == 1
keepIdx(jj,1) = 0;
else
keepIdx(jj,1) = 1;
end
end
%% Convert to table
obj.(task).thr_vals = table(chMean,chStd,chUpper,chLower,prctThr,kurtZ,'VariableNames',{'Channel Mean','Channel Std','Upper Thr','Lower Thr','Prct Thr','Z Kurt'});
%% Convert to logical
obj.(task).keepIdx = logical(keepIdx);
%% Clear variables
clear chMean chStd chUpper chLower prctThr AmpIdx kurtVal kurtMED kurtMAD kurtZ keepIdx I
%% Set bad channels to NaN
obj.(task).LFP_data(~obj.(task).keepIdx,:) = NaN;
end
end
%% Bipolar reference
function bipolarReference(obj)
%% Print
fprintf('Running function bipolarReference..\n');
%% Loop over tasks
for ii = 1:length(obj.validTasks)
%% Get the task
task = obj.validTasks{ii,1};
%% Get short channel names
names = obj.(task).brTABLE{:,1};
%% Loop for referencing
for jj = 1:length(names)
%% Grab the data
I = contains(obj.(task).chanSname,names{jj,1});
tmpData = obj.(task).LFP_data(I,:);
chanID = obj.(task).chanID(I,1);
keepIdx = obj.(task).keepIdx(I,1);
chanName = obj.(task).chanSname(I,1);
%% Remove data based on keepIdx
tmpData = tmpData(keepIdx,:);
obj.(task).chanRegion{jj,1} = chanID(keepIdx,1);
chanName = chanName(keepIdx,1);
%% Do the bipolar referencing
for kk = size(tmpData,1):-1:1
if kk > 1
refName = append(chanName{kk,1},'-',chanName{kk-1,1});
obj.(task).referencedData{jj,1}(kk,:) = tmpData(kk,:) - tmpData(kk-1,:);
obj.(task).referencedChName{jj,1}{kk,1} = refName;
obj.(task).groupChName{jj,1}{kk,1} = refName;
clear refName
else
refName = append(chanName{1,1},'-',chanName{end,1});
obj.(task).referencedData{jj,1}(kk,:) = tmpData(1,:) - tmpData(end,:);
obj.(task).referencedChName{jj,1}{kk,1} = refName;
obj.(task).groupChName{jj,1}{kk,1} = refName;
clear refName
end
end
%% Keep unreferenced names
obj.(task).usedChans{jj,1} = chanName;
%% Clear
clear I tmpData chanID keepIdx chanName;
end
%% Convert
obj.(task).chanRegion = vertcat(obj.(task).chanRegion{:});
obj.(task).referencedChName = vertcat(obj.(task).referencedChName{:});
obj.(task).referencedData = cell2mat(obj.(task).referencedData);
obj.(task).usedChans = vertcat(obj.(task).usedChans{:});
end
end
%% Filter
function dataFilter(obj,lfreq,hfreq)
%% Notes
% This function high-passes the LFP data for each valid task
% and ignores bad channels.
%% Print
fprintf('Running function dataFilter..\n');
%% Loop though the tasks
for ii = 1:length(obj.validTasks)
%% Get the task
task = obj.validTasks{ii,1};
%% Create Butterworth filter parameters
n = 2;
if exist('hfreq','var')
freqs = [lfreq hfreq]./(obj.(task).fs/2);
%b = fir1(n,freqs,'bandpass');
[b,a] = butter(n,freqs,'bandpass');
obj.(task).hfreq = hfreq;
else
freqs = lfreq./(obj.(task).fs/2);
%b = fir1(n,freqs,'high');
[b,a] = butter(n,freqs,'high');
end
%% Loop through the channels and filter if they are valid
for jj = 1:size(obj.(task).referencedData,1)
%% Filter channel if it is valid
if obj.(task).keepIdx(jj,1) == 1
obj.(task).filteredData(jj,:) = filtfilt(b,a,obj.(task).referencedData(jj,:)');
end
end
%% Add high pass frequency to the object
obj.(task).lfreq = lfreq;
end
end
%% Identify TTLs
function identifyTTLs(obj)
%% Notes
% This function identifies the LFP indices for cross onset
% (11), clip on (1), clip off (2), and question (3) phases of
% the task. LFP indices for clip off and response are
% calculated based on the behavior tables for each task.
%% Print
fprintf('Running function identifyTTLs..\n');
%% Loop through valid tasks
for ii = 1:length(obj.validTasks)
%% Get the task
task = obj.validTasks{ii,1};
%% Manually exclude bad trials
if strcmp(obj.subID,'MW27') & strcmp(task,'timeDiscrim')
obj.(task).eventIDs(128) = [];
obj.(task).eventTimes(128) = [];
end
%% Sort the TTLs of interest
obj.(task).Indices.crossOnIdx = obj.(task).LFPIdx(obj.(task).eventIDs == 11);
obj.(task).Indices.clipOnIdx = obj.(task).LFPIdx(obj.(task).eventIDs == 1);
obj.(task).Indices.clipOffIdx = obj.(task).LFPIdx(obj.(task).eventIDs == 2);
obj.(task).Indices.questionIdx = obj.(task).LFPIdx(obj.(task).eventIDs == 3);
%% Find the resp field
fieldNames = fieldnames(obj.(task).behave_info);
for jj = 1:length(fieldNames)
if contains(fieldNames{jj,1},'respMat')
matchedField = fieldNames{jj,1};
end
end
%% Remove bad trial
if strcmp(obj.subID,'MW26') & strcmp(task,'sceneRecog')
obj.sceneRecog.behave_info.respMat_SceneRecog(127) = []; % last trial was not completed
obj.(task).Indices.crossOnIdx(127) = [];
obj.(task).Indices.clipOnIdx(127) = [];
obj.(task).Indices.clipOffIdx(127) = [];
obj.(task).Indices.questionIdx(127) = [];
end
%% Create artificial indicies for crossOff and response
cross = zeros(length(obj.(task).behave_info.(matchedField)),1);
response = zeros(length(obj.(task).behave_info.(matchedField)),1);
for z = 1:length((obj.(task).behave_info.(matchedField)))
cross(z,1) = obj.(task).behave_info.(matchedField)(z).CrossEnd - obj.(task).behave_info.(matchedField)(z).CrossStart;
response(z,1) = obj.(task).behave_info.(matchedField)(z).respTime - obj.(task).behave_info.(matchedField)(z).QuesStart;
end
%% Convert from time to samples and add to object
obj.(task).Indices.crossOffIdx = obj.(task).Indices.crossOnIdx + (floor(obj.(task).fs .* cross));
obj.(task).Indices.responseIdx = obj.(task).Indices.questionIdx + (floor(obj.(task).fs .* response));
end
end
%% Identify boundaries
function identifyBoundaries(obj)
%% Notes
%% Print
fprintf('Running function identifyBoundaries..\n');
%% Loop through valid tasks
for ii = 1:length(obj.validTasks)
%% Grab the task
task = obj.validTasks{ii,1};
%% Find the resp field
fieldNames = fieldnames(obj.(task).behave_info);
for jj = 1:length(fieldNames)
if contains(fieldNames{jj,1},'respMat')
matchedField = fieldNames{jj,1};
end
end
%% Identify clip field name
x = fieldnames(obj.(task).behave_info.(matchedField));
%% Loop through behavior info to get the task boundary type
for jj = 1:length(obj.(task).behave_info.(matchedField))
obj.(task).boundary{jj,1} = extractBefore(obj.(task).behave_info.(matchedField)(jj).(x{4,1}),'_');
end
end
end
%% Allocate data
function allocateData(obj)
%% Notes
% This function allocates the data based of phase of the valid
% task (fixation, presentation, and question), as well as break
% them up into individual epochs for SPOOOFing later on.
%% Print
fprintf('Running function allocateData..\n');
%% Loop through valid tasks
for ii = 1:length(obj.validTasks)
%% Grab the task
task = obj.validTasks{ii,1};
%% Create anonymous function handle
extractSegments = @(s,e) obj.(task).filteredData(:,s:e-1);
%% Grab data segments
obj.(task).Data.fixation = arrayfun(@(i) extractSegments(obj.(task).Indices.crossOnIdx(i),obj.(task).Indices.crossOffIdx(i)), 1:length(obj.(task).boundary), 'UniformOutput', false )';
obj.(task).Data.presentation = arrayfun(@(i) extractSegments(obj.(task).Indices.clipOnIdx(i),obj.(task).Indices.clipOffIdx(i)), 1:length(obj.(task).boundary), 'UniformOutput', false )';
obj.(task).Data.question = arrayfun(@(i) extractSegments(obj.(task).Indices.questionIdx(i),obj.(task).Indices.responseIdx(i)), 1:length(obj.(task).boundary), 'UniformOutput', false )';
obj.(task).Data.epoch = arrayfun(@(i) extractSegments(obj.(task).Indices.crossOnIdx(i),obj.(task).Indices.responseIdx(i)), 1:length(obj.(task).boundary), 'UniformOutput', false )';
end
end
%% Baseline correction
function baselineCorrection(obj)
%% Notes
% This function calculates the average voltage of each channel
% during the fixation phase and subtracts it from the voltage
% for each channel during the presentation and question phases.
% This function also z-scores the data.
%% Print
fprintf('Running function baselineCorrection..\n');
%% Loop through valid tasks
for ii = 1:length(obj.validTasks)
%% Grab the task
task = obj.validTasks{ii,1};
%% Loop through trials
for jj = 1:length(obj.(task).Data.fixation)
%% Calculate channel means
ch_mean = mean(obj.(task).Data.fixation{jj,1},2);
%% Subtract from fixation
obj.(task).Data.fixation{jj,1} = obj.(task).Data.fixation{jj,1} - ch_mean;
%% Subtract from presentation
obj.(task).Data.presentation{jj,1} = obj.(task).Data.presentation{jj,1} - ch_mean;
%% Subtract from question
obj.(task).Data.question{jj,1} = obj.(task).Data.question{jj,1} - ch_mean;
%% Subtract from entire epoch
obj.(task).Data.epoch{jj,1} = obj.(task).Data.epoch{jj,1} - ch_mean;
end
end
end
%% Calculate Z-score
function calculateZscore(obj)
%% Notes
% This function z-scores the data segments.
%% Print
fprintf('Running function calculateZscore..\n');
%% Loop over tasks
for ii = 1:length(obj.validTasks)
%% Get the task
task = obj.validTasks{ii,1};
%% Get field names
names = fieldnames(obj.(task).Data);
%% Loop 0ver names
for jj = 1:length(names)
%% Loop over epochs
for kk = 1:length(obj.(task).Data.(names{jj,1}))
%% Normalize the data
obj.(task).Data.(names{jj,1}){kk,1} = zscore(obj.(task).Data.(names{jj,1}){kk,1});
end
end
end
end
%% Plot phases
function plotPhases(obj)
%% Notes
% This function plots the phases of each task (visual check).
%% Loop through valid tasks
for ii = 1:length(obj.validTasks)
%% Grab the task
task = obj.validTasks{ii,1};
%% Create title
title_str = append(obj.subID,' ','Task',' ',task);
%% Plot
figure(ii)
fig = gca;
fig.XAxis.FontSize = 24;
fig.XAxis.FontWeight = 'bold';
fig.YAxis.FontSize = 24;
fig.YAxis.FontWeight = 'bold';
fig.XLim = ([min(obj.(task).LFP_converted_timestamps) max(obj.(task).LFP_converted_timestamps)]);
fig.YLim = ([1.1*(min(min(obj.(task).referencedData))) 1.1*max(max(obj.(task).referencedData))]);
title(title_str,'FontWeight','bold','FontSize',28);
hold on
for z = 1:size(obj.(task).referencedData,1)
plot(obj.(task).LFP_converted_timestamps,obj.(task).referencedData(z,:))
end
%% Figure properties
xlabel('Time (sec)','FontWeight','bold','FontSize',24);
ylabel('Amplitude (V)','FontWeight','bold','FontSize',24);
%% Bands for cross presentation
crossOnIdx = (obj.(task).Indices.crossOnIdx + obj.(task).correction_factor)./obj.(task).fs;
crossOffIdx = (obj.(task).Indices.crossOffIdx + obj.(task).correction_factor)./obj.(task).fs;
bands = [crossOnIdx,crossOffIdx];
xp = [bands fliplr(bands)];
yp = ([[1;1]*1.1*min(ylim); [1;1]*1.1*max(ylim)]*ones(1,size(bands,1))).';
for k = 1:size(bands,1)
patch(xp(k,:),yp(k,:),[1 0 0],'FaceAlpha',0.1,'EdgeColor','none')
end
%% Bands for clip presentation
clipOnIdx = (obj.(task).Indices.clipOnIdx + obj.(task).correction_factor)./obj.(task).fs;
clipOffIdx = (obj.(task).Indices.clipOffIdx + obj.(task).correction_factor)./obj.(task).fs;
bands = [clipOnIdx,clipOffIdx];
xp = [bands fliplr(bands)];
for k = 1:size(bands,1)
patch(xp(k,:),yp(k,:),[0 1 0],'FaceAlpha',0.1,'EdgeColor','none')
end
%% Bands for response
questionIdx = (obj.(task).Indices.questionIdx + obj.(task).correction_factor)./obj.(task).fs;
responseIdx = (obj.(task).Indices.responseIdx + obj.(task).correction_factor)./obj.(task).fs;
bands = [questionIdx,responseIdx];
xp = [bands fliplr(bands)];
for k = 1:size(bands,1)
patch(xp(k,:),yp(k,:),[0 0 1],'FaceAlpha',0.1,'EdgeColor','none')
end
end
end
%% Average spectrogram
function averageSpectrogram(obj)
%% function averageSpectrogram(obj)
% This function creates an average spectrogram over all trials
% for the encoding task.
%% Print
fprintf('Running function averageSpectrogram..\n');
%% Get field names
names = fieldnames(obj);
%% See if patient performed encoding
if any(strcmp(names,'encode'))
%% If they did, do basic power comparisons
groupChName = obj.encode.brTABLE{:,1};
%% Get the eye to use
eye = obj.encode.eyeToUse;
%% Get the data associated with the eye
fields = fieldnames(obj.encode.eyeInfo);
I = contains(fields,eye,'IgnoreCase',true);
eyeField = fields(I);
%% Get the gaze data
GAZEcl = obj.encode.eyeInfo.(eyeField{1,1}).GAZEcl;
%% Parameters
nEpochs = length(GAZEcl);
nRegions = length(groupChName);
%% Loop over trials
for ii = 1:nEpochs % Epochs
%% Get the eye link start time
ELNKstartTime = obj.encode.eyeInfo.TTLinfo{ii,1}{2,5};
%% Get NLX start time
NLXstartTime = obj.encode.eyeInfo.TTLinfo{ii,1}{2,4};
%% Find the appropriate fixation
if istable(GAZEcl{ii,1}.fixations) % Had at least one fixation
fixations = GAZEcl{ii,1}.fixations.starttime;
[~,fixation] = min(abs(double(fixations) - double(ELNKstartTime)));
else
continue
end
%% Create NLX fixation time
NLXfixation = double(floor((fixations(fixation,1) - ELNKstartTime)./2)) + NLXstartTime;
NLXfixation = NLXfixation - obj.encode.correction_factor;
%% Create start and stop indices
fixation_start = NLXfixation - 25; % 50 ms before onset
fixation_end = NLXfixation + 5*obj.encode.fs; % 5 sec after onset
%% Get the data
data = obj.encode.referencedData(:,fixation_start:fixation_end);
%% Loop over electrodes
for jj = 1:nRegions
%% Names
ch_names = contains(obj.encode.usedChans,groupChName{jj,1});
nChan = sum(ch_names);
%% Skip if no channels found
if nChan == 0
continue
end
%% Find the names in the data
tmpData = data(ch_names,:);
%% Calculate FFT power
[fft_pow,fft_freq] = pspectrum(tmpData',obj.encode.fs);
%% Calculate CWT power
for kk = 1:nChan
[cwt_pow(:,:,kk),cwt_freq] = cwt(tmpData(kk,:),obj.encode.fs);
end
%% Calculate average power
fft_pow = mean(fft_pow,2);
cwt_pow = mean(abs(cwt_pow),3);
%% Add to object
obj.encode.PowerAnalysis.FFT.frequency{ii,1} = fft_freq;
obj.encode.PowerAnalysis.FFT.power{ii,1}{jj,1} = fft_pow;
obj.encode.PowerAnalysis.CWT.frequency{ii,1} = cwt_freq;
obj.encode.PowerAnalysis.CWT.power{ii,1}{jj,1} = cwt_pow;
%% Calculate average power in canonical frequency bands
low_band = [0.5,4,8,13,30];
high_band = [4,8,13,30,150];
for kk = 1:length(low_band)
J = fft_freq(:,1) >= low_band(1,kk) & fft_freq(:,1) <= high_band(1,kk);
K = cwt_freq(:,1) >= low_band(1,kk) & cwt_freq(:,1) <= high_band(1,kk);
if low_band(1,kk) == 0.5
obj.encode.PowerAnalysis.FFT.Delta{ii,1}(jj,1) = mean(fft_pow(J));
obj.encode.PowerAnalysis.CWT.Delta{ii,1}(jj,1) = mean(mean(cwt_pow(K,:)));
elseif low_band(1,kk) == 4
obj.encode.PowerAnalysis.FFT.Theta{ii,1}(jj,1) = mean(fft_pow(J));
obj.encode.PowerAnalysis.CWT.Theta{ii,1}(jj,1) = mean(mean(cwt_pow(K,:)));
elseif low_band(1,kk) == 8
obj.encode.PowerAnalysis.FFT.Alpha{ii,1}(jj,1) = mean(fft_pow(J));
obj.encode.PowerAnalysis.CWT.Alpha{ii,1}(jj,1) = mean(mean(cwt_pow(K,:)));
elseif low_band(1,kk) == 13
obj.encode.PowerAnalysis.FFT.Beta{ii,1}(jj,1) = mean(fft_pow(J));
obj.encode.PowerAnalysis.CWT.Beta{ii,1}(jj,1) = mean(mean(cwt_pow(K,:)));
elseif low_band(1,kk) == 30
obj.encode.PowerAnalysis.FFT.Gamma{ii,1}(jj,1) = mean(fft_pow(J));
obj.encode.PowerAnalysis.CWT.Gamma{ii,1}(jj,1) = mean(mean(cwt_pow(K,:)));
end
clear J K;
end
%% Clear some variables
clear fft_pow cwt_pow fft_freq cwt_freq ch_names nChan;
end
end
end
end
%% Plot spectrograms
function plotSpectrograms(obj)
%% Notes
%% Print
fprintf('Running function plotSpectrogram..\n');
%% Check if encoding
if isstruct(obj.encode)
%% Get power names
names = fieldnames(obj.encode.PowerAnalysis);
%% Reshape power data
for ii = 1:length(obj.encode.brTABLE{:,1})
count = 1;
for jj = 1:length(obj.encode.PowerAnalysis.FFT.power)
if ~isempty(obj.encode.PowerAnalysis.FFT.power{jj,1})
FFT_regions{ii,1}(count,:) = obj.encode.PowerAnalysis.FFT.power{jj,1}(ii,1);
CWT_regions{ii,1}(count,:) = obj.encode.PowerAnalysis.CWT.power{jj,1}(ii,1);
count = count + 1;
end
end
end
%% Create parameters
nRegions = length(CWT_regions);
nEpochs = length(CWT_regions{1,1});
%% Reshape CWT
for ii = 1:nRegions
for jj = 1:nEpochs
tmpCWT(:,:,jj) = CWT_regions{ii,1}{jj,1};
tmpFFT(:,1,jj) = FFT_regions{ii,1}{jj,1};
end
CWT{ii,1} = tmpCWT;
FFT{ii,1} = tmpFFT;
clear tmpCWT tmpFFT
end
%% Prep FFT data for plotting
for ii = 1:length(FFT)
FFT{ii,1} = squeeze(FFT{ii,1});
n = size(FFT{ii,1},2);
FFT_STD = std(FFT{ii,1},0,2);
FFT_CI{ii,1}(:,1) = mean(FFT{ii,1},2) - 1.96*(FFT_STD./sqrt(n));
FFT_CI{ii,1}(:,2) = mean(FFT{ii,1},2) + 1.96*(FFT_STD./sqrt(n));
end
%% Prep CWT data for plotting
for ii = 1:length(CWT)
CWT{ii,1} = squeeze(mean(CWT{ii,1},2));
n = size(CWT{ii,1},2);
CWT_STD = std(CWT{ii,1},0,2);
CWT_CI{ii,1}(:,1) = mean(CWT{ii,1},2) - 1.96*(CWT_STD./sqrt(n));
CWT_CI{ii,1}(:,2) = mean(CWT{ii,1},2) + 1.96*(CWT_STD./sqrt(n));
end
%% Test plot FFT section
figure
for ii = 1:length(FFT)
%figure(ii)
sig_power = 10*log(mean(FFT{ii,1},2));
freq = obj.encode.PowerAnalysis.FFT.frequency{1,1};
plot(freq,sig_power,'LineWidth',3)
lCI = 10*log(FFT_CI{ii,1}(:,1));
hCI = 10*log(FFT_CI{ii,1}(:,2));
hold on
fill([freq;flipud(freq)],[lCI;flipud(hCI)],'r','FaceAlpha',0.5,'EdgeColor','none')
end
fig = gca;
fig.XAxis.FontSize = 24;
fig.XAxis.FontWeight = 'bold';
fig.YAxis.FontSize = 24;
fig.YAxis.FontWeight = 'bold';
title('FFT Power','FontWeight','bold','FontSize',28);
%% Test plot CWT section
figure
for ii = 1:length(CWT)
freq = obj.encode.PowerAnalysis.CWT.frequency{1,1};
lCI = CWT_CI{ii,1}(:,1);
hCI = CWT_CI{ii,1}(:,2);
cwt_pow = mean(CWT{ii,1},2);
plot(freq,cwt_pow,'LineWidth',3)
hold on
fill([freq;flipud(freq)],[lCI;flipud(hCI)],'r','FaceAlpha',0.5,'EdgeColor','none')
end
fig = gca;
fig.XAxis.FontSize = 24;
fig.XAxis.FontWeight = 'bold';
fig.YAxis.FontSize = 24;
fig.YAxis.FontWeight = 'bold';
title('CWT Power','FontWeight','bold','FontSize',28);
end
end
%% Plot frequency bands
function plotFrequencyBands(obj)
%% function plotFrequencyBands(obj)
%% Notes
%% Print
fprintf('Running function plotFrequencyBands..\n');
%% Check for encoding phase
if isstruct(obj.encode)
%% Names of power