-
Notifications
You must be signed in to change notification settings - Fork 58
/
ProcessCellMetrics.m
1667 lines (1485 loc) · 91.2 KB
/
ProcessCellMetrics.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 cell_metrics = ProcessCellMetrics(varargin)
% This function calculates cell metrics for a given recording/session
% Most metrics are single value per cell, either numeric or string type, but
% certain metrics are vectors like the autocorrelograms or cell with double content like waveforms.
% The metrics are based on a number of features: spikes, waveforms, PCA features,
% the ACG and CCGs, LFP, theta, ripples and so fourth
%
% Check the website of CellExplorer for more details: https://cellexplorer.org/
%
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% INPUTS
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
%
% varargin (Variable-length input argument list; see below)
%
% - Parameters defining the session to process -
% basepath - 1. Path to session (base directory)
% sessionName - 3. Database sessionName
% sessionID - 4. Database numeric id
% session - 5. Session struct. Must contain a basepath
%
% - Parameters for the processing - parameters.*
% showGUI - Show GUI dialog to adjust settings/parameters
% metrics - Metrics that will be calculated. A cell with strings
% Examples: 'waveform_metrics','PCA_features','acg_metrics','deepSuperficial',
% 'monoSynaptic_connections','theta_metrics','spatial_metrics',
% 'event_metrics','manipulation_metrics', 'state_metrics','psth_metrics'
% Default: 'all'
% excludeMetrics - Metrics to exclude. Default: 'none'
% removeMetrics - Metrics to remove (supports only deepSuperficial at this point)
% keepCellClassification - logical. Keep existing cell type classifications
% includeInhibitoryConnections - logical. Determines if inhibitory connections are included in the detection of synaptic connections
% manualAdjustMonoSyn - logical. Manually validate monosynaptic connections in the pipeline (requires user input)
% restrictToIntervals - time intervals to restrict the analysis to (in seconds)
% excludeIntervals - time intervals to exclude (in seconds)
% excludeManipulationIntervals - logical. Exclude time intervals around manipulations (loads *.manipulation.mat files and excludes defined manipulation intervals)
% ignoreEventTypes - exclude .events files of specific types
% ignoreManipulationTypes- exclude .manipulations files of specific types
% ignoreStateTypes - exclude .states files of specific types
% showGUI - logical. Show a GUI that allows you to adjust the input parameters/settings
% forceReload - logical. Recalculate existing metrics
% forceReloadSpikes - logical. Reloads spikes and other cellinfo structs
% submitToDatabase - logical. Submit cell metrics to database
% saveMat - logical. Save metrics to cell_metrics.mat
% saveAs - name of .mat file
% saveBackup - logical. Whether a backup of existing metrics should be created
%
% summaryFigures - logical. Plot a summary figure for each cell
% sessionSummaryFigure - logical. Plot summary figure for the whole session
% showFigures - logical. if false, turns off plots from different stages of the processing
% showWaveforms - logical. Shows waveform extraction (turn off to speed up the processing)
%
% debugMode - logical. Activate a debug mode avoiding try/catch
% transferFilesFromClusterpath - logical. Moves previosly generated files from clusteringpath to basepath (new file structure)
%
% - Example calls:
% cell_metrics = ProcessCellMetrics % Load from current path, assumed to be a basepath
% cell_metrics = ProcessCellMetrics('session',session) % Load session from session struct
% cell_metrics = ProcessCellMetrics('basepath',basepath) % Load from basepath
% cell_metrics = ProcessCellMetrics('basepath',basepath,'includeInhibitoryConnections',true) % Load from basepath
% cell_metrics = ProcessCellMetrics('basepath',basepath,'metrics',{'waveform_metrics'}) % Load from basepath
%
% cell_metrics = ProcessCellMetrics('sessionName','rec1') % Load session from database session name
% cell_metrics = ProcessCellMetrics('sessionID',10985) % Load session from database session id
%
% cell_metrics = ProcessCellMetrics('session', session,'fileFormat','nwb','showGUI',true); % saves cell_metrics to a nwb file
%
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% OUTPUT
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
%
% cell_metrics : structure described in details at: https://cellexplorer.org/datastructure/standard-cell-metrics/
% By Peter Petersen
% Last edited: 27-02-2021
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Parsing parameters
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
p = inputParser;
addParameter(p,'sessionID',[],@isnumeric);
addParameter(p,'sessionName',[],@isstr);
addParameter(p,'session',[],@isstruct);
addParameter(p,'spikes',[],@isstruct);
addParameter(p,'basepath',pwd,@isstr);
addParameter(p,'metrics','all',@iscellstr);
addParameter(p,'excludeMetrics',{'none'},@iscellstr);
addParameter(p,'removeMetrics',{'none'},@isstr);
addParameter(p,'restrictToIntervals',[],@isnumeric);
addParameter(p,'excludeIntervals',[],@isnumeric);
addParameter(p,'ignoreEventTypes',{'MergePoints'},@iscell);
addParameter(p,'ignoreManipulationTypes',{'cooling'},@iscell);
addParameter(p,'ignoreStateTypes',{'StateToIgnore'},@iscell);
addParameter(p,'excludeManipulationIntervals',true,@islogical);
addParameter(p,'metricsToExcludeManipulationIntervals',{'waveform_metrics','PCA_features','acg_metrics','monoSynaptic_connections','theta_metrics','spatial_metrics','event_metrics','psth_metrics'},@iscell);
addParameter(p,'keepCellClassification',true,@islogical);
addParameter(p,'manualAdjustMonoSyn',true,@islogical);
addParameter(p,'getWaveformsFromDat',true,@islogical);
addParameter(p,'includeInhibitoryConnections',false,@islogical);
addParameter(p,'showGUI',false,@islogical);
addParameter(p,'forceReload',false,@islogical);
addParameter(p,'forceReloadSpikes',false,@islogical);
addParameter(p,'submitToDatabase',false,@islogical);
addParameter(p,'saveMat',true,@islogical);
addParameter(p,'saveAs','cell_metrics',@isstr);
addParameter(p,'saveBackup',true,@islogical);
addParameter(p,'fileFormat','mat',@isstr);
addParameter(p,'transferFilesFromClusterpath',true,@islogical);
% Plot related parameters
addParameter(p,'showFigures',false,@islogical);
addParameter(p,'showWaveforms',true,@islogical);
addParameter(p,'summaryFigures',false,@islogical);
addParameter(p,'sessionSummaryFigure',true,@islogical);
addParameter(p,'debugMode',false,@islogical);
parse(p,varargin{:})
sessionID = p.Results.sessionID;
sessionin = p.Results.sessionName;
sessionStruct = p.Results.session;
basepath = p.Results.basepath;
parameters = p.Results;
timerCalcMetrics = tic;
% Verifying required toolboxes are installed
installedToolboxes = ver;
installedToolboxes = {installedToolboxes.Name};
requiredToolboxes = {'Curve Fitting Toolbox','Signal Processing Toolbox','Statistics and Machine Learning Toolbox'};
missingToolboxes = requiredToolboxes(~ismember(requiredToolboxes,installedToolboxes));
if ~isempty(missingToolboxes)
for i = 1:numel(missingToolboxes)
warning(['A toolbox required by CellExplorer must be installed: ' missingToolboxes{i}]);
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Loading session metadata from DB or sessionStruct
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if ~isempty(sessionID)
[session, basename, basepath] = db_set_session('sessionId',sessionID);
elseif ~isempty(sessionin)
[session, basename, basepath] = db_set_session('sessionName',sessionin);
elseif ~isempty(sessionStruct)
if isfield(sessionStruct.general,'basePath')
session = sessionStruct;
basename = session.general.name;
basepath = session.general.basePath;
else
[session, basename, basepath] = db_set_session('session',sessionStruct);
if isempty(session.general.entryID)
session.general.entryID = ''; % DB id
end
if isempty(session.spikeSorting{1}.entryID)
session.spikeSorting{1}.entryID = ''; % DB id
end
end
end
% If no session struct is provided it will look for a basename.session.mat file in the basepath and otherwise load the sessionTemplate and show the GUI gui_session
if ~exist('session','var')
basename = basenameFromBasepath(basepath);
if exist(fullfile(basepath,[basename,'.session.mat']),'file')
dispLog(['Loading ',basename,'.session.mat from basepath'],basename);
load(fullfile(basepath,[basename,'.session.mat']),'session');
session.general.basePath = basepath;
elseif exist(fullfile(basepath,'session.mat'),'file')
dispLog('Loading session.mat from basepath',basename);
load(fullfile(basepath,'session.mat'),'session');
session.general.basePath = basepath;
else
cd(basepath)
session = sessionTemplate(basepath);
parameters.showGUI = true;
end
end
% If no arguments are given, the GUI is shown
if nargin==0
parameters.showGUI = true;
end
% Loading preferences
preferences = preferences_ProcessCellMetrics(session);
% Validating format of electrode groups and spike groups (must be of type cell)
if isfield(session.extracellular,'spikeGroups') && isfield(session.extracellular.spikeGroups,'channels') && isnumeric(session.extracellular.spikeGroups.channels)
session.extracellular.spikeGroups.channels = num2cell(session.extracellular.spikeGroups.channels,2);
end
if isfield(session.extracellular,'electrodeGroups') && isfield(session.extracellular.electrodeGroups,'channels') && isnumeric(session.extracellular.electrodeGroups.channels)
session.extracellular.electrodeGroups.channels = num2cell(session.extracellular.electrodeGroups.channels,2)';
end
% Non-standard parameters: vertical spacing and layout
if (~isfield(session,'extracellular') || ~isfield(session.extracellular,'chanCoords') || ~isfield(session.extracellular.chanCoords,'verticalSpacing'))
session.extracellular.chanCoords.verticalSpacing = preferences.general.probesVerticalSpacing;
disp(' Using vertical spacing from preferences')
end
if (~isfield(session,'extracellular') || ~isfield(session.extracellular,'chanCoords') || ~isfield(session.extracellular.chanCoords,'layout'))
session.extracellular.chanCoords.layout = preferences.general.probesLayout;
disp(' Using layout from preferences')
end
if ~isfield(session,'extracellular') || ~isfield(session.extracellular,'electrodeGroups') || ~isfield(session.extracellular.electrodeGroups,'channels') || isempty([session.extracellular.electrodeGroups.channels{:}])
if isfield(session.extracellular,'spikeGroups')
warning('No electrode group has been defined. Copied from spike groups')
session.extracellular.electrodeGroups = session.extracellular.spikeGroups;
session.extracellular.nElectrodeGroups = session.extracellular.nSpikeGroups;
end
end
% Validating that electrode groups and spike groups are 1-indexed
if any([session.extracellular.electrodeGroups.channels{:}]==0)
error('session.extracellular.electrodeGroups.channels contains 0. Must be 1-indexed')
elseif any([session.extracellular.spikeGroups.channels{:}]==0)
error('session.extracellular.spikeGroups.channels contains 0. Must be 1-indexed')
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% showGUI
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if parameters.showGUI
session.general.basePath = basepath;
parameters.preferences = preferences;
[session,parameters,status] = gui_session(session,parameters);
if status==0
dispLog('Cell metrics processing canceled by user',basename)
return
end
basename = session.general.name;
basepath = session.general.basePath;
preferences.putativeCellType.classification_schema = parameters.preferences.putativeCellType.classification_schema;
cd(basepath)
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Moving files generated by CellExplorer (basename.*.mat) from relative spike sorting path (clusteringpath) to the basepath
% Previous version of CellExplorer would save cell_metrics and cellinfo derived files in the clusteringpath
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if parameters.transferFilesFromClusterpath && isfield(session,'spikeSorting') && ~isempty(session.spikeSorting{1}.relativePath)
fileList = dir(fullfile(basepath,session.spikeSorting{1}.relativePath,[basename, '.*.mat']));
fileListClusterpath = {fileList.name};
fileList = dir(fullfile(basepath,[basename, '.*.mat']));
fileListBasepath = {fileList.name};
[fileListToMove,~] = setdiff(fileListClusterpath,fileListBasepath);
if numel(fileListToMove)>0
disp('Moving files from cluster folder to basepath')
for i = 1:numel(fileListToMove)
disp([num2str(i) ,'. transfer: ', fileListToMove{i}]);
movefile(fullfile(basepath,session.spikeSorting{1}.relativePath,fileListToMove{i}),fullfile(basepath,fileListToMove{i}));
end
disp(['File transfer complete (', num2str(numel(fileListToMove)),' files)'])
end
DuplicatedfileList = fileListClusterpath(ismember(fileListClusterpath,fileListBasepath));
if ~isempty(DuplicatedfileList)
warning(['Files existing in both directories are not transferred. Please verify these files should not be transferred: ' DuplicatedfileList{:}])
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Getting spikes - excluding user specified- and manipulation intervals
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
sr = session.extracellular.sr;
if ~isempty(parameters.spikes)
dispLog('Using spikes provided as input',basename)
spikes{1} = parameters.spikes;
parameters.spikes = [];
else
dispLog('Getting spikes',basename)
spikes{1} = loadSpikes('session',session,'labelsToRead',preferences.loadSpikes.labelsToRead,'getWaveformsFromDat',parameters.getWaveformsFromDat,'showWaveforms',parameters.showWaveforms);
end
if parameters.getWaveformsFromDat && (~isfield(spikes{1},'processinginfo') || ~isfield(spikes{1}.processinginfo.params,'WaveformsSource') || ~strcmp(spikes{1}.processinginfo.params.WaveformsSource,'dat file') || spikes{1}.processinginfo.version<3.5 || parameters.forceReloadSpikes == true)
spikes{1} = loadSpikes('forceReload',true,'spikes',spikes{1},'session',session,'labelsToRead',preferences.loadSpikes.labelsToRead,'showWaveforms',parameters.showWaveforms);
end
spikes{1}.numcells = length(spikes{1}.times);
if ~isfield(spikes{1},'total')
spikes{1}.total = cellfun(@(X) length(X),spikes{1}.times);
end
if ~isfield(spikes{1},'spindices')
spikes{1}.spindices = generateSpinDices(spikes{1}.times);
end
if ~isfield(spikes{1},'cluID')
disp('Generating cluIDs from UIDs')
spikes{1}.cluID = spikes{1}.UID;
end
if ~isempty(parameters.restrictToIntervals)
if size(parameters.restrictToIntervals,2) ~= 2
error('restrictToIntervals has to be a Nx2 matrix')
else
dispLog('Restricting analysis to provided intervals',basename)
spikes_indices = cellfun(@(X) ce_InIntervals(X,double(parameters.restrictToIntervals)),spikes{1}.times,'UniformOutput',false);
spikes{1}.times = cellfun(@(X,Y) X(Y),spikes{1}.times,spikes_indices,'UniformOutput',false);
if isfield(spikes{1},'ts')
spikes{1}.ts = cellfun(@(X,Y) X(Y),spikes{1}.ts,spikes_indices,'UniformOutput',false);
end
if isfield(spikes{1},'ids')
spikes{1}.ids = cellfun(@(X,Y) X(Y),spikes{1}.ids,spikes_indices,'UniformOutput',false);
end
if isfield(spikes{1},'amplitudes')
spikes{1}.amplitudes = cellfun(@(X,Y) X(Y),spikes{1}.amplitudes,spikes_indices,'UniformOutput',false);
end
% Removing empty units from structure
unitsToRemove = find(cellfun(@isempty,spikes{1}.times));
fieldsToProcess = fieldnames(spikes{1});
fieldsToProcess = fieldsToProcess(structfun(@(X) (isnumeric(X) || iscell(X)) && numel(X)==numel(spikes{1}.times),spikes{1}));
for iField = 1:numel(fieldsToProcess)
spikes{1}.(fieldsToProcess{iField})(unitsToRemove) = [];
end
spikes{1}.total = cell2mat(cellfun(@(X,Y) length(X),spikes{1}.times,'UniformOutput',false));
spikes{1}.numcells = numel(spikes{1}.times);
if isempty(spikes{1}.total)
error(['CellExplorer: No spikes in the specified interval (' num2str(parameters.restrictToIntervals(1)) ,' - ', num2str(parameters.restrictToIntervals(2)),')'])
end
spikes{1}.spindices = generateSpinDices(spikes{1}.times);
end
end
if parameters.excludeManipulationIntervals
manipulationFiles = dir(fullfile(basepath,[basename,'.*.manipulation.mat']));
manipulationFiles = {manipulationFiles.name};
manipulationFiles(find(contains(manipulationFiles,parameters.ignoreManipulationTypes)))=[];
if ~isempty(manipulationFiles)
dispLog('Excluding manipulation events',basename)
for iEvents = 1:length(manipulationFiles)
eventName = strsplit(manipulationFiles{iEvents},'.');
eventName = eventName{end-2};
eventOut = load(fullfile(basepath,manipulationFiles{iEvents}));
if size(eventOut.(eventName).timestamps,2) == 2
disp([' Excluding manipulation type: ' eventName])
parameters.excludeIntervals = [parameters.excludeIntervals;eventOut.(eventName).timestamps];
else
warning('manipulation timestamps has to be a Nx2 matrix')
end
end
end
end
if ~isempty(parameters.excludeIntervals)
% Checks if intervals are formatted correctly
if size(parameters.excludeIntervals,2) ~= 2
error('excludeIntervals has to be a Nx2 matrix')
else
disp([' Excluding ',num2str(size(parameters.excludeIntervals,1)),' intervals in spikes (' num2str(sum(diff(parameters.excludeIntervals'))),' seconds)'])
spikes{2} = spikes{1};
spikes_indices = cellfun(@(X) ~ce_InIntervals(X,double(parameters.excludeIntervals)),spikes{1}.times,'UniformOutput',false);
spikes{2}.times = cellfun(@(X,Y) X(Y),spikes{1}.times,spikes_indices,'UniformOutput',false);
if isfield(spikes{1},'ts')
try
spikes{2}.ts = cellfun(@(X,Y) X(Y),spikes{1}.ts,spikes_indices,'UniformOutput',false);
end
end
if isfield(spikes{1},'ids')
spikes{2}.ids = cellfun(@(X,Y) X(Y),spikes{1}.ids,spikes_indices,'UniformOutput',false);
end
if isfield(spikes{1},'amplitudes')
spikes{2}.amplitudes = cellfun(@(X,Y) X(Y),spikes{1}.amplitudes,spikes_indices,'UniformOutput',false);
end
spikes{2}.total = cell2mat(cellfun(@(X,Y) length(X),spikes{2}.times,'UniformOutput',false));
spikes{2}.spindices = generateSpinDices(spikes{2}.times);
end
else
parameters.metricsToExcludeManipulationIntervals = {'none'};
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Initializing cell_metrics struct
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
saveAsFullfile = fullfile(basepath,[basename,'.',parameters.saveAs,'.cellinfo.',parameters.fileFormat]);
if exist(saveAsFullfile,'file') && ~parameters.forceReload
dispLog(['Loading existing metrics: ' saveAsFullfile],basename)
load(saveAsFullfile)
elseif exist(fullfile(basepath,[parameters.saveAs,'.',parameters.fileFormat]),'file') && ~parameters.forceReload
% For legacy naming convention
warning(['Loading existing legacy metrics: ' parameters.saveAs])
load(fullfile(basepath,[parameters.saveAs,'.mat']))
else
cell_metrics = [];
end
% Importing fields from spikes struct to cell_metrics
spikes_fields = fieldnames(spikes{1});
spikes_fields = setdiff(spikes_fields,{'times','ts','rawWaveform','filtWaveform', 'rawWaveform_all', 'rawWaveform_std', 'filtWaveform_all', 'filtWaveform_std', 'timeWaveform', 'timeWaveform_all', 'channels_all', 'peakVoltage_sorted', 'maxWaveform_all', 'peakVoltage_expFitLengthConstant', 'processinginfo', 'numcells', 'UID', 'sessionName'});
spikes_type = structfun(@(X) (iscell(X) || isnumeric(X)) && all(size(X) == [1,spikes{1}.numcells]), spikes{1},'uni',0);
for j = 1:numel(spikes_fields)
if spikes_type.(spikes_fields{j}) && iscell(spikes{1}.(spikes_fields{j})) && all(cellfun(@ischar, spikes{1}.(spikes_fields{j})))
cell_metrics.(spikes_fields{j}) = spikes{1}.(spikes_fields{j});
elseif spikes_type.(spikes_fields{j}) && isnumeric(spikes{1}.(spikes_fields{j}))
cell_metrics.(spikes_fields{j}) = spikes{1}.(spikes_fields{j});
end
end
if parameters.saveBackup && ~isempty(cell_metrics)
% Creating backup of existing user adjustable metrics
backupDirectory = 'revisions_cell_metrics';
% dispLog(['Creating backup of existing user adjustable metrics in subfolder ''',backupDirectory,''''],basename);
backupFields = {'labels','tags','deepSuperficial','deepSuperficialDistance','brainRegion','putativeCellType','groundTruthClassification','groups'};
temp = {};
for i = 1:length(backupFields)
if isfield(cell_metrics,backupFields{i})
temp.cell_metrics.(backupFields{i}) = cell_metrics.(backupFields{i});
end
end
if isfield(temp,'cell_metrics')
try
if ~(exist(fullfile(basepath,backupDirectory),'dir'))
mkdir(fullfile(basepath,backupDirectory));
end
save(fullfile(basepath, backupDirectory, [parameters.saveAs, '_',datestr(clock,'yyyy-mm-dd_HHMMSS'), '.mat',]),'cell_metrics','-struct', 'temp')
catch
warning('Failed to save backup data in the CellExplorer pipeline')
end
end
end
cell_metrics.general.basepath = basepath;
cell_metrics.general.basename = basename;
cell_metrics.general.cellCount = numel(spikes{1}.times);
cell_metrics.general.saveAs = parameters.saveAs;
% Saving spike times to metrics
cell_metrics.spikes.times = spikes{1}.times;
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Waveform based calculations
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if any(contains(parameters.metrics,{'waveform_metrics','all'})) && ~any(contains(parameters.excludeMetrics,{'waveform_metrics'}))
spkExclu = setSpkExclu('waveform_metrics',parameters);
bad_channels = get_bad_channels(session);
if isempty(bad_channels)
good_channels = 1:session.extracellular.nChannels;
else
good_channels = setdiff(1:session.extracellular.nChannels,bad_channels);
end
if ~all(isfield(cell_metrics,{'waveforms','peakVoltage','troughToPeak','troughtoPeakDerivative','ab_ratio'})) || ~all(isfield(cell_metrics.waveforms,{'filt','filt_all'})) || parameters.forceReload == true
dispLog('Getting waveforms',basename);
field2copy = {'filtWaveform_std','rawWaveform','rawWaveform_std','rawWaveform_all','filtWaveform_all','timeWaveform_all','channels_all','filtWaveform','timeWaveform'};
field2copyNewNames = {'filt_std','raw','raw_std','raw_all','filt_all','time_all','channels_all','filt','time'};
if parameters.getWaveformsFromDat && (any(~isfield(spikes{spkExclu},field2copy)) || parameters.forceReload == true) && (spkExclu==2 || ~isempty(parameters.restrictToIntervals))
spikes{spkExclu} = getWaveformsFromDat(spikes{spkExclu},session,'showWaveforms',parameters.showWaveforms);
end
if isfield(spikes{spkExclu},'peakVoltage')
cell_metrics.peakVoltage = spikes{spkExclu}.peakVoltage;
else
cell_metrics.peakVoltage = nan(size(spikes{spkExclu}.times));
end
if isfield(spikes{spkExclu},'peakVoltage_expFitLengthConstant')
cell_metrics.peakVoltage_expFitLengthConstant = spikes{spkExclu}.peakVoltage_expFitLengthConstant(:)';
end
for j = 1:numel(field2copy)
if isfield(spikes{spkExclu},field2copy{j})
cell_metrics.waveforms.(field2copyNewNames{j}) = spikes{spkExclu}.(field2copy{j});
end
end
if isfield(spikes{spkExclu},'maxWaveform_all')
for j = 1:cell_metrics.general.cellCount
if numel(spikes{spkExclu}.maxWaveform_all)>=j && ~isempty(spikes{spkExclu}.maxWaveform_all{j})
nChannelFit = min([preferences.waveform.trilat_nChannels,length(spikes{spkExclu}.maxWaveform_all{j}),length(session.extracellular.electrodeGroups.channels{spikes{spkExclu}.shankID(j)})]);
cell_metrics.waveforms.bestChannels{j} = spikes{spkExclu}.maxWaveform_all{j}(1:nChannelFit);
else
cell_metrics.waveforms.bestChannels{j} = [];
end
end
end
if isfield(spikes{spkExclu},'filtWaveform_all')
for j = 1:cell_metrics.general.cellCount
cell_metrics.waveforms.peakVoltage_all{j} = nan(1,session.extracellular.nChannels);
cell_metrics.waveforms.peakVoltage_all{j}(good_channels) = range(spikes{spkExclu}.filtWaveform_all{j}(good_channels,:),2);
end
end
dispLog('Calculating waveform metrics',basename);
waveform_metrics = calc_waveform_metrics(spikes{spkExclu},sr,'showFigures',parameters.showFigures);
cell_metrics.troughToPeak = waveform_metrics.troughtoPeak;
cell_metrics.troughtoPeakDerivative = waveform_metrics.derivative_TroughtoPeak;
cell_metrics.ab_ratio = waveform_metrics.ab_ratio;
cell_metrics.polarity = waveform_metrics.polarity;
% Removing outdated fields
field2remove = {'derivative_TroughtoPeak','filtWaveform','filtWaveform_std','rawWaveform','rawWaveform_std','timeWaveform'};
test = isfield(cell_metrics,field2remove);
cell_metrics = rmfield(cell_metrics,field2remove(test));
end
% Channel coordinates map, trilateration and length constant determined from waveforms across channels
if ~all(isfield(cell_metrics,{'trilat_x','trilat_y','peakVoltage_expFit'})) || parameters.forceReload == true
chanCoordsFile = fullfile(basepath,[basename,'.chanCoords.channelInfo.mat']);
if isfield(session.extracellular,'chanCoords') && isfield(session.extracellular.chanCoords,'x') && isfield(session.extracellular.chanCoords,'y') && ~isempty(session.extracellular.chanCoords.x) && ~isempty(session.extracellular.chanCoords.y)
disp(' Using existing channel coordinates')
chanCoords = session.extracellular.chanCoords;
chanCoords.x = chanCoords.x(:);
chanCoords.y = chanCoords.y(:);
elseif exist(chanCoordsFile,'file')
disp([' Loading channel coordinates from file: ' chanCoordsFile])
load(chanCoordsFile,'chanCoords');
chanCoords.x = chanCoords.x(:);
chanCoords.y = chanCoords.y(:);
session.extracellular.chanCoords = chanCoords;
else
chanCoords = {};
if exist(fullfile(basepath,'chanMap.mat'),'file') % Will look for a chanMap file with default name (compatible with KiloSort)
disp(' Importing chanCoords from chanMap.mat file (e.g. from KiloSort)')
chanMap = load(fullfile(basepath,'chanMap.mat'));
chanCoords.x = chanMap.xcoords(:);
chanCoords.y = chanMap.ycoords(:);
elseif isfield(session,'analysisTags') && isfield(session.analysisTags,'chanMapFile')
% You can use a different filename that must be specified in: session.analysisTags.chanMapFile
chanMap = load(fullfile(basepath,session.analysisTags.chanMapFile));
disp([' Loading channel coordinates from chanCoords file: ' chanMap])
chanCoords.x = chanMap.xcoords(:);
chanCoords.y = chanMap.ycoords(:);
else
disp(' Generating chanCoords')
chanCoords = generateChanCoords(session);
end
session.extracellular.chanCoords = chanCoords;
end
cell_metrics.general.chanCoords = chanCoords;
% Fit exponential
fit_eqn = fittype('a*exp(-x/b)+c','dependent',{'y'},'independent',{'x'},'coefficients',{'a','b','c'});
xdata = {};
ydata = {};
if parameters.debugMode
fig100 = figure;
handle_subfig1 = subplot(2,1,1); hold on
title(handle_subfig1,'Spike amplitude (all)'), xlabel(handle_subfig1,'Distance (µm)'), ylabel(handle_subfig1,'µV')
handle_subfig2 = subplot(2,2,3); hold on
ylabel(handle_subfig2,'Length constant (µm)'), xlabel(handle_subfig2,'Peak voltage (µV)')
handle_subfig3 = subplot(2,2,4); hold off
plot(handle_subfig3,cell_metrics.general.chanCoords.x,cell_metrics.general.chanCoords.y,'.k'), hold on
xlabel(handle_subfig3,'x position (µm)'), ylabel(handle_subfig3,'y position (µm)')
drawnow
end
for j = 1:cell_metrics.general.cellCount
if ~isnan(cell_metrics.peakVoltage(j)) && isfield(cell_metrics.waveforms,'filt_all')
% Trilateration
peakVoltage = range(cell_metrics.waveforms.filt_all{j}');
peakVoltage(bad_channels) = NaN;
filt_all = cell_metrics.waveforms.filt_all{j}';
filt_all(:,bad_channels) = 0;
[~,idx] = sort(range(filt_all),'descend');
clear filt_all
trilat_nChannels = min([preferences.waveform.trilat_nChannels,numel(peakVoltage)]);
bestChannels = cell_metrics.waveforms.channels_all{j}(idx(1:trilat_nChannels));
beta0 = [cell_metrics.general.chanCoords.x(bestChannels(1)),cell_metrics.general.chanCoords.y(bestChannels(1))]; % initial position
trilat_pos = trilat(cell_metrics.general.chanCoords.x(bestChannels),cell_metrics.general.chanCoords.y(bestChannels),peakVoltage(idx(1:trilat_nChannels)),beta0,0); % ,1,cell_metrics.waveforms.filt_all{j}(bestChannels,:)
cell_metrics.trilat_x(j) = trilat_pos(1);
cell_metrics.trilat_y(j) = trilat_pos(2);
% Length constant
x1 = cell_metrics.general.chanCoords.x;
y1 = cell_metrics.general.chanCoords.y;
u = cell_metrics.trilat_x(j);
v = cell_metrics.trilat_y(j);
[channel_distance,idx2] = sort(hypot((x1(:)-u),(y1(:)-v)));
nChannelFit = min([trilat_nChannels,length(session.extracellular.electrodeGroups.channels{spikes{spkExclu}.shankID(j)})]);
x = 1:nChannelFit;
y = peakVoltage(idx(x));
x2 = channel_distance(1:nChannelFit)';
xdata{j} = x2;
ydata{j} = y;
f0 = fit(x2',y',fit_eqn,'StartPoint',[cell_metrics.peakVoltage(j), 30, 5],'Lower',[1, 0.001, 0],'Upper',[5000, 200, 1000]);
fitCoeffValues = coeffvalues(f0);
cell_metrics.peakVoltage_expFit(j) = fitCoeffValues(2);
if parameters.debugMode && ishandle(handle_subfig1)
fig100.Name = ['Cell ',num2str(j),'/',num2str(cell_metrics.general.cellCount)];
delete(handle_subfig1.Children)
plot(handle_subfig1,xdata{j},ydata{j},'.-b'), hold on
plot(handle_subfig1,x2,fitCoeffValues(1)*exp(-x2/fitCoeffValues(2))+fitCoeffValues(3),'r'),
plot(handle_subfig2,cell_metrics.peakVoltage(j),cell_metrics.peakVoltage_expFit(j),'ok')
plot(handle_subfig3,cell_metrics.trilat_x(j),cell_metrics.trilat_y(j),'ob'),
drawnow
end
else
cell_metrics.trilat_x(j) = nan;
cell_metrics.trilat_y(j) = nan;
cell_metrics.peakVoltage_expFit(j) = nan;
xdata{j} = [];
ydata{j} = [];
end
end
if parameters.showFigures
fig1 = figure('Name', 'Length constant and Trilateration','position',[100,100,900,700],'visible','off');
movegui(fig1,'center')
subplot(2,2,1), hold on
for j = 1:cell_metrics.general.cellCount
plot(xdata{j},ydata{j})
end
title('Spike amplitude (all)'), xlabel('Distance (µm)'), ylabel('µV')
subplot(2,2,2), hold off,
histogram(cell_metrics.peakVoltage_expFit,20), xlabel('Length constant (µm)')
subplot(2,2,3), hold on
plot(cell_metrics.peakVoltage,cell_metrics.peakVoltage_expFit,'ok')
ylabel('Length constant (µm)'), xlabel('Peak voltage (µV)')
subplot(2,2,4), hold on
plot(cell_metrics.general.chanCoords.x,cell_metrics.general.chanCoords.y,'.k'), hold on
plot(cell_metrics.trilat_x,cell_metrics.trilat_y,'ob'), xlabel('x position (µm)'), ylabel('y position (µm)')
set(fig1,'visible','on')
end
end
% Common coordinate framework
ccf_file = fullfile(basepath,[basename,'.ccf.channelInfo.mat']);
if exist(ccf_file,'file') %&& (~all(isfield(cell_metrics,{'ccf_x','ccf_y','ccf_z'})) || parameters.forceReload == true)
dispLog('Importing common coordinate framework',basename);
load(ccf_file,'ccf');
if all(isfield(ccf,{'x','y','z'}))
cell_metrics.general.ccf = ccf;
cell_metrics.ccf_x = cell_metrics.general.ccf.x(cell_metrics.maxWaveformCh1)';
cell_metrics.ccf_y = cell_metrics.general.ccf.y(cell_metrics.maxWaveformCh1)';
cell_metrics.ccf_z = cell_metrics.general.ccf.z(cell_metrics.maxWaveformCh1)';
for j = 1:cell_metrics.general.cellCount
if ~isnan(cell_metrics.peakVoltage(j))
peakVoltage = range(cell_metrics.waveforms.filt_all{j}');
trilat_nChannels = min([preferences.waveform.trilat_nChannels,numel(peakVoltage)]);
[~,idx] = sort(peakVoltage,'descend');
bestChannels = cell_metrics.waveforms.channels_all{j}(idx(1:trilat_nChannels));
beta0 = [cell_metrics.general.ccf.x(bestChannels(1)),cell_metrics.general.ccf.y(bestChannels(1)),cell_metrics.general.ccf.z(bestChannels(1))]; % initial position
if isnan(beta0)
cell_metrics.ccf_x(j) = nan;
cell_metrics.ccf_y(j) = nan;
cell_metrics.ccf_z(j) = nan;
else
trilat_pos = trilat3([cell_metrics.general.ccf.x(bestChannels),cell_metrics.general.ccf.y(bestChannels),cell_metrics.general.ccf.z(bestChannels)],peakVoltage(idx(1:trilat_nChannels)),beta0,0);
cell_metrics.ccf_x(j) = trilat_pos(1);
cell_metrics.ccf_y(j) = trilat_pos(2);
cell_metrics.ccf_z(j) = trilat_pos(3);
end
else
cell_metrics.ccf_x(j) = nan;
cell_metrics.ccf_y(j) = nan;
cell_metrics.ccf_z(j) = nan;
end
end
if parameters.showFigures
figure
plot3(cell_metrics.general.ccf.x,cell_metrics.general.ccf.z,cell_metrics.general.ccf.y,'.k'), hold on
plot3(cell_metrics.ccf_x,cell_metrics.ccf_z,cell_metrics.ccf_y,'ob'),
xlabel('x ( Anterior-Posterior; µm)'), zlabel('y (Superior-Inferior; µm)'), ylabel('z (Left-Right; µm)'), axis equal, set(gca, 'ZDir','reverse')
if exist('plotBrainGrid.m','file')
plotAllenBrainGrid, hold on
end
end
end
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% PCA features based calculations: Isolation distance and L-ratio
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% This code must be updated to reflect various spike sorting formats
%
% if any(contains(parameters.metrics,{'PCA_features','all'})) && ~any(contains(parameters.excludeMetrics,{'PCA_features'}))
% spkExclu = setSpkExclu('PCA_features',parameters);
% dispLog('PCA classifications: Isolation distance, L-Ratio',basename)
% if ~all(isfield(cell_metrics,{'isolationDistance66','lRatio'})) || parameters.forceReload == true
% if strcmp(session.spikeSorting{1}.method,{'Neurosuite','KlustaKwik'})
% disp('Getting PCA features for KlustaKwik')
% PCA_features = LoadNeurosuiteFeatures(spikes,session,parameters.excludeIntervals); %(session.spikeSorting{1}.relativePath,basename,sr,parameters.excludeIntervals);
% for j = 1:cell_metrics.general.cellCount
% cell_metrics.isolationDistance(j) = PCA_features.isolationDistance(find(PCA_features.UID == spikes{spkExclu}.UID(j)));
% cell_metrics.lRatio(j) = PCA_features.lRatio(find(PCA_features.UID == spikes{spkExclu}.UID(j)));
% end
% elseif strcmp(session.spikeSorting{1}.method,{'KiloSort'})
% disp('Getting masked PCA features for KiloSort')
% [clusterIDs, unitQuality, contaminationRate] = sqKilosort.maskedClusterQuality(basepath);
% cell_metrics.unitQuality = nan(1,spikes{spkExclu}.numcells);
% cell_metrics.contaminationRate = nan(1,spikes{spkExclu}.numcells);
% for i = 1:spikes{spkExclu}.numcells
% if any(cell_metrics.cluID(i) == clusterIDs)
% idx = find(cell_metrics.cluID(i) == clusterIDs)
% cell_metrics.unitQuality(i) = unitQuality(idx);
% cell_metrics.contaminationRate(i) = contaminationRate(idx);
% end
% end
% keyboard
% elseif strcmp(session.spikeSorting{1}.method,{'MaskedKlustakwik','klusta'})
% disp('Getting masked PCA features for MaskedKlustakwik')
% [clusterIDs, unitQuality, contaminationRate] = sqKwik.maskedClusterQuality(basepath);
% keyboard
% % getPCAfeatures(session)
% % disp(' No PCAs available')
% end
% end
% end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% ACG & CCG based classification
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if any(contains(parameters.metrics,{'acg_metrics','all'})) && ~any(contains(parameters.excludeMetrics,{'acg_metrics'}))
spkExclu = setSpkExclu('acg_metrics',parameters);
if isfield(cell_metrics, 'acg') && isnumeric(cell_metrics.acg)
field2remove = {'acg','acg2'};
test = isfield(cell_metrics,field2remove);
cell_metrics = rmfield(cell_metrics,field2remove(test));
end
if ~all(isfield(cell_metrics,{'acg','thetaModulationIndex','burstIndex_Royer2012','burstIndex_Doublets','acg_tau_decay','acg_tau_rise'})) || parameters.forceReload == true
dispLog('ACG classifications: ThetaModulationIndex, BurstIndex_Royer2012, BurstIndex_Doublets',basename)
acg_metrics = calc_ACG_metrics(spikes{spkExclu},sr,'showFigures',parameters.debugMode);
cell_metrics.acg.wide = acg_metrics.acg_wide; % Wide: 1000ms wide CCG with 1ms bins
cell_metrics.acg.narrow = acg_metrics.acg_narrow; % Narrow: 100ms wide CCG with 0.5ms bins
cell_metrics.thetaModulationIndex = acg_metrics.thetaModulationIndex; % cell_tmi
cell_metrics.burstIndex_Royer2012 = acg_metrics.burstIndex_Royer2012; % cell_burstRoyer2012
cell_metrics.burstIndex_Doublets = acg_metrics.burstIndex_Doublets;
dispLog('Fitting triple exponential to ACG',basename)
fit_params = fit_ACG(acg_metrics.acg_narrow,parameters.debugMode);
cell_metrics.acg_tau_decay = fit_params.acg_tau_decay;
cell_metrics.acg_tau_rise = fit_params.acg_tau_rise;
cell_metrics.acg_c = fit_params.acg_c;
cell_metrics.acg_d = fit_params.acg_d;
cell_metrics.acg_asymptote = fit_params.acg_asymptote;
cell_metrics.acg_refrac = fit_params.acg_refrac;
cell_metrics.acg_fit_rsquare = fit_params.acg_fit_rsquare;
cell_metrics.acg_tau_burst = fit_params.acg_tau_burst;
cell_metrics.acg_h = fit_params.acg_h;
end
if ~isfield(cell_metrics,'acg') || ~isfield(cell_metrics.acg,{'log10'}) || parameters.forceReload == true
dispLog('Calculating log10 ACGs',basename)
acg = calc_logACGs(spikes{spkExclu}.times,'showFigures',parameters.showFigures);
cell_metrics.acg.log10 = acg.log10;
cell_metrics.general.acgs.log10 = acg.log10_bins;
end
if ~isfield(cell_metrics,'isi') || ~isfield(cell_metrics.isi,{'log10'}) || parameters.forceReload == true
dispLog('Calculating log10 ISIs',basename)
isi = calc_logISIs(spikes{spkExclu}.times,'showFigures',parameters.showFigures);
cell_metrics.isi.log10 = isi.log10;
cell_metrics.general.isis.log10 = isi.log10_bins;
end
if ~(isfield(preferences,'acg_metrics') && isfield(preferences.acg_metrics,'population_modIndex') && ~preferences.acg_metrics.population_modIndex) && (~isfield(cell_metrics,{'population_modIndex'}) || ~isfield(cell_metrics.general,'responseCurves') || ~isfield(cell_metrics.general.responseCurves,'meanCCG') || numel(cell_metrics.general.responseCurves.meanCCG.x_bins) ~= 51 || parameters.forceReload == true)
dispLog('Calculating population modulation index',basename)
[meanCCG,tR,population_modIndex] = detectDownStateCells(spikes{spkExclu},sr,'showFigures',parameters.showFigures);
cell_metrics.responseCurves.meanCCG = num2cell(meanCCG,1);
cell_metrics.general.responseCurves.meanCCG.x_bins = tR;
cell_metrics.population_modIndex = population_modIndex;
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Putative MonoSynaptic connections
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if any(contains(parameters.metrics,{'monoSynaptic_connections','all'})) && ~any(contains(parameters.excludeMetrics,{'monoSynaptic_connections'}))
spkExclu = setSpkExclu('monoSynaptic_connections',parameters);
dispLog('MonoSynaptic connections',basename)
if ~exist(fullfile(basepath,[basename,'.mono_res',erase(parameters.saveAs,'cell_metrics'),'.cellinfo.mat']),'file')
mono_res = ce_MonoSynConvClick(spikes{spkExclu},'includeInhibitoryConnections',parameters.includeInhibitoryConnections,'sr',sr);
if parameters.manualAdjustMonoSyn
dispLog('Loading MonoSynaptic GUI for manual adjustment',basename)
mono_res = gui_MonoSyn(mono_res);
end
save(fullfile(basepath,[basename,'.mono_res',erase(parameters.saveAs,'cell_metrics'),'.cellinfo.mat']),'mono_res','-v7.3','-nocompression');
else
disp(' Loading previous detected MonoSynaptic connections')
load(fullfile(basepath,[basename,'.mono_res',erase(parameters.saveAs,'cell_metrics'),'.cellinfo.mat']),'mono_res');
if parameters.includeInhibitoryConnections && (~isfield(mono_res,'sig_con_inhibitory') || (isfield(mono_res,'sig_con_inhibitory') && isempty(mono_res.sig_con_inhibitory_all)))
disp(' Detecting MonoSynaptic inhibitory connections')
mono_res_old = mono_res;
mono_res = ce_MonoSynConvClick(spikes{spkExclu},'includeInhibitoryConnections',parameters.includeInhibitoryConnections,'sr',sr);
mono_res.sig_con_excitatory = mono_res_old.sig_con;
mono_res.sig_con = mono_res_old.sig_con;
if parameters.manualAdjustMonoSyn
dispLog('Loading MonoSynaptic GUI for manual adjustment',basename)
mono_res = gui_MonoSyn(mono_res);
end
save(fullfile(basepath,[basename,'.mono_res',erase(parameters.saveAs,'cell_metrics'),'.cellinfo.mat']),'mono_res','-v7.3','-nocompression');
elseif parameters.forceReload == true && parameters.manualAdjustMonoSyn
mono_res = gui_MonoSyn(mono_res);
save(fullfile(basepath,[basename,'.mono_res',erase(parameters.saveAs,'cell_metrics'),'.cellinfo.mat']),'mono_res','-v7.3','-nocompression');
end
end
field2remove = {'putativeConnections'};
test = isfield(cell_metrics,field2remove);
cell_metrics = rmfield(cell_metrics,field2remove(test));
if ~isempty(mono_res.sig_con)
if isfield(mono_res,'sig_con_excitatory')
cell_metrics.putativeConnections.excitatory = mono_res.sig_con_excitatory; % Vectors with cell pairs
else
cell_metrics.putativeConnections.excitatory = mono_res.sig_con; % Vectors with cell pairs
end
if isfield(mono_res,'sig_con_inhibitory')
cell_metrics.putativeConnections.inhibitory = mono_res.sig_con_inhibitory;
else
cell_metrics.putativeConnections.inhibitory = [];
end
cell_metrics.synapticEffect = repmat({'Unknown'},1,cell_metrics.general.cellCount);
cell_metrics.synapticEffect(cell_metrics.putativeConnections.excitatory(:,1)) = repmat({'Excitatory'},1,size(cell_metrics.putativeConnections.excitatory,1)); % cell_synapticeffect ['Inhibitory','Excitatory','Unknown']
if ~isempty(cell_metrics.putativeConnections.inhibitory)
cell_metrics.synapticEffect(cell_metrics.putativeConnections.inhibitory(:,1)) = repmat({'Inhibitory'},1,size(cell_metrics.putativeConnections.inhibitory,1));
end
cell_metrics.synapticConnectionsOut = zeros(1,cell_metrics.general.cellCount);
cell_metrics.synapticConnectionsIn = zeros(1,cell_metrics.general.cellCount);
[a,b]=hist(cell_metrics.putativeConnections.excitatory(:,1),unique(cell_metrics.putativeConnections.excitatory(:,1)));
cell_metrics.synapticConnectionsOut(b) = a;
cell_metrics.synapticConnectionsOut = cell_metrics.synapticConnectionsOut(1:cell_metrics.general.cellCount);
[a,b]=hist(cell_metrics.putativeConnections.excitatory(:,2),unique(cell_metrics.putativeConnections.excitatory(:,2)));
cell_metrics.synapticConnectionsIn(b) = a;
cell_metrics.synapticConnectionsIn = cell_metrics.synapticConnectionsIn(1:cell_metrics.general.cellCount);
% Connection strength
disp(' Determining transmission probabilities')
ccg2 = mono_res.ccgR;
ccg2(isnan(ccg2)) = 0;
% Excitatory connections
for i = 1:size(cell_metrics.putativeConnections.excitatory,1)
[trans,prob,prob_uncor,pred] = ce_GetTransProb(ccg2(:,cell_metrics.putativeConnections.excitatory(i,1),cell_metrics.putativeConnections.excitatory(i,2)), spikes{spkExclu}.total(cell_metrics.putativeConnections.excitatory(i,1)), mono_res.binSize, 0.020);
cell_metrics.putativeConnections.excitatoryTransProb(i) = trans;
end
% Inhibitory connections
for i = 1:size(cell_metrics.putativeConnections.inhibitory,1)
[trans,prob,prob_uncor,pred] = ce_GetTransProb(ccg2(:,cell_metrics.putativeConnections.inhibitory(i,1),cell_metrics.putativeConnections.inhibitory(i,2)), spikes{spkExclu}.total(cell_metrics.putativeConnections.inhibitory(i,1)), mono_res.binSize, 0.020);
cell_metrics.putativeConnections.inhibitoryTransProb(i) = trans;
end
else
cell_metrics.putativeConnections.excitatory = [];
cell_metrics.putativeConnections.inhibitory = [];
cell_metrics.synapticConnectionsOut = zeros(1,cell_metrics.general.cellCount);
cell_metrics.synapticConnectionsIn = zeros(1,cell_metrics.general.cellCount);
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Deep-Superficial by ripple polarity reversal
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if any(contains(parameters.metrics,{'deepSuperficial','all'})) && ~any(contains(parameters.excludeMetrics,{'deepSuperficial'}))
spkExclu = setSpkExclu('deepSuperficial',parameters);
if (~exist(fullfile(basepath,[basename,'.ripples.events.mat']),'file')) && isfield(session,'channelTags') && isfield(session.channelTags,'Ripple') && isnumeric(session.channelTags.Ripple.channels)
dispLog('Finding ripples',basename)
if ~exist(fullfile(session.general.basePath,[session.general.name, '.lfp']),'file')
disp('Creating lfp file')
ce_LFPfromDat(session)
end
if isfield(session.channelTags,'RippleNoise')
disp(' Using RippleNoise reference channel')
RippleNoiseChannel = double(LoadBinary([basename, '.lfp'],'nChannels',session.extracellular.nChannels,'channels',session.channelTags.RippleNoise.channels,'precision','int16','frequency',session.extracellular.srLfp)); % 0.000050354 *
ripples = bz_FindRipples(basepath,session.channelTags.Ripple.channels-1,'durations',preferences.deepSuperficial.ripples_durations,'passband',preferences.deepSuperficial.ripples_passband,'noise',RippleNoiseChannel);
else
ripples = ce_FindRipples(session,'durations',preferences.deepSuperficial.ripples_durations,'passband',preferences.deepSuperficial.ripples_passband);
end
end
deepSuperficial_file = fullfile(basepath, [basename,'.deepSuperficialfromRipple.channelinfo.mat']);
if exist(fullfile(basepath,[basename,'.ripples.events.mat']),'file') && (~all(isfield(cell_metrics,{'deepSuperficial','deepSuperficialDistance'})) || parameters.forceReload == true)
dispLog('Deep-Superficial by ripple polarity reversal',basename)
if ~exist(deepSuperficial_file,'file')
if ~isfield(session.extracellular,'chanCoords')
session.extracellular.chanCoords = generateChanCoords(session);
end
classification_DeepSuperficial(session);
end
load(deepSuperficial_file,'deepSuperficialfromRipple')
cell_metrics.general.SWR = deepSuperficialfromRipple;
deepSuperficial_ChDistance = deepSuperficialfromRipple.channelDistance; %
deepSuperficial_ChClass = deepSuperficialfromRipple.channelClass;% cell_deep_superficial
cell_metrics.general.deepSuperficial_file = deepSuperficial_file;
for j = 1:cell_metrics.general.cellCount
cell_metrics.deepSuperficial(j) = deepSuperficial_ChClass(spikes{spkExclu}.maxWaveformCh1(j)); % cell_deep_superficial OK
cell_metrics.deepSuperficialDistance(j) = deepSuperficial_ChDistance(spikes{spkExclu}.maxWaveformCh1(j)); % cell_deep_superficial_distance
end
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Theta related activity
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if any(contains(parameters.metrics,{'theta_metrics','all'})) && ~any(contains(parameters.excludeMetrics,{'theta_metrics'})) && exist(fullfile(basepath,[basename,'.animal.behavior.mat']),'file') && isfield(session.channelTags,'Theta') %&& (~isfield(cell_metrics,'thetaEntrainment') || parameters.forceReload == true)
spkExclu = setSpkExclu('theta_metrics',parameters);
dispLog('Theta metrics',basename);
InstantaneousTheta = calcInstantaneousTheta2(session);
load(fullfile(basepath,[basename,'.animal.behavior.mat']),'animal');
theta_bins = preferences.theta.bins;
cell_metrics.thetaPhasePeak = nan(1,cell_metrics.general.cellCount);
cell_metrics.thetaPhaseTrough = nan(1,cell_metrics.general.cellCount);
% cell_metrics.responseCurves.thetaPhase = nan(length(theta_bins)-1,cell_metrics.general.cellCount);
cell_metrics.thetaEntrainment = nan(1,cell_metrics.general.cellCount);
spikes2 = spikes{spkExclu};
if isfield(cell_metrics,'thetaPhaseResponse')
cell_metrics = rmfield(cell_metrics,'thetaPhaseResponse');
end
for j = 1:size(spikes{spkExclu}.times,2)
Theta_channel = session.channelTags.Theta.channels(1);
spikes2.ts{j} = spikes2.ts{j}(spikes{spkExclu}.times{j} < length(InstantaneousTheta.signal_phase{Theta_channel})/session.extracellular.srLfp);
spikes2.times{j} = spikes2.times{j}(spikes{spkExclu}.times{j} < length(InstantaneousTheta.signal_phase{Theta_channel})/session.extracellular.srLfp);
spikes2.ts_eeg{j} = ceil(spikes2.ts{j}*session.extracellular.srLfp/session.extracellular.sr);
spikes2.theta_phase{j} = InstantaneousTheta.signal_phase{Theta_channel}(spikes2.ts_eeg{j});
spikes2.speed{j} = interp1(animal.time,animal.speed,spikes2.times{j});
if sum(spikes2.speed{j} > 10)> preferences.theta.min_spikes % only calculated if the unit has above min_spikes (default: 500)
[counts,centers] = histcounts(spikes2.theta_phase{j}(spikes2.speed{j} > preferences.theta.speed_threshold),theta_bins, 'Normalization', 'probability');
counts = nanconv(counts,[1,1,1,1,1]/5,'edge');
[~,tem2] = max(counts);
[~,tem3] = min(counts);
cell_metrics.responseCurves.thetaPhase{j} = counts(:);
cell_metrics.thetaPhasePeak(j) = centers(tem2)+diff(centers([1,2]))/2;
cell_metrics.thetaPhaseTrough(j) = centers(tem3)+diff(centers([1,2]))/2;
cell_metrics.thetaEntrainment(j) = max(counts)/min(counts);
else
cell_metrics.responseCurves.thetaPhase{j} = nan(length(theta_bins)-1,1);
end
end
cell_metrics.general.responseCurves.thetaPhase.x_bins = theta_bins(1:end-1)+diff(theta_bins([1,2]))/2;
if parameters.showFigures
figure, subplot(2,2,1)
plot(cell_metrics.general.responseCurves.thetaPhase.x_bins,horzcat(cell_metrics.responseCurves.thetaPhase{:})),title('Theta entrainment during locomotion'), xlim([-1,1]*pi)
subplot(2,2,2)
plot(cell_metrics.thetaPhaseTrough,cell_metrics.thetaPhasePeak,'o'),xlabel('Trough'),ylabel('Peak')
subplot(2,2,3)
histogram(cell_metrics.thetaEntrainment,30),title('Theta entrainment')
subplot(2,2,4)
histogram(cell_metrics.thetaPhaseTrough,[-1:0.2:1]*pi),title('Theta trough and peak'), hold on
histogram(cell_metrics.thetaPhasePeak,[-1:0.2:1]*pi), legend({'Trough','Peak'})
end
end
%% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Spatial related metrics
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
if any(contains(parameters.metrics,{'spatial_metrics','all'})) && ~any(contains(parameters.excludeMetrics,{'spatial_metrics'}))
spkExclu = setSpkExclu('spatial_metrics',parameters);
if ~isempty(dir(fullfile(basepath,[basename,'.*.firingRateMap.mat'])))
dispLog('Spatial metrics',basename);
end
% Cleaning legacy fields
field2remove = {'firingRateMap_CoolingStates','firingRateMap_LeftRight','firingRateMaps','firingRateMap','firing_rate_map_states','firing_rate_map','placecell_stability','SpatialCoherence','place_cell','placefield_count','placefield_peak_rate','FiringRateMap','FiringRateMap_CoolingStates','FiringRateMap_StimStates','FiringRateMap_LeftRight'};
test = isfield(cell_metrics,field2remove);
cell_metrics = rmfield(cell_metrics,field2remove(test));
% General firing rate map
if exist(fullfile(basepath,[basename,'.ratemap.firingRateMap.mat']),'file')
temp2 = load(fullfile(basepath,[basename,'.ratemap.firingRateMap.mat']));
if isfield(temp2,'ratemap')
disp(' Loaded ratemap succesfully');
firingRateMap = temp2.ratemap;
if cell_metrics.general.cellCount == length(firingRateMap.map)
cell_metrics.firingRateMaps.firingRateMap = firingRateMap.map;
if isfield(firingRateMap,'x_bins')
cell_metrics.general.firingRateMaps.firingRateMap.x_bins = firingRateMap.x_bins;
end
if isfield(firingRateMap,'boundaries')
cell_metrics.general.firingRateMaps.firingRateMap.boundaries = firingRateMap.boundaries;
end
for j = 1:cell_metrics.general.cellCount
cell_metrics.spatialPeakRate(j) = max(firingRateMap.map{j});
% Finding place cells/fields
temp = place_cell_condition(firingRateMap.map{j});
cell_metrics.spatialCoherence(j) = temp.SpatialCoherence;
cell_metrics.placeCell(j) = temp.condition;
cell_metrics.placeFieldsCount(j) = temp.placefield_count;
temp3 = cumsum(sort(firingRateMap.map{j},'descend'));
if ~all(temp3==0 | isnan(temp3))
cell_metrics.spatialCoverageIndex(j) = find(temp3>0.75*temp3(end),1)/(length(temp3)*0.75); % Spatial coverage index (Royer, NN 2012)