-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlocalize.py
More file actions
2319 lines (1890 loc) · 97.6 KB
/
Copy pathlocalize.py
File metadata and controls
2319 lines (1890 loc) · 97.6 KB
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
"""
Code for localizing and fitting (typically diffraction limited) spots/beads
The fitting code can be run on a CPU using multiprocessing with joblib, or on a GPU using custom modifications
to GPUfit which can be found at https://github.com/QI2lab/Gpufit. To use the GPU code, you must download and
compile this repository and install the python bindings.
"""
from typing import Union, Optional
from collections.abc import Sequence, Callable
from pathlib import Path
import time
from warnings import warn, catch_warnings, filterwarnings
import zarr
import numpy as np
from scipy.signal import fftconvolve
from scipy.ndimage import maximum_filter
import dask
from dask.diagnostics import ProgressBar
from numba import njit, prange
import matplotlib.pyplot as plt
from matplotlib.colors import PowerNorm, LinearSegmentedColormap, Normalize
from matplotlib import colormaps
import localize_psf.rois as roi_fns
from localize_psf.fit import fit_model
import localize_psf.fit_psf as psf
# for filtering on GPU
try:
import cupy as cp
import cupyx.scipy.signal
import cupyx.scipy.ndimage
_cupy_available = True
except ImportError:
cp = np
_cupy_available = False
# custom GPUFit for fitting on GPU
try:
import pygpufit.gpufit as gf
_gpufit_available = True
except ImportError:
_gpufit_available = False
array = Union[np.ndarray, cp.ndarray]
def get_coords(sizes: Sequence[int],
drs: Sequence[float],
broadcast: bool = False) -> tuple[np.ndarray[float]]:
"""
Regularly spaced coordinates which can be broadcast to full size.
For example, if sizes = (nz, ny, nx) and drs = (1, 1, 1) then
coords0.size = (nz, 1, 1)
coords1.size = (1, ny, 1)
coords2.size = (1, 1, nx)
these arrays are broadcastable to size (nz, ny, nx). If the broadcast arrays are desired, they can be obtained by:
>>> coords_bcast = np.broadcast_arrays(coords0, coords1, coords2)
>>> coords0_bc, coords1_bc, coords2_bc = [np.array(c, copy=True) for c in coords_bcast]
note that the second line is necessary because np.broadcast_arrays() produces arrays with references to the
original entries, so assigning to these arrays can produce surprising results.
:param sizes: (s0, s1, ..., sn)
:param drs: (dr0, dr1, ..., drn)
:param broadcast: whether to expand all arrays to full size, or keep as 1D arrays with singleton dimensions
that will be automatically broadcast during arithmetic
:return coords: (coords0, coords1, ..., coordsn)
"""
ndims = len(drs)
coords = [np.expand_dims(np.arange(sz, dtype=float) * dr, axis=list(range(ii)) + list(range(ii + 1, ndims)))
for ii, (sz, dr) in enumerate(zip(sizes, drs))]
if broadcast:
# this produces copies of the arrays instead of views
coords = [np.array(c, copy=True) for c in np.broadcast_arrays(*coords)]
return tuple(coords)
def get_nearest_pixel(centers: np.ndarray[float],
drs: np.ndarray[float]) -> np.ndarray[int]:
"""
Get nearest pixel indices for centers given in real coordinates
:param centers:
:param drs:
:return indices:
"""
drs = np.asarray(drs)
return np.rint(centers / drs).astype(int)
@njit(parallel=True)
def prepare_rois(image: np.ndarray,
coords: tuple[np.ndarray, np.ndarray, np.ndarray],
rois: np.ndarray[int]) -> (np.ndarray[float], tuple[np.ndarray[float], np.ndarray[float], np.ndarray[float]], np.ndarray[int]):
"""
Cut ROI out of image and coordinate arrays and insert into nroi x nmax_roi_size array which is nan padded
:param image: image
:param coords:
:param rois:
:return img_rois, roi_coords, roi_sizes:
"""
nrois = len(rois)
z, y, x = coords
# numba does not support prod with axis argument
sizes = (rois[..., 1] - rois[..., 0]) * (rois[..., 3] - rois[..., 2]) * (rois[..., 5] - rois[..., 4])
nmax_roi_size = np.max(sizes)
img_rois = np.ones((nrois, nmax_roi_size)) * np.nan
x_rois = np.ones((nrois, nmax_roi_size)) * np.nan
y_rois = np.ones((nrois, nmax_roi_size)) * np.nan
z_rois = np.ones((nrois, nmax_roi_size)) * np.nan
nrois = len(rois)
for rr in prange(nrois):
roi = rois[rr]
nz = roi[1] - roi[0]
ny = roi[3] - roi[2]
nx = roi[5] - roi[4]
n_size_roi = nz * ny * nx
img_rois[rr, :n_size_roi] = image[roi[0]:roi[1], roi[2]:roi[3], roi[4]:roi[5]].ravel()
# numba compatible equivalent of np.array_broadcast()
for ii in prange(nz):
for jj in prange(ny):
for kk in prange(nx):
counter = kk + nx * jj + ny * nx * ii
x_rois[rr, counter] = x[0, 0, roi[4] + kk]
y_rois[rr, counter] = y[0, roi[2] + jj, 0]
z_rois[rr, counter] = z[roi[0] + ii, 0, 0]
return img_rois, (z_rois, y_rois, x_rois), sizes
def get_roi(center: Sequence[float],
img: np.ndarray,
coords: Sequence[np.ndarray],
sizes: tuple[int]):
"""
Find ROI which is nearly centered on center. Since center may not correspond to a pixel location, and the
size of the ROI may not be odd, center will not be the exact center of the ROI
:param center: [c_0, c_1, ..., c_n] in same units as x, y, z.
:param img: array of arbitrary size, m0 x m1 x ... x mn
:param coords: (coords0, coords1, ..., coordsN)
:param sizes: [i0, i1, ... in] integers
:return roi, img_roi, coords_roi:
"""
warn("get_roi() is deprecated and will be removed soon. Please use prepare_rois() instead")
# todo: deprecate in favor of vectorized finding ROIs and prepare_rois()
ndims = img.ndim
# get closest coordinates to desired center of roi
ics = [np.argmin(np.abs(r.ravel() - c)) for r, c in zip(coords, center)]
roi = roi_fns.get_centered_rois(ics, sizes, min_vals=[0]*ndims, max_vals=img.shape)[0]
# get coordinates as arrays which only have nonunit size along one direction
coords_roi = [c[tuple([slice(None)] * ii + [slice(roi[2*ii], roi[2*ii + 1])] + [slice(None)] * (ndims - 1 - ii))]
for ii, c in enumerate(coords)]
# broadcast to full arrays, essentially meshgrid
coords_roi = np.broadcast_arrays(*coords_roi)
img_roi = roi_fns.cut_roi(roi, img)[0]
return roi, img_roi, coords_roi
def get_filter_kernel(sigmas: Sequence[float],
drs: Sequence[float],
sigma_cutoff: int = 2) -> np.ndarray:
"""
Gaussian filter kernel for arbitrary dimensions. If drs or sigmas are zero along one dimension, then the kernel
will have unit length and weight along this direction
:param sigmas: (sigma_0, sigma_1, ..., sigma_n)
:param drs: (dr_1, dr_2, ..., dr_n) pixel sizes along each dimension
:param sigma_cutoff: single number or list [s0, s1, ..., sn] giving after how many sigmas we cut off the kernel
:return kernel:
"""
ndims = len(drs)
if isinstance(sigma_cutoff, (int, float)):
sigma_cutoff = [sigma_cutoff] * ndims
# convert to arrays
drs = np.array(drs, copy=True)
sigmas = np.array(sigmas, copy=True)
sigma_cutoff = np.array(sigma_cutoff, copy=True)
# compute kernel size
with np.errstate(invalid="ignore"):
nks = 2 * np.round(sigmas / drs * sigma_cutoff) + 1
nks[np.isnan(nks)] = 1
nks = nks.astype(int)
# nks = [2 * int(np.round(sig / dr * sig_cut)) + 1 for sig, dr, sig_cut in zip(sigmas, drs, sigma_cutoff)]
# now need to correct sigma = 0, as this would result in invalid kernel. Doesn't matter what value we set because
# coordinates will all be zeros
sigmas[sigmas == 0] = 1
# get coordinates to evaluate kernel at
coords = [np.expand_dims(np.arange(nk) * dr, axis=list(range(ii)) + list(range(ii + 1, ndims))) for
ii, (nk, dr) in enumerate(zip(nks, drs))]
coords = [c - np.mean(c) for c in coords]
kernel = np.exp(sum([-rk ** 2 / 2 / sig ** 2 for rk, sig in zip(coords, sigmas)]))
kernel = kernel / np.sum(kernel)
return kernel
def filter_convolve(imgs: array,
kernel: array) -> array:
"""
Convolution filter using kernel with GPU support. To avoid roll-off effects at the edge, the convolved
result is "normalized" by being divided by the kernel convolved with an array of ones.
This function can be run on either the GPU or the CPU. To run on the GPU, ensure that imgs is a cupy array
:param imgs: images to be convolved
:param kernel: kernel to be convolved. Does not need to be the same shape as image.
:return imgs_filtered:
"""
# todo: check and make sure kernel and imgs are compatible. e.g. that kernel is smaller than image in all dims
# todo: estimate how much memory convolution requires? Much more than I expect...
# todo: possibly because issue with fft plan caching, which is resolved by forcing cache to zero and clearing it
use_gpu = isinstance(imgs, cp.ndarray) and _cupy_available
if use_gpu:
xp = cp
convolve = cupyx.scipy.signal.fftconvolve
cp.fft._cache.PlanCache(memsize=0)
else:
xp = np
convolve = fftconvolve
kernel = xp.asarray(kernel)
imgs = xp.asarray(imgs)
# convolve, and deal with edges by normalizing
imgs_filtered = convolve(imgs, kernel, mode="same")
norm = convolve(xp.ones(imgs.shape), kernel, mode="same")
imgs_filtered /= norm
if use_gpu:
cache = cp.fft.config.get_plan_cache()
cache.clear()
return imgs_filtered
def get_max_filter_footprint(min_separations: Sequence[float],
drs: Sequence[float]) -> np.ndarray:
"""
Get footprint for maximum filter. This is a binary mask which is True at points included in the mask
and False at other points. For doing a square maximum filter can choose a footprint of only Trues, but cannot
do this for more complex shapes
:param min_separations: (size_0, size_1, ..., size_n)
:param drs: (dr_0, ..., dr_n)
:return footprint: boolean mask
"""
min_sep_allowed = np.array(min_separations)
drs = np.array(drs)
ns = np.ceil(min_sep_allowed / drs).astype(int)
# ensure at least size 1
ns[ns == 0] = 1
# ensure odd
ns += (1 - np.mod(ns, 2))
footprint = np.ones(ns, dtype=bool)
return footprint
def find_peak_candidates(imgs: array,
footprint: array,
threshold: float,
mask: Optional[np.ndarray] = None) -> (np.ndarray, np.ndarray):
"""
Find peak candidates in image using maximum filter. This can be run on either the GPU or the CPU.
:param imgs: 2D or 3D array. If this is a CuPy array, function will be run on the GPU
:param footprint: footprint to use for maximum filter. Array should have same number of dimensions as imgs.
This can be obtained from get_max_filter_footprint()
:param threshold: only pixels with values greater than or equal to the threshold will be considered
:param mask:
:return inds, amps: np.array([[i0, i1, i2], ...]) array indices of local maxima
"""
use_gpu_filter = isinstance(imgs, cp.ndarray) and _cupy_available
if use_gpu_filter:
xp = cp
max_filter = cupyx.scipy.ndimage.maximum_filter
else:
xp = np
max_filter = maximum_filter
if mask is None:
mask = xp.ones(imgs.shape, dtype=bool)
mask = xp.asarray(mask)
imgs = xp.asarray(imgs)
footprint = xp.asarray(footprint)
img_max_filtered = max_filter(imgs, footprint=footprint)
# don't use reduce because CuPy doesn't support it
is_max = xp.logical_and(xp.logical_and(imgs == img_max_filtered, imgs >= threshold), mask)
amps = imgs[is_max]
inds = xp.argwhere(is_max)
return inds, amps
def filter_nearby_peaks(centers: np.ndarray,
min_xy_dist: float,
min_z_dist: float,
mode: str = "keep-one",
weights: Optional[np.ndarray] = None,
nmax: int = 10000) -> (np.ndarray, np.ndarray):
"""
Combine multiple center positions into a reduced set, where assume all centers separated by no more than
min_xy_dist and min_z_dist come from the same feature.
This function treats xy and z directions separately. Centers must be close in both to be filtered.
:param centers: N x 3 array [cz, cy, cx]
:param min_xy_dist:
:param min_z_dist:
:param mode: "average", "keep-one", or "remove"
:param weights: only used in "average" mode. If weights are provided, a weighted average between nearby
points is computed
:param nmax: maximum number of centers to be processed at once. If the number of centers exceeds this size,
then the problem will be split in half (recursively) and solved on the subregions. Then the overlap zone
between these two regions will be checked and the results will be combined
:return centers_unique: array of unique center coordinates
:return inds: index into the initial array to produce centers_unique. In mode is "keep-one" or "remove"
then centers_unique = centers[inds]. If mode is "average", this will not be true as centers_unique will
not be elements of centers. However, centers[inds] will correspond to one point which was averaged to produce
the corresponding element of centers_unique
"""
if centers.ndim != 2 or centers.shape[1] != 3:
raise ValueError("centers should be a nx3 array where columns are cz, cy, cx")
centers_unique = np.array(centers, copy=True)
inds = np.arange(len(centers), dtype=int)
if weights is None:
weights = np.ones(len(centers_unique))
# only need to act if minimum distances are non-zero and we have any centers to deal with
if (min_xy_dist > 0 or min_z_dist > 0) and centers_unique.size != 0:
# if number of points is large, divide problem into subproblems, solve each of these, and combine results.
# check and make sure region is large enough (relative to the minimum distances) to be divide
# limits of data
clims = np.stack((np.min(centers, axis=0),
np.max(centers, axis=0)), axis=1)
# find ranges as fraction of min_dist
min_dists = np.array([min_z_dist, min_xy_dist, min_xy_dist])
with np.errstate(invalid="ignore"):
# todo: does this have a problem if min_dists = 0?
ranges = (clims[:, 1] - clims[:, 0]) / min_dists
if len(centers_unique) > nmax and not np.all(ranges <= 2):
if mode == "average":
raise NotImplementedError("mode='average' is not implemented with nmax < np.inf. Set nmax to np.inf")
ind_red_dim = np.argmax(ranges)
# divide into two regions and solve separately
in1 = np.logical_and(centers_unique[:, ind_red_dim] >= clims[ind_red_dim, 0],
centers_unique[:, ind_red_dim] < np.mean(clims[ind_red_dim]))
in2 = np.logical_and(centers_unique[:, ind_red_dim] >= np.mean(clims[ind_red_dim]),
centers_unique[:, ind_red_dim] <= clims[ind_red_dim, 1])
if np.any(in1):
cu1, i1 = filter_nearby_peaks(centers_unique[in1], min_xy_dist, min_z_dist, mode=mode)
else:
cu1 = np.zeros((0, 3))
i1 = np.zeros((0, 3))
if np.any(in2):
cu2, i2 = filter_nearby_peaks(centers_unique[in2], min_xy_dist, min_z_dist, mode=mode)
else:
cu2 = np.zeros((0, 3))
i2 = np.zeros((0, 3))
full_inds = np.arange(len(centers_unique), dtype=int)
centers_unique_sectors = np.concatenate((cu1, cu2))
inds_sectors = np.concatenate((full_inds[in1][i1], full_inds[in2][i2]))
# take care of any non-unique points in the overlap region
in_overlap = np.logical_and(centers_unique_sectors[:, ind_red_dim] >= np.mean(clims[ind_red_dim]) - min_dists[ind_red_dim],
centers_unique_sectors[:, ind_red_dim] <= np.mean(clims[ind_red_dim]) + min_dists[ind_red_dim])
if np.any(in_overlap):
centers_unique_overlap, i_overlap = filter_nearby_peaks(centers_unique_sectors[in_overlap], min_xy_dist, min_z_dist, mode=mode)
# get full centers by adding any that were not in the overlap region with the reduced set from the overlap region
centers_unique_sectors = np.concatenate((centers_unique_sectors[np.logical_not(in_overlap)],
centers_unique_overlap))
inds_sectors = np.concatenate((inds_sectors[np.logical_not(in_overlap)],
full_inds[inds_sectors][in_overlap][i_overlap]))
# full results
centers_unique = centers_unique_sectors
inds = inds_sectors
else:
# loop through points, at each step removing any duplicates and shrinking our list
# after looping through a point, it cannot be subsequently removed because the relations we are checking
# are symmetric.
# todo: is it possible this can fail in "average" mode?
# todo: looks like this might be easier if use some tools from scipy.spatial, scipy.spatial.cKDTree
counter = 0
while counter < len(centers_unique):
# compute distances to all other beads
z_dists = np.abs(centers_unique[counter][0] - centers_unique[:, 0])
xy_dists = np.sqrt((centers_unique[counter][1] - centers_unique[:, 1]) ** 2 +
(centers_unique[counter][2] - centers_unique[:, 2]) ** 2)
# beads which are close enough we will combine
combine = np.logical_and(z_dists <= min_z_dist, xy_dists <= min_xy_dist)
if mode == "average":
denom = np.nansum(np.logical_not(np.isnan(np.sum(centers_unique[combine], axis=1))) * weights[combine])
# compute new center from average and reset that position in the list
centers_unique[counter] = np.nansum(centers_unique[combine] * weights[combine][:, None], axis=0, dtype=float) / denom
weights[counter] = denom
combine[counter] = False
elif mode == "keep-one":
# don't want to remove the point itself
combine[counter] = False
elif mode == "remove":
pass
else:
raise ValueError("mode must be 'average', 'keep-one', or 'remove' but was '%s'" % mode)
# remove points from lists
inds = inds[np.logical_not(combine)]
centers_unique = centers_unique[np.logical_not(combine)]
weights = weights[np.logical_not(combine)]
counter += 1
return centers_unique, inds
def localize2d(img: np.ndarray,
mode: str = "radial-symmetry"):
"""
Perform 2D localization using the radial symmetry approach of https://doi.org/10.1038/nmeth.2071
:param img: 2D image of size ny x nx
:param mode: 'radial-symmetry' or 'centroid'
:return xc, yc:
"""
if img.ndim != 2:
raise ValueError("img must be a 2D array, but was %dD" % img.ndim)
ny, nx = img.shape
x = np.arange(nx)
y = np.arange(ny)
if mode == "centroid":
xc = np.sum(img * x[None, :]) / np.sum(img)
yc = np.sum(img * y[:, None]) / np.sum(img)
elif mode == "radial-symmetry":
# gradients taken at point between four pixels, i.e. (xk, yk) = (j + 0.5, i + 0.5)
# using the Roberts cross operator
yk = 0.5 * (y[:-1] + y[1:])
xk = 0.5 * (x[:-1] + x[1:])
# gradients along 45 degree rotated directions
grad_uk = img[1:, 1:] - img[:-1, :-1]
grad_vk = img[1:, :-1] - img[:-1, 1:]
grad_xk = 1 / np.sqrt(2) * (grad_uk - grad_vk)
grad_yk = 1 / np.sqrt(2) * (grad_uk + grad_vk)
with np.errstate(invalid="ignore", divide="ignore"):
# slope of the gradient at this point
mk = grad_yk / grad_xk
mk[np.isnan(mk)] = np.inf
# compute weights by (1) increasing weight where gradient is large and (2) decreasing weight for points far away
# from the centroid (as small slope errors can become large as the line is extended to the centroi)
# approximate distance between (xk, yk) and (xc, yc) by assuming (xc, yc) is centroid of the gradient
grad_norm = np.sqrt(grad_xk**2 + grad_yk**2)
centroid_grad_norm_x = np.sum(xk[None, :] * grad_norm) / np.sum(grad_norm)
centroid_grad_norm_y = np.sum(yk[:, None] * grad_norm) / np.sum(grad_norm)
dk_centroid = np.sqrt((yk[:, None] - centroid_grad_norm_y)**2 + (xk[None, :] - centroid_grad_norm_x)**2)
# weights
wk = grad_norm**2 / dk_centroid
# def chi_sqr(xc, yc):
# val = ((yk[:, None] - yc) - mk * (xk[None, :] - xc))**2 / (mk**2 + 1) * wk
# val[np.isinf(mk)] = (np.tile(xk[None, :], [yk.size, 1])[np.isinf(mk)] - xc)**2
# return np.sum(val)
# line passing through (xk, yk) with slope mk is y = yk + mk*(x - xk)
# minimimum distance of points (xc, yc) is dk**2 = [(yk - yc) - mk*(xk -xc)]**2 / (mk**2 + 1)
# must handle the case mk -> infinity separately. In this case dk**2 -> (xk - xc)**2
# minimize chi^2 = \sum_k dk**2 * wk
# minimizing for xc, yc gives a matrix equation
# [[A, B], [C, D]] * [[xc], [yc]] = [[E], [F]]
# in case the slope is infinite, need to take the limit of the sum manually
summand_a = -mk ** 2 * wk / (mk ** 2 + 1)
summand_a[np.isinf(mk)] = wk[np.isinf(mk)]
A = np.sum(summand_a)
summand_b = mk * wk / (mk**2 + 1)
summand_b[np.isinf(mk)] = 0
B = np.sum(summand_b)
C = -B
D = np.sum(wk / (mk**2 + 1))
summand_e = (mk * wk * (yk[:, None] - mk * xk[None, :])) / (mk**2 + 1)
summand_e[np.isinf(mk)] = - (wk * xk[None, :])[np.isinf(mk)]
E = np.sum(summand_e)
summand_f = (yk[:, None] - mk * xk[None, :]) * wk / (mk**2 + 1)
summand_f[np.isinf(mk)] = 0
F = np.sum(summand_f)
xc = (D * E - B * F) / (A*D - B*C)
yc = (-C * E + A * F) / (A*D - B*C)
else:
raise ValueError("mode must be 'centroid' or 'radial-symmetry', but was '%s'" % mode)
return xc, yc
def localize3d(img: np.ndarray,
mode: str = "radial-symmetry"):
"""
Perform 3D localization using an extension of the radial symmetry approach of https://doi.org/10.1038/nmeth.2071
:param img: 3D image of size nz x ny x nx
:param str mode: 'radial-symmetry' or 'centroid'
:return xc, yc, zc:
"""
if img.ndim != 3:
raise ValueError("img must be a 3D array, but was %dD" % img.ndim)
nz, ny, nx = img.shape
x = np.arange(nx)[None, None, :]
y = np.arange(ny)[None, :, None]
z = np.arange(nz)[:, None, None]
if mode == "centroid":
xc = np.sum(img * x) / np.sum(img)
yc = np.sum(img * y) / np.sum(img)
zc = np.sum(img * z) / np.sum(img)
elif mode == "radial-symmetry":
yk = 0.5 * (y[:, :-1, :] + y[:, 1:, :])
xk = 0.5 * (x[:, :, :-1] + x[:, :, 1:])
zk = 0.5 * (z[:-1] + z[1:])
coords = (zk, yk, xk)
# take a cube of 8 voxels, and compute gradients at the center, using the four pixel diagonals that pass
# through the center
grad_n1 = img[1:, 1:, 1:] - img[:-1, :-1, :-1]
n1 = np.array([1, 1, 1]) / np.sqrt(3) # vectors go [nz, ny, nx]
grad_n2 = img[1:, :-1, 1:] - img[:-1, 1:, :-1]
n2 = np.array([1, -1, 1]) / np.sqrt(3)
grad_n3 = img[1:, :-1, :-1] - img[:-1, 1:, 1:]
n3 = np.array([1, -1, -1]) / np.sqrt(3)
grad_n4 = img[1:, 1:, :-1] - img[:-1, :-1, 1:]
n4 = np.array([1, 1, -1]) / np.sqrt(3)
# compute the gradient xyz components
# 3 unknowns and 4 eqns, so use pseudo-inverse to optimize overdetermined system
mat = np.concatenate((n1[None, :], n2[None, :], n3[None, :], n4[None, :]), axis=0)
gradk = np.linalg.pinv(mat).dot(
np.concatenate((grad_n1.ravel()[None, :], grad_n2.ravel()[None, :],
grad_n3.ravel()[None, :], grad_n4.ravel()[None, :]), axis=0))
gradk = np.reshape(gradk, [3, zk.size, yk.size, xk.size])
# compute weights by (1) increasing weight where gradient is large and (2) decreasing weight for points far away
# from the centroid (as small slope errors can become large as the line is extended to the centroi)
# approximate distance between (xk, yk) and (xc, yc) by assuming (xc, yc) is centroid of the gradient
grad_norm = np.sqrt(np.sum(gradk**2, axis=0))
centroid_gns = np.array([np.sum(zk * grad_norm), np.sum(yk * grad_norm), np.sum(xk * grad_norm)]) / np.sum(grad_norm)
dk_centroid = np.sqrt((zk - centroid_gns[0]) ** 2 + (yk - centroid_gns[1]) ** 2 + (xk - centroid_gns[2]) ** 2)
# weights
wk = grad_norm ** 2 / dk_centroid
# in 3D, parameterize a line passing through point Po along normal n by
# V(t) = Pk + n * t
# distance between line and point Pc minimized at
# tmin = -\sum_{i=1}^3 (Pk_i - Pc_i) / \sum_i n_i^2
# dk^2 = \sum_k \sum_i (Pk + n * tmin - Pc)^2
# again, we want to minimize the quantity
# chi^2 = \sum_k dk^2 * wk
# so we take the derivatives of chi^2 with respect to Pc_x, Pc_y, and Pc_z, which gives a system of linear
# equations, which we can recast into a matrix equation
# np.array([[A, B, C], [D, E, F], [G, H, I]]) * np.array([[Pc_z], [Pc_y], [Pc_x]]) = np.array([[J], [K], [L]])
nk = gradk / np.linalg.norm(gradk, axis=0)
# def chi_sqr(xc, yc, zc):
# cs = (zc, yc, xc)
# chi = 0
# for ii in range(3):
# chi += np.sum((coords[ii] + nk[ii] * (cs[jj] - coords[jj]) - cs[ii]) ** 2 * wk)
# return chi
# build 3x3 matrix from above
mat = np.zeros((3, 3))
for ll in range(3): # rows of matrix
for ii in range(3): # columns of matrix
if ii == ll:
mat[ll, ii] += np.sum(-wk * (nk[ii] * nk[ll] - 1))
else:
mat[ll, ii] += np.sum(-wk * nk[ii] * nk[ll])
for jj in range(3): # internal sum
if jj == ll:
mat[ll, ii] += np.sum(wk * nk[ii] * nk[jj] * (nk[jj] * nk[ll] - 1))
else:
mat[ll, ii] += np.sum(wk * nk[ii] * nk[jj] * nk[jj] * nk[ll])
# build vector from above
vec = np.zeros((3, 1))
coord_sum = zk * nk[0] + yk * nk[1] + xk * nk[2]
for ll in range(3): # sum over J, K, L
for ii in range(3): # internal sum
if ii == ll:
vec[ll] += -np.sum((coords[ii] - nk[ii] * coord_sum) * (nk[ii] * nk[ll] - 1) * wk)
else:
vec[ll] += -np.sum((coords[ii] - nk[ii] * coord_sum) * nk[ii] * nk[ll] * wk)
# invert matrix
zc, yc, xc = np.linalg.inv(mat).dot(vec)
else:
raise ValueError("mode must be 'centroid' or 'radial-symmetry', but was '%s'" % mode)
return xc, yc, zc
# @profile
def fit_rois(img_rois: np.ndarray,
coords_rois: Sequence[np.ndarray, np.ndarray, np.ndarray],
roi_sizes: np.ndarray[int],
init_params: np.ndarray,
max_number_iterations: int = 100,
tolerance: Optional[float] = None,
estimator: str = "LSE",
fixed_params: Optional[np.ndarray] = None,
guess_bounds: bool = False,
use_gpu: bool = _gpufit_available,
debug: bool = False,
verbose: bool = False,
model: psf.pixelated_psf_model = psf.gaussian3d_psf_model()) -> dict:
"""
Fit rois to different model functions. Can use either CPU parallelization with dask or GPU parallelization
using gpufit.
For help cutting ROI's from an image and converting them to the correct format, use the helper function
prepare_rois()
:param img_rois: array of image rois of size nroi x nmax_roi_size. Each ROI should be flattened, padded
with NaN's, and inserted along the 0th dimension.
:param coords_rois: (z_rois, y_rois, ....) the coordinate arrays z_rois should have the same shape as img_rois
:param roi_sizes: array giving size of each ROI
:param init_params: initial parameters for fits, size nfits x model.nparams
:param max_number_iterations: maximum number of iterations to be used for each fit
:param tolerance: only for GPUFIT. Default is 1e-4.
:param estimator: "LSE" or "MLE", only for GPUFIT
:param model: "gaussian", "rotated-gaussian", "gaussian-lorentzian"
:param fixed_params: For entries which are True, the fit function will force that parameter to be identical
to the value in init_params. For entries which are False, the fit function will determine the optimal value.
only supports fixing/unfixing each parameter for all fits
:param guess_bounds: ((lower_bounds), (upper_bounds)) where lower_bounds and upper_bounds are each
lists/tuples/arrays of length nparams
:param use_gpu: whether to perform fitting on the GPU. If true, then GPUfit must be installed
:param debug:
:param verbose:
:param model: model to use for PSF fitting. If doing this on the CPU, use implementations in fit_psf.py, otherwise
model must have a corresponding version in GPU fit.
:return fit_results: dictionary of fit results
"""
if guess_bounds and use_gpu:
warn("use_gpu selected for fitting, but unsupported option guess_bounds selected."
"guess_bounds will be ignored")
zrois, yrois, xrois = coords_rois
if not use_gpu:
tstart = time.perf_counter()
if debug:
results = []
for ii in range(len(img_rois)):
results.append(model.fit(img_rois[ii],
(zrois[ii], yrois[ii], xrois[ii]),
init_params[ii],
fixed_params=fixed_params,
guess_bounds=guess_bounds,
max_nfev=max_number_iterations)
)
else:
# forced to switch to dask form joblib because joblib use pickling to exchange info between process
# and functions (which are arguments to fit_gauss_roi) are not pickle-able
delayed = []
for ii in range(len(img_rois)):
delayed.append(dask.delayed(model.fit)(img_rois[ii],
(zrois[ii], yrois[ii], xrois[ii]),
init_params=init_params[ii],
fixed_params=fixed_params,
guess_bounds=guess_bounds,
max_nfev=max_number_iterations)
)
if verbose:
with ProgressBar():
results = dask.compute(*delayed)
else:
results = dask.compute(*delayed)
fit_t = (time.perf_counter() - tstart)
fit_params = np.asarray([r["fit_params"] for r in results])
chi_sqrs = np.asarray([r["chi_squared"] for r in results])
fit_states = np.asarray([r["status"] for r in results])
niters = np.asarray([r["nfev"] for r in results])
fit_states_key = results[0]["status_codes"]
else:
if model.sf != 1:
raise NotImplementedError("sampling factors other than 1 are not implemented for GPU fitting")
# resolve GPUfit model
models_mapping = {psf.gaussian3d_psf_model: gf.ModelID.GAUSS_3D_ARB}
try:
models_mapping[psf.gaussian_lorentzian_psf_model] = gf.ModelID.GAUSS_LOR_3D_ARB
models_mapping[psf.gaussian3d_asymmetric_rotated_pixelated] = gf.ModelID.GAUSS_3D_ROT_ARB
models_mapping[psf.gaussian3d_asymmetric_pixelated] = gf.ModelID.GAUSS_3D_ASYM_ARB
except AttributeError:
pass
if type(model) in models_mapping.keys():
model_id = models_mapping[type(model)]
else:
raise NotImplementedError(f"model of type {type(model)} has not been implemented in the "
f"installed version of gpufit."
f"The models which have been implemented are {[a for a in models_mapping.keys()]}")
# build GPUfit data
data = img_rois.astype(np.float32)
nfits, n_pts_per_fit = data.shape
# build user data
coords = np.stack((xrois, yrois, zrois), axis=1).ravel()
user_info = np.concatenate((coords.astype(np.float32),
roi_sizes.astype(np.float32)))
# some models have extra non-fit parameters appended at end of user_info
if model_id == gf.ModelID.GAUSS_3D_ARB or \
model_id == gf.ModelID.GAUSS_3D_ROT_ARB or \
model_id == gf.ModelID.GAUSS_3D_ASYM_ARB:
user_info = np.concatenate((user_info,
np.array(model.minimum_sigmas).astype(np.float32)))
# initial parameters
init_params = init_params.astype(np.float32)
nparams = model.nparams
# check arguments
if data.ndim != 2:
raise ValueError(f"data.ndim should = 2 but was {data.ndim:d}")
if init_params.ndim != 2 or init_params.shape != (nfits, nparams):
raise ValueError(f"init_params should have shape ({nfits:d}, {nparams:d}), but had shape {init_params.shape}")
# todo: this now depends on the model
# if user_info.ndim != 1 or user_info.size != (3 * nfits * n_pts_per_fit + nfits):
# raise ValueError(f"user_info should have size ({3 * nfits * n_pts_per_fit + nfits:d}), but had size {user_info.size:d}")
if estimator == "MLE":
est_id = gf.EstimatorID.MLE
elif estimator == "LSE":
est_id = gf.EstimatorID.LSE
else:
raise ValueError(f"'estimator' must be 'MLE' or 'LSE' but was '{estimator:s}'")
# set which parameters to fit/fix
if fixed_params is None:
fixed_params = np.zeros(nparams, dtype=bool)
params_to_fit = np.logical_not(np.array(fixed_params)).astype(np.int32)
# do fitting
fit_params, fit_states, chi_sqrs, niters, fit_t = gf.fit(data,
None,
model_id,
init_params,
tolerance=tolerance,
max_number_iterations=max_number_iterations,
estimator_id=est_id,
parameters_to_fit=params_to_fit,
user_info=user_info)
# defined in Gpufit/constants.h
fit_states_key = {"converged": 0,
"max_iteration": 1,
"singular_hessian": 2,
"neg_curvature_mle": 3,
"gpu_not_ready": 4}
# ensure e.g. Gaussian sigmas are > 0
fit_params = model.normalize_parameters(fit_params)
# collect results
fit_results = {"fit_params": fit_params,
"init_params": init_params,
"fit_states": fit_states,
"fit_states_key": fit_states_key,
"chi_sqrs": chi_sqrs,
"niters": niters,
"fit_time": fit_t,
"model": repr(model)}
return fit_results
def plot_fit_roi(fit_params: Sequence[float],
roi: Sequence[int],
imgs: np.ndarray,
coords: Optional[Sequence[np.ndarray]] = None,
init_params: Optional[np.ndarray] = None,
model: psf.pixelated_psf_model = psf.gaussian3d_psf_model(),
string: Optional[str] = None,
same_color_scale: bool = True,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
cmap="bone",
gamma: float = 1.,
scale_z_display: float = 1.,
figsize: Sequence[float, float] = (16., 8.),
prefix: str = "",
save_dir: Optional[Union[str, Path]] = None):
"""
Plot results obtained from fitting functions fit_gauss_roi() or fit_gauss_rois()
:param fit_params:
:param roi: [zstart, zend, ystart, yend, xstart, xend]
:param imgs: full image, such that imgs[zstart:zend, ystart:yend, xstart:xend] is the region that was fit
:param coords: (z, y, x) broadcastable to same size as imgs
:param init_params: initial parameters used in fit, optional
:param model:
:param string:
:param same_color_scale: whether to use same color scale for data and fits
:param vmin:
:param vmax:
:param cmap:
:param gamma:
:param scale_z_display:
:param figsize: (sx, sz)
:param prefix: prefix prepended before save name
:param save_dir: if None, do not save results
:return figh:
"""
nz, ny, nx = imgs.shape
if coords is None:
coords = np.meshgrid(range(nz), range(ny), range(nx), indexing="ij")
z, y, x = coords
# extract useful coordinate info
dc = x[0, 0, 1] - x[0, 0, 0]
if z.shape[0] > 1:
dz = z[1, 0, 0] - z[0, 0, 0]
else:
# dz = dc
dz = dc * (roi[5] - roi[4] + 1) / 10
if init_params is not None:
center_guess = np.array([init_params[3], init_params[2], init_params[1]])
center_fit = np.array([fit_params[3], fit_params[2], fit_params[1]])
# get ROI and coordinates
img_roi = roi_fns.cut_roi(roi, imgs)[0]
x_roi = roi_fns.cut_roi(roi, x)[0]
y_roi = roi_fns.cut_roi(roi, y)[0]
z_roi = roi_fns.cut_roi(roi, z)[0]
if vmin is None:
vmin = np.percentile(img_roi[np.logical_not(np.isnan(img_roi))], 1)
if vmax is None:
vmax = np.percentile(img_roi[np.logical_not(np.isnan(img_roi))], 99.9)
# git fit
img_fit = model.model((z_roi, y_roi, x_roi), fit_params)
# set extents
extent_xy = [x_roi[0, 0, 0] - 0.5 * dc, x_roi[0, 0, -1] + 0.5 * dc,
y_roi[0, -1, 0] + 0.5 * dc, y_roi[0, 0, 0] - 0.5 * dc]
extent_xz = [x_roi[0, 0, 0] - 0.5 * dc, x_roi[0, 0, -1] + 0.5 * dc,
z_roi[-1, 0, 0] + 0.5 * dz, z_roi[0, 0, 0] - 0.5 * dz]
extent_zy = [z_roi[0, 0, 0] - 0.5 * dz, z_roi[-1, 0, 0] + 0.5 * dz,
y_roi[0, -1, 0] + 0.5 * dc, y_roi[0, 0, 0] - 0.5 * dc]
wx = extent_xy[1] - extent_xy[0]
wy = extent_xy[2] - extent_xy[3]
wz = extent_xz[2] - extent_xz[3]
# ################################
# plot results interpolated on regular grid
# ################################
figh_interp = plt.figure(figsize=figsize)
st_str = f"Fit, max projections, interpolated, ROI = {roi}"
st_str += f"\n{'fit': <10}" + ", ".join([f"{model.parameter_names[ii]:s}="
f"{fit_params[ii]:3.4f}" for ii in range(len(fit_params))])
if init_params is not None:
st_str += f"\n{'guess': <10}" + ", ".join([f"{model.parameter_names[ii]:s}="
f"{init_params[ii]:3.4f}" for ii in range(len(fit_params))])
if string is not None:
st_str += "\n" + string
figh_interp.suptitle(st_str)
grid = figh_interp.add_gridspec(nrows=2, height_ratios=[1, wz / wy * scale_z_display], hspace=0,
ncols=7, width_ratios=[wz / wx * scale_z_display, 1, 0.2, wz / wx * scale_z_display, 1, 0.2, 0.2], wspace=0)
# ################################
# XY, data
# ################################
ax = figh_interp.add_subplot(grid[0, 1])
im = ax.imshow(np.nanmax(img_roi, axis=0),
extent=extent_xy,
cmap=cmap,
norm=PowerNorm(vmin=vmin, vmax=vmax, gamma=gamma))
ax.plot(center_fit[2], center_fit[1], 'm+')
if init_params is not None:
ax.plot(center_guess[2], center_guess[1], 'gx')
ax.set_ylim(extent_xy[2:4])
ax.set_xlim(extent_xy[0:2])
ax.set_xticks([])
ax.set_yticks([])
# ################################
# XZ, data
# ################################
ax = figh_interp.add_subplot(grid[1, 1])
ax.imshow(np.nanmax(img_roi, axis=1),
extent=extent_xz,
cmap=cmap,
norm=PowerNorm(vmin=vmin, vmax=vmax, gamma=gamma))
ax.plot(center_fit[2], center_fit[0], 'm+')
if init_params is not None:
ax.plot(center_guess[2], center_guess[0], 'gx')
ax.set_ylim(extent_xz[2:4])
ax.set_xlim(extent_xz[0:2])
ax.set_xlabel("X (um)")
# ################################
# YZ, data
# ################################
ax = figh_interp.add_subplot(grid[0, 0])
with catch_warnings():
filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
ax.imshow(np.nanmax(img_roi, axis=2).transpose(),
extent=extent_zy,
cmap=cmap,
norm=PowerNorm(vmin=vmin, vmax=vmax, gamma=gamma))
ax.plot(center_fit[0], center_fit[1], 'm+')