-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneralmpep_Analysis.m
More file actions
2034 lines (1759 loc) · 103 KB
/
Generalmpep_Analysis.m
File metadata and controls
2034 lines (1759 loc) · 103 KB
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
%% User Input
% Load all data
OriSetting = PipelineParams;
% Find available datasets (always using dates as folders)
RedoAfterClustering=0;
Redo = 1; % Redo in general
RedoTable = 1;
NewHistologyNeeded = 0; %Automatically to 1 after RedoAfterClustering
%Predefine
SaveRFDir = SaveDir
abortsession = 0;
timeBinSize = 1/100;
pretrialtime = 0.2; %take up to x seconds prior trial
posttrialtime = 0.2; % take up to x seconds post trial
% Build wavelet filter bank
freqlims = [0.85 9.79];
nv = 48;
plotthis = 0; %For intermediate step plots (only for debugging)
CopyToXFileSpecific = 0;
%% Automated
% Build filterbank for wavelet transforms
clear DateOpt
DateOpt = arrayfun(@(X) dir(fullfile(DataDir{DataDir2Use(X)},MiceOpt{X},'*-*')),1:length(MiceOpt),'UniformOutput',0);
DateOpt = cellfun(@(X) X([X.isdir]),DateOpt,'UniformOutput',0);
DateOpt = cellfun(@(X) {X.name},DateOpt,'UniformOutput',0);
for midx = 1:length(MiceOpt)
Dates4Mouse = DateOpt{midx};
for didx = 1:length(Dates4Mouse)
% Within folders, look for 'RF mapping sessions'
thisdate = Dates4Mouse{didx}
subsess = dir(fullfile(DataDir{DataDir2Use(midx)},MiceOpt{midx},Dates4Mouse{didx}));
subsess(1:2) = []; %remove '.' and '..'
flag = 0;
mpepsess = [];
for sesidx=1:length(subsess)
if strcmp(subsess(sesidx).name,'leftovers')
continue
end
listfiles = dir(fullfile(subsess(sesidx).folder,subsess(sesidx).name,'*.p')); %Find protocol file
if any(~cell2mat(cellfun(@isempty,cellfun(@(X) strfind(X,'.p'),{listfiles(:).name},'UniformOutput',0),'UniformOutput',0)))
idx = find(~cell2mat(cellfun(@isempty,cellfun(@(X) strfind(X,'.p'),{listfiles(:).name},'UniformOutput',0),'UniformOutput',0)));
% read which x-file was used
if length(idx)>1
disp('Too many files?!')
keyboard
end
fileID = fopen(fullfile(listfiles(idx).folder,listfiles(idx).name));
A = fscanf(fileID,'%c');
fclose(fileID)
if ~any(strfind(A,'SparseNoise'))
mpepsess = [mpepsess {subsess(sesidx).name}];
flag = 1;
continue
else
disp('RF session, use different script... continue')
end
else
continue
end
end
if ~flag
continue
end
for sesidx = 1:length(mpepsess)
close all
abortsession = 0;
thisses = mpepsess{sesidx}
%% Timeline
% Timeline to go to:
timelinefile = dir(fullfile(DataDir{DataDir2Use(midx)},MiceOpt{midx},thisdate,thisses,'*Timeline.mat'));
timelineabsentwarning =0;
if isempty(timelinefile)
timelineabsentwarning =0;
disp([MiceOpt{midx} ' ' thisdate ' ' thisses ' has no timeline ... skipping'])
continue
end
loadTimeline
% Microphone data
[MicData,MicFS,MicnBits,SP] = LoadMicData(fullfile(DataDir{DataDir2Use(midx)},MiceOpt{midx},thisdate,thisses),0,0);
if ~isempty(SP)
f=SP.F;
Pw=abs(SP.S);
t = abs(SP.T);
else
f=[];
Pw = [];
t = [];
end
%% Load Protocol and identify unique conditions
Protocol = load(fullfile(DataDir{DataDir2Use(midx)},MiceOpt{midx},thisdate,thisses,'Protocol.mat'));
Protocol = Protocol.Protocol;
% extract trial information
ntrials = prod(size(Protocol.seqnums));
ParFullnames = Protocol.pardefs;
ParDefs = Protocol.parnames;
Pars = Protocol.pars;
ncond = size(Pars,2);
xfile = Protocol.xfile;
%% For sound, check whether these frequencies can be found
if any(ismember(ParDefs,'SoundFreq')) && ~isempty(Pw)
FreqsUsed = unique(Pars(ismember(ParDefs,'SoundFreq'),:))./10*1000; %in Hz
avgpw = nanmean(Pw,2);
avgdf = [0; diff(avgpw)];
figure; plot(f,nanmean(Pw,2));
hold on;
peaks = [];
id=find(avgdf>nanmean(avgdf)+1.5*nanstd(avgdf),1,'first');
while id <length(avgdf)
endidx = find(avgdf(id:end)<0,1,'first')+id;
[~,pkidx] = max(avgdf(id:endidx));
peaks = [peaks f(pkidx+id)];
id = endidx+find(avgdf(endidx:end)>nanmean(avgdf(endidx:end))+1.5*nanstd(avgdf(endidx:end)),1,'first');;
end
plot(peaks,avgpw(ismember(f,peaks)),'r*')
[r,c] = find(abs(FreqsUsed-peaks')<1000);
peaks = peaks(unique(r));
plot(peaks,avgpw(ismember(f,peaks)),'g*')
title('Microphone data')
xlabel('frequency (Hz)')
ylabel('|P|')
makepretty
if isempty(peaks)
disp('There was no sound!!')
Pars(ismember(ParDefs,'SoundFreq'),:)=0;
Pars(ismember(ParDefs,'ModFreq'),:)=0;
end
end
%%
sequence = Protocol.seqnums;
[condindx,repidx] = arrayfun(@(X) find(sequence==X),1:ntrials,'UniformOutput',0);
nrep = max(cell2mat(repidx));
% Factors of relevance
parrel = [];
RelName = {};
for parid = 1:size(Pars,1)
if length(unique(Pars(parid,:)))>1
parrel = [parrel parid];
RelName = {RelName{:} ParDefs{parid}};
end
end
notrelid = [];
[CondOpt,idx,cdx] = arrayfun(@(X) unique(Pars(X,:),'stable'),parrel,'UniformOutput',0);
for parid=1:length(parrel)
for parid2=1:length(parrel)
if ~any((cdx{parid} == cdx{parid2})==0)
if nanvar(CondOpt{parid})<nanvar(CondOpt{parid2}) %Categorical, remove this one
notrelid=[notrelid parrel(parid)]; %Remove duplicate conditions (some conditions are 1:1 match, like amplitude and frequency for sound)
end
end
end
end
if any(notrelid)
RelName(ismember(parrel,notrelid))=[];
parrel(ismember(parrel,notrelid))=[];
end
%Remove dcycl - not ideal but for now
parrel(ismember(RelName,'dcyc'))=[];
RelName(ismember(RelName,'dcyc'))=[];
condindx = cell2mat(condindx); %Condition index in trial ordedr
TrialDurations = Pars(strcmp(ParDefs,'dur'),condindx)/10;
ControlCond = find(nanmean(Pars(ismember(ParDefs,{'cr','cb','cg'}),:),1)==0 | nanmean(Pars(ismember(ParDefs,{'lr','lb','lg'}),:),1)==0 ); %^Contrast or luminance 0
RelName(ismember(parrel,find(ismember(ParDefs,{'cr','cb','cg','lr','lb','lg'}))))=[];
parrel(ismember(parrel,find(ismember(ParDefs,{'cr','cb','cg','lr','lb','lg'}))))=[];
newtimevec = -pretrialtime:timeBinSize:max(TrialDurations)+posttrialtime;
timeEdges = -pretrialtime-timeBinSize/2:timeBinSize:max(TrialDurations)+posttrialtime+timeBinSize/2;
%% Loading data from kilosort/phy easily
myKsDir = fullfile(KilosortDir,MiceOpt{midx});
subksdirs = dir(fullfile(myKsDir,thisdate,'**','Probe*')); %This changed because now I suddenly had 2 probes per recording
if length(subksdirs)<1
clear subksdirs
subksdirs.folder = myKsDir; %Should be a struct array
subksdirs.name = 'Probe0';
end
ProbeOpt = (unique({subksdirs(:).name}));
Alignflag = 0; %only needs to be done once
for probeid = 1:length(ProbeOpt)
%Saving directory
thisprobe = ProbeOpt{probeid}
myKsDir = fullfile(KilosortDir,MiceOpt{midx},thisdate,thisprobe);
% Check for multiple subfolders?
subsesopt = dir(fullfile(myKsDir,'**','channel_positions.npy'));
subsesopt = unique({subsesopt(:).folder});
if isempty(subsesopt)
disp(['No data found in ' myKsDir ', continue...'])
continue
end
%Saving directory
tmpfile = dir(fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,'MPEPData.mat'));
if ~Redo && ~isempty(tmpfile) && datetime(tmpfile.date)>= FromDate
disp([MiceOpt{midx} ' ' thisdate ' ' thisses ' already processed on ' tmpfile.date '... skipping'])
if CopyToXFileSpecific
if ~isdir(fullfile('\\znas.cortexlab.net\Lab\Share\Enny\MPEPData_Preprocessed',xfile,MiceOpt{midx},thisdate,thisses,thisprobe))
mkdir(fullfile('\\znas.cortexlab.net\Lab\Share\Enny\MPEPData_Preprocessed',xfile,MiceOpt{midx},thisdate,thisses,thisprobe))
end
copyfile(fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,'MPEPData.mat'),fullfile('\\znas.cortexlab.net\Lab\Share\Enny\MPEPData_Preprocessed',xfile,MiceOpt{midx},thisdate,thisses,thisprobe,'MPEPData.mat'))
end
continue
end
if ~Redo && exist(fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,'MPEPData.mat'))
if ~RedoAfterClustering || exist(fullfile(SaveDir,MiceOpt{midx},thisdate,thisses,thisprobe,'CuratedResults.mat'))
continue
elseif RedoAfterClustering
myKsDir = fullfile(KilosortDir,MiceOpt{midx},thisdate);
myClusFile = dir(fullfile(myKsDir,'cluster_info.tsv'));
if isempty(myClusFile)
disp('This data is not yet curated with phy!!')
continue
end
NewHistologyNeeded = 1; %Automatically to 1 after RedoAfterClustering
end
end
%% Align to Trial Onset times
if ~Alignflag
[starttrialidx,endtrialidx,trialid] = FindTrialOnAndOffSetsPhotoDiode(Actualtime,Timeline(:,ismember(AllInputs,'photoDiode')),TrialDurations);
TrialDurations(isnan(starttrialidx))=[];
endtrialidx(isnan(starttrialidx))=[];
starttrialidx(isnan(starttrialidx))=[];
if isempty(starttrialidx)
continue
end
if any((Actualtime(endtrialidx)-Actualtime(starttrialidx)) - TrialDurations'>1/tmSR*10)
disp(['flips slightly drifting... Average of ' num2str(nanmean((Actualtime(endtrialidx)-Actualtime(starttrialidx)) - TrialDurations')) 'sec'])
end
if ntrials ~= length(starttrialidx)
warning('Can''t find enough trials')
continue
end
Alignflag = 1;
end
%Saving directory
if ~isfolder(fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe))
mkdir(fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe))
end
% Remove current processed data
delete(fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,'*'))
% %% Computing some useful details about spikes/neurons (like depths)
myLFDir = fullfile(DataDir{DataDir2Use(midx)},MiceOpt{midx},thisdate,'ephys');
lfpD = dir(fullfile(myLFDir,'*','*','*.ap.*bin')); % ap file from spikeGLX specifically
if isempty(lfpD)
disp('No data found.. skip')
continue
end
if length(lfpD)~=length(subksdirs)
if ~isempty(dir(fullfile(myLFDir,'*VR*','*','*.ap.*bin')))
lfpD = dir(fullfile(myLFDir,'*VR*','*','*.ap.*bin')); % ap file from spikeGLX specifically
elseif length(lfpD)~=length(subksdirs)
disp('Should be a different amount of probes?')
end
end
lfpD = lfpD(probeid);
% Get information from meta file
[Imecmeta] = ReadMeta2(lfpD.folder,'ap');
lfpFs = str2num(Imecmeta.imSampRate);
nChansInFile = strsplit(Imecmeta.acqApLfSy,','); % neuropixels phase3a, from spikeGLX
nChansInFile = str2num(nChansInFile{1})+1; %add one for sync
%% Get cluster information
PipelineParams.thisdate = thisdate;
PipelineParams.SaveDir = fullfile(SaveDir,MiceOpt{midx},thisdate,thisprobe);
try
[clusinfo, sp, Params] = LoadPreparedClusInfo(subsesopt,PipelineParams);
catch ME
disp(ME)
PipelineParams = ExtractKilosortData(subsesopt,PipelineParams);
[clusinfo, sp, Params] = LoadPreparedClusInfo(subsesopt,PipelineParams);
end
% This extracts the parameters within clusinfo and sp
% struct for further analysis
ExtractFields({sp,clusinfo})
%% load synchronization data
SyncKSDataToTimeline
% In this case, take only relevant recording sesion
Good_IDx = find(Good_ID & ismember(RecSesID',recordingsessionidx));
nclus = length(Good_IDx);
if nclus < 2
disp('Less than 2 good units, skip...')
continue
end
if isfield(Params,'UnitMatch') && Params.UnitMatch == 1
if ~isfield(clusinfo,'UniqueID')
disp('No UniqueID... skip...')
continue
end
cluster_idUsed = UniqueID;
clu_sp = UniqClu;
if all(isnan(UniqueID(Good_IDx)))
disp('No UniqueID... skip')
cluster_idUsed = cluster_id;
clu_sp = clu;
elseif any(isnan(UniqueID(Good_IDx)))
keyboard
end
else
cluster_idUsed = cluster_id;
clu_sp = clu;
end
%if necessary
if syncchanmissing % There were some sessions where the clock was outputted from imec and this signal was also written on flipper. Try to extract that, combined with neuronal data
try
syncchanmissingTrySyncAgain
catch ME
disp(ME)
abortthissession = 1;
end
end
if abortthissession
continue
end
if ~syncchanmissing && ~any(~isnan(spikeTimesCorrected))
warning('No Spikes in this session... continue')
continue
end
%% Get Histology output
% if strcmp(ProbeType{midx},'2_4S')
% thisdate = []; % There's no data for the chronic mice in front of histology.
% end
clear Depth2Area
GetHistologyOutput %I created an extra function to have one line of code in the different scripts
if ~histoflag
disp([MiceOpt{midx} thisdate thisses thisprobe 'No histology data...'])
end
thisdate = Dates4Mouse{didx}; % Reassign thisdate
%% Spikes per trial
SpikeIDx = arrayfun(@(X) find(spikeTimesCorrected>=Actualtime(starttrialidx(X))-pretrialtime&spikeTimesCorrected<=Actualtime(endtrialidx(X))+posttrialtime),1:ntrials,'UniformOutput',0);
SpikeTrialID = nan(1,length(spikeTimesCorrected));
SpikeTrialTime = nan(1,length(spikeTimesCorrected));
for trid = 1:ntrials
SpikeTrialID(SpikeIDx{trid})=trid;
SpikeTrialTime(SpikeIDx{trid}) = spikeTimesCorrected(SpikeIDx{trid})-Actualtime(starttrialidx(trid));
end
%remove NaNs
spikeDepths(isnan(SpikeTrialID))=[];
SpikeTrialTime(isnan(SpikeTrialID))=[];
clu_sp(isnan(SpikeTrialID)) = [];
spikeTimesCorrected(isnan(SpikeTrialID))=[];
RecSes(isnan(SpikeTrialID))=[];
spikeShank(isnan(SpikeTrialID))=[];
SpikeTrialID(isnan(SpikeTrialID))=[];
%% Spike rate / histogram
SpikeRatePerTP = arrayfun(@(Y) arrayfun(@(X) histcounts(SpikeTrialTime(SpikeTrialID == X & clu_sp'== cluster_idUsed(Y) & spikeShank' == clusinfo.Shank(Y) & RecSes' == clusinfo.RecSesID(Y)),...
timeEdges),1:ntrials,'UniformOutput',0),Good_IDx,'UniformOutput',0);
SpikeRatePerTP = cat(1,SpikeRatePerTP{:});
SpikeRatePerTP = cat(1,SpikeRatePerTP{:});
SpikeRatePerTP = reshape(SpikeRatePerTP,length(Good_IDx),ntrials,[]); %Reshape to nclus, ntrials, ntp
SpikeRatePerTP=SpikeRatePerTP./timeBinSize; %in spikes/sec
SpikeRatePerTP = permute(SpikeRatePerTP,[2,3,1]); % Convert to trial,time,unit
SpikeRatePerTP(isnan(SpikeRatePerTP))=0;
% SpikeRatePerTP(repmat(sum(SpikeRatePerTP==0,3)==nclus,[1,1,nclus]))=nan;%
% Fill with nans instead of 0 when longer %Unsure why I did
% this?
%%
if ~any(SpikeRatePerTP(:)>0)
disp(['No spikes for ' MiceOpt{midx} ' ' thisdate ' ' thisses ', skip..'])
continue
end
%% Initialize save data
MpepInfo = table;
if size(cluster_idUsed,1)==1
cluster_idUsed=cluster_idUsed';
end
if size(cluster_id,1)==1
cluster_id=cluster_id';
end
if size(UniqueID,1)==1
UniqueID=UniqueID';
end
MpepInfo.ClusIDUsed = cluster_idUsed(Good_IDx);
MpepInfo.ClusID = cluster_id(Good_IDx);
MpepInfo.UniqueID = UniqueID(Good_IDx);
MpepInfo.depth = depth(Good_IDx);
MpepInfo.RecSes = clusinfo.RecSesID(Good_IDx);
MpepInfo.Shank = clusinfo.Shank(Good_IDx);
MpepInfo.SpikesPerSec = permute(SpikeRatePerTP,[3,1,2]);
[sorteddepth,sortidx] = sort(depth(Good_IDx));
AllCondNames={};
for condid=1:ncond
conditionvals = arrayfun(@(X) [' ' ParDefs{X} '=' num2str(Pars(X,condid))],parrel,'UniformOutput',0);
conditionvals = {[conditionvals{:}]};
AllCondNames = {AllCondNames{:} conditionvals{1}};
end
TrialInfo = table;
TrialInfo.CondNames = arrayfun(@(X) AllCondNames{X},condindx,'UniformOutput',0)';
TrialInfo.CondIndx = condindx';
if histoflag
areacol = clusinfo.Color(Good_IDx,:);
areatmp = clusinfo.Area(Good_IDx);
areatmp = strrep(areatmp,'/','');
end
%% Plot per condition across variables
% figure('name','Average PSTH')
[condsorted,sortid] = sort(condindx);
% imagesc(newtimevec,condsorted,nanmean(SpikeRatePerTP(sortid,:,:),3))
% colormap hot
% ylabel('Condition')
% xlabel('Time (s)')
% saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['AveragePSTH.fig']))
% saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['AveragePSTH.bmp']))
%
figure('name','Average PSTH','units','normalized','outerposition',[0 0 1 1])
for parid = 1:length(parrel)
[CondOpt,idx,cdx] = unique(Pars(parrel(parid),:));
TrialsPerCond = nan(ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
% Find trial index per condition
for cid = 1:length(CondOpt)
Cond2Take = find(Pars(parrel(parid),:)==CondOpt(cid)); %These are the conditions to take
Cond2Take(ismember(Cond2Take,ControlCond))=[]; %Remove control condition
TrialsPerCond(1:length(find(ismember(condindx,Cond2Take))),cid) = find(ismember(condindx,Cond2Take)); %These are the trials to take
end
TrialsPerCond(sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
TrialsPerCond(TrialsPerCond==0)=nan;
subplot(1,length(parrel),parid)
imagesc(newtimevec,[],nanmean(SpikeRatePerTP(TrialsPerCond(~isnan(TrialsPerCond)),:,:),3))
set(gca,'YTick',[size(TrialsPerCond,1)/2:size(TrialsPerCond,1):length(TrialsPerCond(:))-size(TrialsPerCond,1)/2],...
'YTickLabel',CondOpt)
colormap hot
ylabel('Condition')
xlabel('Time (s)')
title([ParFullnames{parrel(parid)}])
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['AveragePSTH.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['AveragePSTH.bmp']))
for parid = 1:length(parrel)
[CondOpt,idx,cdx] = unique(Pars(parrel(parid),:));
TrialsPerCond = nan(ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
AllCondNames = {};
% Find trial index per condition
for cid = 1:length(CondOpt)
Cond2Take = find(Pars(parrel(parid),:)==CondOpt(cid)); %These are the conditions to take
Cond2Take(ismember(Cond2Take,ControlCond))=[]; %Remove control condition
TrialsPerCond(1:length(find(ismember(condindx,Cond2Take))),cid) = find(ismember(condindx,Cond2Take)); %These are the trials to take
conditionvals = [ParDefs{parrel(parid)} '=' num2str(CondOpt(cid))];
AllCondNames = {AllCondNames{:} conditionvals};
end
TrialsPerCond(sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
TrialsPerCond(TrialsPerCond==0)=nan;
eval(['TrialInfo.' ParDefs{parrel(parid)} '= Pars(parrel(parid),condindx)'';'])
cols = jet(length(CondOpt));
figure('name',['PSTH per condition ' ParFullnames{parrel(parid)}],'units','normalized','outerposition',[0 0 1 1])
for cid = 1:length(CondOpt)
subplot(ceil(sqrt(length(CondOpt))),round(sqrt(length(CondOpt))),cid)
tmp = squeeze(nanmean(SpikeRatePerTP(TrialsPerCond(~isnan(TrialsPerCond(:,cid)),cid),:,:),1));
h=shadedErrorBar(newtimevec,nanmean(tmp,2),nanstd(tmp,[],2)./sqrt(nclus-1),'lineProps',{'color',cols(cid,:),'LineWidth',1.5});
ylabel('Spikes/sec')
xlabel('Time (s)')
title(AllCondNames{cid})
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} ' AveragePSTHPerCondition.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} ' AveragePSTHPerCondition.bmp']))
end
%% TF analysis
try
fb=cwtfilterbank('SamplingFrequency',1/timeBinSize,'SignalLength',length(newtimevec),'FrequencyLimits',freqlims,'VoicesPerOctave',nv);
figure
freqz(fb)
psi = wavelets(fb);
F = centerFrequencies(fb);
% Spikes
tmpspks = nanmean(nanmean(SpikeRatePerTP,1),3);
tmpspks(isnan(tmpspks))=0;
[csf,f] = cwt(double(tmpspks),'FilterBank',fb);
% Spikes
tmpspks = nanmean(nanmean(SpikeRatePerTP,1),3);
tmpspks(isnan(tmpspks))=0;
[csf,f] = cwt(double(tmpspks),'FilterBank',fb);
% amplitude?
Ampl= abs(csf);
%Time frequency for different conditions?
figure('name','Average amplitude across trials','units','normalized','outerposition',[0 0 1 1]);
subplot(2,1,1)
h=imagesc(newtimevec,[],nanmean(Ampl,3));
xlabel('Time (s)')
ylabel('Frequency Indx')
title('Amplitude')
colormap hot
set(gca,'ydir','normal')
makepretty
subplot(2,1,2)
avgAmpl = nanmean(Ampl,2);
plot(f,avgAmpl);
xlabel('Frequency (Hz)')
ylabel('Max Amplitude')
makepretty
catch ME
disp(ME)
end
%%
try
for parid = 1:length(parrel)
[CondOpt,idx,cdx] = unique(Pars(parrel(parid),:));
TrialsPerCond = nan(ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
AllCondNames = {};
% Find trial index per condition
for cid = 1:length(CondOpt)
Cond2Take = find(Pars(parrel(parid),:)==CondOpt(cid)); %These are the conditions to take
Cond2Take(ismember(Cond2Take,ControlCond))=[]; %Remove control condition
TrialsPerCond(1:length(find(ismember(condindx,Cond2Take))),cid) = find(ismember(condindx,Cond2Take)); %These are the trials to take
conditionvals = [ParDefs{parrel(parid)} '=' num2str(CondOpt(cid))];
AllCondNames = {AllCondNames{:} conditionvals};
end
TrialsPerCond(sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
TrialsPerCond(TrialsPerCond==0)=nan;
figure('name',['TF per condition ' ParDefs{parrel(parid)}],'units','normalized','outerposition',[0 0 1 1])
for cid = 1:length(CondOpt)
subplot(ceil(sqrt(length(CondOpt))),round(sqrt(length(CondOpt))),cid)
% Spikes
tmpspks = nanmean(nanmean(SpikeRatePerTP(TrialsPerCond(~isnan(TrialsPerCond(:,cid)),cid),:,:),1),3);
tmpspks(isnan(tmpspks))=0;
[csf,f] = cwt(double(tmpspks),'FilterBank',fb);
Ampl= abs(csf);
h=imagesc(newtimevec,[],Ampl);
xlabel('Time (s)')
colormap hot
title(AllCondNames{cid})
set(gca,'YTick','')
hold on
yyaxis right
avgAmpl = nanmean(Ampl,2);
plot(avgAmpl,f,'b-');
ylabel('Frequency (Hz)')
set(gca,'YScale','log')
makepretty
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} ' TFperCondition.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} ' TFperCondition.bmp']))
end
%% Analyze without plotting for all units
if any(ismember(RelName,{'tf','ModFreq'})) % Frequency modulation!
parvec = find(ismember(ParDefs,{'tf','ModFreq'}));
figure('name',['Freq modulation across depth - Rayleigh'],'units','normalized','outerposition',[0 0 1 1]);
for parid = 1:length(parvec)
freqs = unique(Pars(parvec(parid),:))/10;
if length(freqs)==1
continue
end
Rvec = nan(nclus,length(freqs));
Thetavec = nan(nclus,length(freqs));
RayleighP = nan(nclus,length(freqs));
for freqid=1:length(freqs)
trialidx = find(ismember(condindx,find(Pars(parvec(parid),:)==freqs(freqid)*10)));
circledur = 1./freqs(freqid);
angles = arrayfun(@(Y) arrayfun(@(X) (newtimevec(SpikeRatePerTP(X,:,Y)>0)*2*pi)./circledur,trialidx,'UniformOutput',0),1:nclus,'UniformOutput',0);
angles = cellfun(@(Y) [Y{:}],angles,'UniformOutput',0); %Concatenate across trials
clusid = ~cell2mat(cellfun(@isempty,angles,'UniformOutput',0));
RayleighP(clusid,freqid)=cell2mat(cellfun(@(Y) circ_rtest(Y'),angles(clusid),'UniformOutput',0)); % Rayleightest
Thetavec(clusid,freqid) = cell2mat(cellfun(@(Y) circ_mean(Y'),angles(clusid),'UniformOutput',0)); % circular mean
Rvec(clusid,freqid) = cell2mat(cellfun(@(Y) circ_r(Y'),angles(clusid),'UniformOutput',0)); % strength
end
%Save
eval(['MpepInfo.' ParDefs{parvec(parid)} '_Rvec=Rvec;']) % ModFreq should have 2 points per variable to fit in large mpep table
eval(['MpepInfo.' ParDefs{parvec(parid)} '_CircMean=Thetavec;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_RayleighP=RayleighP;'])
subplot(1,5,[(parid-1)*2+1 parid*2])
% Plot this
Pvals = abs(log10(RayleighP));
imagesc(freqs,sorteddepth,Pvals(sortidx,:),[0 10])
xlabel('Frequency')
if parid==1
ylabel('Depth (micron from tip)')
else
set(gca,'YTickLabel',[])
end
set(gca,'YDir','normal','XTick',freqs)
title(ParDefs{parvec(parid)})
colormap hot
freezeColors
end
if histoflag
[areaopt,idx,udx] = unique(areatmp(sortidx),'stable');
areacolsort = areacol(sortidx);
subplot(1,5,5)
h=imagesc(udx);
colormap(cat(1,areacolsort{idx}))
set(gca,'YDir','normal')
set(gca,'YTick',idx,'YTickLabel',areaopt,'XTickLabel',[])
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['Freq modulation across depth - Rayleigh.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['Freq modulation across depth - Rayleigh.bmp']))
end
catch ME
disp(ME)
end
%% Plot per unit
nexample = 5
TotalSpikeRate = squeeze(nansum(nansum(SpikeRatePerTP,1),2));
if nexample>sum(TotalSpikeRate>5000)
nexample=sum(TotalSpikeRate>5000);
end
exampleunits = datasample(find(TotalSpikeRate>5000),nexample,'replace',false);
for uid = 1:nexample
unitid = cluster_idUsed(Good_IDx(exampleunits(uid)));
depthhere = depth(Good_IDx(exampleunits(uid)));
if histoflag
unitname = ['Unit ' num2str(unitid) ', depth=' num2str(depthhere) ', ' areatmp{exampleunits(uid)}];
else
unitname = ['Unit ' num2str(unitid) ', depth=' num2str(depthhere)];
end
for parid = 1:length(parrel)
[CondOpt,idx,cdx] = unique(Pars(parrel(parid),:));
TrialsPerCond = nan(ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
AllCondNames = {};
cols = jet(length(CondOpt));
AllCols = nan(3,ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
% Find trial index per condition
for cid = 1:length(CondOpt)
Cond2Take = find(Pars(parrel(parid),:)==CondOpt(cid)); %These are the conditions to take
Cond2Take(ismember(Cond2Take,ControlCond))=[]; %Remove control condition
TrialsPerCond(1:length(find(ismember(condindx,Cond2Take))),cid) = find(ismember(condindx,Cond2Take)); %These are the trials to take
conditionvals = [ParDefs{parrel(parid)} '=' num2str(CondOpt(cid))];
AllCondNames = {AllCondNames{:} conditionvals};
AllCols(:,1:length(find(ismember(condindx,Cond2Take))),cid) = repmat(cols(cid,:)',[1,length(find(ismember(condindx,Cond2Take)))]);
end
AllCols(:,sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
AllCols = reshape(AllCols,3,[]);
TrialsPerCond(sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
TrialsPerCond(TrialsPerCond==0)=nan;
AllCols = AllCols(:,~isnan(TrialsPerCond(:)));
TrialsPerCond = TrialsPerCond(~isnan(TrialsPerCond));
try
figure('name',[unitname ParDefs{parrel(parid)}],'units','normalized','outerposition',[0 0 1 1])
subplot(2,1,1)
hold on
arrayfun(@(X) scatter(newtimevec(SpikeRatePerTP(TrialsPerCond(X),:,exampleunits(uid))>0),repmat(X,[1,sum(SpikeRatePerTP(TrialsPerCond(X),:,exampleunits(uid))>0)]),8,AllCols(:,X)','filled'),1:length(TrialsPerCond),'UniformOutput',0)
xlabel('Time (s)')
ylabel('Trial (sorted by condition)')
line([0 0],get(gca,'ylim'),'color',[0 0 0],'LineStyle','--')
TrialsPerCond = reshape(TrialsPerCond,[],length(CondOpt));
subplot(2,1,2)
hold on
clear h
for cid=1:length(CondOpt)
tmp = SpikeRatePerTP(TrialsPerCond(:,cid),:,exampleunits(uid));
h(cid)=shadedErrorBar(newtimevec,smooth(nanmean(tmp,1)+max(get(gca,'ylim'))*0.9),smooth(nanstd(tmp,[],1)./sqrt(size(tmp,1)-1)),'lineProps',{'color',cols(cid,:),'LineWidth',1.5});
end
xlabel('time (s)')
ylabel('Spks/Sec')
set(gca,'YTick','')
line([0 0],get(gca,'ylim'),'color',[0 0 0],'LineStyle','--')
legend([h.mainLine],AllCondNames)
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} unitname '_PSTH.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} unitname '_PSTH.bmp']))
catch ME
disp(ME)
end
end
if any(ismember(RelName,{'tf','ModFreq'})) % Frequency modulation!
parvec = find(ismember(ParDefs,{'tf','ModFreq'}));
for parid = 1:length(parvec)
freqs = unique(Pars(parvec(parid),:))/10;
if freqs==0
continue
end
figure('name',[unitname ParDefs{parvec(parid)} ' Frequency Modulation'],'units','normalized','outerposition',[0 0 1 1])
for freqid=1:length(freqs)
trialidx = find(ismember(condindx,find(Pars(parvec(parid),:)==freqs(freqid)*10)));
circledur = 1./freqs(freqid);
angles = arrayfun(@(X) (newtimevec(SpikeRatePerTP(X,:,exampleunits(uid))>0)*2*pi)./circledur,trialidx,'UniformOutput',0);
if isempty([angles{:}])
continue
end
subplot(length(freqs),2,(2*freqid)-1)
try
histogram([angles{:}]',[0:0.2*pi:max([angles{:}])])
ylims = get(gca,'ylim');
arrayfun(@(X) patch([X X+pi X+pi X],[min(ylims) min(ylims) max(ylims) max(ylims)],[0 1 0],'FaceAlpha',0.2,'EdgeColor','none'),0:2*pi:max([angles{:}]),'UniformOutput',0)
set(gca,'XTickLabel',cellfun(@(X) num2str(round(str2num(X)./(2*pi).*circledur*100)./100),(get(gca,'XTickLabel')),'UniformOutput',0))
xlabel('Time (s)')
hold on
ylabel(['nr spikes at phase ' ParDefs{parvec(parid)}])
title([num2str(freqs(freqid)) 'Hz'])
makepretty
subplot(length(freqs),2,2*freqid)
circ_plot([angles{:}]','hist',[],20,true,true,'linewidth',2,'color','r')
p=circ_rtest([angles{:}]');
title(['p=' num2str(p)])
makepretty
catch ME
disp(ME)
end
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[unitname ParDefs{parvec(parid)} ' Frequency Modulation.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[unitname ParDefs{parvec(parid)} ' Frequency Modulation.bmp']))
end
end
end
%% Analyze for different depths
if 0
dptstp = 500; %in um
depthvec = min(spikeDepths):dptstp:max(spikeDepths);
CondOpt=unique(condindx);
SpikeRatePerDepth = arrayfun(@(Y) arrayfun(@(X) histcounts(SpikeTrialTime((SpikeTrialID == X)' & spikeDepths>=depthvec(Y)-dptstp/2&spikeDepths<=depthvec(Y)+dptstp/2),...
timeEdges),1:ntrials,'UniformOutput',0),1:length(depthvec),'UniformOutput',0);
SpikeRatePerDepth = cat(1,SpikeRatePerDepth{:});
SpikeRatePerDepth = cat(1,SpikeRatePerDepth{:});
SpikeRatePerDepth = reshape(SpikeRatePerDepth,length(newtimevec),length(depthvec),[]);
storedepth = [];
cols = summer(length(CondOpt));
for parid = 1:length(parrel)
[CondOpt,idx,cdx] = unique(Pars(parrel(parid),:));
TrialsPerCond = nan(ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
AllCondNames = {};
cols = jet(length(CondOpt));
AllCols = nan(3,ceil(size(SpikeRatePerTP,1)./length(CondOpt)),length(CondOpt));
% Find trial index per condition
for cid = 1:length(CondOpt)
Cond2Take = find(Pars(parrel(parid),:)==CondOpt(cid)); %These are the conditions to take
Cond2Take(ismember(Cond2Take,ControlCond))=[]; %Remove control condition
TrialsPerCond(1:length(find(ismember(condindx,Cond2Take))),cid) = find(ismember(condindx,Cond2Take)); %These are the trials to take
conditionvals = [ParDefs{parrel(parid)} '=' num2str(CondOpt(cid))];
AllCondNames = {AllCondNames{:} conditionvals};
AllCols(:,1:length(find(ismember(condindx,Cond2Take))),cid) = repmat(cols(cid,:)',[1,length(find(ismember(condindx,Cond2Take)))]);
end
AllCols(:,sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
AllCols = reshape(AllCols,3,[]);
TrialsPerCond(sum(isnan(TrialsPerCond),2)==size(TrialsPerCond,2),:)=[];
TrialsPerCond = reshape(TrialsPerCond,[],length(CondOpt));
for dptid=1:length(depthvec)
largefig = figure('name',['Spikes depth ' num2str(depthvec(dptid)) 'um' ParDefs{parrel(parid)}],'units','normalized','outerposition',[0 0 1 1]);
% Extract spike indices for this depth and
% condition
idx = arrayfun(@(X) ismember(SpikeTrialID,X)' & spikeDepths>=depthvec(dptid)-dptstp/2&spikeDepths<=depthvec(dptid)+dptstp/2,TrialsPerCond(:),'UniformOutput',0);
% Extract spike times
spktms = (cellfun(@(X) SpikeTrialTime(X),idx,'UniformOutput',0));
subplot(2,1,1)
hold on
arrayfun(@(X) scatter(spktms{X},depthvec(dptid)+X-1,10,AllCols(:,X)','filled'),1:length(spktms))
xlabel('Time (s)')
ylabel('Depth and trials (sorted by condition)')
line([0 0],get(gca,'ylim'),'color',[0 0 0],'LineStyle','--')
subplot(2,1,2)
hold on
clear h
for cid=1:length(CondOpt)
tmp = squeeze(SpikeRatePerDepth(:,dptid,TrialsPerCond(:,cid)));
h(cid)=shadedErrorBar(newtimevec,smooth(nanmean(tmp,2)+depthvec(dptid)./25+cid),smooth(nanstd(tmp,[],2)./sqrt(size(tmp,2)-1)),'lineProps',{'color',cols(cid,:),'LineWidth',1.5});
end
drawnow
xlabel('time (s)')
ylabel('Spks/Sec')
set(gca,'YTick','')
line([0 0],get(gca,'ylim'),'color',[0 0 0],'LineStyle','--')
legend([h.mainLine],AllCondNames)
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} num2str(depthvec(dptid)) 'um' '_PSTH.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[ParDefs{parrel(parid)} num2str(depthvec(dptid)) 'um' '_PSTH.bmp']))
close(largefig)
end
end
end
clear SpikeRatePerDepth
%% Orientation tuning?
if any(ismember(RelName,{'ori'}))
parvec = find(ismember(ParDefs,{'ori'}));
figure('name',['Orientation tuning across depth'],'units','normalized','outerposition',[0 0 1 1]);
for parid = 1:length(parvec)
oris = unique(Pars(parvec(parid),:));
SpikesPerOri = nan(nclus,ceil(size(SpikeRatePerTP,1)./length(oris)),length(oris));
for Oriid=1:length(oris)
%orientation, contrast not 0!
trialidx = find(ismember(condindx,find(Pars(parvec(parid),:)==oris(Oriid) & nanmean(Pars(ismember(ParDefs,{'cr','cg','cb'}),:),1)~=0)));
SpikesPerOri(:,1:length(trialidx),Oriid) = squeeze(nanmean(SpikeRatePerTP(trialidx,newtimevec>0&newtimevec<=nanmin(TrialDurations),:),2))'; %Average over stimulus presentation
end
% OSI
%Prefered orientation - odd trials
[~,PrefOriIdx] = (arrayfun(@(X) nanmax(nanmean(SpikesPerOri(X,1:2:end,:),2),[],3),1:nclus,'UniformOutput',0));
PrefOriIdx = cell2mat(PrefOriIdx);
PrefOri = oris(PrefOriIdx);
Plus90Ori = mod(PrefOri+90,360);
Plus90OriIdx = cell2mat(arrayfun(@(X) find(oris==X),Plus90Ori,'UniformOutput',0));
OSI = cell2mat(arrayfun(@(X) (nanmean(SpikesPerOri(X,2:2:end,PrefOriIdx(X)),2)-nanmean(SpikesPerOri(X,2:2:end,Plus90OriIdx(X)),2))./...
(nanmean(SpikesPerOri(X,2:2:end,PrefOriIdx(X)),2)+nanmean(SpikesPerOri(X,2:2:end,Plus90OriIdx(X)),2)),1:nclus,'UniformOutput',0));
% DSI
Plus180Ori = mod(PrefOri+180,360);
Plus180OriIdx = cell2mat(arrayfun(@(X) find(oris==X),Plus180Ori,'UniformOutput',0));
DSI = cell2mat(arrayfun(@(X) (nanmean(SpikesPerOri(X,2:2:end,PrefOriIdx(X)),2)-nanmean(SpikesPerOri(X,2:2:end,Plus180OriIdx(X)),2))./...
(nanmean(SpikesPerOri(X,2:2:end,PrefOriIdx(X)),2)+nanmean(SpikesPerOri(X,2:2:end,Plus180OriIdx(X)),2)),1:nclus,'UniformOutput',0));
figure('units','normalized','outerposition',[0 0 1 1],'units','normalized','outerposition',[0 0 1 1]); subplot(2,2,2)
histogram(OSI)
makepretty
title('OSI')
subplot(2,2,4)
histogram(DSI)
makepretty
title('DSI')
OSI = OSI';
DSI = DSI';
% Significant Rayleigh?
spks = squeeze(round(nansum(SpikesPerOri(:,:,:),2)));
angles = arrayfun(@(Y) arrayfun(@(X) repmat(oris(X),[1,spks(Y,X)]),1:length(oris),'UniformOutput',0),...
1:nclus,'UniformOutput',0);
angles = cat(1,angles{:});
unitidx = find(sum(cell2mat(cellfun(@isempty,angles,'UniformOutput',0)),2)<length(oris));
pRayleigh = nan(1,nclus);
pRayleigh(unitidx)=cell2mat(arrayfun(@(Y) circ_rtest([angles{Y,:}]'./360*2*pi),unitidx,'UniformOutput',0));
subplot(2,2,[1,3])
cols = repmat([0 0 0],nclus,1);
cols(pRayleigh<0.05,:)=repmat([1 0 0],sum(pRayleigh<0.05),1);
scatter(abs(log(pRayleigh)),depth(Good_IDx),10,cols,'filled')
hold on
pRayleigh = pRayleigh';
PrefOri = PrefOri';
%Save
eval(['MpepInfo.' ParDefs{parvec(parid)} '_SpikesPerOri=SpikesPerOri;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_OSI=OSI;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_DSI=DSI;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_pRayleigh=pRayleigh;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_PrefOri=PrefOri;'])
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['OrientationModulation.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,['OrientationModulation.bmp']))
% Few example cells
for uid = 1:nexample
unitid = cluster_idUsed(Good_IDx(exampleunits(uid)));
depthhere = depth(Good_IDx(exampleunits(uid)));
if histoflag
unitname = ['Unit ' num2str(unitid) ', depth=' num2str(depthhere) ', ' areatmp{exampleunits(uid)}];
else
unitname = ['Unit ' num2str(unitid) ', depth=' num2str(depthhere)];
end
figure('name',unitname,'units','normalized','outerposition',[0 0 1 1])
subplot(2,1,1)
shadedErrorBar(oris,squeeze(nanmean(SpikesPerOri(exampleunits(uid),:,:),2)),squeeze(nanstd(SpikesPerOri(exampleunits(uid),:,:),[],2)))
xlabel('Orientation')
ylabel('Spks/Sec')
title(['OSI=' num2str(OSI(exampleunits(uid))) ', DSI=' num2str(DSI(exampleunits(uid)))])
makepretty
% Polar Plot
subplot(2,1,2)
spks = round(nansum(squeeze(SpikesPerOri(exampleunits(uid),:,:)),1));
angles = arrayfun(@(X) repmat(oris(X),[1,spks(X)]),1:length(oris),'UniformOutput',0);
angles = [angles{:}];
if ~isempty(angles)
circ_plot(angles'./360*2*pi,'hist',[],30,true,true,'linewidth',2,'color','r')
p=circ_rtest(angles'./360*2*pi);
title(['p=' num2str(p)])
end
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[unitname '_PSTH.fig']))
saveas(gcf,fullfile(SaveRFDir,MiceOpt{midx},thisdate,thisses,thisprobe,[unitname '_PSTH.bmp']))
end
end
%% Frequency tuning?
if any(ismember(RelName,{'SoundFreq'}))
parvec = find(ismember(ParDefs,{'SoundFreq'}));
figure('name',['Frequency tuning across depth'],'units','normalized','outerposition',[0 0 1 1]);
for parid = 1:length(parvec)
oris = unique(Pars(parvec(parid),:));
SpikesPerOri = nan(nclus,ceil(size(SpikeRatePerTP,1)./length(oris)),length(oris));
for Oriid=1:length(oris)
%Frequency, Amplitude not 0!
trialidx = find(ismember(condindx,find(Pars(parvec(parid),:)==oris(Oriid) & nanmean(Pars(ismember(ParDefs,{'ampl'}),:),1)~=0)));
SpikesPerOri(:,1:length(trialidx),Oriid) = squeeze(nanmean(SpikeRatePerTP(trialidx,newtimevec>0&newtimevec<=nanmin(TrialDurations),:),2))'; %Average over stimulus presentation
end
% FMI
%Prefered frequency - odd trials
[~,PrefFreqIdx] = (arrayfun(@(X) nanmax(nanmean(SpikesPerOri(X,1:2:end,:),2),[],3),1:nclus,'UniformOutput',0));
PrefFreqIdx = cell2mat(PrefFreqIdx);
PrefFreq = oris(PrefFreqIdx);
[~,NPrefFreqIdx] = (arrayfun(@(X) nanmin(nanmean(SpikesPerOri(X,1:2:end,:),2),[],3),1:nclus,'UniformOutput',0));
NPrefFreqIdx = cell2mat(NPrefFreqIdx);
NPrefFreq = oris(NPrefFreqIdx);
FMI = cell2mat(arrayfun(@(X) (nanmean(SpikesPerOri(X,2:2:end,PrefFreqIdx(X)),2)-nanmean(SpikesPerOri(X,2:2:end,NPrefFreqIdx(X)),2))./...
(nanmean(SpikesPerOri(X,2:2:end,PrefFreqIdx(X)),2)+nanmean(SpikesPerOri(X,2:2:end,NPrefFreqIdx(X)),2)),1:nclus,'UniformOutput',0));
histogram(FMI)
makepretty
title('Frequency Modulation Index')
FMI = FMI';
PrefFreq = PrefFreq';
NPrefFreq = NPrefFreq';
%Save
eval(['MpepInfo.' ParDefs{parvec(parid)} '_SpikesPerFreq=SpikesPerOri;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_FMI=FMI;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_PrefFreq=PrefFreq;'])
eval(['MpepInfo.' ParDefs{parvec(parid)} '_NPrefFreq=NPrefFreq;'])