-
Notifications
You must be signed in to change notification settings - Fork 375
/
Copy pathonline_cnmf.py
2542 lines (2260 loc) · 126 KB
/
online_cnmf.py
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
#!/usr/bin/env python
""" Online Constrained Nonnegative Matrix Factorization
The general file class which is used to analyze calcium imaging data in an
online fashion using the OnACID algorithm. The output of the algorithm
is storead in an Estimates class
More info:
------------
Giovannucci, A., Friedrich, J., Kaufman, M., Churchland, A., Chklovskii, D.,
Paninski, L., & Pnevmatikakis, E.A. (2017). OnACID: Online analysis of calcium
imaging data in real time. In Advances in Neural Information Processing Systems
(pp. 2381-2391).
@url http://papers.nips.cc/paper/6832-onacid-online-analysis-of-calcium-imaging-data-in-real-time
"""
import cv2
import logging
from math import sqrt
from multiprocessing import cpu_count
import numpy as np
import os
from scipy.ndimage import percentile_filter
from scipy.sparse import coo_matrix, csc_matrix, spdiags, hstack
from scipy.stats import norm
from sklearn.decomposition import NMF
from sklearn.preprocessing import normalize
import tensorflow as tf
from time import time
import caiman
import caiman.base.movies
from caiman.components_evaluation import compute_event_exceptionality
import caiman.mmapping
from caiman.motion_correction import (motion_correct_iteration_fast,
tile_and_correct, tile_and_correct_3d,
high_pass_filter_space, sliding_window,
register_translation_3d, apply_shifts_dft)
import caiman.paths
from caiman.source_extraction.cnmf.cnmf import CNMF
from caiman.source_extraction.cnmf.estimates import Estimates
from caiman.source_extraction.cnmf.initialization import imblur, initialize_components, hals, downscale
from caiman.source_extraction.cnmf.oasis import OASIS
from caiman.source_extraction.cnmf.params import CNMFParams
from caiman.source_extraction.cnmf.pre_processing import get_noise_fft
from caiman.source_extraction.cnmf.utilities import (update_order, peak_local_max, decimation_matrix,
gaussian_filter, uniform_filter)
import caiman.summary_images
from caiman.utils.utils import save_dict_to_hdf5, load_dict_from_hdf5, parmap, load_graph
from caiman.utils.stats import pd_solve
from caiman.utils.nn_models import (fit_NL_model, create_LN_model, quantile_loss, rate_scheduler)
try:
cv2.setNumThreads(0)
except():
pass
#FIXME ???
try:
profile
except:
def profile(a): return a
class OnACID(object):
""" Source extraction of streaming data using online matrix factorization.
The class can be initialized by passing a "params" object for setting up
the relevant parameters and an "Estimates" object for setting an initial
state of the algorithm (optional)
Methods:
initialize_online:
Initialize the online algorithm using a provided method, and prepare
the online object
_prepare_object:
Prepare the online object given a set of estimates
fit_next:
Fit the algorithm on the next data frame
fit_online:
Run the entire online pipeline on a given list of files
"""
def __init__(self, params=None, estimates=None, path=None, dview=None, Ain=None):
"""
Args:
params: CNMFParams
CNMFParams object with parameters that are used to perform online motion correction, followed by online CNMF
estimates: Estimates, optional
Estimates object to load an existing model
path: str, optional
path to a saved OnACID model hdf5 file on disk
dview:
dview instance, multiprocessing object
Ain: csc_matrix, optional
binary masked for seeded initialization as a Compressed Sparse Column matrix.
To use set ``"init_method"`` to ``"seeded"``
"""
if path is None:
self.params = CNMFParams() if params is None else params
self.estimates = Estimates() if estimates is None else estimates
else:
onacid = load_OnlineCNMF(path)
self.params = params if params is not None else onacid.params
self.estimates= estimates if estimates is not None else onacid.estimates
self.dview = dview
if Ain is not None:
self.estimates.A = Ain
@profile
def _prepare_object(self, Yr, T, new_dims=None, idx_components=None):
init_batch = self.params.get('online', 'init_batch')
old_dims = self.params.get('data', 'dims')
self.is1p = (self.params.get('init', 'method_init') == 'corr_pnr' and
self.params.get('init', 'ring_size_factor') is not None)
if idx_components is None:
idx_components = range(self.estimates.A.shape[-1])
self.estimates.A = self.estimates.A.astype(np.float32)
self.estimates.C = self.estimates.C.astype(np.float32)
if self.estimates.f is not None:
self.estimates.f = self.estimates.f.astype(np.float32)
if self.estimates.b is not None:
self.estimates.b = self.estimates.b.astype(np.float32)
self.estimates.YrA = self.estimates.YrA.astype(np.float32)
self.estimates.select_components(idx_components=idx_components)
self.N = self.estimates.A.shape[-1]
self.M = self.params.get('init', 'nb') + self.N
if not self.params.get('online', 'update_num_comps'):
self.params.set('online', {'expected_comps': self.N})
elif (self.params.get('online', 'expected_comps') <=
self.N + self.params.get('online', 'max_num_added')):
self.params.set('online', {'expected_comps': self.N +
self.params.get('online', 'max_num_added') + 200})
expected_comps = self.params.get('online', 'expected_comps')
if Yr.shape[-1] != self.params.get('online', 'init_batch'):
raise Exception(
'The movie size used for initialization does not match with the minibatch size')
if new_dims is not None:
new_Yr = np.zeros([np.prod(new_dims), init_batch])
for ffrr in range(init_batch):
tmp = cv2.resize(Yr[:, ffrr].reshape(old_dims, order='F'), new_dims[::-1])
print(tmp.shape)
new_Yr[:, ffrr] = tmp.reshape([np.prod(new_dims)], order='F')
Yr = new_Yr
A_new = csc_matrix((np.prod(new_dims), self.estimates.A.shape[-1]),
dtype=np.float32)
for neur in range(self.N):
a = self.estimates.A.tocsc()[:, neur].toarray()
a = a.reshape(old_dims, order='F')
a = cv2.resize(a, new_dims[::-1]).reshape([-1, 1], order='F')
A_new[:, neur] = csc_matrix(a)
self.estimates.A = A_new
if self.estimates.b.size:
self.estimates.b = self.estimates.b.reshape(old_dims, order='F')
self.estimates.b = cv2.resize(
self.estimates.b, new_dims[::-1]).reshape([-1, 1], order='F')
else:
self.estimates.b.shape = (np.prod(new_dims), 0)
if self.is1p:
# self.estimates.b0 is calculated below
# ToDo, but not easy: resize self.estimates.W
raise NotImplementedError('change of dimensions not yet implemented for CNMF-E')
self.estimates.dims = new_dims
else:
self.estimates.dims = old_dims
self.estimates.normalize_components()
self.estimates.A = self.estimates.A.todense()
self.estimates.noisyC = np.zeros(
(self.params.get('init', 'nb') + expected_comps, T), dtype=np.float32)
self.estimates.C_on = np.zeros((expected_comps, T), dtype=np.float32)
self.estimates.noisyC[self.params.get('init', 'nb'):self.M, :self.params.get('online', 'init_batch')] = self.estimates.C + self.estimates.YrA
self.estimates.noisyC[:self.params.get('init', 'nb'), :self.params.get('online', 'init_batch')] = self.estimates.f
if self.params.get('preprocess', 'p'):
# if no parameter for calculating the spike size threshold is given, then use L1 penalty
if self.params.get('temporal', 's_min') is None:
use_L1 = True
else:
use_L1 = False
self.estimates.OASISinstances = [OASIS(
g=gam[0], lam=0 if not use_L1 else l,
s_min=0 if use_L1 else (self.params.get('temporal', 's_min') if self.params.get('temporal', 's_min') > 0 else
(-self.params.get('temporal', 's_min') * sn * np.sqrt(1 - np.sum(gam)))),
b=b,
g2=0 if self.params.get('preprocess', 'p') < 2 else gam[1])
for gam, l, b, sn in zip(self.estimates.g, self.estimates.lam, self.estimates.bl, self.estimates.neurons_sn)]
for i, o in enumerate(self.estimates.OASISinstances):
o.fit(self.estimates.noisyC[i + self.params.get('init', 'nb'), :init_batch])
self.estimates.C_on[i, :init_batch] = o.c
else:
self.estimates.C_on[:self.N, :init_batch] = self.estimates.C
if self.is1p:
ssub_B = self.params.get('init', 'ssub_B') * self.params.get('init', 'ssub')
X = Yr[:, :init_batch] - np.asarray(self.estimates.A.dot(self.estimates.C))
self.estimates.b0 = X.mean(1)
X -= self.estimates.b0[:, None]
if ssub_B > 1:
self.estimates.downscale_matrix = decimation_matrix(self.estimates.dims, ssub_B)
self.estimates.upscale_matrix = self.estimates.downscale_matrix.T
self.estimates.upscale_matrix.data = np.ones_like(self.estimates.upscale_matrix.data)
X = self.estimates.downscale_matrix.dot(X)
if self.params.get('online', 'full_XXt'):
self.estimates.XXt = X.dot(X.T)
else:
self.XXt_mats = []
self.XXt_vecs = []
self.W_ind = []
W = self.estimates.W
for p in range(W.shape[0]):
index = W.indices[W.indptr[p]:W.indptr[p + 1]]
self.W_ind.append(index)
x_i = X[index]
self.XXt_mats.append(x_i.dot(x_i.T))
self.XXt_vecs.append(x_i.dot(X[p].T))
self.estimates.Ab, self.ind_A, self.estimates.CY, self.estimates.CC = init_shapes_and_sufficient_stats(
Yr[:, :init_batch].reshape(self.estimates.dims + (-1,), order='F'),
self.estimates.A, self.estimates.C_on[:self.N, :init_batch],
self.estimates.b, self.estimates.noisyC[:self.params.get('init', 'nb'), :init_batch],
W=self.estimates.W if self.is1p else None, b0=self.estimates.b0 if self.is1p else None,
ssub_B=self.params.get('init', 'ssub_B') * self.params.get('init', 'ssub'),
downscale_matrix=self.estimates.downscale_matrix if (self.is1p and ssub_B > 1) else None,
upscale_matrix=self.estimates.upscale_matrix if (self.is1p and ssub_B > 1) else None)
self.estimates.CY = self.estimates.CY * 1. / self.params.get('online', 'init_batch')
self.estimates.CC = 1 * self.estimates.CC / self.params.get('online', 'init_batch')
logging.info(f'Expecting {expected_comps} components')
self.estimates.CY.resize([expected_comps + self.params.get('init', 'nb'), self.estimates.CY.shape[-1]], refcheck=False)
if self.params.get('online', 'use_dense'):
self.estimates.Ab_dense = np.zeros((self.estimates.CY.shape[-1], expected_comps + self.params.get('init', 'nb')),
dtype=np.float32)
self.estimates.Ab_dense[:, :self.estimates.Ab.shape[1]] = self.estimates.Ab.toarray()
self.estimates.C_on = np.vstack(
[self.estimates.noisyC[:self.params.get('init', 'nb'), :], self.estimates.C_on.astype(np.float32)])
if not self.is1p:
self.params.set('init', {'gSiz': np.add(np.multiply(np.ceil(
self.params.get('init', 'gSig')).astype(int), 2), 1)})
self.estimates.Yr_buf = RingBuffer(Yr[:, self.params.get('online', 'init_batch') - self.params.get('online', 'minibatch_shape'):
self.params.get('online', 'init_batch')].T.copy(), self.params.get('online', 'minibatch_shape'))
self.estimates.Yres_buf = RingBuffer(self.estimates.Yr_buf - self.estimates.Ab.dot(
self.estimates.C_on[:self.M, self.params.get('online', 'init_batch') - self.params.get('online', 'minibatch_shape'):
self.params.get('online', 'init_batch')]).T, self.params.get('online', 'minibatch_shape'))
if self.is1p:
estim = self.estimates
d1, d2 = estim.dims
estim.Yres_buf -= estim.b0
if ssub_B == 1:
estim.Atb = estim.Ab.T.dot(estim.W.dot(estim.b0) - estim.b0)
estim.AtW = estim.Ab.T.dot(estim.W)
estim.AtWA = estim.AtW.dot(estim.Ab).toarray()
estim.Yres_buf -= estim.W.dot(estim.Yres_buf.T).T
else:
A_ds = estim.downscale_matrix.dot(estim.Ab)
estim.Atb = estim.Ab.T.dot(estim.upscale_matrix.dot(
estim.W.dot(estim.downscale_matrix.dot(estim.b0))) - estim.b0)
estim.AtW = A_ds.T.dot(estim.W)
estim.AtWA = estim.AtW.dot(A_ds).toarray()
estim.Yres_buf -= estim.upscale_matrix.dot(estim.W.dot(
estim.downscale_matrix.dot(estim.Yres_buf.T))).T
self.estimates.sn = np.array(np.std(self.estimates.Yres_buf,axis=0))
self.estimates.vr = np.array(np.var(self.estimates.Yres_buf,axis=0))
self.estimates.mn = self.estimates.Yres_buf.mean(0)
self.estimates.mean_buff = self.estimates.Yres_buf.mean(0)
self.estimates.ind_new = []
if self.params.get('online', 'use_corr_img'):
self.estimates.rho_buf = None
self.estimates.sv = None
else:
self.estimates.rho_buf = imblur(np.maximum(self.estimates.Yres_buf.T, 0).reshape(
self.estimates.dims + (-1,), order='F'), sig=self.params.get('init', 'gSig'),
siz=self.params.get('init', 'gSiz'), nDimBlur=len(self.estimates.dims))**2
self.estimates.rho_buf = np.reshape(
self.estimates.rho_buf, (np.prod(self.estimates.dims), -1)).T
self.estimates.rho_buf = np.ascontiguousarray(self.estimates.rho_buf)
self.estimates.rho_buf = RingBuffer(self.estimates.rho_buf, self.params.get('online', 'minibatch_shape'))
self.estimates.sv = np.sum(self.estimates.rho_buf.get_last_frames(
min(self.params.get('online', 'init_batch'), self.params.get('online', 'minibatch_shape')) - 1), 0)
self.estimates.AtA = (self.estimates.Ab.T.dot(self.estimates.Ab)).toarray()
self.estimates.AtY_buf = self.estimates.Ab.T.dot(self.estimates.Yr_buf.T)
self.estimates.groups = list(map(list, update_order(self.estimates.Ab)[0]))
self.update_counter = 2**np.linspace(0, 1, self.N, dtype=np.float32)
self.estimates.CC = np.ascontiguousarray(self.estimates.CC)
self.estimates.CY = np.ascontiguousarray(self.estimates.CY)
self.time_neuron_added:list = []
for nneeuu in range(self.N):
self.time_neuron_added.append((nneeuu, self.params.get('online', 'init_batch')))
if self.params.get('online', 'dist_shape_update'):
self.time_spend = 0
self.comp_upd:list = []
# setup per patch classifier
if self.params.get('online', 'path_to_model') is None or self.params.get('online', 'sniper_mode') is False:
loaded_model = None
self.params.set('online', {'sniper_mode': False})
self.tf_in = None
self.tf_out = None
else:
if caiman.keras is not None:
logging.info('Using Keras')
model_from_json = caiman.keras.models.model_from_json
path = self.params.get('online', 'path_to_model').split(".")[:-1]
json_path = ".".join(path + ["json"])
model_path = ".".join(path + ["h5"])
json_file = open(json_path, 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights(model_path)
self.tf_in = None
self.tf_out = None
else:
logging.info('Using Tensorflow')
path = self.params.get('online', 'path_to_model').split(".")[:-1]
model_path = '.'.join(path + ['h5', 'pb'])
loaded_model = load_graph(model_path)
self.tf_in = loaded_model.get_tensor_by_name('prefix/conv2d_1_input:0')
self.tf_out = loaded_model.get_tensor_by_name('prefix/output_node0:0')
loaded_model = tf.Session(graph=loaded_model)
self.loaded_model = loaded_model
if self.is1p:
from skimage.morphology import disk
radius = int(round(self.params.get('init', 'ring_size_factor') *
self.params.get('init', 'gSiz')[0] / float(ssub_B)))
ring = disk(radius + 1)
ring[1:-1, 1:-1] -= disk(radius)
self._ringidx = [i - radius - 1 for i in np.nonzero(ring)]
self._dims_B = ((self.estimates.dims[0] - 1) // ssub_B + 1,
(self.estimates.dims[1] - 1) // ssub_B + 1)
def get_indices_of_pixels_on_ring(self, pixel):
pixel = np.unravel_index(pixel, self._dims_B, order='F')
x = pixel[0] + self._ringidx[0]
y = pixel[1] + self._ringidx[1]
inside = (x >= 0) * (x < self._dims_B[0]) * (y >= 0) * (y < self._dims_B[1])
return np.ravel_multi_index((x[inside], y[inside]), self._dims_B, order='F')
self.get_indices_of_pixels_on_ring = get_indices_of_pixels_on_ring.__get__(self)
# generate list of indices of XX' that get accessed
if self.params.get('online', 'full_XXt'):
l = np.prod(self._dims_B)
tmp = np.zeros((l, l), dtype=bool)
for p in range(l):
index = self.get_indices_of_pixels_on_ring(p)
tmp[index[:, None], index] = True
tmp[index, p] = True
self.estimates.XXt_ind = list([np.where(t)[0] for t in tmp])
if self.params.get('online', 'use_corr_img'):
Yres = Yr[:, :init_batch] - self.estimates.Ab.dot(
self.estimates.C_on[:self.M, :init_batch])
if self.is1p:
Yres -= self.estimates.b0[:, None]
if ssub_B == 1:
Yres -= self.estimates.W.dot(Yres)
else:
Yres -= estim.upscale_matrix.dot(estim.W.dot(
estim.downscale_matrix.dot(Yres)))
Yres = Yres.reshape((d1, d2, -1), order='F')
(self.estimates.first_moment, self.estimates.second_moment,
self.estimates.crosscorr, self.estimates.col_ind, self.estimates.row_ind,
self.estimates.num_neigbors, self.estimates.corrM, self.estimates.corr_img) = \
caiman.summary_images.prepare_local_correlations(Yres, swap_dim=True, eight_neighbours=False)
self.estimates.max_img = Yres.max(-1)
self.comp_upd = []
self.t_shapes:list = []
self.t_detect:list = []
self.t_motion:list = []
self.t_stat:list = []
return self
@profile
def fit_next(self, t, frame_in, num_iters_hals=3):
"""
This method fits the next frame using the CaImAn online algorithm and
updates the object. Does NOT perform motion correction, see ``mc_next()``
Args
t : int
temporal index of the next frame to fit
frame_in : array
flattened array of shape (x * y [ * z],) containing the t-th image.
num_iters_hals: int, optional
maximal number of iterations for HALS (NNLS via blockCD)
"""
t_start = time()
# locally scoped variables for brevity of code and faster look up
nb_ = self.params.get('init', 'nb')
Ab_ = self.estimates.Ab
mbs = self.params.get('online', 'minibatch_shape')
ssub_B = self.params.get('init', 'ssub_B') * self.params.get('init', 'ssub')
expected_comps = self.params.get('online', 'expected_comps')
frame = frame_in.astype(np.float32)
self.estimates.Yr_buf.append(frame)
if len(self.estimates.ind_new) > 0:
self.estimates.mean_buff = self.estimates.Yres_buf.mean(0)
if (not self.params.get('online', 'simultaneously')) or self.params.get('preprocess', 'p') == 0:
# get noisy fluor value via NNLS (project data on shapes & demix)
C_in = self.estimates.noisyC[:self.M, t - 1].copy()
if self.is1p:
self.estimates.C_on[:self.M, t], self.estimates.noisyC[:self.M, t] = demix1p(
frame, self.estimates.Ab, C_in, self.estimates.AtA, Atb=self.estimates.Atb,
AtW=self.estimates.AtW, AtWA=self.estimates.AtWA, iters=num_iters_hals,
groups=self.estimates.groups, ssub_B=ssub_B,
downscale_matrix=self.estimates.downscale_matrix if ssub_B > 1 else None)
else:
self.estimates.C_on[:self.M, t], self.estimates.noisyC[:self.M, t] = HALS4activity(
frame, self.estimates.Ab, C_in, self.estimates.AtA, iters=num_iters_hals, groups=self.estimates.groups)
if self.params.get('preprocess', 'p'):
# denoise & deconvolve
for i, o in enumerate(self.estimates.OASISinstances):
o.fit_next(self.estimates.noisyC[nb_ + i, t])
self.estimates.C_on[nb_ + i, t - o.get_l_of_last_pool() +
1: t + 1] = o.get_c_of_last_pool()
else:
if self.is1p:
raise NotImplementedError(
'simultaneous demixing and deconvolution not implemented yet for CNMF-E')
# update buffer, initialize C with previous value
self.estimates.C_on[:, t] = self.estimates.C_on[:, t - 1]
self.estimates.noisyC[:, t] = self.estimates.C_on[:, t - 1]
self.estimates.AtY_buf = np.concatenate((self.estimates.AtY_buf[:, 1:], self.estimates.Ab.T.dot(frame)[:, None]), 1) \
if self.params.get('online', 'n_refit') else self.estimates.Ab.T.dot(frame)[:, None]
# demix, denoise & deconvolve
(self.estimates.C_on[:self.M, t + 1 - mbs:t + 1], self.estimates.noisyC[:self.M, t + 1 - mbs:t + 1],
self.estimates.OASISinstances) = demix_and_deconvolve(
self.estimates.C_on[:self.M, t + 1 - mbs:t + 1],
self.estimates.noisyC[:self.M, t + 1 - mbs:t + 1],
self.estimates.AtY_buf, self.estimates.AtA, self.estimates.OASISinstances, iters=num_iters_hals,
n_refit=self.params.get('online', 'n_refit'))
for i, o in enumerate(self.estimates.OASISinstances):
self.estimates.C_on[nb_ + i, t - o.get_l_of_last_pool() + 1: t +
1] = o.get_c_of_last_pool()
#self.estimates.mean_buff = self.estimates.Yres_buf.mean(0)
res_frame = frame - self.estimates.Ab.dot(self.estimates.C_on[:self.M, t])
if self.is1p:
self.estimates.b0 = self.estimates.b0 * (t-1)/t + res_frame/t
res_frame -= self.estimates.b0
res_frame -= (self.estimates.W.dot(res_frame) if ssub_B == 1 else
self.estimates.upscale_matrix.dot(self.estimates.W.dot(
self.estimates.downscale_matrix.dot(res_frame))))
mn_ = self.estimates.mn.copy()
self.estimates.mn = (t-1)/t*self.estimates.mn + res_frame/t
self.estimates.vr = (t-1)/t*self.estimates.vr + (res_frame - mn_)*(res_frame - self.estimates.mn)/t
self.estimates.sn = np.sqrt(self.estimates.vr)
t_new = time()
num_added = 0
if self.params.get('online', 'update_num_comps'):
if self.params.get('online', 'use_corr_img'):
corr_img_mode = 'simple' #'exponential' # 'cumulative'
self.estimates.corr_img = caiman.summary_images.update_local_correlations(
t + 1 if corr_img_mode == 'cumulative' else mbs,
res_frame.reshape((1,) + self.estimates.dims, order='F'),
self.estimates.first_moment, self.estimates.second_moment,
self.estimates.crosscorr, self.estimates.col_ind, self.estimates.row_ind,
self.estimates.num_neigbors, self.estimates.corrM,
del_frames=[self.estimates.Yres_buf[self.estimates.Yres_buf.cur]]
if corr_img_mode == 'simple' else None)
self.estimates.mean_buff += (res_frame-self.estimates.Yres_buf[self.estimates.Yres_buf.cur])/self.params.get('online', 'minibatch_shape')
self.estimates.Yres_buf.append(res_frame)
res_frame = np.reshape(res_frame, self.estimates.dims, order='F')
if self.params.get('online', 'use_corr_img'):
self.estimates.max_img = np.max([self.estimates.max_img, res_frame], 0)
else:
rho = imblur(np.maximum(res_frame,0), sig=self.params.get('init', 'gSig'),
siz=self.params.get('init', 'gSiz'),
nDimBlur=len(self.params.get('data', 'dims')))**2
rho = np.reshape(rho, np.prod(self.params.get('data', 'dims')))
self.estimates.rho_buf.append(rho)
# old_max_img = self.estimates.max_img.copy()
if self.params.get('preprocess', 'p') == 1:
g_est = np.mean(self.estimates.g)
elif self.params.get('preprocess', 'p') == 2:
g_est = np.mean(self.estimates.g, 0)
else:
g_est = 0
use_corr = self.params.get('online', 'use_corr_img')
(self.estimates.Ab, Cf_temp, self.estimates.Yres_buf, self.estimates.rho_buf,
self.estimates.CC, self.estimates.CY, self.ind_A, self.estimates.sv,
self.estimates.groups, self.estimates.ind_new, self.ind_new_all,
self.estimates.sv, self.cnn_pos) = update_num_components(
t, self.estimates.sv, self.estimates.Ab, self.estimates.C_on[:self.M, (t - mbs + 1):(t + 1)],
self.estimates.Yres_buf, self.estimates.Yr_buf, self.estimates.rho_buf,
self.params.get('data', 'dims'), self.params.get('init', 'gSig'),
self.params.get('init', 'gSiz'), self.ind_A, self.estimates.CY, self.estimates.CC,
rval_thr=self.params.get('online', 'rval_thr'),
thresh_fitness_delta=self.params.get('online', 'thresh_fitness_delta'),
thresh_fitness_raw=self.params.get('online', 'thresh_fitness_raw'),
thresh_overlap=self.params.get('online', 'thresh_overlap'), groups=self.estimates.groups,
batch_update_suff_stat=self.params.get('online', 'batch_update_suff_stat'),
gnb=self.params.get('init', 'nb'), sn=self.estimates.sn,
g=g_est, s_min=self.params.get('temporal', 's_min'),
Ab_dense=self.estimates.Ab_dense if self.params.get('online', 'use_dense') else None,
oases=self.estimates.OASISinstances if self.params.get('preprocess', 'p') else None,
N_samples_exceptionality=self.params.get('online', 'N_samples_exceptionality'),
max_num_added=self.params.get('online', 'max_num_added'),
min_num_trial=self.params.get('online', 'min_num_trial'),
loaded_model = self.loaded_model, test_both=self.params.get('online', 'test_both'),
thresh_CNN_noisy = self.params.get('online', 'thresh_CNN_noisy'),
sniper_mode=self.params.get('online', 'sniper_mode'),
use_peak_max=self.params.get('online', 'use_peak_max'),
mean_buff=self.estimates.mean_buff,
tf_in=self.tf_in, tf_out=self.tf_out,
ssub_B=ssub_B, W=self.estimates.W if self.is1p else None,
b0=self.estimates.b0 if self.is1p else None,
corr_img=self.estimates.corr_img if use_corr else None,
first_moment=self.estimates.first_moment if use_corr else None,
second_moment=self.estimates.second_moment if use_corr else None,
crosscorr=self.estimates.crosscorr if use_corr else None,
col_ind=self.estimates.col_ind if use_corr else None,
row_ind=self.estimates.row_ind if use_corr else None,
corr_img_mode=corr_img_mode if use_corr else None,
downscale_matrix=self.estimates.downscale_matrix if
(self.is1p and ssub_B > 1) else None,
upscale_matrix=self.estimates.upscale_matrix if
(self.is1p and ssub_B > 1) else None,
max_img=self.estimates.max_img if use_corr else None)
num_added = len(self.ind_A) - self.N
if num_added > 0:
self.N += num_added
self.M += num_added
if self.N + self.params.get('online', 'max_num_added') > expected_comps:
expected_comps += 200
self.params.set('online', {'expected_comps': expected_comps})
self.estimates.CY.resize(
[expected_comps + nb_, self.estimates.CY.shape[-1]])
self.estimates.C_on.resize(
[expected_comps + nb_, self.estimates.C_on.shape[-1]], refcheck=False)
self.estimates.noisyC.resize(
[expected_comps + nb_, self.estimates.C_on.shape[-1]])
if self.params.get('online', 'use_dense'): # resize won't work due to contingency issue
self.estimates.Ab_dense = np.zeros((self.estimates.CY.shape[-1], expected_comps + nb_),
dtype=np.float32)
self.estimates.Ab_dense[:, :Ab_.shape[1]] = Ab_.toarray()
logging.info('Increasing number of expected components to:' +
str(expected_comps))
self.update_counter.resize(self.N, refcheck=False)
self.estimates.noisyC[self.M - num_added:self.M, t - mbs +
1:t + 1] = Cf_temp[self.M - num_added:self.M]
for _ct in range(self.M - num_added, self.M):
self.time_neuron_added.append((_ct - nb_, t))
if self.params.get('preprocess', 'p'):
# N.B. OASISinstances are already updated within update_num_components
self.estimates.C_on[_ct, t - mbs + 1: t +
1] = self.estimates.OASISinstances[_ct - nb_].get_c(mbs)
else:
self.estimates.C_on[_ct, t - mbs + 1: t + 1] = np.maximum(
0, self.estimates.noisyC[_ct, t - mbs + 1: t + 1])
if self.params.get('online', 'simultaneously') and self.params.get('online', 'n_refit'):
self.estimates.AtY_buf = np.concatenate((
self.estimates.AtY_buf, [Ab_.data[Ab_.indptr[_ct]:Ab_.indptr[_ct + 1]].dot(
self.estimates.Yr_buf.T[Ab_.indices[Ab_.indptr[_ct]:Ab_.indptr[_ct + 1]]])]))
# N.B. Ab_dense is already updated within update_num_components as side effect
AtA = self.estimates.AtA
self.estimates.AtA = np.zeros((self.M, self.M), dtype=np.float32)
self.estimates.AtA[:-num_added, :-num_added] = AtA
if self.params.get('online', 'use_dense'):
self.estimates.AtA[:, -num_added:] = self.estimates.Ab.T.dot(
self.estimates.Ab_dense[:, self.M - num_added:self.M])
else:
self.estimates.AtA[:, -num_added:] = self.estimates.Ab.T.dot(
self.estimates.Ab[:, -num_added:]).toarray()
self.estimates.AtA[-num_added:] = self.estimates.AtA[:, -num_added:].T
if self.is1p:
# # update XXt and W: TODO only update necessary pixels not all!
if ssub_B == 1:
# self.estimates.AtW = Ab_.T.dot(self.estimates.W)
# self.estimates.AtWA = self.estimates.AtW.dot(Ab_).toarray()
# faster incremental update of AtW and AtWA instead of above lines:
csr_append(self.estimates.AtW, Ab_.T[-num_added:].dot(self.estimates.W))
AtWA = self.estimates.AtWA
self.estimates.AtWA = np.zeros((self.M, self.M), dtype=np.float32)
self.estimates.AtWA[:-num_added, :-num_added] = AtWA
self.estimates.AtWA[:, -num_added:] = self.estimates.AtW.dot(
Ab_[:, -num_added:]).toarray()
self.estimates.AtWA[-num_added:] = self.estimates.AtW[-num_added:].dot(
Ab_).toarray()
self.estimates.Atb = self.estimates.AtW.dot(
self.estimates.b0) - Ab_.T.dot(self.estimates.b0)
else:
A_ds = self.estimates.downscale_matrix.dot(self.estimates.Ab)
csr_append(self.estimates.AtW, A_ds.T[-num_added:].dot(self.estimates.W))
AtWA = self.estimates.AtWA
self.estimates.AtWA = np.zeros((self.M, self.M), dtype=np.float32)
self.estimates.AtWA[:-num_added, :-num_added] = AtWA
self.estimates.AtWA[:, -num_added:] = self.estimates.AtW.dot(
A_ds[:, -num_added:]).toarray()
self.estimates.AtWA[-num_added:] = self.estimates.AtW[-num_added:].dot(
A_ds).toarray()
self.estimates.Atb = ssub_B**2 * self.estimates.AtW.dot(
self.estimates.downscale_matrix.dot(
self.estimates.b0)) - Ab_.T.dot(self.estimates.b0)
# set the update counter to 0 for components that are overlapping the newly added
idx_overlap = self.estimates.AtA[nb_:-num_added, -num_added:].nonzero()[0]
self.update_counter[idx_overlap] = 0
self.t_detect.append(time() - t_new)
t_stat = time()
if self.params.get('online', 'batch_update_suff_stat'):
# faster update using minibatch of frames
min_batch = min(self.params.get('online', 'update_freq'), mbs)
if ((t + 1 - self.params.get('online', 'init_batch')) % min_batch == 0):
ccf = self.estimates.C_on[:self.M, t - min_batch + 1:t + 1]
y = self.estimates.Yr_buf.get_last_frames(min_batch)
if self.is1p: # subtract background
if ssub_B == 1:
x = (y - self.estimates.Ab.dot(ccf).T - self.estimates.b0).T
y -= self.estimates.W.dot(x).T
else:
x = self.estimates.downscale_matrix.dot(
y.T - self.estimates.Ab.dot(ccf) - self.estimates.b0[:, None])
y -= self.estimates.upscale_matrix.dot(self.estimates.W.dot(x)).T
y -= self.estimates.b0
# exploit that we only access some elements of XXt, hence update only these
if self.params.get('online', 'full_XXt'):
XXt = self.estimates.XXt # alias for faster repeated look up in large loop
for i, idx in enumerate(self.estimates.XXt_ind):
XXt[i, idx] += (x[i].dot(x[idx].T)).flatten()
else:
XXt_mats = self.XXt_mats
XXt_vecs = self.XXt_vecs
W = self.estimates.W
for p in range(len(XXt_mats)):
# index = W.indices[W.indptr[p]:W.indptr[p + 1]]
x_i = x[self.W_ind[p]]
XXt_mats[p] += x_i.dot(x_i.T)
XXt_vecs[p] += x_i.dot(x[p].T)
# much faster: exploit that we only access CY[m, ind_pixels], hence update only these
n0 = min_batch
t0 = 0 * self.params.get('online', 'init_batch')
w1 = (t - n0 + t0) * 1. / (t + t0) # (1 - 1./t)#mbs*1. / t
w2 = 1. / (t + t0) # 1.*mbs /t
ccf = np.ascontiguousarray(ccf)
y = np.asfortranarray(y)
for m in range(self.N):
self.estimates.CY[m + nb_, self.ind_A[m]] *= w1
self.estimates.CY[m + nb_, self.ind_A[m]] += w2 * \
ccf[m + nb_].dot(y[:, self.ind_A[m]])
self.estimates.CY[:nb_] = self.estimates.CY[:nb_] * w1 + \
w2 * ccf[:nb_].dot(y) # background
self.estimates.CC = self.estimates.CC * w1 + w2 * ccf.dot(ccf.T)
else:
ccf = self.estimates.C_on[:self.M, t - self.params.get('online', 'minibatch_suff_stat'):t -
self.params.get('online', 'minibatch_suff_stat') + 1]
y = self.estimates.Yr_buf.get_last_frames(self.params.get('online', 'minibatch_suff_stat') + 1)[:1]
if self.is1p: # subtract background
if ssub_B == 1:
x = (y - self.estimates.Ab.dot(ccf).T - self.estimates.b0).T
y -= self.estimates.W.dot(x).T
else:
x = self.estimates.downscale_matrix.dot(
y.T - self.estimates.Ab.dot(ccf) - self.estimates.b0[:, None])
y -= self.estimates.upscale_matrix.dot(self.estimates.W.dot(x)).T
y -= self.estimates.b0
# exploit that we only access some elements of XXt, hence update only these
if self.params.get('online', 'full_XXt'):
XXt = self.estimates.XXt # alias for faster repeated look up in large loop
for i, idx in enumerate(self.estimates.XXt_ind):
XXt[i, idx] += (x[i] * x[idx]).flatten()
else:
XXt_mats = self.XXt_mats
XXt_vecs = self.XXt_vecs
W = self.estimates.W
for p in range(len(XXt_mats)):
x_i = x[self.W_ind[p]]
XXt_mats[p] += np.outer(x_i, x_i)
XXt_vecs[p] += x_i.dot(x[p].T)
# much faster: exploit that we only access CY[m, ind_pixels], hence update only these
ccf = np.ascontiguousarray(ccf)
y = np.asfortranarray(y)
for m in range(self.N):
self.estimates.CY[m + nb_, self.ind_A[m]] *= (1 - 1. / t)
self.estimates.CY[m + nb_, self.ind_A[m]] += ccf[m +
nb_].dot(y[:, self.ind_A[m]]) / t
self.estimates.CY[:nb_] = self.estimates.CY[:nb_] * (1 - 1. / t) + ccf[:nb_].dot(y / t)
self.estimates.CC = self.estimates.CC * (1 - 1. / t) + ccf.dot(ccf.T / t)
self.t_stat.append(time() - t_stat)
# update shapes
t_sh = time()
if not self.params.get('online', 'dist_shape_update'): # bulk shape update
if ((t + 1 - self.params.get('online', 'init_batch')) %
self.params.get('online', 'update_freq') == 0):
logging.info('Updating Shapes')
if self.N > self.params.get('online', 'max_comp_update_shape'):
indicator_components = np.where(self.update_counter <=
self.params.get('online', 'num_times_comp_updated'))[0]
self.update_counter[indicator_components] += 1
else:
indicator_components = None
if self.params.get('online', 'use_dense'):
# update dense Ab and sparse Ab simultaneously;
# this is faster than calling update_shapes with sparse Ab only
Ab_, self.ind_A, self.estimates.Ab_dense[:, :self.M] = update_shapes(
self.estimates.CY, self.estimates.CC, self.estimates.Ab, self.ind_A,
indicator_components=indicator_components,
Ab_dense=self.estimates.Ab_dense[:, :self.M],
sn=self.estimates.sn, q=0.5, iters=self.params.get('online', 'iters_shape'))
else:
Ab_, self.ind_A, _ = update_shapes(
self.estimates.CY, self.estimates.CC, Ab_, self.ind_A,
indicator_components=indicator_components, sn=self.estimates.sn,
q=0.5, iters=self.params.get('online', 'iters_shape'))
self.estimates.AtA = (Ab_.T.dot(Ab_)).toarray()
if self.is1p and ((t + 1 - self.params.get('online', 'init_batch')) %
(self.params.get('online', 'W_update_factor') * self.params.get('online', 'update_freq')) == 0):
W = self.estimates.W
if self.params.get('online', 'full_XXt'):
XXt = self.estimates.XXt # alias for considerably faster look up in large loop
def process_pixel(p):
index = self.W_ind[p]
tmp = XXt[index[:, None], index]
tmp[np.diag_indices(len(tmp))] += np.trace(tmp) * 1e-5
return pd_solve(tmp, XXt[index, p])
if False: # current_process().name == 'MainProcess':
W.data = np.concatenate(parmap(process_pixel, range(W.shape[0])))
else:
W.data = np.concatenate(list(map(process_pixel, range(W.shape[0]))))
else:
XXt_mats = self.XXt_mats
XXt_vecs = self.XXt_vecs
if self.dview is None:
W.data = np.concatenate(list(map(inv_mat_vec, zip(XXt_mats, XXt_vecs))))
elif 'multiprocessing' in str(type(self.dview)):
W.data = np.concatenate(list(self.dview.imap(inv_mat_vec, zip(XXt_mats, XXt_vecs), chunksize=256)))
else:
W.data = np.concatenate(list(self.dview.map_sync(inv_mat_vec, zip(XXt_mats, XXt_vecs))))
self.dview.results.clear()
if ssub_B == 1:
self.estimates.Atb = Ab_.T.dot(W.dot(self.estimates.b0) - self.estimates.b0)
self.estimates.AtW = Ab_.T.dot(W)
self.estimates.AtWA = self.estimates.AtW.dot(Ab_).toarray()
else:
d1, d2 = self.estimates.dims
A_ds = self.estimates.downscale_matrix.dot(self.estimates.Ab)
self.estimates.Atb = Ab_.T.dot(self.estimates.upscale_matrix.dot(W.dot(
self.estimates.downscale_matrix.dot(self.estimates.b0))) - self.estimates.b0)
self.estimates.AtW = A_ds.T.dot(W)
self.estimates.AtWA = self.estimates.AtW.dot(A_ds).toarray()
ind_zero = list(np.where(self.estimates.AtA.diagonal() < 1e-10)[0])
if len(ind_zero) > 0:
ind_zero.sort()
ind_zero = ind_zero[::-1]
ind_keep = list(set(range(Ab_.shape[-1])) - set(ind_zero))
ind_keep.sort()
if self.params.get('online', 'use_dense'):
self.estimates.Ab_dense = np.delete(
self.estimates.Ab_dense, ind_zero, axis=1)
self.estimates.AtA = np.delete(self.estimates.AtA, ind_zero, axis=0)
self.estimates.AtA = np.delete(self.estimates.AtA, ind_zero, axis=1)
self.estimates.CY = np.delete(self.estimates.CY, ind_zero, axis=0)
self.estimates.CC = np.delete(self.estimates.CC, ind_zero, axis=0)
self.estimates.CC = np.delete(self.estimates.CC, ind_zero, axis=1)
self.M -= len(ind_zero)
self.N -= len(ind_zero)
self.estimates.noisyC = np.delete(self.estimates.noisyC, ind_zero, axis=0)
for ii in ind_zero:
del self.estimates.OASISinstances[ii - self.params.get('init', 'nb')]
self.estimates.C_on = np.delete(self.estimates.C_on, ind_zero, axis=0)
self.estimates.AtY_buf = np.delete(self.estimates.AtY_buf, ind_zero, axis=0)
Ab_ = csc_matrix(Ab_[:, ind_keep])
self.Ab_dense_copy = self.estimates.Ab_dense
self.Ab_copy = Ab_
self.estimates.Ab = Ab_
self.ind_A = list(
[(self.estimates.Ab.indices[self.estimates.Ab.indptr[ii]:self.estimates.Ab.indptr[ii + 1]]) for ii in range(self.params.get('init', 'nb'), self.M)])
self.estimates.groups = list(map(list, update_order(Ab_)[0]))
if self.params.get('online', 'n_refit'):
self.estimates.AtY_buf = Ab_.T.dot(self.estimates.Yr_buf.T)
else: # distributed shape update
self.update_counter *= 2**(-1. / self.params.get('online', 'update_freq'))
if (not num_added) and (time() - t_start < 2*self.time_spend / (t - self.params.get('online', 'init_batch') + 1)):
candidates = np.where(self.update_counter <= 1)[0]
if len(candidates):
indicator_components = candidates[:self.N // mbs + 1]
self.comp_upd.append(len(indicator_components))
self.update_counter[indicator_components] += 1
update_bkgrd = (t % mbs == 0)
if self.params.get('online', 'use_dense'):
# update dense Ab and sparse Ab simultaneously;
# this is faster than calling update_shapes with sparse Ab only
Ab_, self.ind_A, self.estimates.Ab_dense[:, :self.M] = update_shapes(
self.estimates.CY, self.estimates.CC, self.estimates.Ab, self.ind_A,
indicator_components=indicator_components, update_bkgrd=update_bkgrd,
Ab_dense=self.estimates.Ab_dense[:, :self.M], sn=self.estimates.sn,
q=0.5, iters=self.params.get('online', 'iters_shape'))
if update_bkgrd:
self.estimates.AtA = (Ab_.T.dot(Ab_)).toarray()
else:
indicator_components += nb_
self.estimates.AtA[indicator_components, indicator_components[:, None]] = \
self.estimates.Ab_dense[:, indicator_components].T.dot(
self.estimates.Ab_dense[:, indicator_components])
else:
Ab_, self.ind_A, _ = update_shapes(
self.estimates.CY, self.estimates.CC, Ab_, self.ind_A,
indicator_components=indicator_components, update_bkgrd=update_bkgrd,
q=0.5, iters=self.params.get('online', 'iters_shape'))
self.estimates.AtA = (Ab_.T.dot(Ab_)).toarray()
else:
self.comp_upd.append(0)
self.estimates.Ab = Ab_
else:
self.comp_upd.append(0)
self.time_spend += time() - t_start
self.t_shapes.append(time() - t_sh)
return self
def initialize_online(self, model_LN=None, T=None):
fls = self.params.get('data', 'fnames')
opts = self.params.get_group('online')
Y = caiman.load(fls[0], subindices=slice(0, opts['init_batch'],
None), var_name_hdf5=self.params.get('data', 'var_name_hdf5')).astype(np.float32)
if model_LN is not None:
Y = Y - caiman.movie(np.squeeze(model_LN.predict(np.expand_dims(Y, -1))))
Y = np.maximum(Y, 0)
# Downsample if needed
ds_factor = np.maximum(opts['ds_factor'], 1)
if ds_factor > 1:
Y = Y.resize(1./ds_factor, 1./ds_factor)
self.estimates.shifts = [] # store motion shifts here
self.estimates.time_new_comp = []
if self.params.get('online', 'motion_correct'):
mc = caiman.motion_correction.MotionCorrect(Y, dview=self.dview, **self.params.get_group('motion'))
mc.motion_correct(save_movie=True)
fname_new = caiman.save_memmap(mc.mmap_file, base_name='memmap_', order='C', dview=self.dview)
Y = caiman.load(fname_new, is3D=self.params.get('motion', 'is3D'))
if self.params.get('motion', 'pw_rigid'):
if self.params.get('motion', 'is3D'):
self.estimates.shifts.extend(list(map(tuple, np.transpose([x, y, z])))
for (x, y, z) in zip(mc.x_shifts_els, mc.y_shifts_els, mc.z_shifts_els))
else:
self.estimates.shifts.extend(list(map(tuple, np.transpose([x, y])))
for (x, y) in zip(mc.x_shifts_els, mc.y_shifts_els))
else:
self.estimates.shifts.extend(mc.shifts_rig)
self.min_mov = mc.min_mov
img_min = Y.min()
if self.params.get('online', 'normalize'):
Y = Y - img_min
img_norm = np.std(Y, axis=0)
img_norm += np.median(img_norm) # normalize data to equalize the FOV
logging.info('Frame size:' + str(img_norm.shape))
if self.params.get('online', 'normalize'):
Y = Y/img_norm[None, :, :]
if opts['show_movie']:
self.bnd_Y = np.percentile(Y,(0.001,100-0.001))
Yr = Y.to_2D().T # convert data into 2D array
self.img_min = img_min
self.img_norm = img_norm
if self.params.get('online', 'init_method') == 'bare':
# bare: no initialization is done
# cnmf: runs offline CNMF using offline CNMF init params on a small portion of the movie to obtain spatial footprints of neurons which are then used to seed online CNMF
init = self.params.get_group('init').copy()
is1p = (init['method_init'] == 'corr_pnr' and init['ring_size_factor'] is not None)
if is1p:
self.estimates.sn, psx = get_noise_fft(
Yr, noise_range=self.params.get('preprocess', 'noise_range'),
noise_method=self.params.get('preprocess', 'noise_method'),
max_num_samples_fft=self.params.get('preprocess', 'max_num_samples_fft'))
for key in ('K', 'nb', 'gSig', 'method_init'):
init.pop(key, None)
tmp = bare_initialization(
Y.transpose(1, 2, 0), init_batch=self.params.get('online', 'init_batch'),
k=self.params.get('init', 'K'), gnb=self.params.get('init', 'nb'),
method_init=self.params.get('init', 'method_init'), sn=self.estimates.sn,
gSig=self.params.get('init', 'gSig'), return_object=False,
options_total=self.params.to_dict(), **init)
if is1p:
(self.estimates.A, self.estimates.b, self.estimates.C, self.estimates.f,
self.estimates.YrA, self.estimates.W, self.estimates.b0) = tmp
else:
(self.estimates.A, self.estimates.b, self.estimates.C, self.estimates.f,
self.estimates.YrA) = tmp
self.estimates.S = np.zeros_like(self.estimates.C)
nr = self.estimates.C.shape[0]
self.estimates.g = np.array([-np.poly([0.9] * max(self.params.get('preprocess', 'p'), 1))[1:]
for gg in np.ones(nr)])
self.estimates.bl = np.zeros(nr)
self.estimates.c1 = np.zeros(nr)
self.estimates.neurons_sn = np.std(self.estimates.YrA, axis=-1)
self.estimates.lam = np.zeros(nr)
elif self.params.get('online', 'init_method') == 'cnmf':
n_processes = cpu_count() - 1 or 1
cnm = CNMF(n_processes=n_processes, params=self.params, dview=self.dview)
cnm.estimates.shifts = self.estimates.shifts
if self.params.get('patch', 'rf') is None:
cnm.dview = None
cnm.fit(np.array(Y))
self.estimates = cnm.estimates
else:
temp_init_file = os.path.join(caiman.paths.get_tempdir(), 'init_file.hdf5')
Y.save(temp_init_file)
f_new = caiman.mmapping.save_memmap([temp_init_file], base_name='Yr', order='C',
slices=[slice(0, opts['init_batch']), None, None])
Yrm, dims_, T_ = caiman.mmapping.load_memmap(f_new)
Y = np.reshape(Yrm.T, [T_] + list(dims_), order='F')
cnm.fit(Y)
self.estimates = cnm.estimates
if self.params.get('online', 'normalize'):
self.estimates.A /= self.img_norm.reshape(-1, order='F')[:, np.newaxis]
self.estimates.b /= self.img_norm.reshape(-1, order='F')[:, np.newaxis]
self.estimates.A = csc_matrix(self.estimates.A)
elif self.params.get('online', 'init_method') == 'seeded':
self.estimates.A, self.estimates.b, self.estimates.C, self.estimates.f, self.estimates.YrA = seeded_initialization(
Y.transpose(1, 2, 0), self.estimates.A, gnb=self.params.get('init', 'nb'), k=self.params.get('init', 'K'),
gSig=self.params.get('init', 'gSig'), return_object=False)
self.estimates.S = np.zeros_like(self.estimates.C)
nr = self.estimates.C.shape[0]
self.estimates.g = np.array([-np.poly([0.9] * max(self.params.get('preprocess', 'p'), 1))[1:]
for gg in np.ones(nr)])
self.estimates.bl = np.zeros(nr)
self.estimates.c1 = np.zeros(nr)
self.estimates.neurons_sn = np.std(self.estimates.YrA, axis=-1)
self.estimates.lam = np.zeros(nr)
else:
raise Exception('Unknown initialization method!')
dims, Ts = caiman.base.movies.get_file_size(fls, var_name_hdf5=self.params.get('data', 'var_name_hdf5'))
dims = Y.shape[1:]
self.params.set('data', {'dims': dims})
T1 = np.array(Ts).sum()*self.params.get('online', 'epochs') if T is None else T
self._prepare_object(Yr, T1)
if opts['show_movie']:
self.bnd_AC = np.percentile(np.ravel(self.estimates.A.dot(self.estimates.C)),
(0.001, 100-0.005))
return self
def save(self,filename):
"""save object in hdf5 file format
Args:
filename: str