-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpikeSort.m
2249 lines (1865 loc) · 65 KB
/
SpikeSort.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
%% Matlab Spike Sorter
%This is an open-code free Matlab tool which allows user to make offline
%manual and semi-automatic sorting of spikes. This pretends to be a start
%point to the development of a full functionally Matlab tool for spike sorting.
%Developed by Joaquin Mansilla Yulan and Dr. Ing. Sergio Lew
%Facultad de Ingeniería - Universidad de Buenos Aires
%Github
%% INITIALIZATION FUNCTIONS
function varargout = SpikeSort(varargin)
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @SpikeSort_OpeningFcn, ...
'gui_OutputFcn', @SpikeSort_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 initialization code - DO NOT EDIT
end
% --- Executes just before SpikeSort is made visible.
%Declare all global variables
function SpikeSort_OpeningFcn(hObject, eventdata, handles, varargin)
% Define Global Variables
%Parameters:
global Channels; % Channels is the number of channels
global Fs %Sampling Frecuency
global DataBlock % Longest Raw Data package length to process at once
global Scale
global SL %Sample Length (Bits)
global norm %Normalization 1:Yes 0:NO
global GcaColor %Color of figures background
global WfsColor %Color of Wfs signals
global SelColor %Color of selected signals
global RawColor %Color of raw data signals
global BlockTime %Waiting time for plotting figures
global RecordPathName %Path name of data to be recorded
global Ls % ms length of each waveform
global ps % Point Size
global DensityRes %Grid resolution of density plot (3D histogram)
global ISI %InterSpike Interval
%Raw Data variables:
global PathName %Path name of the loaded data
global RwDPlot %Raw Data Spikes plot object
global ThPlot %Threshold plot object
global fileType %Type of loaded file: 1- Binary File, 2- 1 Channel.mat File, 3- Saved File
global matdata %Raw data from 1 channel -mat data
global data % Raw Data
global MaxDataLen; % Raw Data package length to process at once
global threshold % Amplitude threshold to detect Spikes
global dataView % Raw Data displayed
global slider_step; % step of slidebar (Raw Data plot)
global normScale % Multiplying factor to normalize data
%Waveform variables:
global WFmatrix % WaveForm Matrix
global SpikeTime % Time Position of each Spike (Waveform)
global SelectedUnitsIDX % Selection vector
global showRange; % samples to show
global MouseSelection % ploted points of pointer selection
global MouseSelectionI %Index of pointer selection
%Features Variables:
global FeaturePoints % 2D or 3D Feature points
global FeaTime % One Feature (to plot over time)
global slice %PLot object of Slice 1 and 2
%Cluster Variables:
global UnitStatus % Units - Clusters vector
global Unitn %Number of Units (clusters)
%Program Variables:
global ListC % List of Clustering Algorithms
global ListF % List of Features Algorithms
global handles2Spk %Handles to SpikeSorter GUI
global handles2Par %Handles to Parameters GUI
%Set default parameters
Set_default_parameters(handles);
handles2Spk=handles;
handles.output = hObject;
guidata(hObject, handles);
set(handles.WFaxes,'xtick',[])
set(handles.WFaxes,'ytick',[])
set(handles.WFaxes,'Color',GcaColor);
set(handles.Featureaxes,'xtick',[]);
set(handles.Featureaxes,'ytick',[]);
set(handles.Featureaxes,'Color',GcaColor);
set(handles.FeatureTimeaxes,'xtick',[])
set(handles.FeatureTimeaxes,'ytick',[])
set(handles.FeatureTimeaxes,'Color',GcaColor);
set(handles.Signalaxes,'Color',GcaColor);
ListC=search_fnc_from_file('clustering_algorithm.m');
ListF=search_fnc_from_file('Features.m');
set(handles.Clus_Alg,'String',ListC);
set(handles.Feat1,'String',ListF);
set(handles.Feat2,'String',ListF);
set(handles.Feat3,'String',strvcat('---',ListF));
set(handles.FeatTime,'String',ListF);
set(handles.Feat2,'Value',2);
% axes(handles.logoUBA)
% imshow('logo.png')
% axis off
% axis image
% --- Outputs from this function are returned to the command line.
function varargout = SpikeSort_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
%% FILE, MEMORY AND GENERAL FUNCTIONS
%Open Parameters GUI
function Parameter_Configuration_Callback(hObject, eventdata, handles)
global handles2Par
handles2Par=guidata(Parameters);
% LOAD FILE
%Loads a Binary File Raw Data.
function File_Callback(hObject, eventdata, handles)
[auxFileName,auxPathName,FilterIndex] = uigetfile('*.*'); % Get the file location and name of the selected file
if auxFileName~=0
% Clear all variables and plots
Reset_Variables(handles);
Reset_plots(handles);
global SL
global DataBlock
global fileType
global data
global FileName
global PathName
global MaxDataLen;
global slider_step;
global Channels
% File Info
fileType=1;
FileName=auxFileName;
PathName=auxPathName;
fileInfo = dir([PathName FileName]);
fileSize = fileInfo.bytes;
Set_RecordPath;
% Load File
MaxDataLen=min(DataBlock,fileSize/(Channels*2*5)); % The longest Raw Data channel package to process at once will be DataBlock *SL bits
fid=fopen([PathName FileName],'rb'); %opens a file in binary read mode.
SL_str=num2str(SL);
eval(['data=fread(fid,[Channels MaxDataLen],''int' SL_str ''');']); %Reads binary data from the opened file
fclose(fid);
% Set Slider Step
slider_step=min(1,1/fix((fileSize/(SL/8*MaxDataLen*Channels)-1))); %Set the slider step of the slide bar (raw data plot)
set(handles.slider1,'SliderStep',[slider_step/10 slider_step]);
%Scale or Normalize
Get_normfactor(handles);
Data_scaling(handles)
%Quantization
data=eval(['int' SL_str '(data);']);
% Filter
Channel_and_Filter(handles);
% Plot Raw Data
plot_channel(handles);
end
%Load 1 Channel
%Loads One Channel Raw Data contained in a .mat variable file.
% --------------------------------------------------------------------
function Channel_Raw_Callback(hObject, eventdata, handles)
[auxFileName,auxPathName,FilterIndex] = uigetfile('*.*'); % Get the file location and name of the selected file
if auxFileName~=0
% Clear all variables and plots
Reset_Variables(handles);
Reset_plots(handles);
global SL
global DataBlock
global fileType
global data
global matdata
global FileName
global PathName
global MaxDataLen;
global slider_step;
global Channels
global norm
global Scale
% Save File Info
fileType=2;
FileName=auxFileName;
PathName=auxPathName;
Set_RecordPath;
% Load File
set(handles.Channels,'String','1');
Channels=1;
aux=load([PathName FileName]); %Reads raw data from the opened .mat file
aux2=fields(aux);
matdata=aux.(cell2mat(aux2));
SL_str=num2str(SL);
%Scale or Normalize
if norm==1
matdata=2^(SL-1)*(matdata/(max(max(matdata),abs(min(matdata)))));
else
matdata=matdata/Scale;
end
%Quantization
matdata=eval(['int' SL_str '(matdata)']);
MaxDataLen=min(DataBlock,length(matdata)/5); % The longest Raw Data channel package to process at once will be DataBlock *SL bits
data=matdata(1:MaxDataLen);
% Filter
Channel_and_Filter(handles);
% Set Slider Step
slider_step=min(1,1/fix(length(matdata)/MaxDataLen-1)); %Set the slider step of the slide bar (raw data plot)
set(handles.slider1,'SliderStep',[slider_step/10 slider_step]);
% Plot Raw Data
plot_channel(handles);
end
% Load Recorded Units
%Loads all recorded results from a recorded sort.
function Recorded_Units_Callback(hObject, eventdata, handles)
[auxFileName,auxPathName,FilterIndex] = uigetfile('*.*'); % Get the file location and name of the selected file
if auxFileName~=0 % if loads any file
%Clear all variables and plots
Reset_Variables(handles);
Reset_plots(handles);
% Load Recordes DAta
load([auxPathName auxFileName]); % Warning: Resets global Workspace also
if (max(SpikeTime)>40000) %from old Spike Sorter
SpikeTime=SpikeTime/(Fs*60);
end
get_Features(handles);
plot_Wfs(handles);
%Set other global variables
global Unitn
global FileName
global PathName
global fileType
Unitn=max(UnitStatus);
% Save File Info
FileName=auxFileName;
PathName=auxPathName;
fileType=3;
Set_RecordPath;
end
% Save Spikes and Spike Time
% Saves Waveforms data, time position of each waveform and clusters (Units)
function Save_Callback(hObject, eventdata, handles)
global FileName
global PathName
global WFmatrix
global UnitStatus
global SpikeTime
global fileType
global BlockTime
global RecordPathName
% Block objects and start error timer
time=start_timer(handles,BlockTime);
s = warning('off');
%Save Data
if fileType==3 %if file is recorded data
fold=[RecordPathName FileName];
else
mkdir(RecordPathName);
Channel = get(handles.Channel,'Value');
fold=[RecordPathName FileName '_C' num2str(Channel) '.mat']; %Set output adress
end
if exist(fold, 'file')==2 %Overwrite check
ovw=questdlg('Saved data already exists. Do you want to overwrite?' ,'Overwrite data','Yes','No','No');
if strcmp(ovw,'Yes')
save(fold,'WFmatrix','SpikeTime','UnitStatus');
msgbox(['Data saved: ' fold]);
end
else
save(fold,'WFmatrix','SpikeTime','UnitStatus');
msgbox(['Data saved: ' fold]);
end
% Unblock objects and end error timer
warning(s)
end_timer(time,1,handles);
%Set Record Directory Path
function Set_RecordPath
global RecordPathName
global fileType
global PathName
global FileName
if fileType==3 %if file is recorded data
RecordPathName=PathName;
else
RecordPathName=[PathName 'Saves_' FileName '\'];
end
%Save mean Spikes
%Save the mean signal (centroid) of each cluster.
function Spike_mean_Callback(hObject, eventdata, handles)
global UnitStatus
global WFmatrix
auxcd=cd;
path=which('SpikeSort.m');
path=path(1:(end-11));
cd(path);
path=[path 'Spikes.mat']; %Set output adress
for i=(1:max(UnitStatus));
Spikes(i,:)=mean(WFmatrix((find(UnitStatus==i)),:));
figure(i)
plot(Spikes(i,:))
end
if (exist('Spikes.mat','file')==2)
k=[];
aux=Spikes;
load('Spikes.mat');
for i=1:(length(aux(:,1)))
for j=1:(length(Spikes(:,1)))
if (isequal(aux(i,:),Spikes(j,:)))
k=[k;i];
end
end
end
aux(k,:)=[];
Spikes=[Spikes;aux];
save(path,'Spikes')
else
save(path,'Spikes')
end
cd(auxcd);
%Get normazlization factor of all raw data
function Get_normfactor(handles)
global norm
global normScale
global slider_step
global data
global SL
if norm==1
max_abs=0;
ndataBlocks=1/slider_step;
for i=0:ndataBlocks
slider=i*slider_step;
%Get position
seek_on_data(slider)
aux=max(max(max(data)),abs(min(min(data))));
if aux>max_abs
max_abs=aux;
end
end
normScale=2^(SL-1)/max_abs;
end
%Raw Data Scaling
%Scale or Normalize Raw Data on Data according to norm parameter value
function Data_scaling(handles)
global data
global norm
global Scale
global normScale
if norm==1
data=data*normScale;
else
data=data/Scale;
end
%Reset Variables
%Reset all variables to initial values
function Reset_Variables(handles)
global RwDPlot
global ThPlot
global matdata
global data
global threshold
global dataView
global MaxDataLen
global slider_step
global WFmatrix
global FeaturePoints
global FeaTime
global SelectedUnitsIDX
global UnitStatus
global SpikeTime
global showRange
global Unitn
global slice
global MouseSelection
global MouseSelectionI
global ListC
global ListF
global handles2Spk
global fileType
global FileName
global PathName
fileType=0;
FileName=[];
PathName=[];
RwDPlot=[];
ThPlot=[];
matdata=[];
handles2Spk=handles;
ListC=search_fnc_from_file('clustering_algorithm.m');
ListF=search_fnc_from_file('Features.m');
MaxDataLen=0;
data=[];
threshold=0;
dataView=[];
FeaturePoints=[];
FeaTime=[];
SelectedUnitsIDX=[];
UnitStatus=[];
SpikeTime=[];
WFmatrix=[];
showRange=1;
Unitn=0;
slice=zeros(1,2);
set(handles.Slice_1,'String','0');
set(handles.Slice_2,'String','0');
MouseSelection=0;
MouseSelectionI=0;
slider_step=1;
set(handles.Channel,'Value',1);
set(handles.Clusters,'Value',1);
set(handles.Fil,'Value',1);
set(handles.Th,'String',0);
set(handles.slider1,'Max',1);
set(handles.slider1,'Min',0);
%Set parameters to default values
function Set_default_parameters(handles)
global Channels
global Fs
global DataBlock
global Scale
global SL
global norm
global GcaColor
global WfsColor
global SelColor
global RawColor
global BlockTime
global RecordPathName
global Ls
global ps
global DensityRes
global ISI
Channels=25;
Fs=30030;
DataBlock=801000;
Scale=2.048;
SL=16;
norm=0;
GcaColor=[0 0.15 0.35];
WfsColor=[0.35 0.6 0.55];
SelColor=[1 1 1];
RawColor=[0.8 0.3 0.3];
BlockTime=7;
RecordPathName=[];
Ls=4;
ps=25;
DensityRes=[100 100];
ISI=2;
% Free Memory
function FreeMem_Callback(hObject, eventdata, handles)
clear
clear global
% Fix
% Unblock all objects
function Fix_Callback(hObject, eventdata, handles)
unblock_objects(handles);
% Logo_Button
function Logo_Button_Callback(hObject, eventdata, handles)
cdata=get(hObject,'cdata');
msgbox(['Matlab Spike Sorter was developed by:' sprintf('\n') ...
'Joaquin Mansilla Yulan' sprintf('\n') 'Dr. Ing. Sergio Lew' ...
sprintf('\n') 'Instituto de Ingeniería Biomédica - Universidad' ...
' de Buenos Aires'],'Spike Sorter','custom',cdata);
%TIMER FUNCTIONS
%Initiate block timer
%Block all objects while timer on
%This function is usually used when SpikeSorter is plotting
function [time]=start_timer(handles,sec)
time=timer('TimerFcn',{@end_timer,handles},'StartDelay',sec);
block_objects(handles);
start(time);
%Ends block timer
%Unblock all objects and stop timer
%This function is usually used after plotting
function end_timer(obj,event,handles)
s = warning('off');
delete(obj);
warning(s);
unblock_objects(handles);
%Unblock
%Unblocks buttons after plotting
function unblock_objects(handles)
aux=get(handles.SelectWFs,'Enable');
set(handles.SpikeSort, 'pointer', 'arrow')
if strcmp(aux,'off');
set(handles.SelectWFs,'Enable','on');
set(handles.SelWfsPol,'Enable','on');
set(handles.PlotColors,'Enable','on');
set(handles.showReduced,'Enable','on');
set(handles.Sort,'Enable','on');
set(handles.Clusters,'Enable','on');
set(handles.Right_1,'Enable','on');
set(handles.Slice_1,'Enable','on');
set(handles.Left_1,'Enable','on');
set(handles.Right_2,'Enable','on');
set(handles.Slice_2,'Enable','on');
set(handles.Left_2,'Enable','on');
set(handles.AlignMax,'Enable','on');
set(handles.AlignMin,'Enable','on');
set(handles.SelectData,'Enable','on');
set(handles.SelFtPol,'Enable','on');
set(handles.Add_Unit,'Enable','on');
set(handles.ClearUnits,'Enable','on');
set(handles.PlotUnitsSel,'Enable','on');
set(handles.DeselectData,'Enable','on');
set(handles.DeleteData,'Enable','on');
set(handles.PlotFeatures,'Enable','on');
set(handles.ShowSpikes,'Enable','on');
set(handles.FeatTime,'Enable','on');
set(handles.SelRectFeaTime,'Enable','on');
set(handles.SelFeaTimePol,'Enable','on');
end
%Block
%Blocks buttons while plotting
function block_objects(handles)
aux=get(handles.SelectWFs,'Enable');
set(handles.SpikeSort, 'pointer', 'watch')
if strcmp(aux,'on');
set(handles.SelectWFs,'Enable','off');
set(handles.SelWfsPol,'Enable','off');
set(handles.PlotColors,'Enable','off');
set(handles.showReduced,'Enable','off');
set(handles.Sort,'Enable','off');
set(handles.Clusters,'Enable','off');
set(handles.Right_1,'Enable','off');
set(handles.Slice_1,'Enable','off');
set(handles.Left_1,'Enable','off');
set(handles.Right_2,'Enable','off');
set(handles.Slice_2,'Enable','off');
set(handles.Left_2,'Enable','off');
set(handles.AlignMax,'Enable','off');
set(handles.AlignMin,'Enable','off');
set(handles.SelectData,'Enable','off');
set(handles.SelFtPol,'Enable','off');
set(handles.Add_Unit,'Enable','off');
set(handles.ClearUnits,'Enable','off');
set(handles.PlotUnitsSel,'Enable','off');
set(handles.DeselectData,'Enable','off');
set(handles.DeleteData,'Enable','off');
set(handles.PlotFeatures,'Enable','off');
set(handles.ShowSpikes,'Enable','off');
set(handles.FeatTime,'Enable','off');
set(handles.SelRectFeaTime,'Enable','off');
set(handles.SelFeaTimePol,'Enable','off');
end
%Search name functions
%Create a list of function names in a script delimited by %##%
%Used to create a list of feature alghoritms available
%Used to create a list of clustering alghoritms available
function [List]=search_fnc_from_file(file)
List=[];
fid=fopen(file,'r');
f=fread(fid,'char');
f=char(f');
i=strfind(f,'HERE');
Istart=strfind(f(i:end),'%##')+i+2;
Ifinal=strfind(f(i:end),'##%')+i-2;
for j=1:length(Ifinal)
if j==1
List(j,:)=f(Istart(j):Ifinal(j));
else
auxlist=f(Istart(j):Ifinal(j));
List=strvcat(List,auxlist);
end
end
fclose(fid);
%% RAW DATA FUNCTIONS
%Change channel
%Callback to channel selection. Plots the selected channel after filtering.
function Channel_Callback(hObject, eventdata, handles)
global SelColor
global SelectedUnitsIDX
% Reset threshold to 0
Reset_threshold(handles);
%Change channel and Filter
Channel_and_Filter(handles);
%Plot raw data
plot_channel(handles);
%Plot threshold
plot_Th(handles);
%Plot selected Spikes on raw data
plot_sel_rawdata(handles,SelectedUnitsIDX,SelColor);
%Reset threshold to 0 value
function Reset_threshold(handles)
global threshold
threshold=0;
set(handles.Th,'String',num2str(round(threshold)));
%Change Channels parameter from SpikeSort
function Channels_Callback(hObject, eventdata, handles)
global Channels
Channels=str2double(get(handles.Channels,'String'));
% Slider movement.
%Callback to slidebar movement.
function slider1_Callback(hObject, eventdata, handles)
global SelColor
global SelectedUnitsIDX
%Slide into Raw Data
slider=get(hObject,'Value');
move_raw_data(handles,slider);
%Filter
Channel_and_Filter(handles);
%Plot raw data
plot_channel(handles);
%Plot threshold
plot_Th(handles);
%Plot selected Spikes on raw data
plot_sel_rawdata(handles,SelectedUnitsIDX,SelColor);
%Filter
% Changes the channel and applies a High-pass filter to actual channel signal.
%Also, creates dataView from data and channel & filter parameters
function Channel_and_Filter(handles)
global data
global dataView
global Fs
Channel = get(handles.Channel,'Value');
aux=get(handles.Fil,'String');
f=str2num(cell2mat(aux(get(handles.Fil,'Value'))));
%Apply High-Pass filter at f cutoff frequency
if f>0
h= firls(300,[0 0.8*f/Fs 1.2*f/Fs 1],[0 0 1 1]);
dataView=conv(double(data(Channel,:)),h,'same');
dataView=int16(dataView);
else
dataView=data(Channel,:);
end
%Filter current signal
function Fil_Callback(hObject, eventdata, handles)
%Filter
Channel_and_Filter(handles);
%Plot raw data
plot_channel(handles);
%Plot threshold
plot_Th(handles);
%Move threshold up
function Up_Callback(hObject, eventdata, handles)
global threshold
global dataView
%Set new Threshold
threshold = threshold + max(dataView)/40;
set(handles.Th,'String',num2str(round(threshold)));
%Plot Threshold
plot_Th(handles);
%Move threshold down
function Down_Callback(~, eventdata, handles)
global threshold
global dataView
%Set new Threshold
threshold = threshold - max(dataView)/40;
set(handles.Th,'String',num2str(round(threshold)));
%Plot Threshold
plot_Th(handles);
%Set threshold
function Th_Callback(hObject, eventdata, handles)
%Set new Threshold
global threshold
threshold=str2num(get(handles.Th,'String'));
%Plot Threshold
plot_Th(handles);
%Plot Raw Data
function plot_channel(handles)
global dataView
global slider_step
global Fs
global GcaColor
global RawColor
global norm
if isempty(dataView)==0
%Time axis
W=10000;
p=(get(handles.slider1,'Value')/slider_step)*length(dataView)/Fs; % get inital position of time axis
t=(1/Fs+p):1/Fs:(length(dataView)/Fs+p); %Time axis
%Plot data
axes(handles.Signalaxes);
hold off
plot(t,dataView,'Color',RawColor)
%Set graphic features
set(gca,'Color',GcaColor);
xlim([p (length(dataView)/Fs+p)])
ylim([mean(double(dataView(1:W)))-15*std(double(dataView(1:W))),mean(double(dataView(1:W)))+15*std(double(dataView(1:W)))])
xlabel('Time (S)','FontSize', 9);
if norm==0
ylabel('Voltage (uV)','FontSize', 9);
else
ylabel('Amplitude','FontSize', 9);
end
end
%Plot Threshold
function plot_Th(handles)
global ThPlot
global threshold
%Deletes old threshold plot and plot new one
axes(handles.Signalaxes);
hold on
delete(ThPlot);
lim=axis;
x=[lim(1) lim(2)];
ThPlot=plot(x,[threshold threshold],'Color',[0 0.8 0]);
%Plot selected Spikes on RawData
function plot_sel_rawdata(handles,IDX,SColor)
global SpikeTime
global MaxDataLen
global dataView
global slider_step
global Ls
global Fs
global RwDPlot
if not(isempty(IDX) & isempty(SpikeTime)) % Plots selected waveforms
L=round((Ls*Fs/(2*1000)));
delete(RwDPlot);
axes(handles.Signalaxes);
hold on
pack=get(handles.slider1,'Value')/slider_step;
pii=round(pack*MaxDataLen);
pf=round(MaxDataLen+pii);
auxSpikeTime=SpikeTime(IDX);
auxSpikeTime=round(auxSpikeTime(auxSpikeTime>(pii/(Fs*60)) & auxSpikeTime<(pf/(Fs*60)))*60*Fs);
t=[];
%spike=[];
dataux=[];
for i=1:length(auxSpikeTime)
%spike=[spike auxSpikeTime(i)-pii-L:auxSpikeTime(i)-pii+(L-1)];
%t=(spike+pii)/F;
dataux=[dataux 0 dataView(auxSpikeTime(i)-pii-L:auxSpikeTime(i)-pii+(L-1)) 0];
taux=(auxSpikeTime(i)-L:auxSpikeTime(i)+(L-1))/Fs;
t=[t (auxSpikeTime(i)-(L-1))/Fs taux (auxSpikeTime(i)+L)/Fs];
end
RwDPlot=plot(t,dataux,'Color',SColor);
end
%Asign to Data a new portion of Raw Data according to slider
function move_raw_data(handles,slider)
global SL
global matdata
global fileType
global slider_step;
global FileName
global PathName
global MaxDataLen;
global data
global Channels
switch fileType
case 1 %Binary File
%Moves data to slider position
seek_on_data(slider)
%Scale or Normalize
Data_scaling(handles)
%Quantization
SL_str=num2str(SL);
data=eval(['int' SL_str '(data);']);
case 2 % One channel .mat file
ii=round((slider/slider_step)*MaxDataLen);
data=matdata(ii+1:ii+MaxDataLen);
end
%Asign to Data a new portion of binary Raw Data file according to slider (double type)
%Subfunction of move_raw_data
function seek_on_data(slider)
global SL
global slider_step;
global FileName
global PathName
global MaxDataLen;
global data
global Channels
seek=round(SL/8*Channels*MaxDataLen*(slider/slider_step));
rem=mod(seek,(Channels*SL/8));
seek=seek-rem;
fid=fopen([PathName FileName],'rb');
if (fseek(fid,seek,-1)==0)
%Load File
SL_str=num2str(SL);
eval(['data=fread(fid,[Channels MaxDataLen],''int' SL_str ''');']); %Reads binary data from the opened file
end
fclose(fid);
%% WAVEFORMS FUNCTIONS
%WFs local detection
function PrevWf_Callback(hObject, eventdata, handles)
global dataView
global WFmatrix
global SpikeTime
global Ls
global UnitStatus
global Fs
%Detects Spikes under or over threshold on Dataview
L=round((Ls*Fs/(2*1000)));
WFmatrix=[];
SpikeTime=[];
[idxpos]=Spike_position;
%Create Spike Waveforms
for n=1:length(idxpos)
WFmatrix(n,:)=dataView(idxpos(n)-L:idxpos(n)+L-1);
UnitStatus(n,:)=0;
SpikeTime(n,:)=idxpos(n);
end
SpikeTime=SpikeTime/(Fs*60); %Time ocurrence of Spikes in minutes
%Plot Waveforms
plot_Wfs(handles);
set(handles.WFsN,'String',[num2str(size(WFmatrix,1)) ' WFs']);
%Get Feature points
get_Features(handles);
%WFdetection
%Detects Waveforms (Spikes) over or under the threshold.
function WFdetection_Callback(hObject, eventdata, handles)
global dataView
global MaxDataLen;
global threshold
global WFmatrix
global SpikeTime
global Ls
global UnitStatus
global slider_step
global Fs
%Reset Variables
WFmatrix=[];
SpikeTime=[];
UnitStatus=[];
auxWFmatrix=[];
%Obtain Parameters
L=round((Ls*Fs/(2*1000)));
spkidx=0;
ndataBlocks=1/slider_step; %Warning: Last datablock is lost if the loaded file is not a multiple of 40 MB
aux=get(handles.Fil,'String');
f=str2double(cell2mat(aux(get(handles.Fil,'Value'))));
if (f==0 || threshold==0)
errordlg('No Filter or Threshold found','Error');
else
for i=0:ndataBlocks
slider=i*slider_step;
% get data block
move_raw_data(handles,slider);
%%Filter
Channel_and_Filter(handles);
% Detect Spikes position
[idxpos]=Spike_position;
%Creation of waveforms
if isempty(idxpos)==0
for n=1:length(idxpos)
spkidx=spkidx+1;
auxWFmatrix(n,:)=dataView(idxpos(n)-L:idxpos(n)+L-1);
SpikeTime(spkidx,:)=idxpos(n)+i*MaxDataLen;
end
WFmatrix=[WFmatrix;auxWFmatrix];
end
set(handles.percentDetection,'String',[num2str(i/ndataBlocks*100) '% completed'])
pause(0.1)
auxWFmatrix=[];
end
UnitStatus=zeros(spkidx,1);
SpikeTime=SpikeTime/(Fs*60);
%Plot Wfs, Raw Data and Features
set(handles.percentDetection,'String','')
set(handles.WFsN,'String',[num2str(size(WFmatrix,1)) ' WFs']);
%Get Features
get_Features(handles);
%Reset Dataview
slider=get(handles.slider1,'Value');
move_raw_data(handles,slider);
plot_erase(handles)
end
%Detects Spike position on Dataview signal
function [idxpos]=Spike_position
global Ls
global threshold
global dataView