-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sources2D.m
2109 lines (1898 loc) · 84.3 KB
/
Sources2D.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 Sources2D < handle
% This class is a wrapper of Constrained NMF for standard 2D data. It
% Both CNMF and CNMF-E model can be used.
% Author: Pengcheng Zhou, Columbia University, 2017
%% properties
properties
% spatial
A; % spatial components of neurons
A_prev; % previous estimation of A
% temporal
C; % temporal components of neurons
C_prev; % previous estimation of C
C_raw; % raw traces of temporal components
S; % spike counts
kernel; % calcium dynamics. this one is less used these days.
% background
b; % spatial components of backgrounds
f; % temporal components of backgrounds
W; % a sparse weight matrix matrix
b0; % constant baselines for each pixel
b0_new; % correct the changes in b0 when we update A & C
% optiosn
options; % options for model fitting
P; % some estimated parameters or parameters relating to data
% data info
Fs = nan; % frame rate
file = '';
frame_range; % frame range of the data
%quality control
ids; % unique identifier for each neuron
tags; % tags bad neurons with multiple criterion using a 16 bits number
% ai indicates the bit value of the ith digits from
% right to the left
% a1 = 1 means that neuron has too few nonzero pixels
% a2 = 1 means that neuron has silent calcium transients
% a3 = 1 indicates that the residual after being deconvolved has
% much smaller std than the raw data, which is uaually the case
% when temporal traces are random noise
% a4 = 1 indicates that the CNMF-E fails in deconvolving temporal
% traces. this usually happens when neurons are false positives.
% a4 = 1 indicates that the neuron has small PNR
%others
Cn; % correlation image
PNR; % peak-to-noise ratio image.
Coor; % neuron contours
neurons_per_patch;
Df; % background for each component to normalize the filtered raw data
C_df; % temporal components of neurons and background normalized by Df
S_df; % spike counts of neurons normalized by Df
batches = cell(0); % results for each small batch data
file_id = []; % file id for each batch.
end
%% methods
methods
%% constructor and options setting
function obj = Sources2D(varargin)
obj.options = CNMFSetParms();
obj.P =struct('mat_file', [], 'mat_data', [], 'indicator', '', 'k_options', 0, ...
'k_snapshot', 0, 'k_del', 0, 'k_merge', 0, 'k_trim', 0, 'sn', [], ...
'kernel_pars',[], 'k_ids', 0);
if nargin>0
obj.options = CNMFSetParms(obj.options, varargin{:});
end
obj.kernel = create_kernel('exp2');
end
%------------------------------------------------------------------OPTIONS------------%
%% update parameters
function updateParams(obj, varargin)
obj.options = CNMFSetParms(obj.options, varargin{:});
end
%------------------------------------------------------------------PREPROCESSING-------%
%% data preprocessing
function Y = preprocess(obj,Y,p)
[obj.P,Y] = preprocess_data(Y,p,obj.options);
end
%------------------------------------------------------------------LOAD DATA-----------%
%% select data
function nam = select_data(obj, nam)
%% select file
if ~exist('nam', 'var') || isempty(nam) || ~exist(nam, 'file')
% choose files using graphical interfaces
try
load .dir.mat; %load previous path
catch
dir_nm = [cd(), filesep]; %use the current path
end
[file_nm, dir_nm] = uigetfile(fullfile(dir_nm, '*.tif;*.mat;*.h5;*.avi'));
nam = [dir_nm, file_nm]; % full name of the data file
else
% file has been selected
nam = get_fullname(nam);
[dir_nm, ~, ~] = fileparts(nam);
end
if dir_nm~=0
try
save .dir.mat dir_nm;
catch
fprintf('You do not have the access to write file to the current folder');
end
else
fprintf('no file was selected. STOP!\n');
return;
end
obj.file = nam;
end
%% select multiple datasets
function nams = select_multiple_files(obj, nams)
if ~isempty(nams)
nams = unique(nams);
ind_keep = true(size(nams));
for m=1:length(nams)
if ~exist(nams{m}, 'file')
ind_keep = false;
else
nams{m} = get_fullname(nams{m});
end
end
nams = nams(ind_keep);
fprintf('\n----------------------------------------\n');
for m=1:length(nams)
fprintf('%d:\t%s\n', m, nams{m});
end
fprintf('\n----------------------------------------\n');
obj.file = nams;
return;
end
fprintf('\t-------------------------- GUIDE --------------------------\n');
fprintf('\ttype -i to remove the selected i-th file\n');
fprintf('\ttype 0 to stop the data selection\n');
fprintf('\ttype anything else to select more data\n');
fprintf('\t-------------------------- END --------------------------\n\n');
if ~exist('nams', 'var') || isempty(nams)
nams = cell(0);
end
while true
if isempty(nams)
fprintf('You haven''t selected any file yet\n');
else
ind_keep = true(size(nams));
for m=1:length(nams)
if ~exist(nams{m}, 'file')
ind_keep = false;
end
end
nams = nams(ind_keep);
fprintf('\n----------------------------------------\n');
for m=1:length(nams)
fprintf('%d:\t%s\n', m, nams{m});
end
fprintf('\n----------------------------------------\n');
end
% make choise
your_ans = input('make your choice: ');
if your_ans==0
break;
elseif your_ans<0 && round(abs(your_ans))<length(nams)
nams(round(abs(your_ans))) = [];
else
nams{end+1} = obj.select_data([]); %#ok<AGROW>
end
end
obj.file = unique(nams);
end
%% load the patched file into the memory
function map_data_to_memory(obj)
mat_file = obj.P.mat_file;
if exist(mat_file, 'file')
data_nam = sprintf('mat_data_%d', string2hash(mat_file));
if isempty(evalin('base', sprintf('whos(''%s'')', data_nam)))
% the data has not been mapped yet
evalin('base', sprintf('%s=load(''%s''); ', data_nam, mat_file));
end
end
end
%% load data within selected patch position and selected frames
function Ypatch = load_patch_data(obj, patch_pos, frame_range)
mat_data = obj.P.mat_data;
dims = mat_data.dims;
d1 = dims(1);
d2 = dims(2);
T = dims(3);
if ~exist('patch_pos', 'var') || isempty(patch_pos)
patch_pos = [1, d1, 1, d2];
end
if ~exist('frame_range', 'var') || isempty(frame_range)
frame_range = [1, T];
end
Ypatch = get_patch_data(mat_data, patch_pos, frame_range, false);
end
%% distribute data and be ready to run source extraction
function getReady(obj, pars_envs, filter_kernel)
% data and its extension
if iscell(obj.file)
nam = obj.file{1};
else
nam = obj.file;
end
% parameters for scaling things
if ~exist('pars_envs', 'var') || isempty(pars_envs)
memory_size_to_use = 16.0; %GB
memory_size_per_patch = 1.0; % GB;
patch_dims = [64, 64];
else
memory_size_to_use = pars_envs.memory_size_to_use;
memory_size_per_patch = pars_envs.memory_size_per_patch;
patch_dims = pars_envs.patch_dims;
end
if ~exist('filter_kernel', 'var')
filter_kernel = [];
end
% overlapping area
w_overlap = obj.options.ring_radius;
% distribute data
[data, dims, obj.P.folder_analysis] = distribute_data(nam,...
patch_dims, w_overlap, memory_size_per_patch, memory_size_to_use,...
[], filter_kernel);
obj.P.mat_data = data;
obj.P.mat_file = data.Properties.Source;
obj.updateParams('d1', dims(1), 'd2', dims(2));
obj.P.numFrames = dims(3);
% estimate the noise level for each pixel
try
obj.P.sn = obj.P.mat_data.sn;
catch
obj.P.sn = obj.estimate_noise();
mat_data = obj.P.mat_data;
mat_data.Properties.Writable = true;
mat_data.sn = obj.P.sn;
mat_data.Properties.Writable = false;
end
%% map the data to the memory
temp = cast(0, data.dtype);
temp = whos('temp');
data_space = prod(data.dims) * temp.bytes / (2^30);
if data_space < memory_size_to_use
obj.map_data_to_memory();
end
end
%% distribute data and be ready to run batch mode source extraction
function getReady_batch(obj, pars_envs, log_folder)
%% parameters for scaling things
if ~exist('pars_envs', 'var') || isempty(pars_envs)
pars_envs = struct('memory_size_to_use', 4, ... % GB, memory space you allow to use in MATLAB
'memory_size_per_patch', 0.3, ... % GB, space for loading data within one patch
'patch_dims', [64, 64], ... %GB, patch size
'batch_frames', []); % number of frames per batch
end
batch_frames = pars_envs.batch_frames;
if ~exist('log_folder', 'var')||isempty(log_folder)||(~exist(log_folder, 'dir'))
obj.P.log_folder = [cd(), filesep];
else
obj.P.log_folder = log_folder;
end
%% distribute all files
nams = unique(obj.file);
obj.file = nams;
% pre-allocate spaces for saving results of multiple patches
batches_ = cell(100, 1);
file_id_ = zeros(100,1, 'like', uint8(1));
numFrames = zeros(100,1);
k_batch = 0;
for m=1:length(nams)
neuron = obj.copy();
neuron.file = nams{m};
neuron.getReady(pars_envs);
if m==1
obj.options = neuron.options;
end
T = neuron.P.numFrames;
if isempty(batch_frames)
batch_frames = T;
end
nbatches = round(T/batch_frames);
if nbatches<=1
frame_range_t = [1, T];
else
frame_range_t = round(linspace(1, T, nbatches+1));
end
nbatches = length(frame_range_t) -1;
for n=1:nbatches
k_batch = k_batch +1;
tmp_neuron = neuron.copy();
tmp_neuron.frame_range = frame_range_t(n:(n+1))-[0, 1*(n~=nbatches)];
batch_i.neuron = tmp_neuron;
batch_i.shifts = []; % shifts allowed
file_id_(k_batch) = m;
batches_{k_batch} = batch_i;
numFrames(k_batch) = diff(tmp_neuron.frame_range)+1;
end
end
obj.batches = batches_(1:k_batch);
obj.file_id = file_id_(1:k_batch);
obj.P.numFrames = numFrames(1:k_batch);
end
%% estimate noise
function sn = estimate_noise(obj, frame_range, method)
mat_data = obj.P.mat_data;
dims = mat_data.dims;
T = dims(3);
if ~exist('frame_range', 'var') || isempty(frame_range)
frame_range = [1, min(T, 3000)];
end
T = diff(frame_range)+1;
if ~exist('method', 'var') || isempty(method)
method = 'psd';
end
if strcmpi(method, 'hist')
% fit the histogram of with a parametric gaussian shape.
% it works badly when the
% most frames are involved in calcium transients.
foo = @(Y) GetSn_hist(Y, false);
elseif strcmpi(method, 'std')
% simly use the standard deviation. works badly when
% neurons have large calcium transients
foo = @(Y) std(Y, 0, 2);
else
% default options is using the power spectrum method.
% works badly when noises have temporal correlations
foo = @GetSn;
end
block_idx_r = mat_data.block_idx_r;
block_idx_c = mat_data.block_idx_c;
nr_block = length(block_idx_r) - 1;
nc_block = length(block_idx_c) - 1;
sn = cell(nr_block, nc_block);
fprintf('estimating the nosie level for every pixel.......\n');
tic;
for mblock=1:(nr_block*nc_block)
[m, n] = ind2sub([nr_block, nc_block], mblock);
r0 = block_idx_r(m); %#ok<PFBNS>
r1 = block_idx_r(m+1);
c0 = block_idx_c(n); %#ok<PFBNS>
c1 = block_idx_c(n+1);
Ypatch = get_patch_data(mat_data, [r0, r1, c0, c1], frame_range, false);
Ypatch = double(reshape(Ypatch, [], T));
tmp_sn = reshape(foo(Ypatch), r1-r0+1, c1-c0+1);
if m~=nr_block
tmp_sn(end-1, :) = [];
end
if n~=nc_block
tmp_sn(:, end-1) = [];
end
sn{mblock} = tmp_sn;
end
fprintf('Time cost for estimating the nosie levels: %.3f \n\n', toc);
sn = cell2mat(sn);
end
%% pick parameters
[gSig, gSiz, ring_radius, min_corr, min_pnr] = set_parameters(obj)
%------------------------------------------------------------------INITIALIZATION-----------%
%% fast initialization, for 2P data, CNMF
function [center] = initComponents(obj, Y, K, tau)
if nargin<4 ; tau = []; end
[obj.A, obj.C, obj.b, obj.f, center] = initialize_components(Y, K, tau, obj.options);
end
%% initialize neurons using patch method
% for 1P and 2P data, CNMF and CNMF-E
[center, Cn, PNR] = initComponents_parallel(obj, K, frame_range, save_avi, use_parallel, use_prev)
%% initialize neurons for multiple batches
% for 1P and 2P data, CNMF and CNMF-E
[center, Cn, PNR] = initComponents_batch(obj, K, frame_range, save_avi, use_parallel)
%% fast initialization for microendoscopic data
[center, Cn, pnr] = initComponents_endoscope(obj, Y, K, patch_sz, debug_on, save_avi);
[center] = initComponents_2p(obj,Y, K, options, sn, debug_on, save_avi);
%% pick neurons from the residual
% for 1P and 2P data, CNMF and CNMF-E
[center, Cn, PNR] = initComponents_residual_parallel(obj, K, save_avi, use_parallel, min_corr, min_pnr, seed_method)
%------------------------------------------------------------------UPDATE MODEL VARIABLES---%
%% update background components in parallel
% for 1P and 2P data, CNMF and CNMF-E
update_background_parallel(obj, use_parallel)
%% update background for all batches
update_background_batch(obj, use_parallel)
%% update spatial components in parallel
% for 1P and 2P data, CNMF and CNMF-E
update_spatial_parallel(obj, use_parallel, update_sn)
%% update spatial components in batch mode
update_spatial_batch(obj, use_parallel);
%% update temporal components in parallel
% for 1P and 2P data, CNMF and CNMF-E
update_temporal_parallel(obj, use_parallel, use_c_hat)
%% update temporal components in batch mode
% for 1P and 2P data, CNMF and CNMF-E
update_temporal_batch(obj, use_parallel)
%% update spatial components, 2P data, CNMF
function updateSpatial(obj, Y)
[obj.A, obj.b, obj.C] = update_spatial_components(Y, ...
obj.C, obj.f, obj.A, obj.P, obj.options);
end
%% udpate spatial components without background, no background components
function updateSpatial_nb(obj, Y)
[obj.A, obj.C] = update_spatial_components_nb(Y, ...
obj.C, obj.A, obj.P, obj.options);
end
%% udpate spatial components using NNLS and thresholding
function updateSpatial_nnls(obj, Y)
[obj.A, obj.C] = update_spatial_nnls(Y, ...
obj.C, obj.A, obj.P, obj.options);
end
%% update temporal components for endoscope data
updateSpatial_endoscope(obj, Y, numIter, method, IND_thresh);
%% update temporal components
function updateTemporal(obj, Y)
[obj.C, obj.f, obj.P, obj.S] = update_temporal_components(...
Y, obj.A, obj.b, obj.C, obj.f, obj.P, obj.options);
end
%% udpate temporal components with fast deconvolution
updateTemporal_endoscope(obj, Y, allow_deletion)
updateTemporal_endoscope_parallel(obj, Y, smin)
%% update temporal components without background
function updateTemporal_nb(obj, Y)
[obj.C, obj.P, obj.S] = update_temporal_components_nb(...
Y, obj.A, obj.b, obj.C, obj.f, obj.P, obj.options);
end
%------------------------------------------------------------------MERGE NEURONS ---------%
%% merge found components
function [nr, merged_ROIs] = merge(obj, Y)
[obj.A, obj.C, nr, merged_ROIs, obj.P, obj.S] = merge_components(...
Y,obj.A, [], obj.C, [], obj.P,obj.S, obj.options);
end
%% quick merge neurons based on spatial and temporal correlation
[merged_ROIs, newIDs] = quickMerge(obj, merge_thr)
%% quick merge neurons based on spatial and temporal correlation
[merged_ROIs, newIDs] = MergeNeighbors(obj, dmin, method)
%------------------------------------------------------------------EXPORT---%
function save_neurons(obj, folder_nm, with_craw)
if ~exist('folder_nm', 'var') || isempty(folder_nm)
folder_nm = [obj.P.log_folder, 'neurons'];
end
if ~exist('with_craw', 'var')||isempty(with_craw)
with_craw = true;
end
if exist(folder_nm, 'dir')
temp = cd();
cd(folder_nm);
delete *;
cd(temp);
else
mkdir(folder_nm);
end
if with_craw
obj.viewNeurons([], obj.C_raw, folder_nm);
else
obj.viewNeurons([], [], folder_nm);
end
end
%% export the result as a video
avi_filename = show_demixed_video(obj,save_avi, kt, frame_range, center_ac, range_ac, range_Y, multi_factor, use_craw) %% compute the residual
% function [Y_res] = residual(obj, Yr)
% Y_res = Yr - obj.A*obj.C - obj.b*obj.f;
% end
%% take the snapshot of current results
function [A, C, b, f, P, S] = snapshot(obj)
A = obj.A;
C = obj.C;
b = obj.b;
f = obj.f;
P = obj.P;
try
S = obj.S;
catch
S = [];
end
end
%% extract DF/F signal after performing NMF
function [C_df, Df, S_df] = extractDF_F(obj, Y, i)
if ~exist('i', 'var')
i = size(obj.A, 2) + 1;
end
[obj.C_df, obj.Df, obj.S_df] = extract_DF_F(Y, [obj.A, obj.b],...
[obj.C; obj.f], obj.S, i);
C_df = obj.C_df;
Df = obj.Df;
S_df = obj.S_df;
end
%% extract DF/F signal for microendoscopic data
function [C_df,C_raw_df, Df] = extract_DF_F_endoscope(obj, Ybg)
options_ = obj.options;
A_ = obj.A;
C_ = obj.C;
[K,T] = size(obj.C); % number of frames
Ybg = bsxfun(@times, A_, 1./sum(A_.^2, 1))' * Ybg; % estimate the background for each neurons
if isempty(options_.df_window) || (options_.df_window > T)
% use quantiles of the whole recording session as the
% baseline
if options_.df_prctile == 50
Df = median(Ybg,2);
else
Df = prctile(Ybg,options_.df_prctile,2);
end
C_df = spdiags(Df,0,K,K)\C_;
C_raw_df = spdiags(Df,0,K,K)\obj.C_raw;
else
% estimate the baseline for each short period
if options_.df_prctile == 50
Df = medfilt1(Ybg,options_.df_window,[],2,'truncate');
else
Df = zeros(size(Ybg));
for i = 1:size(Df,1)
df_temp = running_percentile(Ybg(i,:), options_.df_window, options_.df_prctile);
Df(i,:) = df_temp(:)';
end
end
C_df = C_./Df;
C_raw_df = obj.C_raw./Df;
end
end
%% order_ROIs
function [srt] = orderROIs(obj, srt)
%% order neurons
% srt: sorting order
nA = sqrt(sum(obj.A.^2));
nr = length(nA);
if nargin<2
srt='srt';
end
K = size(obj.C, 1);
if ischar(srt)
if strcmpi(srt, 'decay_time')
% time constant
if K<0
disp('Are you kidding? You extracted 0 neurons!');
return;
else
taud = zeros(K, 1);
for m=1:K
temp = ar2exp(obj.P.kernel_pars(m));
taud(m) = temp(1);
end
[~, srt] = sort(taud);
end
elseif strcmp(srt, 'mean')
if obj.options.deconv_flag
temp = mean(obj.C,2)'.*sum(obj.A);
else
temp = mean(obj.C,2)'.*sum(obj.A)./obj.P.neuron.sn';
end
[~, srt] = sort(temp, 'descend');
elseif strcmp(srt, 'sparsity_spatial')
temp = sqrt(sum(obj.A.^2, 1))./sum(abs(obj.A), 1);
[~, srt] = sort(temp);
elseif strcmp(srt, 'sparsity_temporal')
temp = sqrt(sum(obj.C_raw.^2, 2))./sum(abs(obj.C_raw), 2);
[~, srt] = sort(temp, 'descend');
elseif strcmp(srt, 'circularity')
% order neurons based on its circularity
tmp_circularity = zeros(K,1);
for m=1:K
[w, r] = nnmf(obj.reshape(obj.A(:, m),2), 1);
ky = sum(w>max(w)*0.3);
kx = sum(r>max(r)*0.3);
tmp_circularity(m) = abs((kx-ky+0.5)/((kx+ky)^2));
end
[~, srt] = sort(tmp_circularity, 'ascend');
elseif strcmpi(srt, 'pnr')
pnrs = max(obj.C, [], 2)./std(obj.C_raw-obj.C, 0, 2);
[~, srt] = sort(pnrs, 'descend');
else %if strcmpi(srt, 'snr')
snrs = var(obj.C, 0, 2)./var(obj.C_raw-obj.C, 0, 2);
[~, srt] = sort(snrs, 'descend');
end
end
obj.A = obj.A(:, srt);
obj.C = obj.C(srt, :);
try
obj.C_raw = obj.C_raw(srt,:);
obj.S = obj.S(srt,:);
obj.P.kernel_pars = obj.P.kernel_pars(srt, :);
obj.P.neuron_sn = obj.P.neuron_sn(srt);
obj.ids = obj.ids(srt);
obj.tags = obj.tags(srt);
end
end
%% view contours
function [Coor, json_file] = viewContours(obj, Cn, contour_threshold, display, ind, ln_wd)
if or(isempty(Cn), ~exist('Cn', 'var') )
Cn = reshape(obj.P.sn, obj.options.d1, obj.options.d2);
end
if (~exist('display', 'var') || isempty(display)); display=0; end
if (~exist('ind', 'var') || isempty(ind)); ind=1:size(obj.A, 2); end
if (~exist('ln_wd', 'var') || isempty(ln_wd)); ln_wd = 1; end
[obj.Coor, json_file] = plot_contours(obj.A(:, ind), Cn, ...
contour_threshold, display, [], [], ln_wd);
Coor = obj.Coor;
end
%% plot components
function plotComponents(obj, Y, Cn)
if ~exist('Cn', 'var')
Cn = [];
end
view_components(Y, obj.A, obj.C, obj.b, obj.f, Cn, obj.options);
end
%% plot components GUI
function plotComponentsGUI(obj, Y, Cn)
if ~exist('Cn', 'var')
Cn = [];
end
plot_components_GUI(Y,obj.A,obj.C,obj.b,obj.f,Cn,obj.options)
end
%% make movie
function makePatchVideo(obj, Y)
make_patch_video(obj.A, obj.C, obj.b, obj.f, Y, obj.Coor,...
obj.options);
end
%% down sample data and initialize it
[obj_ds, Y_ds] = downSample(obj, Y)
%% up-sample the results
upSample(obj, obj_ds, T);
%% copy the objects
function obj_new = copy(obj)
% Instantiate new object of the same class.
obj_new = feval(class(obj));
% Copy all non-hidden properties.
p = properties(obj);
for i = 1:length(p)
obj_new.(p{i}) = obj.(p{i});
end
end
%% concatenate results from multi patches
function concatenate_temporal_batch(obj)
T_k= obj.P.numFrames;
T = sum(T_k);
K = size(obj.A,2);
C_ = zeros(K, T);
C_raw_ = zeros(K, T);
deconv_flag = obj.options.deconv_flag;
if deconv_flag
S_ = zeros(K, T);
end
t = 0;
nbatches = length(obj.batches);
for mbatch=1:nbatches
neuron_k = obj.batches{mbatch}.neuron;
try
C_(:, t+(1:T_k(mbatch))) = neuron_k.C;
catch
pause;
end
C_raw_(:, t+(1:T_k(mbatch))) = neuron_k.C_raw;
if deconv_flag
S_(:, t+(1:T_k(mbatch))) = neuron_k.S;
end
t = t+T_k(mbatch);
end
obj.C = C_;
obj.C_raw = C_raw_;
if deconv_flag
obj.S = S_;
end
end
%% quick view
ind_del = viewNeurons(obj, ind, C2, folder_nm);
displayNeurons(obj, ind, C2, folder_nm);
%% function remove false positives
function ids = remove_false_positives(obj, show_delete)
if ~exist('show_delete', 'var')
show_delete = false;
end
tags_ = obj.tag_neurons_parallel(); % find neurons with fewer nonzero pixels than min_pixel and silent calcium transients
ids = find(tags_);
if isempty(ids)
fprintf('all components are good \n');
else
if show_delete
obj.viewNeurons(ids, obj.C_raw);
else
obj.delete(ids);
end
end
end
%% delete neurons
function delete(obj, ind)
% write the deletion into the log file
if ~exist('ind', 'var') || isempty(ind)
return;
end
try
% folders and files for saving the results
log_file = obj.P.log_file;
flog = fopen(log_file, 'a');
log_data = matfile(obj.P.log_data, 'Writable', true); %#ok<NASGU>
ids_del = obj.ids(ind);
if isempty(ids_del)
fprintf('no neurons to be deleted\n');
fclose(flog);
return;
end
fprintf(flog, '[%s]\b', get_minute());
fprintf('Deleted %d neurons: ', length(ids_del));
fprintf(flog, 'Deleted %d neurons: \n', length(ids_del));
for m=1:length(ids_del)
fprintf('%2d, ', ids_del(m));
fprintf(flog, '%2d, ', ids_del(m));
end
fprintf(flog, '\n');
fprintf('\nThe IDS of these neurons were saved as intermediate_results.ids_del_%s\n\n', tmp_str);
if obj.options.save_intermediate
tmp_str = get_date();
tmp_str=strrep(tmp_str, '-', '_');
eval(sprintf('log_data.ids_del_%s = ids_del;', tmp_str));
fprintf(flog, '\tThe IDS of these neurons were saved as intermediate_results.ids_del_%s\n\n', tmp_str);
end
fclose(flog);
end
obj.A(:, ind) = [];
obj.C(ind, :) = [];
if ~isempty(obj.S)
try obj.S(ind, :) = []; catch; end
end
if ~isempty(obj.C_raw)
try obj.C_raw(ind, :) = []; catch; end
end
if isfield(obj.P, 'kernel_pars')&&( ~isempty(obj.P.kernel_pars))
try obj.P.kernel_pars(ind, :) = []; catch; end
end
try obj.ids(ind) = []; catch; end
try obj.tags(ind) =[]; catch; end
% save the log
end
%% merge neurons
%% estimate neuron centers
function [center] = estCenter(obj)
center = com(obj.A, obj.options.d1, obj.options.d2);
end
%% update A & C using HALS
function [obj, IDs] = HALS_AC(obj, Y)
%update A,C,b,f with HALS
Y = obj.reshape(Y, 1);
[obj.A, obj.C, obj.b, obj.f, IDs] = HALS_2d(Y, obj.A, obj.C, obj.b,...
obj.f, obj.options);
end
%% update backgrounds
[B, F] = updateBG(obj, Y, nb, model)
%% reshape data
function Y = reshape(obj, Y, dim)
% reshape the imaging data into diffrent dimensions
d1 = obj.options.d1;
d2 = obj.options.d2;
if dim==1
Y=reshape(Y, d1*d2, []); %each frame is a vector
else
Y = reshape(full(Y), d1, d2, []); %each frame is an image
end
end
%% deconvolve all temporal components
C_ = deconvTemporal(obj, use_parallel, method_noise)
%% decorrelate all tmeporal components
C_ = decorrTemporal(obj, wd);
%% play movie
function playMovie(obj, Y, min_max, col_map, avi_nm, t_pause)
Y = double(Y);
d1 = obj.options.d1;
d2 = obj.options.d2;
% play movies
figure('papersize', [d2,d1]/max(d1,d2)*5);
width = d2/max(d1,d2)*500;
height =d1/max(d1,d2)*500;
set(gcf, 'position', [500, 200, width, height]);
axes('position', [0,0, 1, 1]);
if ~exist('col_map', 'var') || isempty(col_map)
col_map = jet;
end
if exist('avi_nm', 'var') && ischar(avi_nm)
avi_file = VideoWriter(avi_nm);
if ~isnan(obj.Fs)
avi_file.FrameRate = obj.Fs;
end
avi_file.open();
avi_flag = true;
else
avi_flag = false;
end
if ismatrix(Y); Y=obj.reshape(Y, 2); end
[~, ~, T] = size(Y);
if (nargin<3) || (isempty(min_max))
temp = Y(:, :, randi(T, min(100, T), 1));
min_max = quantile(temp(:), [0.2, 0.9999]);
min_max(1) = max(min_max(1), 0);
min_max(2) = max(min_max(2), min_max(1)+0.1);
end
if ~exist('t_pause', 'var'); t_pause=0.01; end
for t=1:size(Y,3)
imagesc(Y(:, :, t), min_max); colormap(col_map);
axis equal; axis off tight;
if isnan(obj.Fs)
title(sprintf('Frame %d', t));
else
text(1, 10, sprintf('Time = %.2f', t/obj.Fs), 'fontsize', 15, 'color', 'w');
end
pause(t_pause);
if avi_flag
temp = getframe(gcf);
temp.cdata = imresize(temp.cdata, [height, width]);
avi_file.writeVideo(temp);
end
end
if avi_flag
avi_file.close();
end
end
%% export AVI
function exportAVI(obj, Y, min_max, avi_nm, col_map)
% export matrix data to movie
%min_max: 1*2 vector, scale
%avi_nm: string, file name
%col_map: colormap
T = size(Y, ndims(Y));
Y = Y(:);
if ~exist('col_map', 'var') || isempty(col_map)
col_map = jet;
end
if ~exist('avi_nm', 'var') || isempty(avi_nm)
avi_nm = 'a_movie_with_no_name.avi';
end
if ~exist('min_max', 'var') || isempty(min_max)
min_max = [min(Y(1:10:end)), max(Y(1:10:end))];
end
Y = uint8(64*(Y-min_max(1))/diff(min_max));
Y(Y<1) = 1;
Y(Y>64) = 64;
col_map = uint8(255*col_map);
Y = reshape(col_map(Y, :), obj.options.d1, [], T, 3);
Y = permute(Y, [1,2,4,3]);
avi_file = VideoWriter(avi_nm);
avi_file.open();
for m=1:T
% temp.cdata = squeeze(Y(:, :, :, m));
% temp.colormap = [];
avi_file.writeVideo(squeeze(Y(:, :, :, m)));
end
avi_file.close();
end
%% trim spatial components
function [ind_small] = trimSpatial(obj, thr, sz)
% remove small nonzero pixels
if nargin<2; thr = 0.01; end
if nargin<3; sz = 5; end
se = strel('square', sz);
ind_small = false(size(obj.A, 2), 1);
for m=1:size(obj.A,2)
ai = obj.A(:,m);
ai_open = imopen(obj.reshape(ai,2), se);
temp = full(ai_open>max(ai)*thr);
l = bwlabel(obj.reshape(temp,2), 4); % remove disconnected components
[~, ind_max] = max(ai_open(:));
ai(l(:)~=l(ind_max)) = 0;
if sum(ai(:)>0) < obj.options.min_pixel %the ROI is too small
ind_small(m) = true;
end
obj.A(:, m) = ai(:);
end
% ind_small = find(ind_small);
% obj.delete(ind_small);
end
%% keep spatial shapes compact
function compactSpatial(obj)
for m=1:size(obj.A, 2)
ai = obj.reshape(obj.A(:, m), 2);
ai = circular_constraints(ai);
obj.A(:, m) = ai(:);
end
end
%% solve A & C with regression
function [ind_delete] = regressAC(obj, Y)
if ~ismatrix(Y); Y=obj.reshape(Y,2); end
maxIter = 1;
A2 = obj.A; % initial spatial components
for miter=1:maxIter
ind_nonzero = obj.trimSpatial(50); % remove tiny nonzero pixels
active_pixel = determine_search_location(A2, 'dilate', obj.options);
K = size(A2, 2); %number of neurons
tmp_C = (A2'*A2)\(A2'*Y); % update temporal components
tmp_C(tmp_C<0) = 0;
% % tmp_C(bsxfun(@gt, quantile(tmp_C, 0.95, 2), tmp_C)) = 0;
% tmp_C(bsxfun(@gt, mean(tmp_C, 2)+std(tmp_C, 0.0, 2), tmp_C)) = 0;
A2 = (Y*tmp_C')/(tmp_C*tmp_C'); % update spatial components
A2(or(A2<0, ~active_pixel)) = 0;
for m=1:K
% remove disconnected pixels
img = obj.reshape(A2(:,m), 2);
lb = bwlabel(img>max(img(:))/50, 4);
img(lb~=mode(lb(ind_nonzero(:, m)))) = 0 ; %find pixels connected to the original components
A2(:,m) = img(:);
end
center_ratio = sum(A2.*ind_nonzero, 1)./sum(A2, 1); %
% captured too much pixels, ignore newly captured pixels
ind_too_much = (center_ratio<0.4);
A2(:, ind_too_much) = A2(:, ind_too_much) .*ind_nonzero(:, ind_too_much);
% captured too much noiser pixels or all pxiels are zero, ignore this neuron
ind_delete = or(center_ratio<0.01, sum(A2,1)==0);
A2(:, ind_delete) = [];
obj.A = A2;
end
temp = (A2'*A2)\(A2'*Y);
temp(temp<0) = 0;
obj.C = temp;
end
%% regress A given C