-
Notifications
You must be signed in to change notification settings - Fork 0
/
Msort.m
6652 lines (5553 loc) · 250 KB
/
Msort.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 = Msort(varargin)
% MSORT MATLAB code for Msort.fig
% MSORT, by itself, creates a new MSORT or raises the existing
% singleton*.
%
% H = MSORT returns the handle to a new MSORT or the handle to
% the existing singleton*.
%
% MSORT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MSORT.M with the given input arguments.
%
% MSORT('Property','Value',...) creates a new MSORT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Msort_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Msort_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Msort
% Last Modified by GUIDE v2.5 17-Dec-2014 15:32:38
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Msort_OpeningFcn, ...
'gui_OutputFcn', @Msort_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 Msort is made visible.
function Msort_OpeningFcn(hObject, ~, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Msort (see VARARGIN)
p=strrep(path,'\','/');
contains_Plex=regexp(p,'Plexon/mexPlex', 'once');
if(isempty(contains_Plex))
Plexon_folder = sprintf('%s\\Plexon',pwd);
mexPlex_folder = sprintf('%s\\Plexon\\mexPlex',pwd);
addpath(Plexon_folder,mexPlex_folder);
end
% determine default data directory
Msort_path=which('Msort.m');
p=regexp(Msort_path,strrep(sprintf('(?<path>.*%c).*.m',filesep),'\','\\'),'names');
param_file=sprintf('%sMsort.cfg',p.path);
params=load_params(param_file);
default_dir = params.default_file_dir;
setappdata(hObject,'default_dir',default_dir);
% Choose default command line output for Msort
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
set_theme(handles); % set palette
warning off all;
% UIWAIT makes Msort wait for user response (see UIRESUME)
% uiwait(handles.fig_msort);
% --- set color theme
function set_theme(handles)
global palette;
theme = 'material';
% note: theme must implement the following values:
% palette.background
% palette.gridlines
% palette.text
% palette.header
% palette.button
% palette.button_text
% palette.undo
% palette.green
% palette.red
% palette.orange
% palette.blue
% palette.ax_background
switch(theme)
case 'material'
colors=import_colors(theme);
palette.background=colors.light_grey;
palette.gridlines=colors.grey;
palette.text=colors.dark_grey;
palette.header=colors.blue;
palette.button=1-(1-colors.blue)/3;
palette.button_text=colors.dark_grey;
palette.undo=1-(1-colors.pink)/2;
palette.view_button=1-(1-colors.indigo)/3;
palette.green=colors.green;
palette.red=colors.red;
palette.orange=colors.orange;
palette.blue=colors.indigo;
palette.teal=colors.teal;
palette.ax_background = 1-(1-colors.light_grey)/2;
cluster_colors=[colors.red;colors.purple;colors.indigo;colors.teal;...
colors.brown;colors.blue_grey;colors.green;colors.orange;...
colors.pink;colors.green;colors.indigo;colors.amber;...
colors.cyan;colors.deep_purple;colors.light_green;...
colors.dark_grey;colors.pink];
case 'dark'
palette.background=[0 0 0];
palette.gridlines=[.5 .5 .5];
palette.text=[.7 .7 .7];
palette.header=[.87 .87 .87];
palette.button=[237 237 237]/255;
palette.button_text=[.2 .2 .2];
palette.undo=[236 214 214]/255;
palette.view_button=[186 212 244]/255;
palette.green=[0 .7 0];
palette.red=[.7 0 0];
palette.orange=[255 127 39]/255;
palette.blue=[0 0 .7];
palette.ax_background = [0 0 0];
cluster_colors=distinguishable_colors(10,'k');
case 'solarized'
end
% set background
set([handles.filename_panel handles.information_panel handles.features_panel handles.feature_control_panel handles.options_panel handles.cluster_panel ...
handles.group_panel handles.group_cmd_panel handles.params_panel handles.clusters_panel handles.cleanup_panel...
handles.interface_panel handles.channel_panel handles.status_panel],...
'backgroundcolor',palette.background,'foregroundcolor',palette.header);
set([get(handles.group_panel,'children')' get(handles.group_cmd_panel,'children')' ...
get(handles.clusters_panel,'children')' get(handles.cleanup_panel,'children')' ...
get(handles.interface_panel,'children')' get(handles.information_panel,'children')'...
get(handles.channel_panel,'children')' get(handles.options_panel,'children')' ...
get(handles.filename_panel,'children')' get(handles.status_panel,'children')' ...
get(handles.params_panel,'children')' get(handles.feature_control_panel,'children')'],...
'backgroundcolor',palette.background,'foregroundcolor',palette.text);
% set buttons
set(findobj(handles.output,'style','pushbutton'),'backgroundcolor',palette.button,'foregroundcolor',palette.button_text);
set([handles.deselect_button handles.undo_button],'backgroundcolor',palette.undo,'foregroundcolor',palette.button_text);
set(handles.output,'color',palette.background);
% determine palette-based cluster colors
palette.cluster_colors=cluster_colors;
% --- Outputs from this function are returned to the command line.
function varargout = Msort_OutputFcn(~, ~, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
set(get(handles.output,'JavaFrame'),'Maximized',1);
% --- Executes on button press in group1_button.
function group1_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group1_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(1, handles);
% --- Executes on button press in group2_button.
function group2_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group2_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(2, handles);
% --- Executes on button press in group3_button.
function group3_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group3_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(3, handles);
% --- Executes on button press in group4_button.
function group4_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group4_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(4, handles);
% --- Executes on button press in group5_button.
function group5_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group5_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(5, handles);
% --- Executes on button press in group6_button.
function group6_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group6_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(6, handles);
% --- Executes on button press in group7_button.
function group7_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group7_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(7, handles);
% --- Executes on button press in group8_button.
function group8_button_Callback(~, ~, handles) %#ok<DEFNU>
% hObject handle to group8_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
load_group(8, handles);
% --- Loads group data into the Features panel
function load_group(group_num, handles)
clearvars -global -except palette;
global waveforms features data_v Ts palette; %#ok<NUSED>
set(handles.status_label,'String',sprintf('Loading group %g. Please wait...',group_num));
set(handles.status_light,'BackgroundColor',palette.red); drawnow;
setappdata(handles.output,'group_num',group_num);
setappdata(handles.output,'original_timestamps',[]);
setappdata(handles.output,'timestamps',[]);
setappdata(handles.output,'idx',[]);
% swap visible group panels
set(handles.group_panel,'visible','off'); drawnow;
set(handles.group_cmd_panel,'visible','on');
% Group panel
group_panel=[handles.voltage_plot_button, handles.return_button, handles.rethreshold_button, handles.features_button, handles.stats_button];
set(handles.group_cmd_panel,'Title',sprintf('Group %g',group_num));
% Clusters Panel
clusters_panel=[handles.cluster_menu, handles.merge_button, handles.split_button, handles.restore_wfs_button,...
handles.recluster_button handles.channel_sort_button handles.cluster_options_button handles.template_button handles.apply_templates_button];
% Parameters Panel
params_panel=[handles.cluster_options_button, handles.scale_checkbox, handles.param_button];
% Cleanup Panel
cleanup_panel = [handles.display_cleanup_button, handles.clear_misaligned_button handles.move_misaligned_button handles.errorbar_field, handles.errorbar_slider, handles.std_dev_label handles.cleanup_button handles.ISI_move_button];
set([group_panel clusters_panel params_panel cleanup_panel],'enable','off','visible','off');
setappdata(handles.output,'show_display_tools',false);
setappdata(handles.output,'big_mode',false);
% delete associated data, reset all panels
setappdata(handles.output,'timestamps',[]);
setappdata(handles.output,'idx',[]);
setappdata(handles.output,'normalized_waveforms',[]);
setappdata(handles.output,'t',[]);
clear_panel(handles.features_panel);
drawnow;
% load necessary data
plx_file = getappdata(handles.output,'plx_file');
% get channels from file
xml_file=getappdata(handles.output,'xml_file');
exp=xml2struct(xml_file);
setappdata(handles.output,'exp',exp);
if(~iscell(exp.experiment.shank)),exp.experiment.shank={exp.experiment.shank}; end
num_channels = length(exp.experiment.shank{group_num}.channel);
channels = zeros(1,num_channels);
disabled = false(1,num_channels);
thresholds = zeros(2,num_channels);
for i = 1:num_channels
if(num_channels==1)
channels(i)=str2double(exp.experiment.shank{group_num}.channel.Attributes.num);
else
channels(i) = str2double(exp.experiment.shank{group_num}.channel{i}.Attributes.num);
end
% should have two thresholds as of 2013.02.14; top is positive, bottom is negative
if(num_channels==1)
if(isfield(exp.experiment.shank{group_num}.channel,'threshold2'))
thresholds(1,i)=str2double(exp.experiment.shank{group_num}.channel.threshold.Text);
thresholds(2,i)=str2double(exp.experiment.shank{group_num}.channel.threshold.Text);
else
t=str2double(exp.experiment.shank{group_num}.channel.threshold.Text);
if(t>0), thresholds(1,i)=t;
else thresholds(2,i)=t;
end
end
if(strcmp(exp.experiment.shank{group_num}.channel.enabled.Text,'false'))
disabled(i)=true;
end
else
if(isfield(exp.experiment.shank{group_num}.channel{i},'threshold2'))
thresholds(1,i) = str2double(exp.experiment.shank{group_num}.channel{i}.threshold.Text);
thresholds(2,i) = str2double(exp.experiment.shank{group_num}.channel{i}.threshold2.Text);
else
t=str2double(exp.experiment.shank{group_num}.channel{i}.threshold.Text);
if(t>0), thresholds(1,i)=t;
else thresholds(2,i)=t;
end
end
if(strcmp(exp.experiment.shank{group_num}.channel{i}.enabled.Text,'false'))
disabled(i)=true;
end
end
end
channels(disabled)=[]; thresholds(:,disabled)=[];
num_channels=length(channels);
setappdata(handles.output,'num_channels',num_channels);
setappdata(handles.output,'disabled',disabled);
% determine if our .mat file contains all processed channels
mat_file=getappdata(handles.output,'mat_file');
vars=whos('-file',mat_file);
vars={vars.name}; expr=regexp(vars,'data_(?<channel>\d*$)','names');
locs=cellfun(@(x) ~isempty(x),expr); vars_data=expr(locs);
num_channels_completed=length(vars_data);
channels_completed=zeros(1,num_channels_completed);
for i = 1:num_channels_completed
channels_completed(i) = str2double(vars_data{i}.channel);
end
% compare to our loaded .xml file
channels_needed=channels;
found=0;
for i = 1:length(channels_needed)
if(any(channels_completed==channels_needed(i)))
found=found+1;
end
end
% request plx2mat to user
if(found<length(channels_needed))
reply = questdlg(sprintf('%g of %g total channels have been processed. Continue with the rest? This may take a while.',found,length(channels_needed)),'PLX -> MAT Processing','Yes','No','Yes');
%choice = 'Yes';
switch reply
case 'Yes'
% get electrode type
electrode_type=exp.experiment.electrode.Text;
switch plx_file(end-2:end)
case 'plx'
plx2mat(plx_file,electrode_type,group_num);
case 'abf'
abf2mat(plx_file);
end
% play beep
if(get(handles.sound_checkbox,'Value')), stop_alert; end
load_group(group_num,handles);
return;
case 'No'
set(handles.group_cmd_panel,'visible','off');
set(handles.group_panel,'visible','on');
return;
end
end
% determine what we can load
vars=whos('-file',mat_file);
names=cell(1,length(vars));
for i=1:length(vars)
names{i}=vars(i).name;
end
% generate list of variables we need
varlist = {'Ts',...
sprintf('idx_%g',group_num),...
sprintf('original_timestamps_%g',group_num),...
sprintf('num_PCs_%g',group_num),...
sprintf('trigger_ch_%g',group_num);
};
for i = 1:length(channels)
varlist{end+1}=sprintf('data_%g',channels(i)); %#ok<AGROW>
end
std_list=cell(1,num_channels);
for i = 1:length(channels)
std_list{i}=sprintf('std_%g',channels(i));
end
% determine which variables are in there
vars_exist=false(1,length(varlist));
for i = 1:length(varlist)
if(any(strcmp(varlist{i},names)))
vars_exist(i)=true;
end
end
% load the data
varlist=varlist(vars_exist);
h=waitbar(0,'Loading variables','name','Loading Variables','color',palette.background);
set(findobj(h,'type','patch'), 'edgecolor',palette.text,'facecolor',palette.header);
for i = 1:length(varlist)
waitbar(i/length(varlist),h);
load(mat_file,varlist{i});
end
delete(h);
if(~isempty(std_list))
load(mat_file,std_list{:});
end
% join data channels
if(exist(sprintf('data_%g',channels(1)),'var'))
s=sprintf('[data_%g''',channels(1));
s2=sprintf('[std_%g',channels(1));
else
s='[';
s2='[';
end
for i = 2:num_channels
if(exist(sprintf('data_%g',channels(i)),'var'))
s=sprintf('%s data_%g''',s,channels(i));
s2=sprintf('%s std_%g',s2,channels(i));
end
end
s=sprintf('%s]',s);
s2=sprintf('%s]',s2);
cmd=sprintf('data_v = %s;',s); eval(cmd);
cmd=sprintf('std_devs = %s;',s2); eval(cmd);
% grab data squared
%data_squared=data_v.^2;
% save data into standard variables
%standard_names = {'Ts','idx','timestamps','num_PCs','trigger_ch','data_squared'};
standard_names = {'Ts','idx','timestamps','num_PCs','trigger_ch'};
vars_exist(end-length(channels)+1:end)=[]; %vars_exist(end+1)=true;
varlist(end-length(channels)+1:end)=[]; %varlist{end+1}='data';
%varlist{end+1}='data_squared';
standard_names=standard_names(vars_exist);
for i = 1:length(varlist)
eval(sprintf('setappdata(handles.output,standard_names{i},%s);',varlist{i}));
end
setappdata(handles.output,'std_devs',std_devs);
setappdata(handles.output,'t_before',str2double(get(handles.t_before_field,'String')));
setappdata(handles.output,'t_after',str2double(get(handles.t_after_field,'String')));
% set channel colors
num_channels=length(channels);
channel_colors=get_channel_colors(num_channels);
setappdata(handles.output,'channel_colors',channel_colors);
% If we have num_PCs and normalized_waves, set those boxes as well
if(any(strcmp(standard_names,'normalized_waves')))
eval(sprintf('normalized_waves=normalized_waves_%g;',group_num));
if(normalized_waves), set(handles.scale_checkbox,'Value',get(handles.scale_checkbox,'Max'));
else set(handles.scale_checkbox,'Value',get(handles.scale_checkbox,'Min'));
end
end
% grab waveforms using timestamps
varname=sprintf('original_timestamps_%g',group_num);
if(~exist(varname,'var'))
setappdata(handles.output,'timestamps',[]);
else
eval(sprintf('setappdata(handles.output,''timestamps'',original_timestamps_%g);',group_num));
end
capture_waveforms(handles);
% set idx & num clusters, if exists
if(any(strcmp(standard_names,'idx')))
eval(sprintf('idx=idx_%g;',group_num));
if(any(idx))
u=unique([0 idx]);
num_clusters=length(u);
setappdata(handles.output,'idx',idx);
else
num_clusters=1;
end
else
num_clusters=1;
end
setappdata(handles.output,'num_clusters',num_clusters);
setappdata(handles.output,'cluster_number',num_clusters-1);
selected_axes=false(1,num_clusters);
selected_axes(num_clusters)=true;
setappdata(handles.output,'selected_axes',selected_axes);
cluster_colors=get_cluster_colors(handles);
setappdata(handles.output,'cluster_colors',cluster_colors);
% update application
setappdata(handles.output,'channels',channels);
setappdata(handles.output,'thresholds',thresholds);
setappdata(handles.output,'display_cleanup_tools',false);
% re-enable buttons and GUI components
channel_colors=get_channel_colors(num_channels);
setappdata(handles.output,'channel_colors',channel_colors);
% populate the clusters panel with relevant data, depends on # channels
channel_tag_pos=get(handles.channel_tag,'position');
x_offset=channel_tag_pos(1)+channel_tag_pos(3); margin_right=channel_tag_pos(1);
ch_tag_width=(1-x_offset-margin_right)/num_channels;
ch_tag_height=channel_tag_pos(4);
% create channel tags and UI controls
cluster_ch_tags=zeros(1,num_channels);
num_PCs_field=zeros(1,num_channels);
num_PCs_slider=zeros(1,num_channels);
peak_checkbox=zeros(1,num_channels);
valley_checkbox=zeros(1,num_channels);
slope_checkbox=zeros(1,num_channels);
energy_checkbox=zeros(1,num_channels);
amplitude_checkbox=zeros(1,num_channels);
for i = 1:num_channels
x=x_offset+(ch_tag_width)*(i-1);
% channel tag
y=channel_tag_pos(2);
cluster_ch_tags(i)=uicontrol('Style','text','fontsize',16,'fontweight','bold',...
'units','normalized','position',[x y ch_tag_width ch_tag_height],'HorizontalAlignment','right','String',...
sprintf('Ch %g',channels(i)),'Parent',handles.cluster_panel,'BackgroundColor',palette.background,'ForegroundColor',channel_colors(i,:));
% num PCs
xPC=x+ch_tag_width;
y=get(handles.num_PCs_tag,'position'); y=y(2);
field_width=.05; slider_width=.03;
sliderMax=3; sliderMin=0;
num_PCs_field(i)=uicontrol('Style','Edit','fontsize',12,'units','normalized',...
'position',[xPC-field_width-slider_width y field_width ch_tag_height],...
'Parent',handles.cluster_panel,'String','3','BackgroundColor','white');
num_PCs_slider(i)=uicontrol('Style','slider','units','normalized',...
'position',[xPC-slider_width y slider_width ch_tag_height],...
'Parent',handles.cluster_panel,'Value',3,'Min',sliderMin,'Max',sliderMax,'Sliderstep',[1 1]/(sliderMax-sliderMin));
% width for checkbox
checkbox_width=.02;
% Peak
y=get(handles.peak_tag,'position'); y=y(2);
peak_checkbox(i)=uicontrol('Style','Checkbox','units','normalized',...
'position',[xPC-checkbox_width y checkbox_width ch_tag_height],...
'Parent',handles.cluster_panel,'Value',0,'fontsize',14,'BackgroundColor',palette.background);
% Valley
y=get(handles.valley_tag,'position'); y=y(2);
valley_checkbox(i)=uicontrol('Style','Checkbox','units','normalized',...
'position',[xPC-checkbox_width y checkbox_width ch_tag_height],...
'Parent',handles.cluster_panel,'Value',0,'fontsize',14,'BackgroundColor',palette.background);
% Slope
y=get(handles.slope_tag,'position'); y=y(2);
slope_checkbox(i)=uicontrol('Style','Checkbox','units','normalized',...
'position',[xPC-checkbox_width y checkbox_width ch_tag_height],...
'Parent',handles.cluster_panel,'Value',0,'fontsize',14,'BackgroundColor',palette.background);
% Energy
y=get(handles.energy_tag,'position'); y=y(2);
energy_checkbox(i)=uicontrol('Style','Checkbox','units','normalized',...
'position',[xPC-checkbox_width y checkbox_width ch_tag_height],...
'Parent',handles.cluster_panel,'Value',0,'fontsize',14,'BackgroundColor',palette.background);
% amplitude
y=get(handles.amplitude_tag,'position'); y=y(2);
amplitude_checkbox(i)=uicontrol('Style','Checkbox','units','normalized',...
'position',[xPC-checkbox_width y checkbox_width ch_tag_height],...
'Parent',handles.cluster_panel,'Value',0,'fontsize',14,'BackgroundColor',palette.background);
end
% set handles
handles.num_PCs_field=num_PCs_field;
handles.num_PCs_slider=num_PCs_slider;
handles.peak_checkbox=peak_checkbox;
handles.valley_checkbox=valley_checkbox;
handles.slope_checkbox=slope_checkbox;
handles.energy_checkbox=energy_checkbox;
handles.amplitude_checkbox=amplitude_checkbox;
% makes for easy deleting
handles.cluster_controls=[num_PCs_field num_PCs_slider peak_checkbox valley_checkbox slope_checkbox energy_checkbox amplitude_checkbox];
% Create channel tags/checkboxes on the bottom left
ch_tags = zeros(1,num_channels);
ch_colorboxes = zeros(1,num_channels);
margin_y=.05; margin_x=.1;
ch_width=(1-3*margin_x)/2;
ch_height=(1-(num_channels+1)*margin_y)/max(8,num_channels);
for i = 1:num_channels
y=1-(margin_y+ch_height)*i;
ch_tags(i)=uicontrol('Style','Checkbox','units','Normalized','String',sprintf('%g',channels(i)),...
'position',[margin_x y ch_width ch_height],'Parent',handles.channel_panel,...
'BackgroundColor',palette.background,'ForegroundColor',palette.text);
ch_colorboxes(i)=uicontrol('Style','text','units','Normalized','String','',...
'position',[2*margin_x+ch_width y ch_width ch_height],'Parent',handles.channel_panel,...
'BackgroundColor',channel_colors(i,:));
end
handles.ch_tags=ch_tags;
handles.ch_colorboxes=ch_colorboxes;
% update handles structure so we can pass it to the callback functions
guidata(handles.output,handles);
% Update call back functions
for i = 1:num_channels
set(num_PCs_field(i),'CallBack',{@num_PCs_field_Callback,num_PCs_slider(i),handles});
set(num_PCs_slider(i),'CallBack',{@num_PCs_slider_Callback,num_PCs_field(i),handles});
set(peak_checkbox(i),'CallBack',{@cluster_checkbox_Callback,peak_checkbox,handles});
set(valley_checkbox(i),'CallBack',{@cluster_checkbox_Callback,valley_checkbox,handles});
set(slope_checkbox(i),'CallBack',{@cluster_checkbox_Callback,slope_checkbox,handles});
set(energy_checkbox(i),'CallBack',{@cluster_checkbox_Callback,energy_checkbox,handles});
set(amplitude_checkbox(i),'Callback',{@cluster_checkbox_Callback,amplitude_checkbox,handles});
set(ch_tags(i),'CallBack',{@ch_tags_Callback,handles});
end
fix_feature_menu(handles);
selected_channels=false(1,num_channels);
setappdata(handles.output,'selected_channels',selected_channels);
% create dummy waveform axes
ax_waveforms=zeros(1,num_channels);
for i = 1:num_channels
ax_waveforms(i)=axes('parent',handles.features_panel,'color','w','visible','off',...
'xcolor',palette.text,'ycolor',palette.text,'xtick',[],'ytick',[],'clipping','off','linewidth',1.5); %#ok<LAXES>
hold(ax_waveforms(i),'all');
end
setappdata(handles.output,'ax_waveforms',ax_waveforms);
ax_features=axes('position',[.225 0.04 1-.225 1-.04],'parent',handles.features_panel,...
'color',palette.ax_background,'visible','off','linewidth',1.5,'box','on','xcolor',palette.text,'ycolor',palette.text);
set(ax_features,'ButtonDownFcn',{@select_features,handles});
hold(ax_features,'all');
setappdata(handles.output,'ax_features',ax_features);
% restore visibility
set([group_panel clusters_panel params_panel cleanup_panel handles.undo_button],'enable','on','visible','on');
% Update application data
setappdata(handles.output,'selected_features',[1 8 1]);
% Display voltage plot
setappdata(handles.output,'voltage_start',1);
plot_voltages(handles);
% set keyboard handling
set(handles.output,'WindowKeyPressFcn',{@key_press,handles},'WindowKeyReleaseFcn',@ctrl_release);
% update hidden clusters
fix_clusters(handles);
setappdata(handles.output,'clusters_hidden',true);
set(handles.hide_clusters_label,'visible','off');
% set status
set(handles.status_light,'BackgroundColor',palette.green);
set(handles.status_label,'String','Ready');
% controls the num_PCs slider & field
function num_PCs_slider_Callback(hObject,~,field,handles)
value=round(get(hObject,'Value'));
% if we're linked, make sure to update all of the values
if(value>get(hObject,'Max')), value=get(hObject,'Max'); end
if(value<get(hObject,'Min')), value=get(hObject,'Min'); end
if(get(handles.link_channels_checkbox,'Value'))
set(handles.num_PCs_field,'String',sprintf('%2.0f',value));
set(handles.num_PCs_slider,'Value',value);
else
set(hObject,'Value',value);
set(field,'String',sprintf('%2.0f',value));
end
% controls the num_PCs slider & field
function num_PCs_field_Callback(hObject,~,slider,handles)
value=str2double(get(hObject,'String'));
if(isnan(value)), value=1; end
if(value>get(slider,'Max')), value=get(hObject,'Max'); end
if(value<get(hObject,'Min')), value=get(hObject,'Min'); end
if(get(handles.link_channels_checkbox,'Value'))
set(handles.num_PCs_field,'String',sprintf('%2.0f',value));
set(handles.num_PCs_slider,'Value',value);
else
set(slider,'Value',value);
set(hObject,'String',sprintf('%2.0f',value));
end
function cluster_checkbox_Callback(hObject,~,row,handles)
linked=get(handles.link_channels_checkbox,'Value');
if(linked)
set(row,'Value',get(hObject,'Value'));
end
% -- Generate plot of voltages
function plot_voltages(handles)
global Ts data_v data_spk data_t window_size y_offset voltage_plots spike_plots threshold_plots ax palette;
clear_panel(handles.features_panel);
set(handles.feature_control_panel,'visible','off');
set(handles.status_light,'BackgroundColor',palette.red);
set(handles.status_label,'String','Plotting voltage traces...'); drawnow;
channels=getappdata(handles.output,'channels');
num_channels=length(channels);
% Display voltage plots
Fs=getappdata(handles.output,'Fs');
thresholds=getappdata(handles.output,'thresholds');
% Get rid of non-spikes from voltage trace
if(isempty(data_v))
%if(get(handles.square_voltage_checkbox,'Value'))
% data_v=getappdata(handles.output,'data_squared')';
%else
data_v=(getappdata(handles.output,'data'))';
%end
end
% create scrollbar
total_time=Ts(end)-Ts(1);
window_time=1; % in seconds
window_size=round(window_time*Fs);
if(~get(handles.square_voltage_checkbox,'Value'))
std_devs = get(handles.voltage_range_slider,'Value');
if(~isfinite(std_devs)),std_devs=15; end
y_offset=repmat(num_channels-1:-1:0,window_size,1)*std_devs+std_devs;
else
std_devs=15^2;
y_offset=repmat(num_channels-1:-1:0,window_size,1)*std_devs+std_devs;
end
% create initial plot
start=1; stop=start+window_size-1;
t_start=Ts(start); t_stop=Ts(stop);
data_chunk=data_v(start:stop,:)+y_offset;
margin_left = .03; margin_right = .01;
margin_top = .02; margin_bot = .05;
plot_width = 1-(margin_left+margin_right);
plot_height = 1-(margin_top+margin_bot);
ax=axes('Parent',handles.features_panel,'position',[margin_left margin_bot plot_width plot_height],...
'color',palette.ax_background,'ycolor',palette.text,'xcolor',palette.text,'box','on','xlim',[Ts(start) Ts(stop)],...
'ylim',[0 (num_channels+.5)*std_devs],'ytick',(0:.5:num_channels-1)*std_devs,...
'yticklabel',[],'linewidth',1.5);
xlabel('Time (s)','fontsize',16,'fontweight','bold','color',palette.text);
hold(ax,'all'); grid(ax,'on');
channel_colors=getappdata(handles.output,'channel_colors');
cluster_colors=getappdata(handles.output,'cluster_colors');
% make dim
timestamps=getappdata(handles.output,'timestamps');
if(~isempty(timestamps))
set(ax,'ColorOrder',palette.gridlines);
else
set(ax,'ColorOrder',channel_colors);
end
% plot data
voltage_plots=plot(Ts(start:stop),data_chunk(start:stop,:),'linesmooth','on');
% plot spike waveforms
if(~isempty(timestamps))
idx=getappdata(handles.output,'idx');
if(isempty(idx)),idx=zeros(1,length(timestamps),'uint8'); setappdata(handles.output,'idx',idx); end
num_clusters=getappdata(handles.output,'num_clusters');
t_before=getappdata(handles.output,'t_before');
t_after=getappdata(handles.output,'t_after');
% we need spike times and their indices into the data_chunk matrix
locs=timestamps>t_start-t_after*1e-6 & timestamps<t_stop+t_before*1e-6;
visible_timestamps=timestamps(locs)-Ts(start);
visible_idx=idx(locs);
% get vector and indexing for actual waveform shapes
Fs=getappdata(handles.output,'Fs');
pts_before=round(t_before*1e-6*Fs); pts_after=round(t_after*1e-6*Fs);
t_ind=-pts_before:pts_after; t=t_ind/Fs;
% we need a matrix of actual spike times, xC for each channel
counts=zeros(1,num_clusters);
[counts_exist,u]=count_uniques(visible_idx);
counts(u+1)=counts_exist;
max_spikenum=max(counts);
if(max_spikenum==0),max_spikenum=1; end
expanded_len=(pts_before+pts_after+1)*num_channels;
t_template = [t nan]';
% we have one spike matrix, each column is the same color
max_len=max_spikenum*(expanded_len+num_channels);
data_spk = nan(max_len,num_clusters);
data_t = nan(max_len,num_clusters);
for i = u+1
spk_locs=round(visible_timestamps(visible_idx==i-1)*Fs)+1;
x_offset=repmat(visible_timestamps(visible_idx==i-1),expanded_len+num_channels,1);
t=repmat(t_template,num_channels,counts(i))+x_offset;
% get waveform indices
offset=repmat(t_ind',[1 counts(i)]);
spk_locs2=repmat(spk_locs,[pts_before+pts_after+1 1]);
spikes=spk_locs2+offset;
spikes_allchannels=repmat(spikes,[1 1 num_channels]);
offset=repmat((0:num_channels-1)*size(data_chunk,1),[counts(i) 1 pts_before+pts_after+1]);
offset=permute(offset,[3 1 2]);
spk_locs=permute(spikes_allchannels+offset,[1 3 2]);
neglocs=spk_locs<1 | spk_locs>window_size*num_channels;
spk_locs(neglocs)=1;
wf_data=data_chunk(spk_locs);
wf_data(neglocs)=nan;
wf_data=reshape([wf_data;nan(1,num_channels,counts(i))],1,[]);
t_data=reshape(t,1,[]);
data_t(1:length(t_data),i)=t_data;
data_spk(1:length(t_data),i)=wf_data;
end
set(ax,'ColorOrder',cluster_colors);
spike_plots=plot(data_t,data_spk,'linesmooth','on');
end
% plot thresholds
threshold_plots=zeros(2,num_channels);
if(get(handles.square_voltage_checkbox,'Value'))
thresholds(2,:)=0;
threshold_offset=repmat(num_channels-1:-1:0,2,1)*std_devs+std_devs;
else
threshold_offset=repmat(num_channels-1:-1:0,2,1)*std_devs+std_devs;
end
zerolocs=thresholds==0;
thresholds=thresholds+threshold_offset; thresholds(zerolocs)=0;
bright_colors=1-(1-channel_colors)*.4;
for i = 1:num_channels
if(thresholds(1,i)~=0)
threshold_plots(1,i)=plot([Ts(1) Ts(end)],[thresholds(1,i) thresholds(1,i)],'--','color',bright_colors(i,:),'linewidth',1);
end
if(thresholds(2,i)~=0)
threshold_plots(2,i)=plot([Ts(1) Ts(end)],[thresholds(2,i) thresholds(2,i)],'--','color',bright_colors(i,:),'linewidth',1);
end
end
threshold_plots(zerolocs)=[];
uistack(threshold_plots(:),'bottom');
% Create channel tags
ch_tag_height=.03;
subplot_height=std_devs/(std_devs*(num_channels+1));
ch_tag_y = (num_channels-1:-1:0)*(subplot_height)+subplot_height/2-ch_tag_height+margin_bot+ch_tag_height/2+subplot_height/2;
ch_tag_width=margin_left-.013;
t=zeros(1,num_channels);
for i = 1:num_channels
t(i)=uicontrol('Style','Text','String',sprintf('%g',channels(i)),'fontsize',20,...
'fontweight','bold','ForegroundColor',channel_colors(i,:),'BackgroundColor',palette.background,'HorizontalAlignment','Right',...
'position',[margin_left-ch_tag_width-.005 ch_tag_y(i) ch_tag_width ch_tag_height],...
'Units','Normalized','Parent',handles.features_panel);
end
overlap=0.3;
minor_step=window_time*overlap/total_time; major_step=1/5;
slider=uicontrol('style','slider','Parent',handles.features_panel,'units','normalized','position',[margin_left margin_bot plot_width .02],...
'backgroundcolor',palette.background,'SliderStep',[minor_step major_step],'Min',1,'Max',length(Ts)-window_size,'Value',1,...
'CallBack',{@voltage_slider_Callback,handles});
setappdata(slider,'voltage_plots',voltage_plots);
voltage_start=getappdata(handles.output,'voltage_start');
if(~isempty(voltage_start))
set(slider,'Value',voltage_start);
voltage_slider_Callback(slider,[],handles);
end
setappdata(handles.output,'voltage_plot',ax);
setappdata(handles.output,'ch_voltage_tags',t);
setappdata(handles.output,'panel_selected','voltage');
setappdata(handles.output,'voltage_slider',slider);
% --- helper function for the voltage plot slider
function voltage_slider_Callback(hObject,~,handles)
global Ts data_v data_spk data_t window_size y_offset voltage_plots spike_plots ax;
% determine which range of data to display
start=max(floor(get(hObject,'Value')),get(hObject,'Min')); stop=start+window_size-1;
setappdata(handles.output,'voltage_start',start);
setappdata(handles.output,'voltage_stop',stop);
ind=start:stop;
if(stop>length(Ts)) % uh oh
d=stop-length(Ts);
start=start-d; stop=stop-d;
end
ysiz=size(y_offset,1); len=length(ind);
if(ysiz>len),y_offset=y_offset(1:len,:);
elseif(ysiz<len)
extra=len-ysiz;
y_offset(end+1:end+extra,:)=repmat(y_offset(1,:),extra,1);
end
% determine which data chunk to show
data_chunk=data_v(start:stop,:)+y_offset;
for i = 1:size(data_chunk,2)
set(voltage_plots(i),'YData',data_chunk(:,i),'XData',Ts(start:stop));
end
% determine which spikes to show
timestamps=getappdata(handles.output,'timestamps');
num_channels=length(voltage_plots);
t_start=Ts(start); t_stop=Ts(stop);
if(~isempty(timestamps))
idx=getappdata(handles.output,'idx');
num_clusters=getappdata(handles.output,'num_clusters');
t_before=getappdata(handles.output,'t_before');
t_after=getappdata(handles.output,'t_after');
% we need spike times and their indices into the data_chunk matrix
locs=timestamps>t_start-t_after*1e-6 & timestamps<t_stop+t_before*1e-6;
visible_timestamps=timestamps(locs)-Ts(start);
%visible_timestamps=timestamps(locs);
visible_idx=idx(locs);
% get vector and indexing for actual waveform shapes
Fs=getappdata(handles.output,'Fs');
pts_before=round(t_before*1e-6*Fs); pts_after=round(t_after*1e-6*Fs);
t_ind=-pts_before:pts_after; t=t_ind/Fs;
% we need a matrix of actual spike times, xC for each channel
counts=zeros(1,num_clusters);
[counts_exist,u]=count_uniques(visible_idx);
counts(u+1)=counts_exist;
max_spikenum=max(counts);
expanded_len=(pts_before+pts_after+1)*num_channels;
t_template = [t nan]';
% we have one spike matrix, each column is the same color
max_len=max_spikenum*(expanded_len+num_channels);
data_spk = nan(max_len,num_clusters);
data_t = nan(max_len,num_clusters);
for i = u+1
% why do we need -1?
spk_locs=round(visible_timestamps(visible_idx==i-1)*Fs)+1;
x_offset=repmat(visible_timestamps(visible_idx==i-1),expanded_len+num_channels,1);
t=repmat(t_template,num_channels,counts(i))+x_offset;
% get waveform indices
offset=repmat(t_ind',[1 counts(i)]);
spk_locs2=repmat(spk_locs,[pts_before+pts_after+1 1]);
spikes=spk_locs2+offset;
spikes_allchannels=repmat(spikes,[1 1 num_channels]);
offset=repmat((0:num_channels-1)*size(data_chunk,1),[counts(i) 1 pts_before+pts_after+1]);
offset=permute(offset,[3 1 2]);
spk_locs=permute(spikes_allchannels+offset,[1 3 2]);
neglocs=spk_locs<1 | spk_locs>window_size*num_channels;
spk_locs(neglocs)=1;
wf_data=data_chunk(spk_locs);
wf_data(neglocs)=nan;
wf_data=reshape([wf_data;nan(1,num_channels,counts(i))],1,[]);
t_data=reshape(t,1,[]);
data_t(1:length(t_data),i)=t_data+Ts(start);
data_spk(1:length(t_data),i)=wf_data;
end