-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpike_sorter_algorithm.m
More file actions
1628 lines (1377 loc) · 58.6 KB
/
Spike_sorter_algorithm.m
File metadata and controls
1628 lines (1377 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
close all
clear all
format long
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read in recording
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
filenames = input('Enter recording filename (.wav format) ','s');
[ya,fs] = audioread(filenames);
% Manually enter the filename here
%[ya,fs]=audioread('Experiment.wav');
dt = 1.d0/fs; % Time between recordings
n = length(ya); % Number of recordings
totaltime = n*dt;
fprintf('Press Ctrl C together anytime to end analysis \n');
fprintf('Length of recording in seconds %8.7f \n',totaltime);
fprintf('Total number of data points is %d \n',n);
fprintf('Sampling rate in Hertz %8.7f \n',1.0/dt);
fprintf('Time step in milliseconds %8.7f \n',1000*dt)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Read in recording
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yamax = max(abs(ya));
fprintf('Maximum absolute height of spikes %d \n',yamax)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Set parameters for analysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
num_selections = 2; % Number of features to use for spike sorting
%totalsignal = 0; % Set totalsignal = 1 to plot the entire recording
% Parameter which manages addition of points to cluster, Suggested range: [.25,1.5]
fraction_radius_group_orig = .6;
fraction_radius_group = fraction_radius_group_orig;
% Parameter which manages distance between clusters, Suggested range: [.25,1]
fraction_radius_all_scores_orig = 0.5;
fraction_radius_all_scores = fraction_radius_all_scores_orig;
% Parameter which regulates the minimum distance the points of one cluster
% can be to another cluster
minimum_distance_cluster_parameter_orig = .125;
minimum_distance_cluster_parameter_orig = .25;
minimum_distance_cluster_parameter = minimum_distance_cluster_parameter_orig;
ijump = 10;
% Spike features to select from to do analysis
fprintf('\n')
fprintf('************* Selection parameters *********************')
fprintf('\n')
fprintf('1: Height 2: Negative height \n');
fprintf('3: Half positive width 4: Full positive width \n');
fprintf('5: Half negative width 6: Full negative width \n');
fprintf('7: Positive area 8: Negative area 9: Total area\n');
fprintf('10: Distance between positive and negative peaks \n');
fprintf('********************************************************** \n')
fprintf('\n')
stra = cellstr(char('Positive spike height','Negative spike height','Positive half-width',...
'Positive full-width','Negative half-width','Negative full-width',...
'Positive area','Negative area','Total area',...
'Time between peaks',...
'PCA Score 1','PCA Score 2'));
pca_temp = -1;
nit = 0;
while (pca_temp ~= 0 && pca_temp ~= 1)
nit = nit + 1;
if (nit > 1)
fprintf('Please enter 0 or 1 \n')
end
pca_temp = input('Enter 0 for manual selection or 1 to use Principal Component Analysis ');
end
pca = pca_temp;
if (pca == 0)
for ijk = 1:2
if (ijk == 1)
iii = 0;
while (iii > 10 || iii < 1)
iii = input('Enter number for selection criteria 1: ');
fprintf('Value needs to be between 1 and 10 \n');
end
selection(ijk) = iii;
else
iii = 0;
while (iii > 10 || iii < 1)
iii = input('Enter number for selection criteria 2: ');
fprintf('Value needs to be between 1 and 10 \n');
end
selection(ijk) = iii;
end
end
%selection(1) = 3;
%selection(2) = 1;
end
% Set pca = 1 to use Principal Component Analysis to perform clustering
% pca = 0;
% pca = 1;
if (pca == 1)
selection(1) = 11;
selection(2) = 12;
end
splt = cellstr(char('r-','g-','m-','b-','y-','c-'));
splto = cellstr(char('ro','go','mo','bo','yo','co'));
spltb = cellstr(char('r','g','m','b','y','c'));
colors = {'red','green','magenta','blue','yellow','cyan'};
createplot = 1; % Set createplot to create high resolution plots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Set parameters for analysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot recording, Select start and end times for analysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%fprintf('Enter 1 to plot total signal, 0 to continue without plotting total signal \n');
%fprintf('If a 1 is entered, the program will end due to time required to plot entire signal. \n');
%fprintf('Program can then be rerun and 0 can be entered \n');
totalsignal = input('Enter 1 to plot total signal, 0 to continue ');
if (totalsignal == 1)
ifirst = 1;
ilast = n;
if (n > 1000000)
fprintf('Since the recording is very large %d \n',n)
fprintf('Plot every %d points of recording \n',ijump);
ijump = 10;
end
xpkt = [ifirst:ijump:ilast];
xpkt = xpkt*dt;
ypkt = ya(ifirst:ijump:ilast);
axmin = double(ifirst)*dt;
axmax = double(ilast)*dt;
ypkmin = min(ypkt);
ypkmax = max(ypkt);
subplot(2,1,1)
plot(xpkt,ypkt)
axis([axmin axmax ypkmin ypkmax])
fprintf('Plotting total signal \n');
xlabel('Time (seconds)','FontSize',16)
ylabel('Amplitude','FontSize',16)
set(gca,'linewidth',2)
set(gca,'FontSize',12)
%fprintf('Plotting entire signal for 5 seconds \n')
hold on
%pause(5)
%close all
%fprintf('Press enter to continue \n');
%pause
%fprintf('Ending program \n')
%return
end
starttime_temp = -1;
while (starttime_temp < 0 || starttime_temp >= totaltime)
fprintf('Start time needs to be greater than 0 and less than total time %8.7f \n',totaltime);
starttime_temp = input('Enter start time (in seconds) to begin analysis ');
end
starttime = starttime_temp;
endtime_temp = starttime;
while(endtime_temp <= starttime || endtime_temp > totaltime)
fprintf('End time needs to be greater than start time %d and less than total time %8.7f \n',starttime,totaltime);
endtime_temp = input('Enter end time (in seconds) at which to end analysis ');
end
endtime = endtime_temp;
threshold_temp = -1.;
while (threshold_temp < 0 || threshold_temp > yamax)
fprintf('Spike threshold needs to be greater than 0 and less than the maximum spike height %8.7f \n',yamax);
threshold_temp = input('Enter minimum threshold for spikes to be considered for analysis ');
end
threshold = threshold_temp;
fprintf('Threshold in spike sorting algorithm %4.4f \n',threshold);
mstart = floor(max(floor(starttime/dt)+1,2)); % Beginning integer recording value corresponding to start time
mfinish = floor(max(floor(endtime/dt))); % End integer recording value corresponding to end time
ioverlay = 1; % Set overlay = 1 to create plot of overlayed spikes
fprintf('Extracting recording from start time to end time \n')
minypk = 1.d+20;
maxypk = -1.d+20;
xpk(:,1) = [mstart*dt:dt:mfinish*dt];
ypk = ya(mstart:mfinish,1);
minypk = min(ypk);
maxypk = max(ypk);
nelem = mfinish - mstart + 1;
if (nelem > 1000000)
ijump_selection = 10;
else
ijump_selection = 1;
end
xpk_plot = xpk(1:ijump_selection:nelem);
ypk_plot = ypk(1:ijump_selection:nelem);
if (totalsignal == 1)
plot(xpk_plot,ypk_plot,'c-')
axis([axmin axmax ypkmin ypkmax])
hold off
end
xp_threshold(1) = xpk(1);
yp_threshold(1) = threshold;
xp_threshold(2) = xpk(mfinish-mstart+1,1);
yp_threshold(2) = threshold;
if (totalsignal == 1)
subplot(2,1,2)
end
plot(xpk_plot,ypk_plot,'c-')
if (totalsignal == 1)
axis([min(xpk_plot) max(xpk_plot) ypkmin ypkmax])
end
hold on
plot(xp_threshold,yp_threshold,'r-','Linewidth',2)
%if (totalsignal == 1)
% legend('Total signal','Selected signal','Threshold')
%else
% legend('Selected signal','Threshold')
%end
legend('Selected signal ','Threshold','Orientation','horizontal','Location','South')
%legend('','Threshold')
legend boxoff
xlabel('Time (seconds)','FontSize',16)
ylabel('Amplitude','FontSize',16)
set(gca,'linewidth',2)
set(gca,'FontSize',12)
%fprintf('Plotting recording from selected start to end times for 5 seconds\n');
if (createplot == 1)
highres('totalsignal')
end
fprintf('Are you satisfied with your choice of the spike threshold and start and end times for analysis? \n')
ithreshold = input('Enter 0: No (program will end and can be rerun) OR 1: Yes ');
if (ithreshold == 0)
return
end
hold off
close all
%fprintf('Press enter to continue \n');
%pause
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Plot recording, Select start and end times for analysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Find locations of peaks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Finding location of peaks \n')
istart = 0;
ilocation = 0;
ypkmax = 0.d0;
ijk = 0;
peak = zeros(mfinish-mstart+1,1); % Stores the recordings where the peaks occur
for i = mstart:mfinish
if (abs(ya(i,1)) < threshold)
istart = 1;
end
if (abs(ya(i,1)) > threshold && istart == 1)
if (abs(ya(i,1)) > ypkmax)
ypkmax = abs(ya(i,1));
ilocation = i;
end
end
if (ilocation > 0)
if (abs(ya(i-1,1)) >= .5d0*threshold && abs(ya(i,1)) <= .5d0*threshold && istart == 1)
ijk = ijk + 1;
if (mod(ijk,400) == 0)
fprintf('Number of peaks (positive or negative) found above threshold %d \n',ijk)
end
peak_pre(ijk) = ilocation;
height_pre(ijk) = ya(ilocation,1);
facya = .5*(ya(ilocation+1,1) - ya(ilocation-1,1))/(ya(ilocation+1,1)-2.0*ya(ilocation,1)+ya(ilocation-1,1));
peak_int(ijk) = dt*(double(ilocation) - facya);
ypkmax = 0.d0;
ilocation = 0;
istart = 0;
end
end
end
npeaks = ijk;
ifilter = 0;
for ijk = 1:npeaks
if (height_pre(ijk) > 0.0)
ifilter = ifilter + 1;
peak(ifilter) = peak_pre(ijk);
height(ifilter) = height_pre(ijk);
else
iloc = peak_pre(ijk);
if (ijk + 1 <= npeaks)
iloc_ahead = peak_pre(ijk+1);
else
iloc_ahead = -100000;
end
if (ijk - 1 >= 1)
iloc_before = peak_pre(ijk-1);
else
iloc_before = -100000;
end
time_ahead = double(iloc_ahead - iloc)*dt/1000.; % time to next spike in ms
time_before = double(iloc - iloc_before)*dt/1000.; % time to previous spike in ms
if (time_ahead <= 2.0 || time_before <= 2.0)
too_close = 1; % Spike is within 2 ms of another spike
else
too_close = 0;
end
max_allowed = floor(1.5/(dt*1000)); % Positive peak needs to be within 1.5 ms
if (too_close == 0)
% Search for positive peak
ii = iloc;
ypkmax = 0.0;
ilocation = 0;
while (ii <= max_allowed)
if (ya(ii,1) > ypkmax && ya(ii,1) >= .5*threshold)
ypkmax = ya(ii,1);
ilocation = ii;
end
ii = ii + 1;
end
ilocation
if (location > 0)
ifilter = ifilter + 1;
peak(ifilter) = ilocation;
height(ifilter) = ypkmax;
end
end
end
end
npeaks = ifilter;
fprintf('Number of peaks above threshold %d \n \n',npeaks);
if (npeaks < 10)
fprintf('Number of peaks may be too few to do a spike sorting analysis \n')
fprintf('Try decreasing threshold or increasing time range \n');
fprintf('Ending progam \n');
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Find locations of peaks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Determining other features of action potential
% For example: negpeak is location of negative peak,
% peak is location of positive peak
% beginpeak firstneg negpeak secondneg firstzero beghalfheight peak endhalfheight endpeak
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
firstzero = zeros(npeaks,1);
beginpeak = zeros(npeaks,1);
endpeak = zeros(npeaks,1);
for kk = 1:npeaks
ijk = 0;
firstzerol = 0;
secondpeak = 0;
heightnegative(kk) = 1.d+10;
for j = peak(kk):-1:peak(kk)-200
if (ya(j,1) >= 0.d0 && ya(j-1,1) <= 0.d0 && firstzerol == 0 && secondpeak == 0)
firstzerol = 1;
firstzero(kk) = j; % firstzero stores the location of first zero to left of peak
firstzero_int(kk) = dt*( double(j-1) + (0.d0 - ya(j-1,1))/(ya(j,1) - ya(j-1,1)) );
end
if (ya(j,1) <= 0.d0 && ya(j-1,1) >= 0.d0 && firstzerol == 1 && secondpeak == 0)
beginpeak(kk) = j; % beginpeak stores the second zero to left of peak
beginpeak_int(kk) = dt*( double(j-1) + (0.d0 - ya(j-1,1))/(ya(j,1) - ya(j-1,1)) );
secondpeak = 1;
end
end
beginpeak(kk) = max(beginpeak(kk),peak(kk)-200);
heightnegative(kk) = 1.d+10;
areaneg(kk) = 0.d0;
for j = beginpeak(kk):firstzero(kk)
if (ya(j,1) <= heightnegative(kk))
heightnegative(kk) = ya(j,1); % stores location of negative peak
negpeak(kk) = j;
end
areaneg(kk) = areaneg(kk) + abs(ya(j,1));
end
jlo = negpeak(kk);
facya = .5*(ya(jlo+1,1) - ya(jlo-1,1))/(ya(jlo+1,1)-2.0*ya(jlo,1)+ya(jlo-1,1));
negpeak_int(kk) = dt*(double(jlo) - facya);
firstzeror = 0;
for j = peak(kk)+5:peak(kk)+100
%if (ya(j-1,1) >= 0.d0 && ya(j,1) <= 0.d0 && firstzeror == 0)
if (ya(j,1) > ya(j-1,1) && firstzeror == 0)
endpeak(kk) = j; % endpeak stores location of zero to right of peak
facya = .5*(ya(j,1) - ya(j-2,1))/(ya(j,1)-2.0*ya(j-1,1)+ya(j-2,1));
endpeak_int(kk) = dt*(double(j-1) - facya);
firstzeror = 1;
end
end
endpeak(kk) = min(endpeak(kk),peak(kk)+100);
areapos(kk) = 0.d0;
for j = firstzero(kk):endpeak(kk)
areapos(kk) = areapos(kk) + abs(ya(j,1));
end
halfheightnegative = .5d0*heightnegative(kk);
for j = beginpeak(kk):firstzero(kk)
if (ya(j-1,1) >= halfheightnegative && ya(j,1) <= halfheightnegative)
firstneg(kk) = j; % firstneg and secondneg store locations of negative half height
firstneg_int(kk) = dt*( double(j-1) + (halfheightnegative - ya(j-1,1))/(ya(j,1) - ya(j-1,1)) );
end
if (ya(j-1,1) <= halfheightnegative && ya(j,1) >= halfheightnegative)
secondneg(kk) = j;
secondneg_int(kk) = dt*( double(j-1) + (halfheightnegative - ya(j-1,1))/(ya(j,1) - ya(j-1,1)) );
end
end
halfheight = .5d0*height(kk);
for j = firstzero(kk):peak(kk)
if (ya(j-1,1) <= halfheight && ya(j,1) >= halfheight)
beghalfheight(kk) = j; % beghalfheight and endhalfheight store locations of positive half height
beghalfheight_int(kk) = dt*( double(j-1) + (halfheight - ya(j-1,1))/(ya(j,1) - ya(j-1,1)) );
end
end
for j = peak(kk)+1:endpeak(kk)
if (ya(j-1,1) >= halfheight && ya(j,1) <= halfheight)
endhalfheight(kk) = j;
endhalfheight_int(kk) = dt*( double(j-1) + (halfheight - ya(j-1,1))/(ya(j,1) - ya(j-1,1)) );
end
end
end
% beginpeak firstneg negpeak secondneg firstzero beghalfheight peak endhalfheight endpeak
maxdistb = -1.d0;
for kk = 1:npeaks
distancebeginpeak = peak(kk) - beginpeak(kk);
maxdistb = max(maxdistb,distancebeginpeak);
end
ap_before = .5;
ap_after = .2;
maxdistb = floor(ap_before/(1000*dt));
maxdiste = -1.d0;
for kk = 1:npeaks
distanceendpeak = endpeak(kk) - peak(kk);
maxdiste = max(maxdiste,distanceendpeak);
end
maxdiste = floor(ap_after/(1000*dt));
for kk = 1:npeaks
halfposheightdur(kk) = double(endhalfheight(kk)-beghalfheight(kk))*dt;
halfposheightdur(kk) = endhalfheight_int(kk) - beghalfheight_int(kk);
fullposheightdur(kk) = double(endpeak(kk)-firstzero(kk))*dt;
fullposheightdur(kk) = endpeak_int(kk) - firstzero_int(kk);
halfnegheightdur(kk) = double(secondneg(kk)-firstneg(kk))*dt;
halfnegheightdur(kk) = secondneg_int(kk) - firstneg_int(kk);
fullnegheightdur(kk) = double(firstzero(kk)-beginpeak(kk))*dt;
fullnegheightdur(kk) = firstzero_int(kk) - beginpeak_int(kk);
distancepeaks(kk) = double(peak(kk) - negpeak(kk))*dt;
distancepeaks(kk) = peak_int(kk) - negpeak_int(kk);
areapos(kk) = areapos(kk)*dt;
areaneg(kk) = areaneg(kk)*dt;
areatot(kk) = areapos(kk) + areaneg(kk);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Determining other features of action potential
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Normalize features of action potential
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
heightmean = mean(height);
heightsd = std(height);
heightnegativemean = mean(heightnegative);
heightnegativesd = std(heightnegative);
areaposmean = mean(areapos);
areapossd = std(areapos);
areanegmean = mean(areaneg);
areanegsd = std(areaneg);
areatotmean = mean(areatot);
areatotsd = std(areatot);
halfposheightdurmean = mean(halfposheightdur);
halfposheightdursd = std(halfposheightdur);
fullposheightdurmean = mean(fullposheightdur);
fullposheightdursd = std(fullposheightdur);
halfnegheightdurmean = mean(halfnegheightdur);
halfnegheightdursd = std(halfnegheightdur);
fullnegheightdurmean = mean(fullnegheightdur);
fullnegheightdursd = std(fullnegheightdur);
distancepeaksmean = mean(distancepeaks);
distancepeakssd = std(distancepeaks);
% Normalize features of action potential
for kk = 1:npeaks
heightz(kk) = (height(kk) - heightmean)/heightsd;
heightnegativez(kk) = (heightnegative(kk) - heightnegativemean)/heightnegativesd;
areaposz(kk) = (areapos(kk) - areaposmean)/areapossd;
areanegz(kk) = (areaneg(kk) - areanegmean)/areanegsd;
areatotz(kk) = (areatot(kk) - areatotmean)/areatotsd;
halfposheightdurz(kk) = (halfposheightdur(kk) - halfposheightdurmean)/halfposheightdursd;
fullposheightdurz(kk) = (fullposheightdur(kk) - fullposheightdurmean)/fullposheightdursd;
halfnegheightdurz(kk) = (halfnegheightdur(kk) - halfnegheightdurmean)/halfnegheightdursd;
fullnegheightdurz(kk) = (fullnegheightdur(kk) - fullnegheightdurmean)/fullnegheightdursd;
distancepeaksz(kk) = (distancepeaks(kk) - distancepeaksmean)/distancepeakssd;
end
coefficient_variation(1) = heightsd/heightmean;
coefficient_variation(2) = -heightnegativesd/heightnegativemean;
coefficient_variation(3) = abs(halfposheightdursd/halfposheightdurmean);
coefficient_variation(4) = fullposheightdursd/fullposheightdurmean;
coefficient_variation(5) = halfnegheightdursd/halfnegheightdurmean;
coefficient_variation(6) = fullnegheightdursd/fullnegheightdurmean;
coefficient_variation(7) = areapossd/areaposmean;
coefficient_variation(8) = areanegsd/areanegmean;
coefficient_variation(9) = areatotsd/areatotmean;
coefficient_variation(10) = abs(distancepeakssd/distancepeaksmean);
[coef_variation_sort,points_sort_coef] = sort(coefficient_variation,2,'descend');
% Print out coefficient of variation from largest to smallest
for i = 1:10
jj = points_sort_coef(i);
fprintf('Coefficient of variation of %s is %d \n',stra{jj},coefficient_variation(jj));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Normalize features of action potential
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n');
fprintf('First selection criteria %s \n', stra{selection(1)});
fprintf('Second selection criteria %s \n', stra{selection(2)});
xscore = zeros(npeaks,1);
yscore = zeros(npeaks,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Manual Selection of Criteria
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (pca == 0)
for ijk = 1:num_selections
if (selection(ijk) == 1)
for kk = 1:npeaks
score(kk,ijk) = heightz(kk);
scoreo(kk,ijk) = height(kk);
end
end
if (selection(ijk) == 2)
for kk = 1:npeaks
score(kk,ijk) = heightnegativez(kk);
scoreo(kk,ijk) = heightnegative(kk);
end
end
if (selection(ijk) == 3)
for kk = 1:npeaks
score(kk,ijk) = halfposheightdurz(kk);
scoreo(kk,ijk) = halfposheightdur(kk);
end
end
if (selection(ijk) == 4)
for kk = 1:npeaks
score(kk,ijk) = fullposheightdurz(kk);
scoreo(kk,ijk) = fullposheightdur(kk);
end
end
if (selection(ijk) == 5)
for kk = 1:npeaks
score(kk,ijk) = halfnegheightdurz(kk);
scoreo(kk,ijk) = halfnegheightdur(kk);
end
end
if (selection(ijk) == 6)
for kk = 1:npeaks
score(kk,ijk) = fullnegheightdurz(kk);
scoreo(kk,ijk) = fullnegheightdur(kk);
end
end
if (selection(ijk) == 7)
for kk = 1:npeaks
score(kk,ijk) = areaposz(kk);
scoreo(kk,ijk) = areapos(kk);
end
end
if (selection(ijk) == 8)
for kk = 1:npeaks
score(kk,ijk) = areanegz(kk);
scoreo(kk,ijk) = areaneg(kk);
end
end
if (selection(ijk) == 9)
for kk = 1:npeaks
score(kk,ijk) = areatotz(kk);
scoreo(kk,ijk) = areatot(kk);
end
end
if (selection(ijk) == 10)
for kk = 1:npeaks
score(kk,ijk) = distancepeaksz(kk);
scoreo(kk,ijk) = distancepeaks(kk);
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Manual Selection of Criteria
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Principal Component Analysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
range = maxdiste+maxdistb+1;
xpkk = zeros(range,1);
ypkk = zeros(range,1);
xmat = zeros(npeaks,range);
for kk = 1:npeaks
% beginpeak firstneg negpeak secondneg firstzero beghalfheight peak endhalfheight endpeak
ijk = 0;
if (peak(kk)-maxdistb < beginpeak(kk)-1)
for j = peak(kk)-maxdistb:beginpeak(kk)-1
ijk = ijk + 1;
xpkk(ijk) = ijk;
ypkk(ijk) = 0.d0;
end
end
for j = firstneg(kk):peak(kk)
ijk = ijk + 1;
xpkk(ijk) = ijk;
ypkk(ijk) = ya(j,1);
end
for j = peak(kk)+1:endpeak(kk)
ijk = ijk + 1;
xpkk(ijk) = ijk;
ypkk(ijk) = ya(j,1);
end
if (peak(kk)+maxdiste > endpeak(kk)+1)
for j = endpeak(kk)+1:peak(kk)+maxdiste
ijk = ijk + 1;
xpkk(ijk) = ijk;
ypkk(ijk) = 0.d0;
end
end
ijk = 0;
for j = peak(kk)-maxdistb:peak(kk)+maxdiste
ijk = ijk + 1;
xmat(kk,ijk) = ypkk(ijk);
end
end
if (pca == 1)
sigma = zeros(range,range);
U = zeros(range,range);
V = zeros(range,range);
S = zeros(range,range);
Vr = zeros(npeaks,npeaks);
xmatt = zeros(range,npeaks);
mean = zeros(npeaks,1);
xmatt = xmat';
xmatsave = xmatt;
for i = 1:range
mean(i) = 0.d0;
for k = 1:npeaks
mean(i) = mean(i) + xmatt(i,k);
end
mean(i) = mean(i)/double(npeaks);
end
for i = 1:range
for k = 1:npeaks
xmatt(i,k) = xmatt(i,k) - mean(i);
end
end
sig = xmatt;
% xmat is a npeak (m) BY number_of_data_points_action_potential (n)
%%sigma = xmat'*xmat;
%%sigma = sigma/double(npeaks); %Covariance matrix
%%[U,S,V] = svd(sigma); % U is a n BY n matrix, U' is a n BY n matrix
[U,S,Vr] = svd(sig);
pcascores = zeros(range,npeaks);
pcascores = U'*xmatt; % scores is a n BY m matrix
for ijk = 1:num_selections
for i = 1:npeaks
score(i,ijk) = pcascores(ijk,i);
scoreo(i,ijk) = score(i,ijk);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End: Principal Component Analysis
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n');
normalize_scores = 1;
% Set normalize_scores = 0 to use unnormalized scores
if (normalize_scores == 1)
fprintf('Normalizing scores by subtracting mean and dividing by standard deviation \n')
end
for i = 1:npeaks
xscore(i) = score(i,1);
yscore(i) = score(i,2);
xscoreo(i) = scoreo(i,1);
yscoreo(i) = scoreo(i,2);
if (normalize_scores == 0)
xscore(i) = scoreo(i,1);
yscore(i) = scoreo(i,2);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Clustering algorithm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('Begin clustering algorithm \n')
%fprintf('If points are being added too quickly, reduce fraction_radius_group \n')
%fprintf('If points are being skipped or added too slowly or have stopped, increase fraction_radius_group \n')
%fprintf('\n')
% The radius of each point is defined to be distance to the "number_neighbors"
% point which are ordered from least to greatest in terms of distance.
% The smaller the radius, the heigher the density of each point.
% The density of each point is used to select centers of clusters.
number_neighbors = max(2,floor(.1*npeaks));
points_neighbor_sorted = zeros(npeaks,npeaks);
dist_neighbor_sorted = zeros(npeaks,npeaks);
cluster_group = zeros(npeaks,1);
in_cluster = zeros(npeaks,1);
center_group_element = zeros(npeaks,1);
dist_veca = zeros(npeaks,npeaks);
for i = 1:npeaks
radius_group(i) = 1.e+20;
end
fprintf('Finding distances between scores \n')
for i = 1:npeaks
if (mod(i,400) == 0)
fprintf('Finished calculating distance up to peak %d out of %d peaks \n',i,npeaks);
end
for j = 1:npeaks
dist_vec(j) = 0.d0;
for ijk = 1:num_selections
dist_vec(j) = dist_vec(j) + (score(i,ijk)-score(j,ijk))^2;
end
dist_vec(j) = sqrt(dist_vec(j));
% dist_veca(i,j) is the distance from score i to score j
dist_veca(i,j) = dist_vec(j);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[dist_sort,points_sort] = sort(dist_vec,2,'ascend');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define the distance for point i to the number_neighbors closest point
% number_neighbors is defined to be the 1/5 of the total number of
% peaks
dist_neighbor(i) = dist_sort(number_neighbors);
for j = 1:npeaks
points_neighbor_sorted(i,j) = points_sort(j);
dist_neighbor_sorted(i,j) = dist_sort(j);
end
end
number_groups = 0;
iretry_groups = 1;
fprintf('End finding distances between scores \n')
while (iretry_groups == 1 && number_groups < 4)
itry_again_cluster = 1;
nit_center = 0;
while (itry_again_cluster == 1)
nit_center = nit_center + 1;
% Find the point with the highest density
number_groups = number_groups + 1;
center_group_element(number_groups) = 0;
for i = 1:npeaks
% Check to see if the peak i has already been included in a cluster
% or if the peak i is too close to a cluster
ifound = 0;
if (in_cluster(i) == 0)
for j = 1:number_groups-1
for ii = 1:num_group_elements(j)
jj = group_elements(j,ii);
dd = dist_veca(i,jj);
% radius_all_scores is a measure of the size of the entire set of
% scores
if ((i == jj) || (dd < fraction_radius_all_scores*radius_all_scores) )
ifound = 1;
end
end
end
else
ifound = 1;
end
if (ifound == 0)
% Find the point i with the smallest radius to the nearest number_neighbors
% or equivalently the point i with the highest surrounding
% density of scores
if (dist_neighbor(i) < radius_group(number_groups))
center_group_element(number_groups) = i;
radius_group(number_groups) = dist_neighbor(i);
end
end
end
kc = center_group_element(number_groups);
if (kc == 0)
fprintf('\n')
fprintf('No new cluster center was not found \n')
fprintf('Try decreasing value of variable fraction_radius_all_scores \n')
fprintf('Current value of fraction_radius_all_scores %d \n',fraction_radius_all_scores)
fprintf('Enter 0 to stop finding new clusters \n')
itry_again_cluster = input('Enter 1 to continue finding cluster by decreasing fraction_radius_all_scores ');
if (itry_again_cluster == 1)
fraction_radius_all_scores = input('Enter new value of fraction_radius_all_scores: Suggested range [.25,1] ');
end
number_groups = number_groups - 1;
else
itry_again_cluster = 0;
end
end
if (kc > 0)
number_in_cluster = 1;
cluster_group = 0;
cluster_group(1) = kc;
in_cluster(kc) = 1;
rad_search = fraction_radius_group*radius_group(number_groups);
iretry = 1;
nit = 0;
nit_progress = 0;
fprintf('Adding points to cluster %d \n',number_groups);
while (iretry == 1)
nit = nit + 1;
close_points = 0;
number_in_cluster_new = number_in_cluster;
for i = 1:number_in_cluster
ii = cluster_group(i);
jj = 0;
radius_exceeded = 0;
while (jj < npeaks && radius_exceeded == 0)
jj = jj + 1;
ic = points_neighbor_sorted(ii,jj);
if (dist_neighbor_sorted(ii,jj) < rad_search)
% Determine if candidate point ic is far enough way
% from other clusters
ifound = 0;
if (number_groups > 1)
min_distance_neighboring_cluster = minimum_distance_cluster_parameter*radius_all_scores;
end
if (in_cluster(ic) == 0)
close_points = close_points + 1;
for ja = 1:number_groups-1
for iia = 1:num_group_elements(ja)
jja = group_elements(ja,iia);
dd = dist_veca(ic,jja);
% radius_all_scores is a measure of the size
% of the entire set of scores
% fraction_radius_all_score*radius_all_scores
% is the minimum distance that must be
% maintained between cluster centers
% min_distance_neighboring_cluster is the
% minimum distance that must be maintainrf
% between any point in a cluster and points
% in a neighboring cluster
if ( dd < min_distance_neighboring_cluster )
ifound = 1;
end
end
end
else
ifound = 1;
end
if (ifound == 0)
number_in_cluster_new = number_in_cluster_new + 1;
cluster_group(number_in_cluster_new) = ic;
in_cluster(ic) = 1;
end
else
radius_exceeded = 1;
end
end
end
no_change = 0;
if (number_in_cluster == number_in_cluster_new && nit > 1)
nit_progress = nit_progress + 1;
fprintf('No additional points were added to cluster \n');
if (close_points == 0)
fprintf('Suggest increasing parameter fraction_radius_group \n');
fprintf('to retry adding additional points to cluster \n');
fprintf('Current value of fraction_radius_group is %d \n',fraction_radius_group);
fprintf('Enter 0 to keep value of fraction_radius_group \n')
itry_again = 0;