-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline_mprof_new.py
1870 lines (1627 loc) · 66.3 KB
/
pipeline_mprof_new.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
"""This file contains the pipeline that will be profiled by the memory_profiler package. This file implements the new version of CAIMAN (as opposed to pipeline_mprof_old.py implementing the old version of CAIMAN). Because memory_profiler requires decorators to help it run, this code cannot be imported to other files without error (unless you were to implement something that could ignore the decorators). Use pipeline_memray_new.py for that function (or better practice probably would be to make a new file that is more readable).
"""
import pickle
import pandas as pd
import numpy as np
from scipy.signal.windows import tukey
from scipy import interpolate as interp
from scipy import ndimage
import scipy
from scipy.ndimage import percentile_filter
from caiman.source_extraction.cnmf import deconvolution
from scipy import fftpack
import pyfftw
from imreg_dft import utils
from caiman import load_memmap, components_evaluation
import time, sys, os, glob
import multiprocessing as mp
from caiman.source_extraction.cnmf.params import CNMFParams
from caiman.source_extraction.cnmf.estimates import Estimates
from caiman.source_extraction.cnmf import (
map_reduce,
merging,
initialization,
pre_processing,
spatial,
temporal,
)
@profile
def pipeline_with_dataload(
file_location,
scan_idx=0,
temporal_fill_fraction=1,
in_place=False,
fps=15,
should_perform_raster_correction=True,
should_perform_motion_correction=True,
should_extract_masks=True,
should_deconvolve=False,
):
#data = load_pickle(file_location)
#scan = extract_scan_from_pandas(data, scan_idx)
mmap_filename = 'segmentation/data/caiman/caiman_d1_240_d2_240_d3_1_order_C_frames_61717_.mmap'
mmap_scan, (image_height, image_width), num_frames = load_memmap(mmap_filename)
scan = np.array(mmap_scan)
scan = scan.reshape(image_height, image_width, num_frames, order='F')
pipeline_output = pipeline(
scan,
temporal_fill_fraction,
in_place,
fps,
should_perform_raster_correction,
should_perform_motion_correction,
should_extract_masks,
should_deconvolve,
mmap_scan
)
return pipeline_output
@profile
def load_pickle(filename):
with open(filename, "rb") as file:
data = pickle.load(file)
return data
@profile
def extract_scan_from_pandas(data, scan_idx):
return data.loc[scan_idx, "mini_scan"]
@profile
def pipeline(
scan,
temporal_fill_fraction=1,
in_place=False,
fps=15,
should_perform_raster_correction=True,
should_perform_motion_correction=True,
should_extract_masks=True,
should_deconvolve=True,
mmap_scan=None
):
if should_perform_raster_correction:
print("Performing raster correction...")
scan = perform_raster_correction(scan, temporal_fill_fraction, in_place)
if should_perform_motion_correction:
print('Performing motion correction...')
scan = perform_motion_correction(scan, in_place)
if should_extract_masks:
print('Performing segmentation...')
# Save as memory mapped file in F order (that's how caiman wants it)
#mmap_filename = save_as_memmap(scan, base_name="data/caiman/caiman").filename
# 'Load' scan
#mmap_scan, (image_height, image_width), num_frames = load_memmap(mmap_filename)
profiling_params = params = {'num_background_components': 1,
'merge_threshold': 0.7,
'fps': 8.3091,
'init_on_patches': True,
'proportion_patch_overlap': 0.2,
'num_components_per_patch': 6,
'init_method': 'greedy_roi',
'patch_size': [20.0, 20.0],
'soma_diameter': [3.2, 3.2],
'num_processes': 8,
'num_pixels_per_process': 10000}
(
masks,
traces,
background_masks,
background_traces,
raw_traces,
) = extract_masks_adapted(scan, mmap_scan, **params)
if should_deconvolve:
print('Performing deconvolution...')
spike_traces = []
AR_coeff_all = []
for trace in traces:
spike_trace, AR_coeffs = deconvolve_detrended(trace, fps)
spike_traces.append(spike_trace)
AR_coeff_all.append(AR_coeffs)
return (
spike_traces,
AR_coeff_all,
masks,
traces,
background_masks,
background_traces,
raw_traces,
)
return masks, traces, background_masks, background_traces, raw_traces
@profile
def anscombe_transform_raster(mini_scan):
return 2 * np.sqrt(mini_scan - mini_scan.min() + 3 / 8) # anscombe transform
@profile
def anscombe_transform_motion(mini_scan):
return 2 * np.sqrt(mini_scan - mini_scan.min() + 3 / 8) # anscombe transform
def select_middle_frames(scan, skip_rows=0, skip_cols=0):
# Load some frames from the middle of the scan
num_frames = scan.shape[-1]
middle_frame = int(np.floor(num_frames / 2))
frames = slice(max(middle_frame - 1000, 0), middle_frame + 1000)
last_row = -scan.shape[0] if skip_rows == 0 else skip_rows
last_col = -scan.shape[1] if skip_cols == 0 else skip_cols
mini_scan = scan[skip_rows:-last_row, skip_cols:-last_col, frames]
return mini_scan
@profile
def raster_template_prep(scan):
# Load middle 2000 frames from the scan
mini_scan = select_middle_frames(scan)
# get the height and width of the scan
height, width = mini_scan.shape[:2]
return mini_scan, height, width
@profile
def compute_raster_template(scan):
mini_scan, height, width = raster_template_prep(scan)
# Create template (average frame tapered to avoid edge artifacts)
taper = np.sqrt(
np.outer(
tukey(height, 0.4),
tukey(width, 0.4),
)
)
anscombed = anscombe_transform_raster(mini_scan)
template = np.mean(anscombed, axis=-1) * taper
return template
@profile
def raster_phase_prep(image, temporal_fill_fraction):
# Make sure image has even number of rows (so number of even and odd rows is the same)
image = image[:-1] if image.shape[0] % 2 == 1 else image
# Get some params
image_height, image_width = image.shape
skip_rows = round(image_height * 0.05) # rows near the top or bottom have artifacts
skip_cols = round(image_width * 0.10) # so do columns
# Create images with even and odd rows
even_rows = image[::2][skip_rows:-skip_rows]
odd_rows = image[1::2][skip_rows:-skip_rows]
# Scan angle at which each pixel was recorded.
max_angle = (np.pi / 2) * temporal_fill_fraction
scan_angles = np.linspace(-max_angle, max_angle, image_width + 2)[1:-1]
# sin_index = np.sin(scan_angles)
even_interp, odd_interp = create_interp_functions(scan_angles, even_rows, odd_rows)
return image, skip_rows, skip_cols, scan_angles, even_interp, odd_interp
@profile
def create_interp_functions(scan_angles, even_rows, odd_rows):
even_interp = interp.interp1d(scan_angles, even_rows, fill_value="extrapolate")
odd_interp = interp.interp1d(scan_angles, odd_rows, fill_value="extrapolate")
return even_interp, odd_interp
@profile
def compute_raster_phase(image: np.array, temporal_fill_fraction: float) -> float:
"""Compute raster correction for bidirectional resonant scanners.
It shifts the even and odd rows of the image in the x axis to find the scan angle
that aligns them better. Positive raster phase will shift even rows to the right and
odd rows to the left (assuming first row is row 0).
:param np.array image: The image to be corrected.
:param float temporal_fill_fraction: Fraction of time during which the scan is
recording a line against the total time per line.
:return: An angle (in radians). Estimate of the mismatch angle between the expected
initial angle and the one recorded.
:rtype: float
"""
# Make sure image has even number of rows (so number of even and odd rows is the same)
(
image,
skip_rows,
skip_cols,
scan_angles,
even_interp,
odd_interp,
) = raster_phase_prep(image, temporal_fill_fraction)
# Greedy search for the best raster phase: starts at coarse estimates and refines them
angle_shift = 0
for scale in [1e-2, 1e-3, 1e-4, 1e-5, 1e-6]:
angle_shifts = angle_shift + scale * np.linspace(-9, 9, 19)
match_values = []
for new_angle_shift in angle_shifts:
shifted_evens = even_interp(scan_angles + new_angle_shift)
shifted_odds = odd_interp(scan_angles - new_angle_shift)
match_values.append(
np.sum(
shifted_evens[:, skip_cols:-skip_cols]
* shifted_odds[:, skip_cols:-skip_cols]
)
)
angle_shift = angle_shifts[np.argmax(match_values)]
return angle_shift
@profile
def make_copy_correct_raster(scan):
return scan.copy()
@profile
def correct_raster_prep(scan, temporal_fill_fraction, in_place):
# Basic checks
if not isinstance(scan, np.ndarray):
raise PipelineException("Scan needs to be a numpy array.")
if scan.ndim < 2:
raise PipelineException("Scan with less than 2 dimensions.")
# Assert scan is float
if not np.issubdtype(scan.dtype, np.floating):
print("Warning: Changing scan type from", str(scan.dtype), "to np.float32")
scan = scan.astype(np.float32, copy=(not in_place))
elif not in_place:
scan = make_copy_correct_raster(
scan
) # copy it anyway preserving the original float dtype
# Get some dimensions
original_shape = scan.shape
image_height = original_shape[0]
image_width = original_shape[1]
# Scan angle at which each pixel was recorded.
max_angle = (np.pi / 2) * temporal_fill_fraction
scan_angles = np.linspace(-max_angle, max_angle, image_width + 2)[1:-1]
# We iterate over every image in the scan (first 2 dimensions). Same correction
# regardless of what channel, slice or frame they belong to.
reshaped_scan = np.reshape(scan, (image_height, image_width, -1))
num_images = reshaped_scan.shape[-1]
return reshaped_scan, num_images, original_shape, scan_angles
def correction_post(reshaped_scan, original_shape):
scan = np.reshape(reshaped_scan, original_shape)
return scan
@profile
def correct_raster(scan, raster_phase, temporal_fill_fraction, in_place=True):
"""Raster correction for resonant scans.
Corrects multi-photon images in n-dimensional scans. Positive raster phase shifts
even lines to the left and odd lines to the right. Negative raster phase shifts even
lines to the right and odd lines to the left.
:param np.array scan: Volume with images to be corrected in the first two dimensions.
Works for 2-dimensions and up, usually (image_height, image_width, num_frames).
:param float raster_phase: Angle difference between expected and recorded scan angle.
:param float temporal_fill_fraction: Ratio between active acquisition and total
length of the scan line.
:param bool in_place: If True (default), the original array is modified in place.
:return: Raster-corrected scan.
:rtype: Same as scan if scan.dtype is subtype of np.float, else np.float32.
:raises: PipelineException
"""
reshaped_scan, num_images, original_shape, scan_angles = correct_raster_prep(
scan, temporal_fill_fraction, in_place
)
for i in range(num_images):
# Get current image
image = reshaped_scan[:, :, i]
(
even_interp_function,
odd_interp_function,
) = create_interp_functions_raster_correction(scan_angles, image, in_place)
# Correct even rows of the image (0, 2, ...)
reshaped_scan[::2, :, i] = even_interp_function(scan_angles + raster_phase)
# Correct odd rows of the image (1, 3, ...)
reshaped_scan[1::2, :, i] = odd_interp_function(scan_angles - raster_phase)
scan = correction_post(reshaped_scan, original_shape)
return scan
def create_interp_functions_raster_correction(scan_angles, image, in_place):
# Correct even rows of the image (0, 2, ...)
even_interp_function = interp.interp1d(
scan_angles,
image[::2, :],
bounds_error=False,
fill_value=0,
copy=(not in_place),
)
odd_interp_function = interp.interp1d(
scan_angles,
image[1::2, :],
bounds_error=False,
fill_value=0,
copy=(not in_place),
)
return even_interp_function, odd_interp_function
@profile
def perform_raster_correction(scan, temporal_fill_fraction=1, in_place=False):
raster_template = compute_raster_template(scan)
raster_phase = compute_raster_phase(raster_template, temporal_fill_fraction)
raster_corrected_scan = correct_raster(
scan,
raster_phase,
temporal_fill_fraction=temporal_fill_fraction,
in_place=in_place,
)
return raster_corrected_scan
@profile
def motion_template_prep(scan):
## Get needed info
px_height, px_width = scan.shape[:2]
skip_rows = int(
round(px_height * 0.10)
) # we discard some rows/cols to avoid edge artifacts
skip_cols = int(round(px_width * 0.10))
## Select template source
# Default behavior: use middle 2000 frames as template source
mini_scan = select_middle_frames(scan, skip_rows, skip_cols)
return mini_scan
@profile
def create_motion_template(scan):
"""
Creates the template all frames are compared against to determine the
amount of motion that occured. Exclusively used for the first iteration
of motion correction.
"""
mini_scan = motion_template_prep(scan)
# Create template
mini_scan = anscombe_transform_motion(mini_scan)
template = np.mean(mini_scan, axis=-1).squeeze()
# Apply spatial filtering (if needed)
template = ndimage.gaussian_filter(template, 0.7) # **
# * Anscombe tranform to normalize noise, increase contrast and decrease outliers' leverage
# ** Small amount of gaussian smoothing to get rid of high frequency noise
return template
@profile
def create_copy_motion_shifts_prep(scan, in_place):
if not in_place:
scan = scan.copy()
return scan
@profile
def motion_shifts_prep(scan, template, in_place, num_threads):
# Add third dimension if scan is a single image
# if scan.ndim == 2:
# scan = np.expand_dims(scan, -1)
scan = create_copy_motion_shifts_prep(scan, in_place)
# Get some params
image_height, image_width, num_frames = scan.shape
skip_rows = int(
round(image_height * 0.10)
) # we discard some rows/cols to avoid edge artifacts
skip_cols = int(round(image_width * 0.10))
scan = scan[
skip_rows:-skip_rows,
skip_cols:-skip_cols,
:,
]
(
image_height,
image_width,
num_frames,
) = scan.shape # recalculate after removing edge rows/cols
taper = np.outer(tukey(image_height, 0.2), tukey(image_width, 0.2))
template_freq, abs_template_freq, eps, fft, ifft = fftw_prep(
image_height, image_width, template, taper, num_threads, in_place
)
return (
scan,
num_frames,
taper,
template_freq,
abs_template_freq,
eps,
fft,
ifft,
image_height,
image_width,
)
def fftw_prep(image_height, image_width, template, taper, num_threads, in_place):
# Prepare fftw
frame = pyfftw.empty_aligned((image_height, image_width), dtype="complex64")
fft = pyfftw.builders.fft2(
frame, threads=num_threads, overwrite_input=in_place, avoid_copy=True
)
ifft = pyfftw.builders.ifft2(
frame, threads=num_threads, overwrite_input=in_place, avoid_copy=True
)
# Get fourier transform of template
template_freq = fft(template * taper).conj() # we only need the conjugate
abs_template_freq = abs(template_freq)
eps = abs_template_freq.max() * 1e-15
return template_freq, abs_template_freq, eps, fft, ifft
def compute_cross_power(
fft, scan, i, taper, template_freq, abs_template_freq, eps, ifft
):
image_freq = fft(scan[:, :, i] * taper)
cross_power = (image_freq * template_freq) / (
abs(image_freq) * abs_template_freq + eps
)
shifted_cross_power = np.fft.fftshift(abs(ifft(cross_power)))
return shifted_cross_power
def map_deviations(y_shifts, x_shifts, i, shifts, image_height, image_width):
y_shifts[i] = shifts[0] - image_height // 2
x_shifts[i] = shifts[1] - image_width // 2
return y_shifts, x_shifts
def get_best_shift(shifted_cross_power):
shifts = np.unravel_index(np.argmax(shifted_cross_power), shifted_cross_power.shape)
shifts = utils._interpolate(shifted_cross_power, shifts, rad=3)
return shifts
@profile
def compute_motion_shifts(scan, template, in_place=True, num_threads=8):
"""Compute shifts in y and x for rigid subpixel motion correction.
Returns the number of pixels that each image in the scan was to the right (x_shift)
or below (y_shift) the template. Negative shifts mean the image was to the left or
above the template.
:param np.array scan: 2 or 3-dimensional scan (image_height, image_width[, num_frames]).
:param np.array template: 2-d template image. Each frame in scan is aligned to this.
:param bool in_place: Whether the scan can be overwritten.
:param int num_threads: Number of threads used for the ffts.
:returns: (y_shifts, x_shifts) Two arrays (num_frames) with the y, x motion shifts.
..note:: Based in imreg_dft.translation().
"""
(
scan,
num_frames,
taper,
template_freq,
abs_template_freq,
eps,
fft,
ifft,
image_height,
image_width,
) = motion_shifts_prep(scan, template, in_place, num_threads)
# Compute subpixel shifts per image
y_shifts = np.empty(num_frames)
x_shifts = np.empty(num_frames)
for i in range(num_frames):
# Compute correlation via cross power spectrum
shifted_cross_power = compute_cross_power(
fft, scan, i, taper, template_freq, abs_template_freq, eps, ifft
)
# Get best shift
shifts = get_best_shift(shifted_cross_power)
# Map back to deviations from center
y_shifts, x_shifts = map_deviations(
y_shifts, x_shifts, i, shifts, image_height, image_width
)
return y_shifts, x_shifts
@profile
def make_copy_correct_motion_prep(scan):
return scan.copy()
@profile
def make_two_copy_correct_motion(scan1, scan2):
return scan1.copy(), scan2.copy()
@profile
def correct_motion_prep(scan, y_shifts, x_shifts, in_place):
# Basic checks
if not isinstance(scan, np.ndarray):
raise PipelineException("Scan needs to be a numpy array.")
if scan.ndim < 2:
raise PipelineException("Scan with less than 2 dimensions.")
if np.ndim(y_shifts) != 1 or np.ndim(x_shifts) != 1:
raise PipelineException(
"Dimension of one or both motion arrays differs from 1."
)
if len(x_shifts) != len(y_shifts):
raise PipelineException("Length of motion arrays differ.")
# Assert scan is float (integer precision is not good enough)
if not np.issubdtype(scan.dtype, np.floating):
print("Warning: Changing scan type from", str(scan.dtype), "to np.float32")
scan = scan.astype(np.float32, copy=(not in_place))
elif not in_place:
scan = make_copy_correct_motion_prep(
scan
) # copy it anyway preserving the original dtype
# Get some dimensions
original_shape = scan.shape
image_height = original_shape[0]
image_width = original_shape[1]
# Reshape input (to deal with more than 2-D volumes)
reshaped_scan = np.reshape(scan, (image_height, image_width, -1))
if reshaped_scan.shape[-1] != len(x_shifts):
raise PipelineException("Scan and motion arrays have different dimensions")
# Ignore NaN values (present in some older data)
y_clean, x_clean = make_two_copy_correct_motion(y_shifts, x_shifts)
y_clean[np.logical_or(np.isnan(y_shifts), np.isnan(x_shifts))] = 0
x_clean[np.logical_or(np.isnan(y_shifts), np.isnan(x_shifts))] = 0
return y_clean, x_clean, reshaped_scan, original_shape
def make_copy_correct_motion(image):
return image.copy()
def motion_correction_shift(image, y_shift, x_shift, reshaped_scan, i):
ndimage.shift(image, (-y_shift, -x_shift), order=1, output=reshaped_scan[:, :, i])
@profile
def correct_motion(scan, x_shifts, y_shifts, in_place=True):
"""Motion correction for multi-photon scans.
Shifts each image in the scan x_shift pixels to the left and y_shift pixels up.
:param np.array scan: Volume with images to be corrected in the first two dimensions.
Works for 2-dimensions and up, usually (image_height, image_width, num_frames).
:param list/np.array x_shifts: 1-d array with x motion shifts for each image.
:param list/np.array y_shifts: 1-d array with x motion shifts for each image.
:param bool in_place: If True (default), the original array is modified in place.
:return: Motion corrected scan
:rtype: Same as scan if scan.dtype is subtype of np.float, else np.float32.
:raises: PipelineException
"""
y_clean, x_clean, reshaped_scan, original_shape = correct_motion_prep(
scan, y_shifts, x_shifts, in_place
)
# Shift each frame
for i, (y_shift, x_shift) in enumerate(zip(y_clean, x_clean)):
image = make_copy_correct_motion(reshaped_scan[:, :, i])
motion_correction_shift(image, y_shift, x_shift, reshaped_scan, i)
scan = correction_post(reshaped_scan, original_shape)
return scan
@profile
def perform_motion_correction(scan, in_place=False):
motion_template = create_motion_template(scan)
y_shifts, x_shifts = compute_motion_shifts(scan, motion_template, in_place)
motion_corrected_scan = correct_motion(scan, x_shifts, y_shifts, in_place)
return motion_corrected_scan
@profile
def log(*messages):
"""Simple logging function."""
formatted_time = "[{}]".format(time.ctime())
print(formatted_time, *messages, flush=True, file=sys.__stdout__)
def _greedyROI(
scan, num_components=200, neuron_size=(11, 11), num_background_components=1
):
"""Initialize components by searching for gaussian shaped, highly active squares.
#one by one by moving a gaussian window over every pixel and
taking the highest activation as the center of the next neuron.
:param np.array scan: 3-dimensional scan (image_height, image_width, num_frames).
:param int num_components: The desired number of components.
:param (float, float) neuron_size: Expected size of the somas in pixels (y, x).
:param int num_background_components: Number of components that model the background.
"""
from scipy import ndimage
# Get some params
image_height, image_width, num_frames = scan.shape
# Get the gaussian kernel
gaussian_stddev = (
np.array(neuron_size) / 4
) # entire neuron in four standard deviations
gaussian_kernel = _gaussian2d(gaussian_stddev)
# Create residual scan (scan minus background)
residual_scan = scan - np.mean(scan, axis=(0, 1)) # image-wise brightness
background = ndimage.gaussian_filter(np.mean(residual_scan, axis=-1), neuron_size)
residual_scan -= np.expand_dims(background, -1)
# Create components
masks = np.zeros([image_height, image_width, num_components], dtype=np.float32)
traces = np.zeros([num_components, num_frames], dtype=np.float32)
mean_frame = np.mean(residual_scan, axis=-1)
for i in range(num_components):
# Get center of next component
neuron_locations = ndimage.gaussian_filter(mean_frame, gaussian_stddev)
y, x = np.unravel_index(
np.argmax(neuron_locations), [image_height, image_width]
)
# Compute initial trace (bit messy because of edges)
half_kernel = np.fix(np.array(gaussian_kernel.shape) / 2).astype(np.int32)
big_yslice = slice(max(y - half_kernel[0], 0), y + half_kernel[0] + 1)
big_xslice = slice(max(x - half_kernel[1], 0), x + half_kernel[1] + 1)
kernel_yslice = slice(
max(0, half_kernel[0] - y),
None
if image_height > y + half_kernel[0]
else image_height - y - half_kernel[0] - 1,
)
kernel_xslice = slice(
max(0, half_kernel[1] - x),
None
if image_width > x + half_kernel[1]
else image_width - x - half_kernel[1] - 1,
)
cropped_kernel = gaussian_kernel[kernel_yslice, kernel_xslice]
trace = np.average(
residual_scan[big_yslice, big_xslice].reshape(-1, num_frames),
weights=cropped_kernel.ravel(),
axis=0,
)
# Get mask and trace using 1-rank NMF
half_neuron = np.fix(np.array(neuron_size) / 2).astype(np.int32)
yslice = slice(max(y - half_neuron[0], 0), y + half_neuron[0] + 1)
xslice = slice(max(x - half_neuron[1], 0), x + half_neuron[1] + 1)
mask, trace = _rank1_NMF(residual_scan[yslice, xslice], trace)
# Update residual scan
neuron_activity = np.expand_dims(mask, -1) * trace
residual_scan[yslice, xslice] -= neuron_activity
mean_frame[yslice, xslice] = np.mean(residual_scan[yslice, xslice], axis=-1)
# Store results
masks[yslice, xslice, i] = mask
traces[i] = trace
# Create background components
residual_scan += np.mean(scan, axis=(0, 1)) # add back overall brightness
residual_scan += np.expand_dims(background, -1) # and background
if num_background_components == 1:
background_masks = np.expand_dims(np.mean(residual_scan, axis=-1), axis=-1)
background_traces = np.expand_dims(np.mean(residual_scan, axis=(0, 1)), axis=0)
else:
from sklearn.decomposition import NMF
print(
"Warning: Fitting more than one background component uses scikit-learn's "
"NMF and may take some time."
""
)
model = NMF(num_background_components, random_state=123, verbose=True)
flat_masks = model.fit_transform(residual_scan.reshape(-1, num_frames))
background_masks = flat_masks.reshape([image_height, image_width, -1])
background_traces = model.components_
return masks, traces, background_masks, background_traces
def _gaussian2d(stddev, truncate=4):
"""Creates a 2-d gaussian kernel truncated at 4 standard deviations (8 in total).
:param (float, float) stddev: Standard deviations in y and x.
:param float truncate: Number of stddevs at each side of the kernel.
..note:: Kernel sizes will always be odd.
"""
from matplotlib import mlab
half_kernel = np.round(stddev * truncate) # kernel_size = 2 * half_kernel + 1
y, x = np.meshgrid(
np.arange(-half_kernel[0], half_kernel[0] + 1),
np.arange(-half_kernel[1], half_kernel[1] + 1),
)
kernel = mlab.bivariate_normal(x, y, sigmay=stddev[0], sigmax=stddev[1])
return kernel
# Based on caiman.source_extraction.cnmf.initialization.finetune()
def _rank1_NMF(scan, trace, num_iterations=5):
num_frames = scan.shape[-1]
for i in range(num_iterations):
mask = np.maximum(np.dot(scan, trace), 0)
mask = mask * np.sum(mask) / np.sum(mask**2)
trace = np.average(scan.reshape(-1, num_frames), weights=mask.ravel(), axis=0)
return mask, trace
@profile
def save_as_memmap(scan, base_name="caiman", chunk_size=5000):
"""Save the scan as a memory mapped file as expected by caiman
:param np.array scan: Scan to save shaped (image_height, image_width, num_frames)
:param string base_name: Base file name for the scan. No underscores.
:param int chunk_size: Write the mmap_scan chunk frames at a time. Memory efficient.
:returns: Filename of the mmap file.
:rtype: string
"""
# Get some params
image_height, image_width, num_frames = scan.shape
num_pixels = image_height * image_width
# Build filename
filename = "{}_d1_{}_d2_{}_d3_1_order_C_frames_{}_.mmap".format(
base_name, image_height, image_width, num_frames
)
# Create memory mapped file
mmap_scan = np.memmap(
filename, mode="w+", shape=(num_pixels, num_frames), dtype=np.float32
)
for i in range(0, num_frames, chunk_size):
chunk = scan[..., i : i + chunk_size].reshape((num_pixels, -1), order="F")
mmap_scan[:, i : i + chunk_size] = chunk
mmap_scan.flush()
return mmap_scan
@profile
def extract_masks_adapted(
scan,
mmap_scan,
num_components=200,
num_background_components=1,
merge_threshold=0.8,
init_on_patches=True,
init_method="greedy_roi",
soma_diameter=(14, 14),
snmf_alpha=0.5,
patch_size=(50, 50),
proportion_patch_overlap=0.2,
num_components_per_patch=5,
num_processes=8,
num_pixels_per_process=5000,
fps=15,
):
"""Extract masks from multi-photon scans using CNMF.
Uses constrained non-negative matrix factorization to find spatial components (masks)
and their fluorescence traces in a scan. Default values work well for somatic scans.
Performed operations are:
[Initialization on full image | Initialization on patches -> merge components] ->
spatial update -> temporal update -> merge components -> spatial update ->
temporal update
:param np.array scan: 3-dimensional scan (image_height, image_width, num_frames).
:param np.memmap mmap_scan: 2-d scan (image_height * image_width, num_frames)
:param int num_components: An estimate of the number of spatial components in the scan
:param int num_background_components: Number of components to model the background.
:param int merge_threshold: Maximal temporal correlation allowed between the activity
of overlapping components before merging them.
:param bool init_on_patches: If True, run the initialization methods on small patches
of the scan rather than on the whole image.
:param string init_method: Initialization method for the components.
'greedy_roi': Look for a gaussian-shaped patch, apply rank-1 NMF, store
components, calculate residual scan and repeat for num_components.
'sparse_nmf': Regularized non-negative matrix factorization (as impl. in sklearn)
:param (float, float) soma_diameter: Estimated neuron size in y and x (pixels). Used
in'greedy_roi' initialization to search for neurons of this size.
:param int snmf_alpha: Regularization parameter (alpha) for sparse NMF (if used).
:param (float, float) patch_size: Size of the patches in y and x (pixels).
:param float proportion_patch_overlap: Patches are sampled in a sliding window. This
controls how much overlap is between adjacent patches (0 for none, 0.9 for 90%).
:param int num_components_per_patch: Number of components per patch (used if
init_on_patches=True)
:param int num_processes: Number of processes to run in parallel. None for as many
processes as available cores.
:param int num_pixels_per_process: Number of pixels that a process handles each
iteration.
:param fps: Frame rate. Used for temporal downsampling and to remove bad components.
:returns: Weighted masks (image_height x image_width x num_components). Inferred
location of each component.
:returns: Denoised fluorescence traces (num_components x num_frames).
:returns: Masks for background components (image_height x image_width x
num_background_components).
:returns: Traces for background components (image_height x image_width x
num_background_components).
:returns: Raw fluorescence traces (num_components x num_frames). Fluorescence of each
component in the scan minus activity from other components and background.
..warning:: The produced number of components is not exactly what you ask for because
some components will be merged or deleted.
..warning:: Better results if scans are nonnegative.
"""
# Get some params
image_height, image_width, num_frames = scan.shape
# Start processes
log("Starting {} processes...".format(num_processes))
pool = mp.Pool(processes=num_processes)
# Initialize components
log("Initializing components...")
if init_on_patches:
# TODO: Redo this (per-patch initialization) in a nicer/more efficient way
# Make sure they are integers
patch_size = np.array(patch_size)
half_patch_size = np.int32(np.round(patch_size / 2))
num_components_per_patch = int(round(num_components_per_patch))
patch_overlap = np.int32(np.round(patch_size * proportion_patch_overlap))
# Create options dictionary (needed for run_CNMF_patches)
options = {
"patch": {
"nb_batch": num_background_components,
"only_init": True,
"remove_very_bad_comps": False,
"rf": half_patch_size,
"stride": patch_overlap,
}, # remove_very_bads_comps unnecesary (same as default)
"preprocess": {
"check_nan": False
}, # check_nan is unnecessary (same as default value)
"spatial": {
"nb": num_background_components,
"n_pixels_per_process": num_pixels_per_process,
}, # nb is unnecessary, it is pased to the function and in init_params
"temporal": {
"p": 0,
"block_size_temp": 10000,
"method_deconvolution": "cvxpy",
},
"init": {
"K": num_components_per_patch,
"gSig": np.array(soma_diameter) / 2,
"method_init": init_method,
"alpha_snmf": snmf_alpha,
"nb": num_background_components,
"ssub": 1,
"tsub": max(int(fps / 2), 1),
"normalize_init": True,
"rolling_sum": True,
"rolling_length": 100,
},
# gSiz, ssub, tsub, options_local_NMF, normalize_init, rolling_sum unnecessary (same as default values)
"merging": {"merge_thr": 0.8},
}
params = CNMFParams()
for key in options:
params.set(key, options[key])
# Initialize per patch
res = map_reduce.run_CNMF_patches(
mmap_scan.filename,
(image_height, image_width, num_frames),
params,
dview=pool,
memory_fact=params.get("patch", "memory_fact"),
gnb=params.get("init", "nb"),
border_pix=params.get("patch", "border_pix"),
low_rank_background=params.get("patch", "low_rank_background"),
del_duplicates=params.get("patch", "del_duplicates"),
) # indices=[slice(None)]*3
initial_A, initial_C, YrA, initial_b, initial_f, pixels_noise, _ = res
# bl, c1, g, neurons_noise = None, None, None, None
# Merge spatially overlapping components
merged_masks = ["dummy"]
while len(merged_masks) > 0:
res = merging.merge_components(
mmap_scan,
initial_A,
initial_b,
initial_C,
YrA,
initial_f,
initial_C,
pixels_noise,
params.get_group("temporal"),
params.get_group("spatial"),
dview=pool,
thr=params.get("merging", "merge_thr"),
mx=np.Inf,
) # ,
# bl=bl,
# c1=c1
# sn=neurons_noise,
# g=g
# )
(