-
Notifications
You must be signed in to change notification settings - Fork 0
/
runBatchAnalysis.m
2499 lines (2139 loc) · 110 KB
/
runBatchAnalysis.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
function [analysisOutFilename] = runBatchAnalysis(inputs)
%%Unpack Inputs
analysisLog = struct();
load(inputs{1},'outputDir') % Path to spikes.
spikeDataBank = saveSpikeDataBank([], [], 'load', outputDir); %Spike variables
load(inputs{1}) % Non spike variables, including path to spikes.
%Overwrite switches with what is currently in file
load(fullfile(outputDir, 'batchAnalysisParams.mat'));
%% Pre-Analysis processing
runList = fields(spikeDataBank);
if ~isfield(spikeDataBank.(runList{end}), 'stimPresCount')
spikeDataBank = stimulusStatistics(spikeDataBank, stimStructParams);
saveEnv()
end
if ~exist('unitCounts','var') || ~exist('trueCellStruct', 'var') || ~isfield(spikeDataBank.(runList{end}), 'gridHoles')
[spikeDataBank, trueCellStruct, unitCounts, resultTable, nullCells] = tableRefFunx(spikeDataBank, cellCountParams.batchRunxls, cellCountParams.recordingLogxls);
saveEnv(1)
end
meanPSTHParams.tTestTable = resultTable;
% Report
reportSubEventCounts(cellCountParams.subEventBatchStructPath, trueCellStruct)
% Remove repeated Runs
if ~calcSwitch.excludeRepeats && isfield(analysisLog, 'repeatsExcluded')
error('Repeats already excluded in this spikeDataBank, delete and restart or change parameters')
elseif calcSwitch.excludeRepeats && ~isfield(analysisLog, 'repeatsExcluded')
% Exclude repeated recordings at the same site.
for run_ind = 1:length(runList)
sessionName = extractBetween(runList{run_ind}, 2, length(runList{run_ind}));
validInd = trueCellInd(strcmp(sessionName, trueCellInfo(:,1)));
if sum(validInd) == 0
% Remove entire field if all channels are repeated recordings.
spikeDataBank = rmfield(spikeDataBank,(runList{run_ind}));
else
for event_ind = 1:length(spikeDataBank.(runList{run_ind}).spikesByEvent)
% Remove individual channel info where one of the channels is
% recording new units.
spikeDataBank.(runList{run_ind}).spikesByEvent{event_ind} = spikeDataBank.(runList{run_ind}).spikesByEvent{event_ind}(validInd);
end
spikeDataBank.(runList{run_ind}).gridHoles(validInd) = spikeDataBank.(runList{run_ind}).gridHoles(validInd);
spikeDataBank.(runList{run_ind}).recDepth(validInd) = spikeDataBank.(runList{run_ind}).recDepth(validInd);
end
end
%Save modified struct.
runListIndex = unitCounts.Exclude;
analysisLog.repeatsExcluded = 1;
saveEnv()
else
runListIndex = unitCounts.nonExclude;
end
%% Analyses
% Generate a cell array containing the PSTHes from spikeDataBank, along
% with additional dimension for identifying information. Expansions in
% analyses should begin here, if pulling from spikeDataBank.
if 1%~exist('stimPSTHStruct', 'var')
stimPSTHStruct = pullPSTH(spikeDataBank, meanPSTHParams);
saveEnv(0);
end
% Combine PSTH across all runs for a particular stimulus.
if plotSwitch.meanPSTH || (plotSwitch.subEventPSTH && ~exist('meanPSTHStruct', 'var'))
[stimPSTH, meanPSTHStruct] = meanPSTH(stimPSTHStruct, meanPSTHParams, figStruct);
saveEnv(0)
end
% Combine PSTH across all runs for a particular event.
if plotSwitch.subEventPSTH %&& ~exist('meanPSTHStruct','var')
subEventPSTHStruct = subEventPSTH(spikeDataBank, meanPSTHStruct, subEventPSTHParams, figStruct);
end
% Gather information on frame rates
if plotSwitch.frameFiringRates %&& ~exist('frameFiringStruct','var')
[spikeDataBank, frameFiringStruct] = frameFiringRates(spikeDataBank, frameFiringParams, figStruct);
saveEnv(1)
end
% Check whether the novelty of the runs
if plotSwitch.novelty
assert(logical(exist('meanPSTHStruct','var')), 'Must run w/ meanPSTH enabled for novelty analysis');
spikeDataBank = noveltyAnalysis(spikeDataBank, stimPSTH, meanPSTHStruct, [], noveltyParams, figStruct);
end
% Perform sliding window ANOVA and Omega calculations
if plotSwitch.slidingWindowANOVA % && ~isfield(spikeDataBank, [Some new field generated by function])
spikeDataBank = slidingWindowTest(spikeDataBank, slidingTestParams, figStruct);
saveEnv()
end
if plotSwitch.neuralDecodingTB
NeuralDecodingTB(spikeDataBank, NDTParams);
end
end
%% Functions
function spikeDataBank = stimulusStatistics(spikeDataBank, params)
% Stimuli Presentation count and 'Novelty' Related Information.
%Code below creates a single large vector of stimuli used, and uses this to
%create individual vectors containing which viewing of the stimulus this
%represent (i.e. 'this run represents the 10th viewing of X.avi'). It also
%appends a dateTime vector to each structure related to how long since the
%last recording day.
runList = fields(spikeDataBank);
tok2Find = {'S20', 'Mo00'};
tok2Rep = {'', 'R'};
runListLabels = regexprep(runList, tok2Find, tok2Rep);
% Extract the eventIDs field, generate a cell array of unique stimuli
allStimuliVec = struct2cell(structfun(@(x) x.eventIDs, spikeDataBank,'UniformOutput', 0));
allStimuliVec = unique(vertcat(allStimuliVec{:}));
tokens2Find = {'.avi', '_\d{3}', 'monkey', 'human'};
tokens2Rep = {'', '', 'm', 'h'};
allStimuliVecNames = regexprep(allStimuliVec, tokens2Find, tokens2Rep);
allStimuliVecNames = strrep(allStimuliVecNames, '_', ' '); % For the Animation tags.
% Produce matrix (N stim * M runs) which gives 0 for non present stim, count of stim presentation otherwise.
stimLogicalArray = zeros(length(allStimuliVec),length(runList));
for run_ind = 1:length(runList)
stimLogicalArray(:,run_ind) = ismember(allStimuliVec, spikeDataBank.(runList{run_ind}).eventIDs);
end
% Turn that matrix into a matrix of nth presentation.
csStimLogicalArray = cumsum(stimLogicalArray,2);
csStimLogicalArray(~stimLogicalArray) = 0;
% When was a stimulus first seen? Index of runList where first presentation took place.
[firstStimPresInd, ~] = find(csStimLogicalArray' == 1);
% Sort the previous count array by the first presentations
[~, newInd] = sort(firstStimPresInd);
csStimLogicalArraySorted = csStimLogicalArray(newInd, :);
allStimuliVecNames = allStimuliVecNames(newInd, :);
% If this is run, it should be saved
params.figStruct.saveFig = 1;
params.figStruct.closeFig = 0;
sliceStart = [1 40 80];
sliceEnd = [39 79 107];
% Generate image figure for this using XYGrid
for ii = 1:length(sliceStart)
figTitle = sprintf('StimRunGrid_%d', ii);
h = figure('NumberTitle', 'off', 'Name', figTitle, 'units', 'normalized', 'outerposition', [0 0 1 1]);
XYGrid(h, csStimLogicalArraySorted(sliceStart(ii):sliceEnd(ii), :), allStimuliVecNames(sliceStart(ii):sliceEnd(ii)), runListLabels, params.xyStimParams);
saveFigure(params.outDir, figTitle, [], params.figStruct, [])
end
% Generate image figure for eventData using XYGrid
tmp = load(params.eventDataPath);
eventListPlot = strrep(tmp.eventData.Properties.VariableNames, '_', ' ');
eventData = tmp.eventData(allStimuliVec,:);
for ii = 1:length(sliceStart)
figTitle = sprintf('StimEventGrid_%d', ii);
h = figure('NumberTitle', 'off', 'Name', figTitle, 'units', 'normalized', 'outerposition', [0 0 1 1]);
XYGrid(h, eventData(sliceStart(ii):sliceEnd(ii), :), allStimuliVecNames(sliceStart(ii):sliceEnd(ii)), eventListPlot, params.xyEventparams)
saveFigure(params.outDir, figTitle, [], params.figStruct, [])
end
% Simple subEvent visualization, which happen when.
eventMat = generateEventImage(tmp.eventData, 2800); % Hard coded stim length.
eventMat = eventMat(:, 1:2800, :); % Remove excess due to events persisting longer than stim was shown.
for event_i = 1:length(eventListPlot)
for ii = 1:length(sliceStart)
figTitle = sprintf('Time of %s event occurances - %d', eventListPlot{event_i}, ii);
h = figure('NumberTitle', 'off', 'Name', figTitle, 'units', 'normalized', 'outerposition', [0 0 1 1]);
params.xyEventparams.plotTitle = figTitle;
XYGrid(h, eventMat(sliceStart(ii):sliceEnd(ii), :, event_i), allStimuliVecNames(sliceStart(ii):sliceEnd(ii)), [], params.xyEventparams)
saveFigure(params.outDir, figTitle, [], params.figStruct, [])
end
end
% Append a dateTime to each field with the time in days since the last
% recording. Add the relevant slice of the larger csStimLogicalArray.
allDateTimeVec = NaT(size(runList));
for run_ind = 1:length(runList)
allDateTimeVec(run_ind) = datetime(extractBetween(spikeDataBank.(runList{run_ind}).dateSubject,1,8),'InputFormat','yyyyMMdd'); %Generate 'daysSinceLastRec' for each field.
end
% find unique recording dates, and the distance between them. Add these
% to the spikeDataBank later.
uniqueDateTimeVec = unique(allDateTimeVec);
daysSinceLastRec = [1000; days(diff(uniqueDateTimeVec))];
% use the dateTime and stimulus presentation matrix to find out how long
% in days takes place before a particular showing of a stimulus.
daysSinceLastPres = zeros(size(stimLogicalArray));
for stim_ind = 1:size(stimLogicalArray,1)
presentationInd = logical(stimLogicalArray(stim_ind,:)); %When was the stim shown
daysSinceLastPres(stim_ind,presentationInd) = [1000; days(diff(allDateTimeVec(presentationInd)))]; %Duration between those dates in days
end
% Fill out spikeDataBank with generated values.
for run_ind = 1:size(stimLogicalArray,2)
[~, big2SmallInd] = ismember(spikeDataBank.(runList{run_ind}).eventIDs,allStimuliVec);
spikeDataBank.(runList{run_ind}).daysSinceLastPres = daysSinceLastPres(big2SmallInd,run_ind);
spikeDataBank.(runList{run_ind}).stimPresCount = csStimLogicalArray(big2SmallInd,run_ind);
spikeDataBank.(runList{run_ind}).stimPresArray = csStimLogicalArray(:,run_ind);
spikeDataBank.(runList{run_ind}).dateTime = allDateTimeVec(run_ind);
spikeDataBank.(runList{run_ind}).daysSinceLastRec = daysSinceLastRec(allDateTimeVec(run_ind) == uniqueDateTimeVec);
end
end
function stimPSTHStruct = pullPSTH(spikeDataBank, params)
% Function which combines stimulus presentations across all runs in the spikeDataBank.
% Inputs include spikeDataBank and list of parameters.
disp('Compiling PSTH Struct...');
% Rebuild variables
% extract the eventIDs field, generate a cell array of unique stimuli
allStimuliVec = struct2cell(structfun(@(x) x.eventIDs, spikeDataBank,'UniformOutput', 0));
allStimuliVec = unique(vertcat(allStimuliVec{:}));
% Generate grid for indexing into individual runs and extracting relevant
% PSTHes.
runList = fields(spikeDataBank);
small2BigInd = zeros(length(allStimuliVec), length(runList));
for run_ind = 1:length(runList)
[~, small2BigInd(:,run_ind)] = ismember(allStimuliVec, spikeDataBank.(runList{run_ind}).eventIDs);
end
stimPresCounts = sum(logical(small2BigInd),2);
% Concatonate PSTHs - iterate across stimuli, grab PSTHes from each run, store
groupingType = {'Unsorted', 'Units', 'MUA'};
dataType = {'PSTH', 'PSTH Err', 'presCount','daysSinceLastPres', 'daysSinceLastRec', 'Run of Day', 'Grid Hole', 'Recording Depth', 'Run Ind'};
% {'Run of Day', 'Grid Hole', 'Run of Day', 'Recording Depth'};
stimPSTHStruct = struct();
stimPSTHStruct.stimPresCounts = stimPresCounts;
stimPSTHStruct.IndStructs{1} = allStimuliVec;
stimPSTHStruct.IndStructs{2} = groupingType;
stimPSTHStruct.IndStructs{3} = dataType;
%stimPSTH{stim,grouping,dataType}
stimPSTH = cell([length(allStimuliVec), length(groupingType), length(dataType)]);
for stim_ind = 1:length(allStimuliVec)
% Find the runs where the stimulus was present, generate a list of them.
stimRunIndex = small2BigInd(stim_ind,:);
psthStimIndex = nonzeros(stimRunIndex);
psthRunIndex = find(stimRunIndex);
subRunList = runList(psthRunIndex);
if params.runInclude ~= 0 && length(subRunList) > params.runInclude
subRunList = subRunList(1:params.runInclude);
end
% For all runs containing a particular stimuli, retrieve relevant activity vector in each.
for subRun_ind = 1:length(subRunList)
tmpRunStruct = spikeDataBank.(subRunList{subRun_ind});
for chan_ind = 1:length(tmpRunStruct.psthByImage)
for unit_ind = 1:length(tmpRunStruct.psthByImage{chan_ind})
% Retrieve correct PSTH from run
unitActivity = tmpRunStruct.psthByImage{chan_ind}{unit_ind}(psthStimIndex(subRun_ind),:);
unitErr = tmpRunStruct.psthErrByImage{chan_ind}{unit_ind}(psthStimIndex(subRun_ind),:);
% Do not include activity which does not meet 1 Hz Threshold.
if params.rateThreshold
if mean(unitActivity) < params.rateThreshold
continue
end
end
presCount = tmpRunStruct.stimPresCount(psthStimIndex(subRun_ind));
gridHole = tmpRunStruct.gridHoles;
depth = tmpRunStruct.recDepth;
assert(length(gridHole) == length(depth), 'Mismatch in variables');
assert(~isempty(gridHole), 'gridHole data empty, confirm batchAnalysis excel file contains all relevant runs');
daysSinceLastPres = tmpRunStruct.daysSinceLastPres(psthStimIndex(subRun_ind));
daysSinceLastRec = tmpRunStruct.daysSinceLastRec;
% If desired, Z score PSTHs here based on fixation period activity.
if params.normalize
tmp = tmpRunStruct.psthByImage{chan_ind}{unit_ind}(:,1:abs(tmpRunStruct.start));
tmp = reshape(tmp, [size(tmp,1) * size(tmp,2), 1]);
fixMean = mean(tmp); %Find activity during fixation across all stim.
fixSD = std(tmp);
if params.normalize == 1 && fixMean ~= 0 && fixSD ~= 0
unitActivity = ((unitActivity - fixMean)/fixSD);
unitErr = ((unitErr - fixMean)/fixSD);
end
end
% Store the generated values into a dataArray
dataArray = cell(size(dataType));
dataArray{strcmp(dataType, 'PSTH')} = unitActivity;
dataArray{strcmp(dataType, 'PSTH Err')} = unitErr;
dataArray{strcmp(dataType, 'presCount')} = presCount;
dataArray{strcmp(dataType, 'daysSinceLastPres')} = daysSinceLastPres;
dataArray{strcmp(dataType, 'daysSinceLastRec')} = daysSinceLastRec;
dataArray{strcmp(dataType, 'Run of Day')} = str2double(tmpRunStruct.runNum);
dataArray{strcmp(dataType, 'Grid Hole')} = {num2str(gridHole{chan_ind})};
dataArray{strcmp(dataType, 'Recording Depth')} = depth{chan_ind};
dataArray{strcmp(dataType, 'Run Ind')} = psthRunIndex(subRun_ind);
% Concatonate to the correct Matrix (index matching phyzzy convention)
if unit_ind == 1 % Unsorted
groupInd = 1;
elseif unit_ind == length(tmpRunStruct.psthByImage{chan_ind}) % MUA
groupInd = 3;
else % Unit
groupInd = 2;
end
for data_ind = 1:length(dataArray)
stimPSTH{stim_ind,groupInd,data_ind} = [stimPSTH{stim_ind,groupInd,data_ind}; dataArray{data_ind}];
end
end
end
end
end
stimPSTHStruct.stimPSTH = stimPSTH;
stimPSTHStruct.runList = runList;
% Modify stimPSTHStruct to include accurate info which spans all the runs.
stimPSTHStruct.psthPre = abs(spikeDataBank.(runList{1}).start);
stimPSTHStruct.psthImDur = spikeDataBank.(runList{1}).stimDur;
stimPSTHStruct.psthPost = spikeDataBank.(runList{1}).end - stimPSTHStruct.psthImDur;
end
function [stimPSTH, meanPSTHStruct] = meanPSTH(meanPSTHStruct, params, figStruct)
% Function which combines stimulus presentations across all runs in the spikeDataBank.
% Inputs include spikeDataBank and list of parameters.
disp('Starting mean PSTH Analysis...');
% Step 1 - Unpack variables, generate those needed for plotting.
allStimuliVec = meanPSTHStruct.IndStructs{1};
groupingType = meanPSTHStruct.IndStructs{2};
dataType = meanPSTHStruct.IndStructs{3};
stimPSTH = meanPSTHStruct.stimPSTH;
stimPresCounts = meanPSTHStruct.stimPresCounts;
runList = meanPSTHStruct.runList;
params.psthPre = meanPSTHStruct.psthPre;
params.psthImDur = meanPSTHStruct.psthImDur;
params.psthPost = meanPSTHStruct.psthPost;
% Extract eventData and frameMotionData
% extract the eventIDs field, generate a cell array of unique stimuli
load(params.frameMotionDataPath);
frameMotionDataNames = {frameMotionData.stimVid};
load(params.eventData); % Puts eventData into the workspace.
eventData = eventData(allStimuliVec, :);
eventList = eventData.Properties.VariableNames;
eventMat = generateEventImage(eventData, params.psthImDur);
% Step 2 - modify PSTHes - rewardEpoch removal, firstXRuns, animations,
% topStimOnly
if any([params.plotTopStim, params.removeFollowing, params.stimInclude, params.removeRewardEpoch, params.firstXRuns])
%Initialize a keep index
keepInd = true(size(stimPresCounts));
if params.plotTopStim
keepInd = keepInd & (stimPresCounts >= params.topStimPresThreshold);
end
if params.removeFollowing
keepInd = keepInd & (~contains(allStimuliVec, 'Follow'));
end
% Animation related processing - allows for onlyAnim, no Anim, or all.
if params.stimInclude ~= 0
% If removing or focusing on anims, identify them in the list.
animParam.stimParamsFilename = params.stimParamsFilename;
animParam.plotLabels = {'animSocialInteraction', 'animControl'};
animParam.outLogic = 1;
animParam.removeEmpty = 1;
[tmp, ~, ~] = plotIndex(allStimuliVec, animParam);
animInd = logical(sum(tmp,2));
% If excluding or only including animations, update the meanPSTHStruct
% accordingly to allow for unity between this function and those which rely
% on its outputs.
switch params.stimInclude
case 1
keepInd = keepInd & animInd;
case 2
keepInd = keepInd & ~animInd;
end
end
% Once keep ind has been generated across all switches, edit appropriate
% structures
stimPresCounts = stimPresCounts(keepInd);
allStimuliVec = allStimuliVec(keepInd,:);
stimPSTH = stimPSTH(keepInd, :, :);
eventMat = eventMat(keepInd, :, :);
meanPSTHStruct.stimPresCounts = stimPresCounts;
meanPSTHStruct.IndStructs{1} = allStimuliVec;
meanPSTHStruct.stimPSTH = stimPSTH;
% If desired, remove the reward epoch from the base matrix, and preserve
% the full matrix for where needed.
if params.removeRewardEpoch
% If removing reward activity, store a copy with it.
rewardStart = meanPSTHStruct.psthPre + meanPSTHStruct.psthImDur;
% Remove them from each.
stimPSTH(:,:, 1:2) = cellfun(@(x) x(:, 1:rewardStart+1), stimPSTH(:,:, 1:2), 'UniformOutput', 0);
params.psthPost = 0;
end
% If you want to only count the first X runs of a stimulus,
if params.firstXRuns
keepMat = cellfun(@(x) x <= params.firstXRuns, stimPSTH(:, :, strcmp(meanPSTHStruct.IndStructs{3}, 'presCount')), 'UniformOutput', 0);
for ii = 1:size(stimPSTH, 1)
for jj = 1:size(stimPSTH, 2)
for kk = 1:size(stimPSTH, 3)
stimPSTH{ii, jj, kk} = stimPSTH{ii, jj, kk}(keepMat{ii, jj},:);
if jj == 3 && kk == 3 %MUA and presCount
% Update stimPresCounts according to the new numbers.
stimPresCounts(ii) = max(stimPSTH{ii, jj, kk});
end
end
end
end
end
end
% Generate the figure directory
dirTags = {' NoReward', 'fixAligned', 'Normalized', 'Pres Threshold', 'AnimOnly', 'NoAnim', sprintf('first%d', params.firstXRuns)};
dirTagSwitch = [params.removeRewardEpoch, params.fixAlign, params.normalize, params.plotTopStim, params.stimInclude == 1, params.stimInclude == 2, params.firstXRuns];
params.outputDir = [params.outputDir strjoin(dirTags(logical(dirTagSwitch)),' - ')];
if ~exist(params.outputDir, 'dir')
mkdir(params.outputDir)
end
% Plotting related variables
eventColors = 'kbrg';
groupIterInd = 3; % An index for which groups to look at. 1 = Unsorted, 2 = Units, 3 = MUA. Combine as fit.
[plotMat, briefStimList, params] = plotIndex(allStimuliVec, params);
if params.normalize
normTag = ' - normalized';
else
normTag = '';
end
allStimuliNames = cellfun(@(x) extractBetween(x, 1, length(x)-4), allStimuliVec);
allStimuliNames = strrep(allStimuliNames, '_', ' ');
stimPresMat = cellfun(@(x) size(x,1),stimPSTH(:,:,end));
meanPSTHStruct.stimPresMat = stimPresMat;
broadLabelInd = plotMat;
dataInd2Plot = strcmp(meanPSTHStruct.IndStructs{3}, 'PSTH') | strcmp(meanPSTHStruct.IndStructs{3}, 'PSTH Err');
% Plot 1 - All Stimuli means in the same plot.
if params.allStimPSTH
for group_ind = groupIterInd
stimCounts = stimPresMat(:,group_ind);
if params.traceCountLabel
allStimuliLabel = cell(length(allStimuliNames),1);
for stim_ind = 1:length(allStimuliNames)
allStimuliLabel{stim_ind} = [allStimuliNames{stim_ind} ',n = ' num2str(stimCounts(stim_ind))];
end
else
allStimuliLabel = allStimuliNames;
end
groupData = stimPSTH(:, group_ind, 1);
groupData = cellfun(@(x) mean(x, 1), groupData, 'UniformOutput',0);
plotData = vertcat(groupData{:});
if params.sortPresCountSort
[~, newOrder] = sort(stimCounts);
allStimuliLabel = allStimuliLabel(newOrder);
plotData = plotData(newOrder, :);
end
catPSTHTitle = sprintf('All Stimuli, Mean PSTH %s, %s', normTag, groupingType{group_ind});
h = figure('NumberTitle', 'off', 'Name', catPSTHTitle,'units','normalized','outerposition',[0 0 params.plotSizeAllStimPSTH]);
[~, cbh] = plotPSTH(plotData, [], axes(), params, 'color', catPSTHTitle, allStimuliLabel);
if params.normalize == 1
cbh.Label.String = 'Signal Change relative to Baseline (%)';
elseif params.normalize == 2
cbh.Label.String = 'Z scored relative to fixation';
ylabel('Normalized Activity (Baseline Z scored)');
else
ylabel('Activity (Firing Rate)');
end
title(catPSTHTitle);
xlabel('Time from Stimulus Onset (ms)');
saveFigure(params.outputDir, ['1. ' catPSTHTitle], [], figStruct, [])
clear allStimuliLabel
end
end
% Plot 2 - Catagory Plot - 'All Chasing Stimuli, mean PSTH'
if params.catPSTH
for broad_ind = 1:length(params.plotLabels)
% Extract relevant slices of larger matricies
sliceStimPSTH = stimPSTH(broadLabelInd(:,broad_ind),:,dataInd2Plot);
sliceStimLabels = briefStimList(broadLabelInd(:,broad_ind));
sliceStimPresMat = stimPresMat(broadLabelInd(:,broad_ind),:);
% Generate a matrix of the meanPSTHes, with the last row being total
% means. Add this to the counts as well.
meanPSTH = cellfun(@(x) mean(x),sliceStimPSTH,'UniformOutput',0);
catMeanMat = cell(1,size(sliceStimPSTH,2),size(sliceStimPSTH,3));
catErrMat = cell(1,size(sliceStimPSTH,2),size(sliceStimPSTH,3));
for group_ind = groupIterInd
for data_ind = find(dataInd2Plot)
tmp = vertcat(sliceStimPSTH{:,group_ind,data_ind});
catMeanMat{1,group_ind,data_ind} = mean(tmp,1);
catErrMat{1,group_ind,data_ind} = std(tmp)/sqrt(size(tmp,1));
end
end
meanPSTH = cat(1, meanPSTH, catMeanMat);
if params.includeMeanTrace
sliceStimPresMat = [sliceStimPresMat; sum(sliceStimPresMat, 1)];
if iscell(params.plotLabels{broad_ind})
params.plotLabels{broad_ind} = strjoin(params.plotLabels{broad_ind});
end
sliceStimLabels = [sliceStimLabels; params.plotLabels{broad_ind}];
end
for group_ind = groupIterInd
% Prepare labels
if params.traceCountLabel
stimLabels = cell(length(sliceStimLabels),1);
for stim_ind = 1:length(stimLabels)
stimLabels{stim_ind} = [sliceStimLabels{stim_ind} ',n = ' num2str(sliceStimPresMat(stim_ind,group_ind))];
end
else
stimLabels = sliceStimLabels;
end
% Extract correct data
plotData = vertcat(meanPSTH{:,group_ind,1});
% If Sorting data, do so here.
if params.sortPresCountSort
[~, newOrder] = sort(sliceStimPresMat(:,group_ind));
plotLabels = stimLabels(newOrder);
plotData = plotData(newOrder, :);
else
plotLabels = stimLabels;
end
psthTitle = sprintf('All %s Stimuli - Mean %s%s, %s', params.plotLabels{broad_ind}, dataType{1}, normTag, groupingType{group_ind});
% Plot the Activity
h = figure('NumberTitle', 'off', 'Name', psthTitle,'units','normalized','outerposition',[0 0 params.plotSizeCatPSTH]);
[psthAxes, cbHandle] = plotPSTH(plotData, [], axes(), params, 'color', psthTitle, plotLabels);
psthAxes.FontSize = 15;
psthAxes.YLabel.String = 'Stimulus Name';
title(psthTitle)
hold on
if params.normalize == 1
cbHandle.Label.String = 'Signal Change relative to Baseline (%)';
elseif params.normalize == 2
cbHandle.Label.String = 'Z scored relative to fixation';
end
cbHandle.Label.FontSize = 12;
if params.plotMeanLine
% Include a black line which plots the mean trace on a second axis.
lineProps.col{1} = 'k';
mseb(1:size(plotData,2), plotData(end,:), catErrMat{end,group_ind,2}, lineProps,1);
grandMeanAxes = axes('YAxisLocation','right','Color', 'none','xtick',[],'xticklabel',[],'xlim',[0 size(plotData,2)]);%,'ytick',[],'yticklabel',[]);
grandMeanAxes.YAxis.FontSize = 12;
linkprop([psthAxes, grandMeanAxes],{'Position'});
tmp = psthAxes.Position;
cbHandle.Position(1) = cbHandle.Position(1) + .03;
psthAxes.Position = tmp;
end
saveFigure(params.outputDir, ['2. ' psthTitle], [], figStruct, []);
end
end
end
% Plot 3 - Stimuli Plot - 'All chasing 1 PSTHs, sorted by...'
if params.allRunStimPSTH
% Make a PSTH of each stimulus across all its repetitions.
sortType = {'Run of Day', 'Grid Hole', 'Recording Depth', 'Run Ind'};
% {'Run of Day', 'Grid Hole', 'Recording Depth', 'Run Ind'};
% Must be the same order as the final parts of stimPSTH
[sortMat, sortLabel] = deal(cell(size(stimPSTH,1), size(stimPSTH,2), length(sortType)));
% Generate the PSTH sorting indicies
for stim_i = 1:size(stimPSTH,1)
for group_i = 1:size(stimPSTH,2)
for sort_i = 1:length(sortType) % the sortings that need processing
switch sort_i
case {1,2}
% Store indicies in 1st, labels in 2nd %Grid Holes --> Indicies
[tmpLabels , sortMat{stim_i, group_i, sort_i}] = sort(stimPSTH{stim_i, group_i,strcmp(dataType, sortType{sort_i})});
% Generate Labeling index
uniqueLabels = unique(tmpLabels);
labeledIndex = zeros(length(uniqueLabels),1);
for uni_i = 1:length(uniqueLabels)
if sort_i == 1
labeledIndex(uni_i) = find(tmpLabels == uniqueLabels(uni_i), 1);
elseif sort_i == 2
labeledIndex(uni_i) = find(strcmp(tmpLabels, uniqueLabels(uni_i)),1);
end
end
case 3 %Recording Depth --> Indicies
tmpDepths = [stimPSTH{stim_i, group_i,strcmp(dataType, sortType{sort_i})}];
[tmpLabels , sortMat{stim_i, group_i, sort_i}] = sort(tmpDepths');
labeledIndex = 1:5:length(tmpLabels);
case 4
sortMat{stim_i, group_i, sort_i} = 1:length(stimPSTH{stim_i, group_i, strcmp(dataType, sortType{sort_i})});
tmpLabels = runList(stimPSTH{stim_i, group_i,strcmp(dataType, sortType{sort_i})});
labeledIndex = 1:5:length(tmpLabels);
end
% Use the labeledIndex to generate the proper label array with 0's
% everywhere else.
sortLabelTmp = cell(length(tmpLabels),1);
for tmp_i = 1:length(labeledIndex)
if sort_i == 2 || sort_i == 4
sortLabelTmp{labeledIndex(tmp_i)} = tmpLabels{labeledIndex(tmp_i)};
else
sortLabelTmp{labeledIndex(tmp_i)} = tmpLabels(labeledIndex(tmp_i));
end
end
sortLabel{stim_i, group_i, sort_i} = tmpLabels;
end
end
end
% Iterate through PSTH, generating plots
if params.allRunStimPSTH
for stim_i = 1:length(stimPSTH)
% Get the relevant frameMotion/eventData
eventDataStim = eventData(allStimuliVec{stim_i},:);
stimTimePerFrame = frameMotionData(strcmp(allStimuliVec{stim_i}, frameMotionDataNames)).timePerFrame;
for group_i = groupIterInd
stimData = stimPSTH{stim_i,group_i,1};
for sort_i = 4%1:length(sortType)
figTitle = sprintf('%s - %s PSTHs, Sorted by %s, %s', allStimuliNames{stim_i}, groupingType{group_i} ,sortType{sort_i}, normTag);
h = figure('NumberTitle', 'off', 'Name', figTitle,'units','normalized','outerposition',[0 0 params.plotSizeAllRunStimPSTH]);
sgtitle(figTitle)
sortIndex = sortMat{stim_i, group_i, sort_i};
% Break up PSTHes with many lines into subplots.
TracesPerPlot = ceil(size(sortIndex,2)/3);
if TracesPerPlot < 20
subplot2Plot = 1;
elseif TracesPerPlot < 45
subplot2Plot = 2;
else
subplot2Plot = 3;
end
TracesPerPlot = ceil(size(sortIndex,2)/subplot2Plot);
plotStarts = 1:TracesPerPlot:size(sortIndex,2);
plotEnds = [plotStarts(2:end)-1, size(sortIndex,2)];
subplotAxes = gobjects(subplot2Plot,1);
cbHandle = gobjects(subplot2Plot,1);
for plot_i = 1:subplot2Plot
plotLabels = sortLabel{stim_i, group_i, sort_i}(plotStarts(plot_i):plotEnds(plot_i));
plotData = stimData(plotStarts(plot_i):plotEnds(plot_i), :);
%sortIndex = sortMat{stim_i, group_i, sort_i}(plotStarts(plot_i):plotEnds(plot_i));
psthAxes = subplot(1,subplot2Plot,plot_i);
[subplotAxes(plot_i), cbHandle(plot_i)] = plotPSTH(plotData, [], psthAxes, params, 'color', [], plotLabels); %(sortIndex,:)
cbHandle(plot_i).Label.FontSize = 10;
% Add eventData line if applicable
[eventsPres, legendObjs] = deal([]);
for event_i = 1:length(eventList)
if ~isempty(eventDataStim.(eventList{event_i}){1})
eventsPres = [eventsPres; eventList(event_i)];
hold on
singleEventDataStim = eventDataStim.(eventList{event_i}){1};
for ev_i = 1:size(singleEventDataStim, 1)
startX = singleEventDataStim.startFrame(ev_i) * stimTimePerFrame;
endX = singleEventDataStim.endFrame(ev_i) * stimTimePerFrame;
lineLeg = plot([startX startX], ylim(), 'Color', eventColors(event_i), 'LineWidth', 2);
plot([endX endX], ylim(), 'Color', eventColors(event_i), 'LineWidth', 2);
if ev_i == 1
legendObjs = [legendObjs; lineLeg];
end
end
end
end
if plot_i == subplot2Plot
% Add Legend for event lines, if present
if ~isempty(legendObjs)
legend(legendObjs, eventsPres, 'location', 'northeastoutside', 'Fontsize', 8);
end
% Label the Y
if params.normalize == 1
cbHandle(plot_i).Label.String = 'Signal Change relative to Baseline (%)';
elseif params.normalize == 2
cbHandle(plot_i).Label.String = 'Z score relative to fixation';
end
else
delete(cbHandle(plot_i))
end
set(gca,'FontSize',10,'TickLength',[.01 .01],'LineWidth',.25);
end
linkprop(subplotAxes, 'CLim');
saveFigure(params.outputDir, ['3. ' figTitle], [], figStruct, []);
end
end
end
end
end
% Plot 4 - Line plot with Line per Catagory
if params.lineCatPlot
% Find the end of the 'stimuli catagory' count.
catCount = find(strcmp(params.plotLabels, 'scene'));
if isempty(catCount)
catCount = find(strcmp(params.plotLabels, 'grooming'));
end
singleCatPlotMat = plotMat(:,1:catCount);
singleCatplotLabels = params.plotLabels(1:catCount);
singleCatplotLabelsSocialInd = params.plotLabelSocialInd(1:catCount);
%tmp = distinguishable_colors(catCount);
plotColors = cell(catCount,1);
socCount = sum(singleCatplotLabelsSocialInd);
nonSocCount = sum(~singleCatplotLabelsSocialInd);
socialColorsHSV = repmat(rgb2hsv(params.socialColor), [socCount, 1]);
nonSocialColorsHSV = repmat(rgb2hsv(params.nonSocialColor), [nonSocCount, 1]);
% HSV values cap at 240
hsvGradient = 25/240;
hsvGradientSoc = hsvGradient * (1:socCount);
hsvGradientNonSoc = hsvGradient * (1:nonSocCount);
socialColorsHSV(:,3) = socialColorsHSV(:,3) - hsvGradientSoc';
nonSocialColorsHSV(:,3) = nonSocialColorsHSV(:,3) - hsvGradientNonSoc';
plotColorTmp = [socialColorsHSV; nonSocialColorsHSV];
plotColorTmp = hsv2rgb(plotColorTmp);
for col_i = 1:catCount
plotColors{col_i} = plotColorTmp(col_i,:);
end
for group_ind = groupIterInd
catPSTHTitle = sprintf('%s Mean PSTH per Catagory Label %s', groupingType{group_ind}, normTag);
h = figure('NumberTitle', 'off', 'Name', catPSTHTitle,'units','normalized','outerposition',[0 0 params.plotSizeLineCatPlot]);
hold on
h.Children.FontSize = 15;
% Generate line plots w/ error bars.
lineProps.width = 2;
lineProps.col = plotColors;
lineProps.patch.FaceAlpha = '0.5';
[groupData, groupErr] = deal(cell(size(singleCatPlotMat,2),1));
for cat_ind = 1:size(singleCatPlotMat,2)
tmp = vertcat(stimPSTH{logical(singleCatPlotMat(:,cat_ind)), group_ind});
groupData{cat_ind} = mean(tmp,1);
groupErr{cat_ind} = std(tmp)/sqrt(size(tmp,1));
end
groupData = vertcat(groupData{:});
if params.fixAlign
groupMean = mean(mean(groupData(:,500:800)));
for g_ind = 1:size(groupData,1)
groupData(g_ind,:) = groupData(g_ind,:) - mean(groupData(g_ind,500:800)) + groupMean;
end
end
mseb(-800:(size(groupData,2)-801),groupData, vertcat(groupErr{:}), lineProps);
xlim([-800 (size(groupData,2)-801)])
legend(singleCatplotLabels, 'AutoUpdate','off','location', 'northeastoutside');
ylim manual
line([0 0], ylim(), 'Linewidth', 3, 'color', 'k');
line([2800 2800], ylim(), 'Linewidth',3,'color','k');
xlabel('Time from Stimulus Onset (ms)');
ylabel('Normalized Activity (Baseline Z scored)');
title(catPSTHTitle);
saveFigure(params.outputDir, ['4. ' catPSTHTitle], [], figStruct, []);
end
end
% Plot 5 - Means across broad catagorizations (like Social vs non Social)
if params.lineBroadCatPlot
% Generate line plots across different labeling schemes.
agentInd = plotMat(:,strcmp(params.plotLabels,'agents'));
socialInd = plotMat(:,strcmp(params.plotLabels,'socialInteraction'));
headTurnInd = plotMat(:,strcmp(params.plotLabels,'headTurn'));
allTurnInd = logical(plotMat(:,strcmp(params.plotLabels,'allTurn')));
%headTurnOldInd = logical(plotMat(:,strcmp(params.plotLabels,'headTurnClassic')));
% Agent videos without head turning.
agentNHInd = agentInd & ~headTurnInd;
agentNTInd = agentInd & ~allTurnInd;
% Social videos
socialHTInd = socialInd & headTurnInd; % Head turning vs Not
socialNonHTInd = socialInd & ~headTurnInd; %
socialTInd = socialInd & allTurnInd;
socialNonTInd = socialInd & ~allTurnInd;
% Social Agent vs Non-Social Agent
socialAgentInd = socialInd;
nonSocialAgentInd = agentInd & ~socialInd;
figIncInd = {agentInd, socialInd, headTurnInd, allTurnInd, socialHTInd, socialAgentInd, socialTInd};
figExcInd = {~agentInd, ~socialInd, agentNHInd, agentNTInd, socialNonHTInd, nonSocialAgentInd, socialNonTInd};
figTitInd = {'Agent containing Stimuli Contrast',...
'Social Interactions Contrast',...
'Agents engaging in Head Turning Contrast',...
'Agents engaging in All Turning Contrast',...
'Social Interactions with Head turning Contrast',...
'Agents engaging in Social Interactions Contrast'...
'Social Interactions with all Turning Contrast'};
figLegends = {{'Agent containing Stimuli','Non-Agent containing Stimuli'},...
{'Social Interaction Stimuli','non-Social Interaction Stimuli'},...
{'Agents with Head Turning','Agents without Head Turning'},...
{'Agents with Any Turning','Agents without Any Turning'},...
{'Socially Interacting Agents with Head Turning','Socially Interacting Agents without Head Turning'},...
{'Agents engaging in Social Interactions ','Agents not engaging in Social Interactions'}...
{'Socially Interacting Agents with Any Turning','Socially Interacting Agents without Any Turning'}};
lineProps.col = {params.socialColor, params.nonSocialColor};
assert(length(figIncInd) == length(figLegends), 'Update figTitInd and figLegends to match figIncInd')
meanPSTHStruct.lineBroadCatPlot.figIncInd = figIncInd;
meanPSTHStruct.lineBroadCatPlot.figExcInd = figExcInd;
meanPSTHStruct.lineBroadCatPlot.figTitInd = figTitInd;
meanPSTHStruct.lineBroadCatPlot.figLegends = figLegends;
meanPSTHStruct.lineBroadCatPlot.lineprops = lineProps;
% Append counts to the stimuliNames
allStimuliLabels = arrayfun(@(x) sprintf('%s (n = %d)', allStimuliNames{x}, stimPresCounts(x)), 1:length(stimPresCounts), 'UniformOutput',0)';
for fig_ind = 1:length(figIncInd)
% Retrieve the labels for each plot
line1Array = stimPSTH(figIncInd{fig_ind},:,1);
line2Array = stimPSTH(figExcInd{fig_ind},:,1);
line1Labels = allStimuliLabels(figIncInd{fig_ind});
line2Labels = allStimuliLabels(figExcInd{fig_ind});
line1EventMat = eventMat(figIncInd{fig_ind},:,:);
line2EventMat = eventMat(figExcInd{fig_ind},:,:);
% If there are two lines to plot, cycle through them.
if ~isempty(line1Array) && ~isempty(line2Array)
for group_ind = groupIterInd
% Generate Data
line1Data = vertcat(line1Array{:,group_ind});
line2Data = vertcat(line2Array{:,group_ind});
lineMean = [mean(line1Data, 1); mean(line2Data, 1)];
lineErr = [std(line1Data)/sqrt(size(line1Data,1)); std(line2Data)/sqrt(size(line2Data,1))];
if params.fixAlign
fixMean = mean(mean(lineMean(:,500:800),1));
for line_i = 1:size(lineMean,1)
lineMean(line_i,:) = lineMean(line_i,:) - mean(lineMean(line_i,500:800)) + fixMean;
end
end
% Prepare figure
plotTitle = sprintf('%s - %s, %s', ['mean PSTH of ' figTitInd{fig_ind}], groupingType{group_ind}, normTag);
h = figure('NumberTitle', 'off', 'Name', plotTitle,'units','normalized','outerposition',[0 0 params.plotSizeLineBroadCatPlot]);
params.lineProps = lineProps;
if params.addSubEventBars
figLegItr = [figLegends{fig_ind}, strrep(eventList, '_', ' ')];
else
figLegItr = figLegends{fig_ind};
end
[ ~, ~, ~, legendH] = plotPSTH(lineMean, lineErr, [], params, 'line', plotTitle, figLegItr);
axesH = findobj(gcf, 'Type', 'Axes');
axesH.FontSize = 15;
hold on
legendH.Location = 'northeast';
ylabel('Normalized Activity');
% Add event plots underneath the traces using eventMat and
% add_bar_to_plots.m
if params.addSubEventBars
% Prepare data matrices to plot
line1DataMat = squeeze(sum(line1EventMat, 1))';
line2DataMat = squeeze(sum(line2EventMat, 1))';
eventCount = size(line1DataMat, 1);
comboMat = [line1DataMat; line2DataMat];
% Shift to fit and pad pre and post.
comboMat = comboMat(:, 1:params.psthImDur);
comboMat = [zeros(size(comboMat,1), params.psthPre), comboMat, zeros(size(comboMat,1), params.psthPost)];
cMatSize = size(comboMat);
comboMatShow = ~comboMat == 0;
% Package for the add_bars_to_plots
comboMatArray = mat2cell(comboMat, repmat(eventCount, [2,1]), cMatSize(2));
comboMatShowArray = mat2cell(comboMatShow, repmat(eventCount, [2,1]), cMatSize(2));
% Prepare labels/colors
colorMat = lineProps.col;
% Add the plots
[newBarImg, barDummyHands] = add_bars_to_plots([], [], comboMatArray, colorMat, comboMatShowArray, []);
plotTitle = horzcat(plotTitle, '_eventBar');
end
% Save the figure
saveFigure(params.outputDir, ['5. ' plotTitle], [], figStruct, []);
% If desired, Generate plots of constituient traces.
if params.splitContrib
lineData = {line1Array(:, group_ind), line2Array(:, group_ind)};
lineLabels = {line1Labels, line2Labels};
for line_i = 1:length(lineData)
j = figure();
figTit = sprintf('%s - %s', figLegends{fig_ind}{line_i}, groupingType{group_ind});
meanLines = cellfun(@(x) mean(x), lineData{line_i}, 'UniformOutput', 0);
stdLines = cellfun(@(x) std(x)/sqrt(size(x,1)), lineData{line_i}, 'UniformOutput', 0);
meanLines = vertcat(meanLines{:});
stdLines = vertcat(stdLines{:});
% Sort things based on magnitutde of the peak
peaks = max(meanLines,[],2);
[~, sortOrder] = sort(peaks, 'descend');
plotPSTH(meanLines(sortOrder,:), stdLines(sortOrder,:), [], params, 'line', figTit, lineLabels{line_i}(sortOrder,:));
% Save the figure
saveFigure(params.outputDir, ['5.1. ' figTit], [], figStruct, [])
end
end
end
end
end
end
end
function [subEventPSTHStruct] = subEventPSTH(spikeDataBank, meanPSTHStruct, params, figStruct)
% Function compiles all the PSTHes of subEvents and plots them.
% One version uses spikeDataBank and pregenerated 'subEventSig' to pool and
% plot. 2nd segment uses stimPSTH to take slices out of stimuli PSTHes to
% generat plots.
disp('running subEventPSTH()...');
baselineSubtract = 1;
runList = fields(spikeDataBank);
% Load and extract key things from subEvents. Plots 1 and 2 only need the
% eventList, 3 and after use more features.
load(params.eventData);
eventList = [eventData.Properties.VariableNames 'saccades', 'blinks'];
groupIterInd = 3;
% Extract data from meanPSTHStruct
stimPSTH = meanPSTHStruct.stimPSTH;
allStimuliVec = meanPSTHStruct.IndStructs{1};
% Process names, make them amenable to plotting.
allStimuliNames = regexprep(extractBefore(allStimuliVec, '.avi'), '_\d\d\d', ' ');
% Remove runs with no events from spikeDataBank;
subEventInd = logical(structfun(@(x) x.subEventSigStruct.noSubEvent, spikeDataBank));
spikeDataBankFields = fields(spikeDataBank);
fields2Remove = spikeDataBankFields(subEventInd);
spikeDataBank = rmfield(spikeDataBank, fields2Remove);
runList = fields(spikeDataBank);
% Gather data across all the spikeDataBank Structure, generating a cell
% array with the indicies eventDataArray{event_i}{group_i}{data_i}
% event_i = eventList
groupType = {'Unsorted', 'Unit', 'MUA'};