-
Notifications
You must be signed in to change notification settings - Fork 2
/
SpikeVisualizationGUI.m
2269 lines (2107 loc) · 100 KB
/
SpikeVisualizationGUI.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 varargout = SpikeVisualizationGUI(varargin)
% MATLAB code for SpikeVisualizationGUI.fig
% Last Modified by GUIDE v2.5 17-Nov-2017 16:03:13
% version 0.7 (nov 2017), tested in R2017b
% version 0.5 (sept 2016), tested in R2014b
% Vincent Prevosto
% email: vp35 at duke.edu
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @SpikeVisualizationGUI_OpeningFcn, ...
'gui_OutputFcn', @SpikeVisualizationGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
%% --- Executes just before SpikeVisualizationGUI is made visible.
function SpikeVisualizationGUI_OpeningFcn(hObject, ~, handles, varargin)
% Choose default command line output for SpikeVisualizationGUI
handles.output = hObject;
if ~isempty(varargin)
handles=CatStruct(handles,varargin{:}); % CatStruct available here:
% http://www.mathworks.com/matlabcentral/fileexchange/7842-CatStruct
if isfield(handles,'fname')
set(handles.TB_FileName,'string',handles.fname(1:end-4));
else
set(handles.TB_FileName,'string','');
end
if isempty(handles.spikeFile)
% check if spike sorting results are present in export folder
cd(handles.exportDir);
listExportDir=dir;
listExportDir=listExportDir(cellfun('isempty',cellfun(@(x) strfind('.',x(end)),{listExportDir.name},'UniformOutput',false)));
spikeFileIdx=cellfun(@(x) contains(x,'_spikes.mat'),{listExportDir.name});
if logical(sum(spikeFileIdx))
handles.spikeFile=listExportDir(spikeFileIdx).name;
else %maybe spike sorting results are sub folder
spikeSortingFolderIdx=[listExportDir.isdir];
spikeSortingFolder=[handles.exportDir filesep listExportDir(spikeSortingFolderIdx).name];
listSpikeSortingFolder=dir(spikeSortingFolder);
spikeFileIdx=cellfun(@(x) contains(x,'result'),{listSpikeSortingFolder.name});
if logical(sum(spikeFileIdx))
handles.exportDir=spikeSortingFolder;
handles.spikeFile=listSpikeSortingFolder(spikeFileIdx).name;
else
% ask user to select file to load
[handles.spikeFile,handles.exportDir] = uigetfile({'*.mat;*.hdf5;*.csv','Export Formats';...
'*.dat','Raw data';'*.*','All Files' },'Select data to load',cd);
if handles.spikeFile==0
handles=rmfield(handles,'spikeFile');
handles.exportDir=cd;
end
end
end
end
else
try
handles.userinfo=UserDirInfo;
catch
handles.userinfo=[];
handles.userinfo.user=getenv('username');
end
%% get most recently changed data folder (looks for a folder named "export")
if isfield(handles.userinfo,'directory')
exportDir=regexprep(handles.userinfo.directory,'\\\w+$','\\export');
else
[exportDir,handles.userinfo.directory]=deal(cd);
end
dataDirListing=dir(exportDir);
if ~isempty(dataDirListing)
%removing dots
dataDirListing=dataDirListing(cellfun('isempty',cellfun(@(x) strfind(x,'.'),...
{dataDirListing.name},'UniformOutput',false)));
%removing other folders
dataDirListing=dataDirListing(cellfun('isempty',cellfun(@(x)...
regexp('Behav | Video | Impedance',x),... % list | all | unwanted | folders | here
{dataDirListing.name},'UniformOutput',false)));
[~,fDateIdx]=sort([dataDirListing.datenum],'descend');
recentDataFolder=[exportDir filesep dataDirListing(fDateIdx(1)).name filesep];
else
recentDataFolder=cd;
end
% ask user to select file to load
[handles.spikeFile,handles.exportDir] = uigetfile({'*.mat;*.hdf5;*.csv','Export Formats';...
'*.dat','Raw data';'*.*','All Files' },'Select data to load',recentDataFolder);
if handles.spikeFile==0
handles.spikeFile='';
handles.exportDir=recentDataFolder;
end
end
%define figure colormap
colormapSeed=lines;
handles.cmap=[colormapSeed(1:7,:);(colormapSeed+flipud(colormap(copper)))/2;autumn];
if isfield(handles,'spikeFile') && ~isempty(handles.spikeFile) && sum(strfind(handles.spikeFile,'.dat'))
GetSortedSpikes_PB_Callback(hObject, handles);
end
handles.fileLoaded=0;
%create classification table
handles.classification = table([],[],[],categorical(),{},'VariableNames',{'SortID','Channel','UnitNumber','Classification','Comment'});
if isfield(handles,'spikeFile')
handles=LoadSpikes(handles);
handles=LoadRawData(handles);
end
% Update handles structure
guidata(hObject, handles);
%% --- Executes (conditional) at startup and on button press in GetSortedSpikes_PB.
function GetSortedSpikes_PB_Callback(hObject, ~, handles)
if ~isfield(handles,'datFile')
handles.datFile=[cell2mat(regexp(handles.spikeFile,'.+(?=\_\w+\_\w+\.)','match')) '_nopp'];
end
[status,cmdout]=RunSpykingCircus(cd,handles.datFile,{'runspkc,exportspikes'});
if handles.GetSortedSpikes_PB.ForegroundColor(1)==0.3490
handles.GetSortedSpikes_PB.ForegroundColor=[0.2 0.5 0.7];
else
handles.GetSortedSpikes_PB.ForegroundColor=[0.3490 0.2000 0.3294];
end
%% Load data function
function handles=LoadSpikes(handles)
if isfield(handles,'subset')
handles = rmfield(handles,'subset');
end
% if isfield(handles,'spikeFile')
% handles = rmfield(handles,'spikeFile');
% end
if isfield(handles,'offlineSort_SpikeFile')
handles = rmfield(handles,'offlineSort_SpikeFile');
end
% function declaration
axis_name= @(x) sprintf('Chan %.0f',x);
if isfield(handles,'fname') && strcmp(handles.fname,'')
set(handles.TB_FileName,'string','')
else
if ~isfield(handles,'fname') && isfield(handles,'rec_info')
try
handles.fname=handles.rec_info.exportname;
catch
handles.fname=handles.datFile;
end
end
if handles.fileLoaded==0 & strfind(handles.spikeFile,'Resorted.mat')
cd(handles.exportDir);
spikeData=load(handles.spikeFile);
handles = rmfield(handles,{'spikeFile','exportDir'});
if isfield(handles,'rec_info')
handles = rmfield(handles,'rec_info');
end
if isfield(handles,'Spikes')
handles = rmfield(handles,'Spikes');
end
if isfield(spikeData,'classification')
handles = rmfield(handles,'classification');
end
handles=CatStruct(handles,spikeData);
clear spikeData;
elseif handles.fileLoaded==0
%% load spike data from matlab export, if exists
cd(handles.exportDir);
exportDirListing=dir;
if isempty({exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'_spikes.'),...
{exportDirListing.name},'UniformOutput',false))).name})
handles.offlineSort_SpikeDir=handles.exportDir;
handles.offlineSort_SpikeFile=handles.spikeFile;
%go one folder up
exportDirUp=handles.exportDir(1:regexp(handles.exportDir,'\\\w+\\$'));
exportDirListing=dir(exportDirUp);
handles.spikeFile={exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'_spikes.'),...
{exportDirListing.name},'UniformOutput',false))).name};
if ~isempty(handles.spikeFile)
handles.exportDir=exportDirUp;
cd(handles.exportDir);
end
end
% if ~isfield(handles,'fname') && isfield(handles,'offlineSort_SpikeFile')
% handles.fname=regexp(handles.offlineSort_SpikeFile,'.+?(?=\.)','match');
% handles.fname=handles.fname{1};
% end
if iscell(handles.spikeFile) && size(handles.spikeFile,2)>1
% ask which export file is the good one
[whichOne,status] = listdlg('PromptString','Select correct spike file:',...
'SelectionMode','single',...
'ListString',handles.spikeFile);
if status==1
handles.spikeFile=handles.spikeFile{whichOne};
else
handles.spikeFile=[];
end
% nameComp=cellfun(@(name) sum(ismember(handles.fname(1:end-4),...
% name(1:size(handles.fname(1:end-4),2)))) ,handles.spikeFile);
% if abs(diff(nameComp))<2 %that can be tricky for some files
% %select the most recent
% fileDates=datenum({exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'_spikes.'),...
% {exportDirListing.name},'UniformOutput',false))).date});
% handles.spikeFile=handles.spikeFile{fileDates==max(fileDates)};
% else
% handles.spikeFile=handles.spikeFile{nameComp==max(nameComp)};
% end
else
if iscell(handles.spikeFile)
try
handles.spikeFile=handles.spikeFile{:};
catch
handles.spikeFile=[];
end
end
end
% end
% handles.exportDir='C:\Data\export\PrV75_61_optostim2_BR_6Ch_SyncCh_CAR';
% cd(handles.exportDir);
% handles.spikeFile='PrV75_61_optostim2_BR_6Ch_SyncCh_CAR_Ch3.mat';
set(handles.TB_FileName,'string',[handles.exportDir handles.spikeFile])
%% Load spike data
if ~isempty(handles.spikeFile) && ~strcmp(get(handles.Spikes_PrevSorted_Menu,'Checked'),'on')
spikeData=load(handles.spikeFile);
if isfield(handles,'Spikes')
% This will delete all Spikes data including any changes to HandSort
% Might want to change that in future version
handles = rmfield(handles,'Spikes');
end
handles=CatStruct(handles,spikeData);
%clear
clear spikeData;
end
% check if we need to load recording info
if ~isfield(handles,'rec_info')
try
if ~isempty(handles.spikeFile)
fileName=regexp(handles.spikeFile,'.+(?=_\w+.mat$)','match');
recInfo=load([fileName{:} '_info.mat']);
elseif ~isempty(handles.offlineSort_SpikeFile)
exportDirListing=dir(cd);
if sum(~cellfun('isempty',cellfun(@(x) strfind(x,'_info.'),...
{exportDirListing.name},'UniformOutput',false)))
fileName=exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'_info.'),...
{exportDirListing.name},'UniformOutput',false))).name;
recInfo=load(fileName);
else %might be in folder above
exportDirListing=dir('..');
fileName=exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'_info.'),...
{exportDirListing.name},'UniformOutput',false))).name;
currDir=cd; cd('..');
recInfo=load(fileName); cd(currDir);
end
end
catch
[fileInfoName,fileInfoDir,FilterIndex] = uigetfile({'*.mat;*.txt','File Info Formats';...
'*.*','All Files' },'Select file providing basic recording info, or cancel and enter info');
if FilterIndex==0 % display prompt
prompt={'Sampling rate',...
'Number of channels in spike-sorted file',...
'uV/bit'};
name='Data file information';
numlines=1;
defaultanswer={'30000','32','0.25'};
options.Resize='on';
options.WindowStyle='normal';
info=inputdlg(prompt,name,numlines,defaultanswer,options);
info=cellfun(@(field) str2double(field),info,'UniformOutput',false);
info{2}=1:info{2};
recInfo.rec_info=cell2struct(info, {'samplingRate','exportedChan','bitResolution'}, 1);
else
recInfo=load(fullfile(fileInfoDir,fileInfoName));
end
end
% just in case the field is named differently
field = fieldnames(recInfo);
if ~strcmp(field{:},'rec_info')
[recInfo.('rec_info')] = recInfo.(field{:});
recInfo = rmfield(recInfo,field);
end
%concatenate
if isfield(handles,'rec_info')
handles = rmfield(handles,'rec_info');
end
handles=CatStruct(handles,recInfo);
%clear
clear recInfo;
end
if isfield(handles,'offlineSort_SpikeFile')
% cd(handles.exportDir);
if logical(regexp(handles.offlineSort_SpikeFile,'Ch\d+.')) % Spike2
cd(handles.offlineSort_SpikeDir);
handles.Spikes.Offline_Sorting=LoadSpikeData(handles.offlineSort_SpikeFile,...
handles.rec_info.numRecChan,handles.rec_info.samplingRate);
elseif contains(handles.offlineSort_SpikeFile,'.hdf5') % Spyking-Circus
% first load raw traces in memory
fileName=regexp(handles.offlineSort_SpikeFile,'.+(?=\.\w+\.\w+$)','match');
% tb_filename=[tb_filename{1} '.dat'];
if ~exist([fileName{:} '.dat'],'file') && ~exist([fileName{:} '.mat'],'file')
% try one folder up
cd ..
end
if ~exist([fileName{:} '.dat'],'file') && ~exist([fileName{:} '.mat'],'file')
% then ask where it is
[handles.datFile,handles.datDir] = uigetfile({'*.dat;*.mat','Data Formats';...
'*.*','All Files' },'Select data file for spike waveform extraction');
else
if exist([fileName{1} '.dat'],'file')
handles.datFile=[fileName{1} '.dat'];
elseif exist([fileName{1} '.mat'],'file')
handles.datFile=[fileName{1} '.mat'];
end
handles.datDir=cd;
end
if strfind(handles.datFile,'.mat') % .mat file contain rawData
load(handles.datFile);
elseif strfind(handles.datFile,'.dat')
rawData = memmapfile(fullfile(handles.datDir,handles.datFile),'Format','int16');
end
%% then import spike Data
cd(handles.offlineSort_SpikeDir);
if ~isfield(handles.rec_info,'bitResolution') || isempty(handles.rec_info.bitResolution)
handles.rec_info.bitResolution=0.25; %default 0.25 bit per uV % 0.195 for Open Ephys
end
handles.Spikes.Offline_Sorting=LoadSpikeData_byElectrode(handles.offlineSort_SpikeFile,rawData,...
numel(handles.rec_info.exportedChan),handles.rec_info.samplingRate,handles.rec_info.bitResolution); %handles.tracesInfo.size(1)
clear rawData;
elseif contains(handles.offlineSort_SpikeFile,'rez.mat') % KiloSort
fileName=exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'.dat'),...
{exportDirListing.name},'UniformOutput',false))).name;
if iscell(fileName) && length(fileName)>1
fileName=exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,rec_info.exportname),...
fileName,'UniformOutput',false))).name;
end
% tb_filename=[tb_filename{1} '.dat'];
if ~exist(fileName,'file') % then ask where it is
[handles.datFile,handles.datDir] = uigetfile({'*.dat;*.mat','Data Formats';...
'*.*','All Files' },'Select data file for spike waveform extraction');
else
handles.datFile=fileName;
handles.datDir=cd;
end
if strfind(handles.datFile,'.mat') % .mat file contain rawData
load(handles.datFile);
elseif strfind(handles.datFile,'.dat')
rawData = memmapfile(fullfile(handles.datDir,handles.datFile),'Format','int16');
end
%then import
cd(handles.offlineSort_SpikeDir);
if ~isfield(handles.rec_info,'bitResolution') || isempty(handles.rec_info.bitResolution)
handles.rec_info.bitResolution=0.25; %default 0.25 uV/bit
end
handles.Spikes.Offline_Sorting=LoadSpikeData(handles.offlineSort_SpikeFile,rawData,...
numel(handles.rec_info.exportedChan),handles.rec_info.samplingRate,handles.rec_info.bitResolution); %handles.tracesInfo.size(1)
clear rawData;
elseif contains(handles.offlineSort_SpikeFile,'.csv') || ...
contains(handles.offlineSort_SpikeFile,'_jrc.mat') % assuming JRClust
fileName=exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,'.dat'),...
{exportDirListing.name},'UniformOutput',false))).name;
if iscell(fileName) && length(fileName)>1
fileName=exportDirListing(~cellfun('isempty',cellfun(@(x) strfind(x,rec_info.exportname),...
fileName,'UniformOutput',false))).name;
end
% tb_filename=[tb_filename{1} '.dat'];
if ~exist(fileName,'file') % then ask where it is
[handles.datFile,handles.datDir] = uigetfile({'*.dat;*.mat','Data Formats';...
'*.*','All Files' },'Select data file for spike waveform extraction');
else
handles.datFile=fileName;
handles.datDir=cd;
end
if strfind(handles.datFile,'.mat') % .mat file contain rawData
load(handles.datFile);
elseif strfind(handles.datFile,'.dat')
rawData = memmapfile(fullfile(handles.datDir,handles.datFile),'Format','int16');
end
%then import
cd(handles.offlineSort_SpikeDir);
if ~isfield(handles.rec_info,'bitResolution') || isempty(handles.rec_info.bitResolution)
handles.rec_info.bitResolution=0.25; %default 0.25 uV/bit
end
handles.Spikes.Offline_Sorting=LoadSpikeData(handles.offlineSort_SpikeFile,rawData); %,...
% ,numel(handles.rec_info.exportedChan),handles.rec_info.samplingRate,...
% handles.rec_info.bitResolution); %handles.tracesInfo.size(1)
clear rawData;
end
cd(handles.exportDir);
end
if strcmp(get(handles.Spikes_Th_Menu,'Checked'),'on')
%extract waveforms if needed
if ~isfield(handles.Spikes.Offline_Threshold,'Waveforms')
% first load raw traces
fileName=regexp(handles.spikeFile,'.+(?=_\w+.\w+$)','match');
load([fileName{:} '_raw.mat']);
%then import
handles.Spikes=LoadSpikeData(handles.spikeFile,...
handles.Spikes.Offline_Threshold.electrode,...
handles.Spikes.Offline_Threshold.samplingRate(:,1),rawData);
clear rawData
end
end
if isfield(handles.Spikes,'HandSort')
% all good
elseif isfield(handles.Spikes,'Online_Sorting') || isfield(handles.Spikes,'Offline_Sorting') ...
|| isfield(handles.Spikes,'Offline_Threshold')
if isfield(handles.Spikes,'Offline_Threshold') && strcmp(get(handles.Spikes_Th_Menu,'Checked'),'on')
set(handles.Spikes_SortOff_Menu,'Checked','off');
set(handles.Spikes_SortOn_Menu,'Checked','off');
handles.Spikes.HandSort.Units=handles.Spikes.Offline_Threshold.Units;
handles.Spikes.HandSort.SpikeTimes=handles.Spikes.Offline_Threshold.SpikeTimes;
handles.Spikes.HandSort.Waveforms=handles.Spikes.Offline_Threshold.Waveforms;
handles.Spikes.HandSort.samplingRate=handles.Spikes.Offline_Threshold.samplingRate;
elseif isfield(handles.Spikes,'Offline_Sorting') || strcmp(get(handles.Spikes_SortOff_Menu,'Checked'),'on')
set(handles.Spikes_SortOff_Menu,'Checked','on');
set(handles.Spikes_SortOn_Menu,'Checked','off');
try
handles.Spikes.HandSort.Units=handles.Spikes.Offline_Sorting.Units;
catch
handles.Spikes.HandSort.Units=handles.Spikes.Offline_Sorting.unitID;
end
try
handles.Spikes.HandSort.SpikeTimes=handles.Spikes.Offline_Sorting.SpikeTimes;
catch
handles.Spikes.HandSort.SpikeTimes=handles.Spikes.Offline_Sorting.times;
end
try
handles.Spikes.HandSort.Waveforms=handles.Spikes.Offline_Sorting.Waveforms;
catch
handles.Spikes.HandSort.Waveforms=handles.Spikes.Offline_Sorting.waveforms;
end
handles.Spikes.HandSort.samplingRate=handles.Spikes.Offline_Sorting.samplingRate;
elseif isfield(handles.Spikes,'Online_Sorting') || strcmp(get(handles.Spikes_SortOn_Menu,'Checked'),'on')
set(handles.Spikes_SortOff_Menu,'Checked','off');
set(handles.Spikes_SortOn_Menu,'Checked','on');
handles.Spikes.HandSort.Units=handles.Spikes.Online_Sorting.Units;
handles.Spikes.HandSort.SpikeTimes=handles.Spikes.Online_Sorting.SpikeTimes;
handles.Spikes.HandSort.Waveforms=handles.Spikes.Online_Sorting.Waveforms;
handles.Spikes.HandSort.samplingRate=handles.Spikes.Online_Sorting.samplingRate;
end
% set data classes
handles.Spikes.HandSort.SpikeTimes=...
cellfun(@(spktimes) uint32(spktimes), handles.Spikes.HandSort.SpikeTimes,'UniformOutput',false); %safe for about 40 hours of recording
handles.Spikes.HandSort.Units=...
cellfun(@(units) int8(units), handles.Spikes.HandSort.Units,'UniformOutput',false); %256 units per channel max
handles.Spikes.HandSort.Waveforms=...
cellfun(@(wfs) int16(wfs), handles.Spikes.HandSort.Waveforms,'UniformOutput',false); %256 units per channel max
handles.Spikes.HandSort.samplingRate=uint32(handles.Spikes.HandSort.samplingRate); %uint16 should be enough, but just to be on the safe side
%squeeze in case of ND array
squeezeIt=cellfun(@(x) numel(size(x))>2, handles.Spikes.HandSort.Waveforms,'UniformOutput',true);
if sum(squeezeIt)
handles.Spikes.HandSort.Waveforms=...
cellfun(@(x) squeeze(x), handles.Spikes.HandSort.Waveforms,'UniformOutput',false);
handles.Spikes.HandSort.Waveforms(~squeezeIt)=...
cellfun(@(x) transpose(x), handles.Spikes.HandSort.Waveforms(~squeezeIt),'UniformOutput',false);
end
% re-order along time scale if needed
timeOrder=cellfun(@(times) sum(diff(times)<0),...
handles.Spikes.HandSort.SpikeTimes,'UniformOutput',true);
if sum(timeOrder)
[~,timeIndices]=cellfun(@(times) sort(times),...
handles.Spikes.HandSort.SpikeTimes,'UniformOutput',false);
handles.Spikes.HandSort.Units=cellfun(@(units,times) units(times),...
handles.Spikes.HandSort.Units,timeIndices,'UniformOutput',false);
handles.Spikes.HandSort.SpikeTimes=cellfun(@(spktimes,times) spktimes(times),...
handles.Spikes.HandSort.SpikeTimes,timeIndices,'UniformOutput',false);
handles.Spikes.HandSort.Waveforms=cellfun(@(wf,times) wf(times,:),...
handles.Spikes.HandSort.Waveforms,timeIndices,'UniformOutput',false);
end
% check if empty cells
nonEmpty=~cellfun('isempty',handles.Spikes.HandSort.Units);
% if negative unit IDs (-1), shift all to get 0 as lowest ID
negUnits=cellfun(@(units) sum(units<0), handles.Spikes.HandSort.Units(nonEmpty),...
'UniformOutput',true);
if sum(negUnits)
handles.Spikes.HandSort.Units(nonEmpty)=...
cellfun(@(units) units+abs(min(units)),...
handles.Spikes.HandSort.Units(nonEmpty),'UniformOutput',false);
end
% permute dimensions if not the right orientation
permuteIt=cellfun(@(x,y) find(size(x)==length(y))==1,...
handles.Spikes.HandSort.Waveforms(nonEmpty),...
handles.Spikes.HandSort.Units(nonEmpty),'UniformOutput',true);
if sum(permuteIt)
handles.Spikes.HandSort.Waveforms(nonEmpty)=...
cellfun(@(x) transpose(x), handles.Spikes.HandSort.Waveforms(nonEmpty),...
'UniformOutput',false);
end
permuteIt=cellfun(@(x) size(x,1)<numel(x), handles.Spikes.HandSort.Units(nonEmpty),...
'UniformOutput',true);
if sum(permuteIt) % check units are not right as well
handles.Spikes.HandSort.Units(nonEmpty)=...
cellfun(@(x) transpose(x), handles.Spikes.HandSort.Units(nonEmpty),'UniformOutput',false);
end
% downsample spike times to 1 millisecond bins
% spikeTimes=handles.Spikes.HandSort.SpikeTimes;
for chNum=1:size(handles.Spikes.HandSort.samplingRate,1)
handles.Spikes.HandSort.samplingRate(chNum,2)=1000;
if ~isempty(handles.Spikes.HandSort.SpikeTimes{chNum,1})
handles.Spikes.HandSort.SpikeTimes{chNum,2}=...
uint32(handles.Spikes.HandSort.SpikeTimes{chNum,1})/...
(handles.Spikes.HandSort.samplingRate(chNum,1)/...
handles.Spikes.HandSort.samplingRate(chNum,2));
else
handles.Spikes.HandSort.SpikeTimes{chNum,2}=[];
end
% spikeTimeIdx=zeros(1,size(Spikes.Offline_Threshold.data{ChExN,1},2));
% spikeTimeIdx(Spikes.Offline_Threshold.data{ChExN,1})=1;
%
% binSize=1;
% numBin=ceil(max(spikeTimes{chNum})/...
% (handles.Spikes.HandSort.samplingRate(chNum,1)/...
% handles.Spikes.HandSort.samplingRate(chNum,2))/binSize);
% % binspikeTime = histogram(double(spikeTimes), numBin); %plots directly histogram
% [data,binEdges] = histcounts(double(spikeTimes{chNum}),...
% linspace(0,max(double(spikeTimes{chNum})),numBin));
% data(data>1)=1; %no more than 1 spike per ms
end
end
end
%% Set number of electrodes and units,
if strcmp(get(handles.SelectElectrode_LB,'string'),'none')
% when opening GUI, selects cluster with most spikes and
% channel with most spikes from that cluster
allUnits=single(vertcat(handles.Spikes.HandSort.Units{:}));
[unitOccurence,uniqueUnitIDs]=hist(allUnits,unique(allUnits)); unitOccurence=unitOccurence(uniqueUnitIDs>0);
uniqueUnitIDs=uniqueUnitIDs(uniqueUnitIDs>0);
selectedUnit=int8(uniqueUnitIDs(unitOccurence==max(unitOccurence),1));
% find all occurences of this unit across channels
channelIdx=cellfun(@(x) logical(sum(ismember(x,selectedUnit))), handles.Spikes.HandSort.Units);
occurencePerChannel=cellfun(@(x) sum(ismember(x,selectedUnit)), handles.Spikes.HandSort.Units);
bestChannel=find(occurencePerChannel==max(occurencePerChannel),1);
if diff(size(handles.rec_info.exportedChan))>0
handles.rec_info.exportedChan=handles.rec_info.exportedChan';
end
set(handles.SelectElectrode_LB,'string',num2str(handles.rec_info.exportedChan(channelIdx)));
channelNum=find(bestChannel==handles.rec_info.exportedChan(channelIdx));
if isfield(handles.Spikes,'Online_Sorting') || isfield(handles.Spikes,'Offline_Sorting')
set(handles.SelectElectrode_LB,'value',channelNum);
else
set(handles.SelectElectrode_LB,'value',1)
end
else
channelNum=get(handles.SelectElectrode_LB,'value');
end
%% color electrode by shanks
if isfield(handles.rec_info,'probeID')
try
handles.userinfo=UserDirInfo;
catch
handles.userinfo=[];
end
if ~isfield(handles.userinfo,'probemap')
if ~exist('probemaps', 'dir')
handles.userinfo.probemap = uigetdir(cd,'select probe maps location');
path(handles.userinfo.probemap,path)
else
allPathDirs=strsplit(path,pathsep);
handles.userinfo.probemap=allPathDirs{find(cellfun(@(pathdir) contains(pathdir,'probemaps'),allPathDirs),1)};
end
mapping=load([handles.userinfo.probemap filesep handles.rec_info.probeID '.mat']);
handles.rec_info.differentShanks=logical(bwlabel(mod([mapping.(handles.rec_info.probeID).Shank]+1,2)));
else
shanksID=[handles.rec_info.probeLayout(~cellfun('isempty',...
{handles.rec_info.probeLayout.Electrode})).Shank];
handles.rec_info.differentShanks=logical(bwlabel(mod(shanksID+1,2)));
end
channelNum=ReturnElectrodes(handles.SelectElectrode_LB);
colorChannels=cell(length(channelNum),1);
for elNum=1:length(channelNum) % ASSUMING ALL EXPORTED CHANNELS ARE SORTED !
if handles.rec_info.differentShanks(channelNum(elNum))>0
colorChannels(elNum)=cellfun(@(thatChannel) sprintf(['<HTML><BODY bgcolor="%s">'...
'<FONT color="%s">%s</FONT></BODY></HTML>'],... %size="+1"
'black','white', thatChannel),{num2str(channelNum(elNum))},'UniformOutput',false);
else
colorChannels(elNum)=cellfun(@(thatChannel) sprintf(['<HTML><BODY bgcolor="%s">'...
'<FONT color="%s">%s</FONT></BODY></HTML>'],... %size="+1"
'white','black', thatChannel),{num2str(channelNum(elNum))},'UniformOutput',false);
end
end
set(handles.SelectElectrode_LB, 'String', colorChannels);
set(handles.SelectElectrode_LB ,'ListboxTop',max([1 numel(channelNum)-3]));
end
% namestr = cellstr(get(hObject, 'String'));
% validx = get(hObject, 'Value');
% newstr = regexprep(namestr{validx}, '"red"','"green"');
% namestr{validx} = newstr;
% set(hObject, 'String', namestr);
%% initialize variables
unitsIdx=vertcat(handles.Spikes.HandSort.Units{:}); %handles.Spikes.HandSort.Units{channelNum};
waveForms=horzcat(handles.Spikes.HandSort.Waveforms{:}); %handles.Spikes.HandSort.Waveforms{channelNum};
if ~isempty(unitsIdx)
% how many units on that Channel?
unitsID=unique(unitsIdx); %number of clustered units
set(handles.SelectUnit_LB,'string',num2str(unitsID));
handles=ClassificationColor(handles);
set(handles.SelectUnit_LB,'value',find(unitsID>0));
%% take out big ouliers
% if find(size(waveForms)==length(unitsIdx))==1
% waveForms=waveForms';
% end
WFmeanZ=mean(abs(zscore(single(waveForms))),2);
% if more than one, plot it and keep
if sum(WFmeanZ>6)>1
figure('name', 'Artifacts','position',[30 500 500 400]);
plot(waveForms(:,WFmeanZ>6)','linewidth',2.5); hold on;
plot(mean(waveForms,2),'linewidth',2.5);
legend({'Artifact','Mean waveforms'});
title('Potential artifacts removed, mean sigma > 6');
else
channelNum=ReturnElectrodes(handles.SelectElectrode_LB);
handles.Spikes.HandSort.Units{channelNum(get(handles.SelectElectrode_LB,'value'))}...
(WFmeanZ>6)=-9;%artifacts
end
% here's how this can work:
% Spikes detected from threshold are the benchmark (unit code = 0).
% May want to extract waveforms, but most important is the time.
% Sorted units (whatever the source) "color" those units. One spike per ms max.
handles=Plot_Unsorted_WF(handles);
if get(handles.ShowWF_CB,'value')
handles=Plot_Sorted_WF(handles);
else
cla(handles.SortedUnits_Axes);
end
Plot_Mean_WF(handles);
Plot_ISI(handles);
Plot_ACG(handles);
Plot_XCG(handles);
else
% unitsID=[];
cla(handles.SortedUnits_Axes);
cla(handles.MeanSortedUnits_Axes);
cla(handles.ISI_Axes);
cla(handles.ACG_Axes);
cla(handles.XCorr_Axes);
set(handles.SelectUnit_LB,'string',num2str(0));
set(handles.SelectUnit_LB,'value',1);
end
handles.fileLoaded=1;
end
%% Load raw traces function
function handles=LoadRawData(handles)
try
if ~(isfield(handles,'datFile') && ~isempty(strfind(handles.datFile,'.mat')))
handles.datFile=regexp(handles.spikeFile,'.+(?=_\w+.\w+$)','match');
handles.datFile=[handles.datFile{:} '_raw.mat'];
handles.datDir=cd;
end
handles.tracesInfo=whos('-file',fullfile(handles.datDir,handles.datFile));
handles.tracesInfo=rmfield(handles.tracesInfo,...
{'bytes','global','sparse','complex','nesting','persistent'});
if strfind(fullfile(handles.datDir,handles.datFile),'nopp')
handles.tracesInfo.preproc=0;
else
% if "raw" data has been pre-processed already, do
% not process later
handles.tracesInfo.preproc=1;
end
handles.traces = matfile(fullfile(handles.datDir,handles.datFile));
catch % try to load from .dat file
if ~(isfield(handles,'datFile') && contains(fullfile(handles.datDir,handles.datFile),'.dat'))
if isfield(handles,'offlineSort_SpikeFile')
handles.datFile=regexp(handles.offlineSort_SpikeFile,'.+?(?=\.)','match');
handles.datFile=[handles.datFile{1} '.dat'];
handles.datDir=cd;
else
% ask user for raw data file
end
end
handles.traces = memmapfile(fullfile(handles.datDir,handles.datFile),'Format','int16');
handles.tracesInfo= struct('name','rawData',...
'size',size(handles.traces.Data),...
'numChan',numel(handles.rec_info.exportedChan),...
'source','dat');
try
%check in params file if data was filtered, and find threshold value
fid = fopen([fullfile(handles.datDir,handles.datFile(1:end-4)) '.params'],'r');
catch
fid=-1;
end
if fid~=-1
params=fread(fid,'*char')';
if contains(regexp(params,'(?<=filter_done\s+=\s)\w+(?=\s)','match','once'), 'True')
handles.tracesInfo.preproc=1;
else
handles.tracesInfo.preproc=0;
end
handles.rec_info.threshold=regexp(params,'(?<=spike_thresh\s+=\s)\w+(?=\s)','match','once');
fclose(fid);
else
handles.tracesInfo.preproc=0;
end
end
handles.tracesInfo.excerptSize=handles.rec_info.samplingRate/2; %1 second as default (-:+ around loc)
if isa(handles.traces,'memmapfile')
handles.tracesInfo.excerptLocation=round(max(handles.tracesInfo.size)/2/numel(handles.rec_info.exportedChan)); %mid-recording as default
set(handles.TW_slider,'max',max(handles.tracesInfo.size)/numel(handles.rec_info.exportedChan));
else
handles.tracesInfo.excerptLocation=round(max(handles.tracesInfo.size)/2);
set(handles.TW_slider,'max',max(handles.tracesInfo.size));
end
% set(handles.TW_slider,'sliderstep',[0.01 max([0.01,...
% handles.tracesInfo.excerptSize/max(handles.tracesInfo.size)])]);
% plot "raw" (filtered) trace
DisplayTraces(handles);
% plot spike rasters
DisplayMarkers(handles);
%% Plot unsorted spikes
function handles=Plot_Unsorted_WF(handles)
channelNum=get(handles.SelectElectrode_LB,'value');
waveForms=handles.Spikes.HandSort.Waveforms{channelNum};
unitsIdx=handles.Spikes.HandSort.Units{channelNum};
samplingRate=handles.Spikes.HandSort.samplingRate(channelNum,1);
%% Plot unsorted spikes
numWFtoPlot=str2double(get(handles.ShowHowManyUWF_ET,'string'));
if sum(unitsIdx==0)>numWFtoPlot %then only plot subset of waveforms
subset=find(unitsIdx==0);
handles.subset{1}=subset(1:ceil(sum(unitsIdx==0)/numWFtoPlot):end);
else
handles.subset{1}=find(unitsIdx==0);
end
axes(handles.UnsortedUnits_Axes); hold on;
cla(handles.UnsortedUnits_Axes);
set(handles.UnsortedUnits_Axes,'Visible','on');
if find(size(waveForms)==length(unitsIdx))==1
waveForms=waveForms';
end
plot(waveForms(:,handles.subset{1}),'linewidth',1,'Color',[0 0 0 0.2]);
lineH=flipud(findobj(gca,'Type', 'line'));
% childH=flipud(get(gca,'Children'));
for lineTag=1:size(lineH,1)
lineH(lineTag).Tag=num2str(handles.subset{1}(lineTag)); %Tag the unit ID
end
% foo=reshape([lineH.YData],size([lineH.YData],2)/size(lineH,1),size(lineH,1));
% faa=reshape([childH.YData],size([childH.YData],2)/size(childH,1),size(childH,1));
% lineH(80).Tag
% figure; hold on;
% plot(foo(:,80));
% plot(waveForms(:,handles.subset{1}(80)));
% [lineH.Tag]=deal(num2str(handles.subset{1}));
set(gca,'XTick',linspace(0,size(waveForms(:,handles.subset{1}),1),5),...
'XTickLabel',round(linspace(-round(size(waveForms(:,handles.subset{1}),1)/2),...
round(size(waveForms(:,handles.subset{1}),1)/2),5)/(double(samplingRate)/1000),2),'TickDir','out');
% ordinateLabels=str2num(get(gca,'YTickLabel'))/4;
% set(gca,'YTickLabel',num2str(ordinateLabels));
% legend('Unclustered waveforms','location','southeast')
axis('tight');box off;
xlabel('Time (ms)');
ylabelh=ylabel('Voltage (\muV)');
set(ylabelh,'interpreter','tex');
set(gca,'Color','white','FontSize',10,'FontName','Calibri');
%% Plot clusters
function handles=Plot_Sorted_WF(handles)
% get units's data
[selectedUnits,selectedUnitsListIdx,unitsIDs,~,waveForms,samplingRate]=GetUnitData(handles);
% selected unit ids
axes(handles.SortedUnits_Axes); hold on;%colormap lines; cmap=colormap;
cla(handles.SortedUnits_Axes);
set(handles.SortedUnits_Axes,'Visible','on');
numWFtoPlot=str2double(get(handles.ShowHowManyWF_ET,'string'));
numUnits=nan(1,length(selectedUnits));
for unitP=1:length(selectedUnits)
numUnits(unitP)=sum(unitsIDs==selectedUnits(unitP));
%if there are too many waveforms to plot
if sum(unitsIDs==selectedUnits(unitP))>numWFtoPlot %then only plot subset of waveforms
subset=find(unitsIDs==selectedUnits(unitP));
handles.subset{selectedUnitsListIdx(unitP)}=subset(1:round(numUnits(unitP)/numWFtoPlot):end);
else
handles.subset{selectedUnitsListIdx(unitP)}=find(unitsIDs==selectedUnits(unitP));
end
%make sure waveforms can be plotted
if find(size(waveForms)==length(unitsIDs))==1
waveForms=waveForms'; %figure; hold on; plot(waveForms(:,1:10))
end
plot(waveForms(:,handles.subset{selectedUnitsListIdx(unitP)}),...
'linewidth',1,'Color',[handles.cmap(selectedUnits(unitP),:),0.4],...
'Tag',num2str(selectedUnits(unitP)));
%Change waveform tags from cluster number to unit ID
lineH=flipud(findobj(gca,'Type', 'line'));
skippedTags=0;
if unitP==1 %define keepTags
keepTags=cell(size(lineH,1),1);
end
for lineTag=1:size(lineH,1)
% check if it's the right cluster
if strcmp(lineH(lineTag).Tag,num2str(selectedUnits(unitP)))
%record Tags
keepTags{lineTag,1}=num2str(handles.subset{selectedUnitsListIdx(unitP)}(lineTag-skippedTags)); %Tag the unit ID
else
skippedTags=skippedTags+1;
end
end
% figure;hold on
% plot(lineH(lineTag).YData);
% plot(waveForms(:,handles.subset{selectedUnitsListIdx(unitP)}(lineTag-passedTags)))
end
%apply Tags
if exist('lineH','var')
for lineTag=1:size(lineH,1)
lineH(lineTag).Tag=keepTags{lineTag};
end
firstOfClus=[1, find(diff(cellfun(@(col) sum(col), {lineH.Color})))+1];
legH=legend(lineH(firstOfClus),{num2str(numUnits')},'location','southeast');
set(legH,'Box','Off','FontSize',7,'LineWidth',0.2,'Position',...
[0.54 legH.Position(2)+legH.Position(3)-0.01 0 0]);
end
set(gca,'Ylim',[min(min(waveForms)) max(max(waveForms))],'XTick',linspace(0,...
size(waveForms(:,handles.subset{selectedUnitsListIdx(unitP)}),1),5),...
'XTickLabel',round(linspace(-round(size(waveForms,1)/2),...
round(size(waveForms,1)/2),5)/(double(samplingRate)/1000),2),...
'TickDir','out');
axis('tight');box off;
xlabel('Time (ms)');
ylabel('Voltage (\muV)');
set(gca,'Color','white','FontSize',10,'FontName','Calibri');
hold off
%% Plot mean waveforms
function Plot_Mean_WF(handles)
% get units's data
[selectedUnits,selectedUnitsListIdx,unitsIDs,~,waveForms,samplingRate]=GetUnitData(handles);
% channelNum=get(handles.SelectElectrode_LB,'value');
% waveForms=handles.Spikes.HandSort.Waveforms{channelNum};
% unitsIdx=handles.Spikes.HandSort.Units{channelNum};
% uniqueUnitIDs=unique(unitsIDs);
axes(handles.MeanSortedUnits_Axes); hold on;%colormap lines;
cla(handles.MeanSortedUnits_Axes);
set(handles.MeanSortedUnits_Axes,'Visible','on');
numWFtoPlot=str2double(get(handles.ShowHowManyWF_ET,'string'));
for unitP=1:length(selectedUnits)
if selectedUnits(unitP)==0
continue
end
%if subset is not defined
if size(handles.subset,2)<selectedUnitsListIdx(unitP) || isempty(handles.subset{selectedUnitsListIdx(unitP)})
if sum(unitsIDs==selectedUnits(unitP))>numWFtoPlot %then only plot subset of waveforms
subset=find(unitsIDs==selectedUnits(unitP));
handles.subset{selectedUnitsListIdx(unitP)}=subset(1:round(sum(unitsIDs==selectedUnits(unitP))/numWFtoPlot):end);
else
handles.subset{selectedUnitsListIdx(unitP)}=find(unitsIDs==selectedUnits(unitP));
end
end
selectWF=single(waveForms(:,unitsIDs==selectedUnits(unitP))');
if ~isnan(mean(selectWF))
lineh(unitP)=plot(mean(selectWF),'linewidth',2,'Color',[handles.cmap(selectedUnits(unitP),:),0.7]);
wfSEM=std(selectWF)/ sqrt(size(selectWF,2)); %standard error of the mean
wfSEM = wfSEM * 1.96; % 95% of the data will fall within 1.96 standard deviations of a normal distribution
patch([1:length(wfSEM),fliplr(1:length(wfSEM))],...
[mean(selectWF)-wfSEM,fliplr(mean(selectWF)+wfSEM)],...
handles.cmap(selectedUnits(unitP),:),'EdgeColor','none','FaceAlpha',0.2);
%duplicate mean unit waveform over unsorted plot
% plot(handles.UnsortedUnits_Axes,mean(selectWF),'linewidth',2,'Color',handles.cmap(unitP,:));
if unitP==1
delete(findobj(handles.UnsortedUnits_Axes,'Type', 'patch'));
end
patch([1:length(wfSEM),fliplr(1:length(wfSEM))],...
[mean(selectWF)-wfSEM,fliplr(mean(selectWF)+wfSEM)],...
handles.cmap(selectedUnits(unitP),:),'EdgeColor','none','FaceAlpha',0.5,'Parent', handles.UnsortedUnits_Axes);
set(handles.UnsortedUnits_Axes,'Color','white','FontSize',10,'FontName','Calibri');
end
end
set(gca,'XTick',linspace(0,size(waveForms(:,handles.subset{selectedUnitsListIdx(unitP)}),1),5),...
'XTickLabel',round(linspace(-round(size(waveForms,1)/2),...
round(size(waveForms,1)/2),5)/(double(samplingRate)/1000),2),'TickDir','out');
% ordinateLabels=str2num(get(gca,'YTickLabel'))/4;
% set(gca,'YTickLabel',num2str(ordinateLabels));
if exist('selectWF','var')
legH=legend(lineh,{num2str(selectedUnits)},'location','southeast');
set(legH,'Box','Off');
end
axis('tight');box off;
xlabel('Time (ms)');
ylabel('Voltage (\muV)');
set(gca,'Color','white','FontSize',10,'FontName','Calibri');
hold off
%% Plot traces
function dataExcerpt=DisplayTraces(handles)
channelIndex=get(handles.SelectElectrode_LB,'value');
channelNum=ReturnElectrodes(handles.SelectElectrode_LB);
channelNum=channelNum(channelIndex);
if isa(handles.traces,'memmapfile')
% exwdw=[((30000*106)-15000)*28:((30000*106)+15000)*28-1];
% % dataExcerpt=rawData.Data(exwdw);
% dataExcerpt=handles.traces.Data(exwdw);
% dataExcerpt=reshape(dataExcerpt,[28 30000]);
% figure;
% plot(dataExcerpt(10,:))
% title('el10 106')
winIdxStart=((handles.tracesInfo.excerptLocation-...
double(handles.tracesInfo.excerptSize))*numel(handles.rec_info.exportedChan))+1;
if mod(winIdxStart,numel(handles.rec_info.exportedChan))~=1 %set window index to correct point in data vector
winIdxStart=winIdxStart-...
mod(winIdxStart,numel(handles.rec_info.exportedChan))-...
numel(handles.rec_info.exportedChan)+1; % set index loc to first electrode
% (numel(handles.rec_info.exportedChan) - channelNum); % set index loc to selected electrode
end
winIdxEnd=winIdxStart+...
(2*handles.tracesInfo.excerptSize*numel(handles.rec_info.exportedChan));
excerptWindow=winIdxStart:winIdxEnd-1;
if size(excerptWindow,2)>(2*handles.tracesInfo.excerptSize*...
numel(handles.rec_info.exportedChan)) %for some reason
excerptWindow=excerptWindow(1:end-(size(excerptWindow,2)-...
(2*handles.tracesInfo.excerptSize*numel(handles.rec_info.exportedChan))));
end
dataExcerpt=handles.traces.Data(excerptWindow);
dataExcerpt=reshape(dataExcerpt,[numel(handles.rec_info.exportedChan)...
handles.tracesInfo.excerptSize*2]);
% foo=handles.traces.Data;
% foo=reshape(foo,[numel(handles.rec_info.exportedChan)...
% size(foo,1)/numel(handles.rec_info.exportedChan)]);
else
excerptWindow=handles.tracesInfo.excerptLocation-...
handles.tracesInfo.excerptSize:handles.tracesInfo.excerptLocation+handles.tracesInfo.excerptSize-1;
dataExcerpt=handles.traces.(handles.tracesInfo.name)(:,excerptWindow);
end
if handles.tracesInfo.preproc==0 % raw data is presumed bandpassed filtered at this point
preprocOption={'CAR','all'};
dataExcerpt=PreProcData(dataExcerpt,handles.rec_info.samplingRate,preprocOption);
end
dataExcerpt=int32(dataExcerpt(channelNum,:));
axes(handles.TimeRaster_Axes);
cla(handles.TimeRaster_Axes);
set(handles.TimeRaster_Axes,'Visible','on');
plot(handles.TimeRaster_Axes,dataExcerpt,'k','linewidth',0.1); hold on;
% threshold
if isfield(handles.rec_info,'threshold')
threshold=str2double(handles.rec_info.threshold);
plot(ones(1,size(dataExcerpt,2))*threshold*mad(single(dataExcerpt)),'--','Color',[0 0 0 0.3]);
plot(ones(1,size(dataExcerpt,2))*-threshold*mad(single(dataExcerpt)),'--','Color',[0 0 0 0.3]);
else
% threshold=8;
end
hold off;
timeLabels=round(linspace(round(handles.tracesInfo.excerptLocation-...
handles.tracesInfo.excerptSize)/(handles.rec_info.samplingRate/1000),...
round(handles.tracesInfo.excerptLocation+handles.tracesInfo.excerptSize)/...
(handles.rec_info.samplingRate/1000),4)./1000,3); % duration(X,'Format','h')
set(handles.TimeRaster_Axes,'xtick',round(linspace(0,max(get(handles.TimeRaster_Axes,'xtick')),4)),...
'xticklabel',timeLabels); %,'TickDir','out');
set(handles.TimeRaster_Axes,'ytick',[],'yticklabel',[]); %'ylim'
axis('tight');box off;
set(handles.TimeRaster_Axes,'Color','white','FontSize',12,'FontName','calibri');
% if isa(handles.traces,'memmapfile')
% set(handles.TW_slider,'value',handles.tracesInfo.excerptLocation/numel(handles.rec_info.exportedChan));
% else
set(handles.TW_slider,'value',handles.tracesInfo.excerptLocation);
%% Plot spike unit markers
function spkTimes=DisplayMarkers(handles)
% display color-coded markers for each identified spike
channelIndex=get(handles.SelectElectrode_LB,'value');
channelNum=ReturnElectrodes(handles.SelectElectrode_LB);
channelNum=channelNum(channelIndex);
if contains(get(handles.DisplayNtrodeMarkers_MenuItem,'Checked'),'on')
% get channel values from same Ntrode
shankNum=cumsum(logical([0 diff(handles.rec_info.differentShanks(1:handles.rec_info.numRecChan))]));
channelNum=find(shankNum==shankNum(channelNum));
end
axes(handles.TimeRaster_Axes); hold on
for elNum=1:length(channelNum)
% get which unit to plot
if get(handles.ShowAllUnits_RB,'value') || length(channelNum)>1
unitID=unique(handles.Spikes.HandSort.Units{channelNum(elNum), 1});% unitID=ReturnUnits(handles.SelectUnit_LB);
selectedUnitsListIdx=find(unitID>=0);
selectedUnits=unitID(selectedUnitsListIdx);
else
unitID=ReturnUnits(handles.SelectUnit_LB);
selectedUnitsListIdx=get(handles.SelectUnit_LB,'value');
selectedUnits=unitID(selectedUnitsListIdx);
end
spkTimes=cell(size(selectedUnits,1),1);
if isfield(handles.Spikes,'Online_Sorting') % plot above trace
if ~isempty(handles.Spikes.Online_Sorting.SpikeTimes)
for unitP=1:size(selectedUnits,1)
spkTimes{unitP}=handles.Spikes.Online_Sorting.SpikeTimes{channelNum(elNum)}(...