-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtetrode.m
1822 lines (1480 loc) · 73.7 KB
/
tetrode.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
classdef tetrode<handle
%TETRODE Imports Neuralynx .NTT files and helps with clustering
% Current methods include:
%
% - remove_noise('noise type') e.g. obj.remove_noise('clipping');
% will remove all waveforms that clip the maximum value from the
% dataset. obj.remove_noise('max height', 100); will remove all
% waveforms with a height of >100µV.
%
% - present_figure('atribute') e.g. obj.present_figure('height')
% will plot the height of all waveforms as a scatter plot on 3
% electrodes. You can also provide the electrodes you want to see
% like this: obj.present_figure('height',[1 2 4]); (For electrode
% 1, 2 and 4.
%
% - show_cell(cell_number) e.g. obj.show_cell(1) will plot the
% waveforms on all 4 electrodes on cell 1 and obj.show_cell(nan)
% will simply plot all waveforms.
%
% - set_offline_threshold(threshold (1x4)) e.g.
% obj.set_offline_threshold([65 65 65 65]); Will set a post-hoc
% threshold and delete all waveforms that do not meet this
% threshold on any electrode.
%
% - full_pca() e.g. obj.full_pca() will plot a 3D plot
% with the first 3 principle components of the entire dataset.
% The 3 axis represent the 3pc's, NOT 3 electrodes.
%
% - peri_event() e.g. obj.peri_event(stamps); will plot a
% peri-event histogram of all units (and unclustered datapoints)
% around the timepoints in the array stamps. Note that stamps
% should be in µs. You can also a window (in µs) as a 3rd
% argument.
%
% - set_interval() e.g. obj.set_interval([0 20]); from now on the
% attributes (e.g. 'height', 'pca_1', etc..) are calulated using
% the first 20 datapoints of each waveform.
%
% - save_data('filename') e.g. obj.save_data('filename') will
% save the tetrode object to the current folder.
%
% Tetrode uses part of Fieldtrip, (Copyright (C) 2005), Robert
% Oostenveld. For more information about Fieldtrip (including license
% information (GNU) see: http://www.fieldtriptoolbox.org.
%
% Tetrode is part of Bearphys, Bearphys is made by Johannes de Jong,
% j.w.dejong@berkeley.edu
properties
% In principle all data properties are organized as follows:
% (channels x data points x n)
raw_data % Stores imported tetrode (struct)
data % Data after manipulations (c,d,n)
attributes % Attributes of the sweeps in data (e.g. 'height')
timestamps % Timestamps of the waveforms in data (n)
cells % Clustered units(n);
nr_cells % The total number of clustered units
TTL % Imported TTL arrays (struct)
handles % Handles to figures and plots
settings % Struct with settings.
notes % Notes for
end
% Standard methods
methods
function obj = tetrode(filename, varargin)
%TETRODE Construct an instance of this class
% Deal with input arguments
supress = false;
for i = 1:length(varargin)
switch varargin{i}
case 'supress'
% Supress messages and errors
supress = true;
case 'skipp'
% do nothing
otherwise
warning(['Input: ' varargin{i} ' not recognized.'])
end
end
% Check the filesize
file_info = dir(filename);
filesize = round(file_info.bytes/10^6); %in MB
if filesize > 100 && ~supress
% Ask the user if they are sure
input = questdlg([filename ' is ' num2str(filesize) ' MB. opening might take some time.'],...
'Big file','Continue','Cancel','Cancel');
if ~strcmp(input,'Continue'); disp('No file opened.'); return; end
end
% Uses Fieldtrip m files to import a tetrode file
obj.raw_data = read_neuralynx_ntt(filename, 1, inf);
% Grab the data
obj.data = obj.raw_data.dat;
% Grab any pre-clustered cells
obj.cells = obj.raw_data.CellNumber;
% Find the total number of clusters
obj.nr_cells = max(obj.cells);
% Fill out the timestamps
obj.timestamps = obj.raw_data.TimeStamp;
% Find the recording interval
obj.settings.recording_interval =...
[obj.raw_data.hdr.FirstTimeStamp, obj.raw_data.hdr.LastTimeStamp];
% Fill out the settings
obj.settings.interval = [1, 32];
obj.settings.preferred_electrodes = [1 2 3]; % Because humans like three dimensions
obj.settings.colorlist = ['kgrbmcgrbmgrbmycgrbmgrbmycgrbmgrbmycgrbmgrbmycgrbmgrbmycgrbmgrbmycgrbm'];
obj.settings.remove_check = true; % Prevents removal of sweeps without user confirmation
% Find the DBitVolts (from the header char...)
header = obj.raw_data.hdr.Header;
for i = 1:5000
if strcmp('ADBitVolts', header(i:i+9))
break;
end
end
obj.settings.ADBitVolts(1) = str2num(header(i+11:i+36));
obj.settings.ADBitVolts(2) = str2num(header(i+38:i+63));
obj.settings.ADBitVolts(3) = str2num(header(i+65:i+90));
obj.settings.ADBitVolts(4) = str2num(header(i+92:i+117));
% Grab the recording date
for i = 1:5000
if strcmp('(m/d/y)', header(i:i+6))
break;
end
end
obj.raw_data.date = header(i+9:i+18);
% Grab the recording time
for i = 1:5000
if strcmp('(h:m:s.ms)', header(i:i+9))
break;
end
end
obj.raw_data.time = header(i+11:i+22);
% Figure out which electrodes are not recording anything at all
% and label them 'false' in the working electrodes property
for i=1:4
if sum(sum(obj.data(i,:,:)))==0
obj.settings.working_electrodes(i) = false;
else
obj.settings.working_electrodes(i) = true;
end
end
% Find the Inputrange(from the header char...)
for i = 1:5000
if strcmp('InputRange', header(i:i+9)); break; end
end
new_char = header(i+11:i+30);
for i=1:length(header)
if strcmp(new_char(i),'-'); break; end
end
obj.settings.InputRange = str2num(new_char(1:i-1));
% Find the Threshold Value(from the header char...)
for i = 1:5000
if strcmp('ThreshVal', header(i:i+8)); break; end
end
new_char = header(i+10:i+30);
for i=1:length(header)
if strcmp(new_char(i),'-'); break; end
end
obj.settings.ThresVal = str2num(new_char(1:i-1));
% Fill out the attributes
obj.find_attributes;
% Set the cutoff for display performance issues
obj.settings.disp_cutoff = 40000;
% Figure out the prefered electrodes (which the most variation in height)
for i=1:4
devs(i) = std(obj.attributes(i).height);
end
[~, show_electrodes] = sort(devs, 'descend');
show_electrodes = sort(show_electrodes(1:3));
obj.settings.preferred_electrodes = show_electrodes;
% Load any associated event file
path = fileparts(filename);
obj.load_events(path);
% That's it
end
function find_attributes(obj)
% Find attributes updates all the sweep attributes
% Analyse the following interval
start = obj.settings.interval(1);
stop = obj.settings.interval(2);
% Grab the data from the 4 electrodes
for i=1:4
temp_data = squeeze(obj.data(i,start:stop,:)).*obj.settings.ADBitVolts(i)*10^6;
% grab the peak
obj.attributes(i).peak = max(temp_data);
% grab the valley
obj.attributes(i).valley = min(temp_data);
% grab the height
obj.attributes(i).height = obj.attributes(i).peak - obj.attributes(i).valley;
% grab the energy
% See Schmitzer-Torber et al. Neuroscience 2005
obj.attributes(i).energy = sum(temp_data.^2)./(stop-start + 1);
% run PCA, but only on 'working electrodes'
if obj.settings.working_electrodes(i)
[~ ,score,~ ,~ ,~ ] = pca(squeeze(temp_data)');
obj.attributes(i).pca_1 = score(:,1)';
obj.attributes(i).pca_2 = score(:,2)';
obj.attributes(i).pca_3 = score(:,3)';
else
obj.attributes(i).pca_1 = zeros(1,size(temp_data,2));
obj.attributes(i).pca_2 = zeros(1,size(temp_data,2));
obj.attributes(i).pca_3 = zeros(1,size(temp_data,2));
end
% run PCA on normalized energy waveforms (working
% channels)
if obj.settings.working_electrodes(i)
temp_data = temp_data./sqrt(obj.attributes(i).energy);
[~ ,score,~ ,~ ,~ ] = pca(squeeze(temp_data)');
obj.attributes(i).norm_pca_1 = score(:,1)';
obj.attributes(i).norm_pca_2 = score(:,2)';
obj.attributes(i).norm_pca_3 = score(:,3)';
else
obj.attributes(i).norm_pca_1 = zeros(1,size(temp_data,2));
obj.attributes(i).norm_pca_2 = zeros(1,size(temp_data,2));
obj.attributes(i).norm_pca_3 = zeros(1,size(temp_data,2));
end
end
end
function [removed, removed_indexer] = remove_noise(obj, varargin)
%REMOVE_NOISE Removes noise on the basis of the arguments given
%in varargin
%
% Examples:
% >>remove_noise('max heigh', 100); Will remove all waveforms
% of which the height is bigger then 100µV on ANY electrode.
%
% >>remove_noise('min height', 50); Will remove all waveforms
% of which the height is smaller then 100µV on EVERY
% electrode.
%
% >>remove_noise('indexer',[true false false true]); will
% remove the 2th and 3rd waveform from the dataset. (In
% reality the logical will be much longer of course).
% The output is boolean on wether or not any waveforms were
% actually removed
removed = false;
removed_indexer = [];
no_show = false; % Ask the user before deleting ans waveforms
% Deal with input arguments
for i=1:length(varargin)
switch varargin{i}
% max height
case 'max height'
indexer = obj.attributes(1).height> varargin{i+1}...
| obj.attributes(2).height > varargin{i+1}...
| obj.attributes(3).height > varargin{i+1}...
| obj.attributes(4).height > varargin{i+1};
break;
% max height
case 'min height'
indexer = obj.attributes(1).height< varargin{i+1}...
& obj.attributes(2).height < varargin{i+1}...
& obj.attributes(3).height < varargin{i+1}...
& obj.attributes(4).height < varargin{i+1};
break;
% Remove isolated cluster
case 'remove cluster'
indexer = obj.cells == varargin{i+1};
indexer2 = obj.cells>varargin{i+1};
obj.cells(indexer2) = obj.cells(indexer2)-1;
varargin{i+1} = 'skipp';
warning('Not a finished method, clicking no in the dialog will result in errors')
% Remove all waveforms that clip the max value
case 'clipping'
clip_value = obj.raw_data.hdr.ADMaxValue;
indexer = obj.data==clip_value | obj.data==-1*clip_value;
indexer = logical(squeeze(sum(sum(indexer))));
% Remove all waveforms indexed in the following logical
case 'indexer'
indexer = varargin{i+1};
varargin{i+1} = 'skipp';
% Do not bother showing the findings just delete
case 'no show'
disp('hoi')
no_show = true;
% Skipp this input argument
case 'skipp'
X = 5; % Do nothing.
otherwise
error('Unknown argument type, juse the help method to display example option.')
end
end
% Is the remove check off?
if ~ obj.settings.remove_check
no_show = true;
end
% Check if the indexer even picked up on any waveforms
if sum(indexer)==0
disp('No waveforms met exclusion criteria.')
return
end
if ~no_show
% Show the removed noise
[figure_1, figure_2] = obj.show_cell(indexer,'hypothetical');
% Ask the user if they want to indeed remove these
% waveforms?
w_percentage = 100*sum(indexer)/length(obj.timestamps);
input = questdlg(['Remove these ' num2str(sum(indexer)) '(' num2str(w_percentage) '% of total) waveforms?'],'Remove?','yes','no','no');
if strcmp(input,'yes')
% Mark these sweeps nan
obj.cells(indexer) = nan;
% Change the bool
removed = true;
end
% Close the figures
close(figure_1)
close(figure_2)
else
warning('Removing waveforms without waiting for user input.');
disp('To request user input before removing waveforms, set obj.settings.remove_check to true');
% Mark these sweeps nan
obj.cells(indexer) = nan;
% Change the bool
removed = true;
end
% Give the output arguments
removed_indexer = indexer;
% Make sure the object stays consistent
obj.check_object();
end
function [waveform_figure, scatter_figure] = present_figure(obj, varargin)
%PRESENT_FIGURE presents a 3D scatterplot with the requested
%atribute on 3 electrodes on 3 axis.
%
%Examples:
%
%obj.present_figure('height') will plot the height on the first
%3 electores.
%
%obj.present_figure('height', [1 3 4]) will plot the height on
%electrode 1, 3 and 4.
% By default showing all sweeps?
plot_average = false;
% Set the Y axis to the inputrange
y_axis_is_input_range = false;
% Make a list of all attributes
attribute_list = fieldnames(obj.attributes);
% Colorlist for the markers
colorlist = obj.settings.colorlist;
% Default channels to be displayed
channel = obj.settings.preferred_electrodes;
% By default, don't snow NaN sweeps
plot_nan = false;
% By default plot height
attribute = 'height';
% Deal with input arguments
for i=1:length(varargin)
if isnumeric(varargin{i}) && length(varargin{i})==3
channel = varargin{i};
else
% Check if the argument is an attributed
isattribute = false;
for j=1:length(attribute_list)
if strcmp(attribute_list{j}, varargin{i})
isattribute = true;
attribute = varargin{i};
break;
end
end
% If not an attribute, maybe it's something else
if ~isattribute
switch varargin{i}
case 'show removed'
% Show NaN sweeps as well
plot_nan = true;
case 'average'
% Plot average waveform instead of all
% waveforms
plot_average = true;
otherwise
% We really not know, let the user know
disp(' ')
disp(['Argument ''' varargin{i} ''' not recognized.'])
disp('Currently only the following attributes are supported:')
for i=1:length(attribute_list)
disp([' - ' attribute_list{i}])
end
disp(' ')
disp('In addition present_figure supports the following arguments:')
disp(' - show removed')
disp(' - average')
disp(' - A 3D vector containing the 3 electrodes that should be shown.')
return
end
end
end
end
% Grab the data
for i=1:4
XYZ(i,:) = getfield(obj.attributes(i),attribute);
end
% Make indexers for every cells
for i=0:obj.nr_cells
indexer{i+1} = obj.cells==i;
end
% If there are to many waveforms we will plot only 1% of them
% to maintain performance
cutoff = obj.settings.disp_cutoff;
for i=1:length(indexer)
if sum(indexer{i})>cutoff
new_indexer = zeros(size(indexer{i}));
new_indexer(1:20:end)=indexer{i}(1:20:end);
indexer{i} = logical(new_indexer);
% Plot the waveforms
if i==1
disp(['Unclustered: Showing only 5% (n = ' num2str(sum(indexer{i}==1)) ') of waveforms/datapoints.'])
else
disp(['Cell ' num2str(i-1) ': Showing only 5% (n = ' num2str(sum(indexer{i}==1)) ') of waveforms/datapoins.'])
end
end
end
% Make the figure, plot unclustered datapoints
scatter_figure = figure;
scatter_figure.Position = [432, 300, 560, 420];
% Plot identified clusters
for i=0:obj.nr_cells
% figure out the name of this dataset
if i==0
dataname{i+1} = 'Unclustered';
else
dataname{i+1} = ['Cell ' num2str(i)];
end
scatter3(XYZ(channel(1),indexer{i+1}), XYZ(channel(2),indexer{i+1}), XYZ(channel(3),indexer{i+1}),...
'DisplayName', dataname{i+1},...
'MarkerEdgeColor',colorlist(i+1),...
'Marker','.',...
'SizeData',25);
hold on
end
% If requested by the user, plot NaN sweeps as well
if plot_nan
scatter3(XYZ(channel(1),isnan(obj.cells)), XYZ(channel(2),isnan(obj.cells)), XYZ(channel(3),isnan(obj.cells)),...
'DisplayName', 'removed waveforms',...
'MarkerEdgeColor',colorlist(1),...
'Marker','.',...
'SizeData',1) ;
end
% Label figure and axis
title(attribute)
xlabel(['Electrode ' num2str(channel(1))])
ylabel(['Electrode ' num2str(channel(2))])
zlabel(['Electrode ' num2str(channel(3))])
% ***** Plot the waveforms *****
% Make a figure
waveform_figure = figure('Name','Waveforms');
waveform_figure.Position = [993 300, 560, 420];
% Work on the xaxis
interval = 10^6/obj.raw_data.hdr.SamplingFrequency; %µs
timeline = [0:interval:1000-interval]';
% 4 subplots for 4 electrodes
for i=1:4
subplot(2,2,i)
% Plot all cells and unclustered
for j=0:obj.nr_cells
% Plot ydata in µv
ydata = squeeze(obj.data(i,:,indexer{j+1}).*obj.settings.ADBitVolts(i))*10^6;
% In the special case that there is only one waveform, make
% sure that Y is still oriented in the right way
if sum(indexer{j+1})==1
ydata = ydata';
end
if plot_average
stdev_y = std(ydata');
ydata = mean(ydata,2);
% Plot the stdev shadow
fill([timeline', flipud(timeline)'], [ydata'-stdev_y, fliplr(ydata'+stdev_y)],[1 0 0],...
'FaceColor',colorlist(j+1),...
'linestyle','none',...
'FaceAlpha',0.1)
hold on
end
% Grab the Xdata in µs
xdata = repmat(timeline,1, size(ydata,2),1);
% Convert the data for faster performance
xdata = [xdata; nan(1,size(xdata,2))];
xdata = xdata(:);
ydata = [ydata; nan(1,size(ydata,2))];
ydata = ydata(:);
% Plot the data
plot(xdata, ydata, 'Color',colorlist(j+1),...
'DisplayName',dataname{j+1});
hold on
end
% Labels and titles
ylabel('Voltage (µv)')
xlabel('Time (µs)')
title(['Electrode ' num2str(i)]);
% Set the y_axis to the input range if that is requested
if y_axis_is_input_range
ylim([-obj.settings.InputRange(i) obj.settings.InputRange(i)])
end
% Plot the threshold line
hold on
line(get(gca,'XLim'), [obj.settings.ThresVal(i), obj.settings.ThresVal(i)],...
'Color',[0.2 0.2 0.2],...
'LineStyle','--',...
'DisplayName','Threshold');
end
end
function [waveform_figure, histogram_figure] = show_cell(obj, cell_number, varargin)
%SHOW_CELL Presents the waveform of one cell on 4 electrodes
% Work on the flag
plot_average = false;
hypothetical_cell = false;
disp_fraction = 1;
for i = 1:length(varargin)
switch varargin{i}
% Skip this argument
case 'skipp'
hoihoi = 5;
% We will plot the average and stdev instead of all
% waveforms
case 'average'
plot_average = true;
% Plot a hypothetical cell, not an identified cluster
case 'hypothetical'
hypothetical_cell = true;
% Plot only a fraction of the waveforms
case 'fraction'
disp_fraction = varargin{i+1};
varargin{i+1} = 'skipp';
otherwise
error('Unknown Argument')
end
end
% Real unit or a hypothetical?
if ~ hypothetical_cell
% Does this cell exist?
if cell_number>obj.nr_cells
disp(['This cell does not exist, there are/is only ' num2str(obj.nr_cells) ' cell(s) in this dataset.'])
return;
end
% Make indexer for this cell
if ~isnan(cell_number)
indexer = obj.cells==cell_number;
else % user put NaN, and want's all traces
indexer = ~isnan(obj.cells); %nan cells are noise
end
else
indexer = cell_number;
cell_number = 0;
end
% If there are to many waveforms we will plot only 5% of them
% to maintain performance
cutoff = obj.settings.disp_cutoff;
original_indexer = indexer; % To be used for histogram for instance
if sum(indexer)>cutoff && disp_fraction == 1
disp_fraction = 0.05;
disp(['Showing only 5% (n = ' num2str(sum(indexer==1)*disp_fraction) ') of all waveforms.'])
end
% If the disp_fraction is >1, set it to 1
if disp_fraction>1; disp_fraction=1; end
% This is to plot only a certain fraction of all waveforms,
% either because there are more waveforms than the cutoff or
% because the user specifically requested it.
new_indexer = zeros(size(indexer));
sample = randsample([1:length(indexer)], round(length(indexer)*disp_fraction));
new_indexer(sample) = indexer(sample);
indexer = logical(new_indexer);
% How to name the figure
if isnan(cell_number)
figure_name = 'All Waveforms';
elseif cell_number==0
figure_name = 'Unclustered';
else
figure_name = ['Cell ' num2str(cell_number)];
end
% Work on the xaxis
interval = 10^6/obj.raw_data.hdr.SamplingFrequency; %µs
timeline = [0:interval:1000-interval]';
% Figure out the cell color
cell_color = obj.settings.colorlist(cell_number+1);
% Make a figure and plot the waveforms
waveform_figure = figure('Name',figure_name,...
'Position',[232, 300, 800, 600]);
for i=1:4
subplot(2,2,i)
ydata = squeeze(obj.data(i,:,indexer)).*obj.settings.ADBitVolts(i)*10^6; % Data from bitvalues to µV
% In the special case that there is only one waveform, make
% sure that Y is still oriented in the right way
if sum(indexer)==1
ydata = ydata';
end
% Plot average instead of all sweeps?
if plot_average
stdev_y = std(ydata');
ydata = mean(ydata,2);
% Plot the stdev shadow
fill([timeline', flipud(timeline)'], [ydata'-stdev_y, fliplr(ydata'+stdev_y)],[1 0 0],...
'FaceColor',cell_color,...
'linestyle','none',...
'FaceAlpha',0.1)
hold on
end
% Plot the data
xdata = repmat(timeline,1, size(ydata,2),1); % Timeline in µs
% Convert the data for faster performance
xdata = [xdata; nan(1,size(xdata,2))];
xdata = xdata(:);
ydata = [ydata; nan(1,size(ydata,2))];
ydata = ydata(:);
% Plot the data
plot(xdata, ydata, 'Color', cell_color);
hold on
xlabel('Time (µs)')
ylabel('Voltage (µv)')
%ylim([-obj.settings.InputRange(i) obj.settings.InputRange(i)])
title(['Electrode ' num2str(i)]);
% Plot the threshold line
line(get(gca,'XLim'), [obj.settings.ThresVal(i), obj.settings.ThresVal(i)],...
'Color',[0.2 0.2 0.2],...
'LineStyle','--');
end
% IMPORTANT NOTE: all analysis bellow this point should be done
% using the original_indexer. The 'indexer' is only used for
% display purpouses.
% Work on the inter-spike histogram
histogram_figure = figure('Name','cluster data',...
'Position',[1033 300, 800, 600]);
m_timestamps = obj.timestamps(original_indexer);
intervals = double(m_timestamps(2:end)-m_timestamps(1:end-1));
subplot(2,2,1);
histogram(intervals,5000);
set(gca,'XScale','log')
xlabel('Interval (µs)')
ylabel('Count #')
title('ISI')
grab_lim = xlim();
xlim([10^2 grab_lim(2)]);
line([1000 1000],ylim(),'Color',[1 0 0])
% Plot the waveform count throughout the session (to check if
% stable firing or appearing/disappearing througout the session.
subplot(2,2,2);
session_time = obj.settings.recording_interval;
m_timestamps = double(m_timestamps - session_time(1)).*10^-6;
session_time = double(session_time - session_time(1)).*10^-6;
histogram(m_timestamps, 100)
xlim(session_time)
xlabel('Time (s)')
ylabel('Count #')
title('Firing Distribution')
% Calculate the Mahalanobis distance between the center of this
% cluster and every other spike and compare this to every other
% spike in the tetrode object for good measure.
start_index = obj.settings.interval(1);
end_index = obj.settings.interval(2);
ydata = [];
for i=1:4
% don't include broken electrodes
if ~obj.settings.working_electrodes(i)
continue;
end
% grab all the ydata
ydata_temp = squeeze(obj.data(i,start_index:end_index,:)).*obj.settings.ADBitVolts(i)*10^6; % Data from bitvalues to µV
ydata = [ydata, ydata_temp']; % Matlab Mahalanobis function wants n x m.
end
% If there are enough sweeps we can plot the Mahalanobis
% distance
if size(ydata(original_indexer,:),1)>size(ydata(original_indexer,:),2)
% Calculate Mahalanobis distance
d2 = mahal(ydata, ydata(original_indexer,:));
d2_cell = d2(original_indexer);
d2_not_cell = d2(~original_indexer(:) & ~isnan(obj.cells(:)));
d2_including_noise = d2(~original_indexer);
% We have to trow out outliers because otherwise the histograms
% are just un-interpetable. Note that we don't do this for the
% d2_cell, because in that case the hole point is that we want
% to see the outliers
d2_not_cell = d2_not_cell(~isoutlier(d2_not_cell));
d2_including_noise = d2_including_noise(~isoutlier(d2_including_noise));
% Plot the histograms
subplot(2,2,3);
h1 = histogram(d2_cell,...
'Normalization','probability',...
'DisplayName','Selected Unit');
hold on
h2 = histogram(d2_not_cell,...
'Normalization','probability',...
'DisplayName','Other Waveforms');
h3 = histogram(d2_including_noise,...
'Normalization','probability',...
'DisplayName','Other Including Removed Waveforms');
try
xlim([0 max([mean(d2_cell)+3*std(d2_cell),...
mean(d2_not_cell)+3*std(d2_not_cell),...
mean(d2_including_noise)+3*std(d2_including_noise)])])
catch
warning('Unable to plot Mahalanobix histogram.')
end
xlabel('Mahalanobis distance')
ylabel('probability')
legend();
title('Distance from unit')
% Figure out which one has the smaller binsize and make
% them similar
binWidth = min([h1.BinWidth, h2.BinWidth, h3.BinWidth]);
h1.BinWidth = binWidth;
h2.BinWidth = binWidth;
h3.BinWidth = binWidth;
end
% And finally, we also plot peak hight througout the
% session for every electrode.
subplot(2,2,4)
%smooth_factor = round(0.05 * sum(original_indexer));
for i=1:4
plot(m_timestamps, obj.attributes(i).peak(original_indexer),'.',...
'DisplayName',['Electrode ' num2str(i)])
hold on
end
xlim(session_time)
xlabel('Time (s)')
ylabel('Peak (µV)')
title(['Peak Stability'])
legend();
end
function [plot_handle, results] = peri_event(obj, stamps, varargin)
% PERI_EVENT_PLOT_STAMPS present a peri-event plot of events
% stamps. The stamps that will be used as the '0' timepoint are
% in the variable 'stamps' (1D). All clusters as well as
% non-clustered events will be ploted in different colors, they
% are in the 3rd dimension in the results output.
%
% By default the nr of bins is 50 (bin width is dynamic) but
% the nr of bins can be reset with the 'bins' arguments.
%
% Results is organized as follows: (trials, time bins, data
% sets); There is a TIMELINE in the top row!
%
% Note that the stamps should the in the same unit of time
% (e.g. us) as the data in the tetrode object.
% Error handeling
% TO DO...
% CHECK IF DOUBLE AND UINT64 IS REALLY THE SAME
% Deal with input arguments
window = []; % Plot window
cell_nr = []; % Cells to be analysed
nr_bins = 50; % Number of bins
graph_bars = false; % Showing mean +/- SEM, not bars
for i = 1:length(varargin)
switch varargin{i}
% Skipp this argument
case 'skipp'
skippy = 5;
% Set the windowsize
case 'window'
window = varargin{i+1};
disp(['Window set to ' num2str(window) 'µs.'])
varargin{i+1} = 'skipp';
% Set number of bins
case 'bins'
nr_bins = varargin{i+1};
disp(['Data sorted in ' num2str(nr_bins) 'bins.'])
varargin{i+1} = 'skipp';
% Only a specific cell
case 'cell'
cell_nr = varargin{i+1};
if ~isempty(cell_nr)
disp(['Only plotting cell ' num2str(cell_nr)]);
else
disp(['Plotting all cells.'])
end
varargin{i+1} = 'skipp';
% Plot bars instead of mean +/- SEM
case 'bars'
graph_bars = true;
otherwise
warning('Unknown argument,... ignored.')
end
end
% Colorlist for the markers
temp_colorlist = obj.settings.colorlist;
% check the input arguments
if strcmp(class(stamps),'uint64')
stamps = double(stamps);
end
% Collect the data to be plotted and also figure out the
% correct color for each cell.
if isempty(cell_nr) % Do all cells
cell_nr = [0:obj.nr_cells];
end
units = cell(length(cell_nr), 1);
for i = 1:length(cell_nr)
units{i} = double(obj.timestamps(obj.cells==cell_nr(i)));
colorlist(i) = temp_colorlist(cell_nr(i) + 1);
end
% Error handeling on the intervals. Note that intervals 1000µs
% are just probably some sort of error, but we should put out a
% warning.
intervals = stamps(2:end) - stamps(1:end-1);
error_intervals = [intervals<1000, false];
if sum(error_intervals)>0
warning('Intervals <1000µs between stamps not analyzed.')
stamps = stamps(~error_intervals);
end
intervals = stamps(2:end) - stamps(1:end-1);
% Figure out the appropriate window size
if isempty(window)
% Find the smallest inter-stamp interval
window = round(0.5*(min(intervals)));
end
% Print the window size
disp(['Window set to ' num2str(window) 'µs'])
% Figure out an appropriate bin size for the histogram
bin_size = 2*window/nr_bins;
timeline = round([-window:bin_size:window-bin_size]+0.5*bin_size,2);
% Make the figure
plot_handle = figure;
subplot(2,1,1)
% Make an empty results variable
results = zeros(length(stamps) + 1, nr_bins, length(units));
% for every dataset
for i = 1:length(units)
% Add the timeline in the first row of the results
results(1,:,i) = timeline;
% for every trial
% Start at row 2 because timeline in row 1
for j = 2:length(stamps) + 1
% Substract the trial from the input data to get the
% difference
temp_data = units{i} - stamps(j-1);
temp_data = temp_data(temp_data>-1*window & temp_data<window);
% for every bin
for k = 1:length(timeline)
% Collect results
% note the biger-or-equal on one side, vs smaller
% on the other side
results(j,k,i) = sum(temp_data>=timeline(k)-0.5*bin_size & temp_data<timeline(k)+0.5*bin_size);
end
% Plot the events
super_temp = temp_data(temp_data>= -window & temp_data< window);
plot(super_temp,ones(length(super_temp),1)*(j-1),'.',...
'MarkerEdgeColor',colorlist(i),...
'MarkerFaceColor',colorlist(i),...
'Marker','square',...
'MarkerSize', 3);