-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsim_reconstruction.py
4410 lines (3651 loc) · 181 KB
/
sim_reconstruction.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
"""
Tools for reconstructing 2D sinusoidal SIM images from raw data.
The primary reconstruction code is contained in the class `SimImageSet`
Suppose we illuminate an object :math:`O(r)` with a series of patterns,
.. math::
I_{ij}(r) = A_{ij} \\left[m_i \\cos (2\\pi f_i \\cdot r + \\phi_{ij}) \\right]
Then the images we measure are
.. math::
D_{ij}(r) = \\left[I_{ij}(r) O(r) \\right] * h(r)
where :math:`h(r)` is the point-spread function of the system.
"""
from sys import stdout
from time import perf_counter
from copy import deepcopy
from warnings import warn
from typing import Union, Optional
from collections.abc import Sequence
# parallelization
from dask import delayed, compute
from dask.diagnostics import ProgressBar
import dask.array as da
# numerics
import numpy as np
from scipy.fft import fftshift, ifftshift, fftfreq, fft2
from scipy.optimize import minimize
from scipy.signal import correlate
from scipy.signal.windows import tukey
from skimage.exposure import match_histograms as match_histograms_cpu
# working with external files
from pathlib import Path
from io import StringIO
# loading and exporting data
import json
import tifffile
import h5py
import zarr
from numcodecs import Zlib
# plotting
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.cm import ScalarMappable
from matplotlib.colors import PowerNorm, LogNorm
from matplotlib.patches import Circle, Rectangle
# code from our projects
from mcsim.analysis.optimize import Optimizer, soft_threshold, tv_prox, to_cpu
from mcsim.analysis.fft import ft2, ift2, irft2, conj_transpose_fft, translate_ft
from localize_psf.rois import get_centered_rois, cut_roi
from localize_psf.fit_psf import circ_aperture_otf, blur_img_psf, oversample_voxel
from localize_psf.camera import bin, bin_adjoint, simulated_img
from localize_psf.affine import params2xform
# GPU
try:
import cupy as cp
from cucim.skimage.exposure import match_histograms as match_histograms_gpu
except ImportError:
cp = None
match_histograms_gpu = None
if cp:
array = Union[np.ndarray, cp.ndarray]
else:
array = np.ndarray
class SimImageSet:
allowed_frq_estimation_modes = ["band-correlation", "fourier-transform", "fixed"]
allowed_phase_estimation_modes = ["wicker-iterative", "real-space", "naive", "fixed"]
allowed_combine_bands_modes = ["fairSIM"]
allowed_reconstruction_modes = ["wiener-filter"] # "FISTA"
allowed_mod_depth_estimation_modes = ["band-correlation", "fixed"]
nbands = 3 # hardcoded for 2D sinusoidal SIM
band_inds = np.array([0, 1, -1], dtype=int) # bands are shifted by these multiples of frqs
band_id = np.array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, -1, 0, 0],
[0, 0, 1, 0],
[0, 0, -1, 0],
[0, 0, 0, 1],
[0, 0, 0, -1]
], dtype=int) # n_bands x (n_frqs + 1)
upsample_fact = 2
@classmethod
def initialize(cls,
physical_params: dict,
imgs: np.ndarray,
otf: Optional[np.ndarray] = None,
wiener_parameter: float = 0.1,
frq_estimation_mode: str = "band-correlation",
frq_guess: Optional[np.ndarray] = None,
phase_estimation_mode: str = "wicker-iterative",
phases_guess: Optional[np.ndarray] = None,
combine_bands_mode: str = "fairSIM",
fmax_exclude_band0: float = 0,
mod_depths_guess: Optional[np.ndarray] = None,
use_fixed_mod_depths: bool = False,
mod_depth_otf_mask_threshold: float = 0.1,
minimum_mod_depth: float = 0.5,
normalize_histograms: bool = False,
determine_amplitudes: bool = False,
background: float = 0.,
gain: float = 1.,
max_phase_err: float = 10 * np.pi / 180,
min_p2nr: float = 1.,
trim_negative_values: bool = False,
use_gpu: bool = cp is not None,
print_to_terminal: bool = True,
axes_names: Optional[Sequence[str]] = None,
cam_roi: Optional[Sequence[int, int, int, int]] = None,
data_roi: Optional[Sequence[int, int, int, int]] = None,
):
"""
Simplified constructor for SimImageSet. Use this constructor when all SIM reconstruction parameters
are known at the outset (including e.g. frequency and phase guesses but not necessarily final values).
For usage examples see
>>> help(SimImageSet)
:param physical_params: {'pixel_size', 'na', 'wavelength'}. Pixel size and emission wavelength in um
:param imgs: n0 x n1 x ... nm x nangles x nphases x ny x nx raw data to be reconstructed. The first
m-dimensions will be reconstructed in parallel. These may represent e.g. time-series and z-stack data.
The same reconstruction parameters must be used for the full stack, so these should not represent different
channels.
:param otf: optical transfer function evaluated at the same frequencies as the fourier transforms of imgs.
If None, estimate from NA. This can either be an array of size ny x nx, or an array of size nangles x ny x nx
The second case corresponds to a system that has different OTF's per SIM acquisition angle.
:param wiener_parameter: Attenuation parameter for Wiener filtering. This has a sligtly different meaning
depending on the value of combine_bands_mode
:param frq_estimation_mode: "band-correlation", "fourier-transform", or "fixed"
"band-correlation" first unmixes the bands using the phase guess values and computes the correlation between
the shifted and unshifted band
"fourier-transform" correlates the Fourier transform of the image with itself.
"fixed" uses the frq_guess values
:param frq_guess: 2 x nangles array of guess SIM frequency values
:param phase_estimation_mode: "wicker-iterative", "real-space", "naive", or "fixed"
"wicker-iterative" follows the approach of https://doi.org/10.1364/OE.21.002032.
"real-space" follows the approach of section IV-B in https://doir.org/10.1109/JSTQE.2016.2521542.
"naive" uses the phase of the Fourier transform of the raw data.
"fixed" uses the values provided from phases_guess.
:param phases_guess: nangles x nphases array of phase guesses
:param combine_bands_mode: "fairSIM" if using method of https://doi.org/10.1038/ncomms10980 or "openSIM" if
using method of https://doi.org/10.1109/jstqe.2016.2521542
:param float fmax_exclude_band0: amount of the unshifted bands to exclude, as a fraction of fmax. This can
enhance optical sectioning by replacing the low frequency information in the reconstruction with the data.
from the shifted bands only.
For more details on the band replacement optical sectioning approach, see https://doi.org/10.1364/BOE.5.002580
and https://doi.org/10.1016/j.ymeth.2015.03.020
:param mod_depths_guess: If use_fixed_mod_depths is True, these modulation depths are used
:param use_fixed_mod_depths: if true, use mod_depths_guess instead of estimating the modulation depths from the data
:param mod_depth_otf_mask_threshold:
:param minimum_mod_depth: if modulation depth is estimated to be less than this value, it will be replaced
with this value during reconstruction
:param normalize_histograms: for each phase, normalize histograms of images to account for laser power fluctuations
:param background: Either a single number, or broadcastable to size of imgs. The background will be subtracted
before running the SIM reconstruction
:param determine_amplitudes: whether to determine amplitudes as part of Wicker phase optimization.
This flag only has an effect if phase_estimation_mode is "wicker-iterative"
:param background: a single number, or an array which is broadcastable to the same size as images. This will
be subtracted from the raw data before processing.
:param gain: gain of the camera in ADU/photons. This is a single number or an array which is broadcastable to
the same size as the images whcih is sued to convert the ADU counts to photon numbers.
:param max_phase_err: If the determined phase error between components exceeds this value, use the phase guess
values instead of those determined by the estimation algorithm.
:param min_p2nr: if the peak-to-noise ratio is smaller than this value, use the frequency guesses instead
of the frequencies determined by the estimation algorithm.
:param trim_negative_values: set values in SIM-SR reconstruction which are less than zero to zero
:param use_gpu:
:param print_to_terminal:
:param axes_names: axes names for all input dimensions.
:param cam_roi: ROI camera chip has been cropped to wrt to the entire camera chip
:param data_roi: ROI the data has been cropped to after camera acquistion
"""
tstart = perf_counter()
self = cls(use_gpu, print_to_terminal)
# #############################################
# preprocessing
# #############################################
self.preprocess_data(physical_params["pixel_size"],
physical_params["na"],
physical_params["wavelength"],
imgs,
normalize_histograms,
gain,
background,
axes_names,
cam_roi,
data_roi)
# #############################################
# set reconstruction settings
# #############################################
self.update_recon_settings(wiener_parameter=wiener_parameter,
frq_estimation_mode=frq_estimation_mode,
phase_estimation_mode=phase_estimation_mode,
combine_bands_mode=combine_bands_mode,
fmax_exclude_band0=fmax_exclude_band0,
use_fixed_mod_depths=use_fixed_mod_depths,
mod_depth_otf_mask_threshold=mod_depth_otf_mask_threshold,
minimum_mod_depth=minimum_mod_depth,
determine_amplitudes=determine_amplitudes,
max_phase_err=max_phase_err,
min_p2nr=min_p2nr,
trim_negative_values=trim_negative_values)
# #############################################
# OTF
# #############################################
self.update_otf(otf)
# #############################################
# set guess parameters
# #############################################
self.update_parameter_guesses(frq_guess=frq_guess,
phases_guess=phases_guess,
mod_depths_guess=mod_depths_guess)
self.print_log(f"initialization took {perf_counter() - tstart:.2f}s")
return self
def __init__(self,
use_gpu: bool = cp is not None,
print_to_terminal: bool = True):
"""
Reconstruct raw SIM data into widefield, SIM-SR, SIM-OS, and deconvolved images using the Wiener filter
style reconstruction of Gustafsson and Heintzmann. This code relies on various ideas developed and
implemented elsewhere, see for example fairSIM and openSIM.
An instance of this class may be used directly to reconstruct a single SIM image which is stored as a
3 x 3 x ny x nx NumPy array, or a larger image series of sizes n0 x ... x nm x 3 x 3 x ny x nx as long as
the SIM parameters are the same for all images in the stack.
:param use_gpu: Run SIM computations on the GPU
:param print_to_terminal: Print diagnostic information to the terminal dureing reconstruction
Coordinates:
Both the raw data and the SIM data use the same coordinates as the FFT with the origin in the center.
i.e. the coordinates in the raw image are x = (arange(nx) - (nx // 2)) * dxy
and for the SIM image they are x = ((arange(2*nx) - (2*nx)//2) * 0.5 * dxy
Note that this means they cannot be overlaid by changing the scale for the SIM image by a factor of two.
There is an additional translation. The origin in the raw images is at pixel n//2 while those in the SIM
images are at (2*n) // 2 = n. This translation is due to the fact that for odd n,
n // 2 != (2*n) // 2 * 0.5 = n / 2
Examples:
For normal use cases, it is best to use the classmethod initialize() as the constructor for the class.
initialize() requires that all SIM reconstruction settings be known when the constructor is called.
>>> sim_obj = SimImageSet.initialize(*args, **kwargs)
>>> sim_obj.reconstruct() # estimate parameters and reconstruct data
However, there will be other cases where the desired SIM reconstruction settings are not known when
the class is initialized. In this case, more granular controller is possible
>>> sim_obj = SimImageSet()
>>> sim_obj.preprocess_data()
>>> sim_obj.update_otf()
>>> sim_obj.update_recon_settings()
>>> sim_obj.update_parameter_guesses()
>>> sim_obj.reconstruct()
Results can be printed to the terminal
>>> sim_obj.print_parameters() # print parameters to terminal
Results can be saved to file
>>> sim_obj.save_imgs() # save images to file
Diagnostics can be printed
>>> sim_obj.plot_figs() # plot diagnostic figures
"""
# #############################################
# logging and printing results
# #############################################
self._streams = []
self.log = StringIO() # can save this stream to a file later if desired
self.add_stream(self.log)
if print_to_terminal:
self.add_stream(stdout)
# #############################################
# GPU
# #############################################
self.use_gpu = use_gpu
if self.use_gpu and cp:
raise ValueError("'use_gpu' was true, but CuPy could not be imported")
# #############################################
# Preprocessing setting
# #############################################
self.axes_names = None
self.nangles = None
self.nphases = None
self.ny = None
self.nx = None
self.n_extra_dims = None
self._preprocessing_settings = {}
self._recon_settings = {}
self.na = None
self.wavelength = None
self.fmax = None
self.x = None
self.y = None
self.x_us = None
self.y_us = None
self.dx = None
self.dy = None
self.dx_us = None
self.dy_us = None
self.fx = None
self.fy = None
self.fx_us = None
self.fy_us = None
self.dfx = None
self.dfy = None
self.dfx_us = None
self.dfy_us = None
# #############################################
# guess parameters
# #############################################
self.frqs_guess = None
self.phases_guess = None
self.mod_depths_guess = None
self.band0_frq_fit = None # keep reference only for easy diagnostic plotting
self.band1_frq_fit = None
# #############################################
# parameters
# #############################################
self.otf = None
self.frqs = None
self.phases = None
self.phase_corrections = None
self.amps = None
self.mod_depths = None
# #############################################
# diagnostics
# #############################################
self.p2nr = None
self.peak_phases = None
self.mcnr = None
# #############################################
# images
# #############################################
self.imgs_raw = None
self.imgs = None
self.imgs_ft = None
self.bands_shifted_ft = None
self.weights = None
self.weights_norm = None
self.patterns = None
self.patterns_2x = None
self.widefield = None
self.widefield_deconvolution = None
self.sim_os = None
self.sim_sr = None
self.sim_sr_ft_components = None
self.xform_dict = None
def preprocess_data(self,
pix_size_um: float,
na: float,
wavelength: float,
imgs: array,
normalize_histograms: bool,
gain: float,
background: float,
axes_names: Optional[Sequence[str]] = None,
cam_roi: Optional[Sequence[int, int, int, int]] = None,
data_roi: Optional[Sequence[int, int, int, int]] = None,
):
"""
Preprocess SIM data
:param pix_size_um:
:param na:
:param wavelength:
:param imgs:
:param normalize_histograms:
:param gain:
:param background:
:param axes_names:
:param cam_roi:
:param data_roi:
:return:
"""
self._preprocessing_settings = {"normalize_histograms": normalize_histograms,
"gain": gain,
"offset": background}
# #############################################
# Configure CPU/GPU
# #############################################
if self.use_gpu:
# need to disable fft plane cache, otherwise quickly run out of memory
cp.fft._cache.PlanCache(memsize=0)
xp = cp
match_histograms = match_histograms_gpu
else:
xp = np
match_histograms = match_histograms_cpu
# #############################################
# images
# #############################################
# todo: for full generality would want to store as npatterns x ny x nx array instead
self.nangles, self.nphases, self.ny, self.nx = imgs.shape[-4:]
self.n_extra_dims = imgs.ndim - 4
if axes_names is None:
self.axes_names = ["" for _ in range(self.n_extra_dims)] + ["angles", "phases", "y", "x"]
else:
self.axes_names = axes_names
if len(self.axes_names) != imgs.ndim:
raise ValueError(f"len(axes_names)={len(self.axes_names):d} which did not match data ndim={imgs.ndim:d}")
# ensures imgs dask array with chunksize = 1 raw image
chunk_size = (1,) * (self.n_extra_dims + 2) + imgs.shape[-2:]
# most expensive operation, ~ 0.1s for 9x2048x2048 images
if not isinstance(imgs, da.core.Array):
imgs = da.from_array(imgs, chunks=chunk_size)
else:
imgs = imgs.rechunk(chunk_size)
# ensure on CPU/GPU as appropriate
self.imgs_raw = da.map_blocks(lambda x: xp.array(x.astype(float)),
imgs,
dtype=float,
meta=xp.array((), dtype=float)
)
# #############################################
# real space parameters
# #############################################
self.dx = float(pix_size_um)
self.dy = float(pix_size_um)
self.x = (xp.arange(self.nx) - (self.nx // 2)) * self.dx
self.y = (xp.arange(self.ny) - (self.ny // 2)) * self.dy
self.dx_us = self.dx / self.upsample_fact
self.dy_us = self.dy / self.upsample_fact
self.x_us = (xp.arange(self.nx * self.upsample_fact) - (self.nx * self.upsample_fact) // 2) * self.dx_us
self.y_us = (xp.arange(self.ny * self.upsample_fact) - (self.ny * self.upsample_fact) // 2) * self.dy_us
# #############################################
# physical parameters
# #############################################
self.na = na
self.wavelength = wavelength
self.fmax = 1 / (0.5 * self.wavelength / self.na)
# #############################################
# frequency data
# #############################################
self.fx = xp.fft.fftshift(xp.fft.fftfreq(self.nx, self.dx))
self.fy = xp.fft.fftshift(xp.fft.fftfreq(self.ny, self.dy))
self.fx_us = xp.fft.fftshift(xp.fft.fftfreq(self.upsample_fact * self.nx, self.dx / self.upsample_fact))
self.fy_us = xp.fft.fftshift(xp.fft.fftfreq(self.upsample_fact * self.ny, self.dy / self.upsample_fact))
self.dfx = float(self.fx[1] - self.fx[0])
self.dfy = float(self.fy[1] - self.fy[0])
self.dfx_us = float(self.fx_us[1] - self.fx_us[0])
self.dfy_us = float(self.fy_us[1] - self.fy_us[0])
# #############################################
# image preprocessing
# #############################################
# remove background and convert from ADU to photons
self.imgs = (self.imgs_raw - self._preprocessing_settings["offset"]) / self._preprocessing_settings["gain"]
self.imgs[self.imgs <= 0] = 1e-12
# normalize histograms for each angle
if self._preprocessing_settings["normalize_histograms"]:
# todo: should I rewrite this to handle full chunked images? Then avoid need to rechunk
tstart_norm_histogram = perf_counter()
matched_hists = da.map_blocks(match_histograms,
self.imgs[..., slice(1, None), :, :],
self.imgs[..., slice(0, 1), :, :],
chunks=(1,) * (self.n_extra_dims + 2) + self.imgs.shape[-2:],
dtype=self.imgs.dtype,
meta=xp.array(())
)
self.imgs = da.concatenate((self.imgs[..., slice(0, 1), :, :],
matched_hists),
axis=-3)
self.print_log(f"Normalizing histograms took {perf_counter() - tstart_norm_histogram:.2f}s")
# #############################################
# Rechunk so working on single SIM image at a time, which is necessary during reconstruction
# #############################################
new_chunks = list(self.imgs.chunksize)
new_chunks[-4:] = self.imgs.shape[-4:]
self.imgs = da.rechunk(self.imgs, new_chunks)
# #############################################
# Fourier transform raw SIM images
# #############################################
apodization = xp.outer(xp.asarray(tukey(self.ny, alpha=0.1)),
xp.asarray(tukey(self.nx, alpha=0.1)))
# todo: want to do a real ft instead
self.imgs_ft = da.map_blocks(ft2,
self.imgs * apodization,
dtype=complex,
meta=xp.array(())
)
# #############################################
# affine transformation connecting SIM and raw images
# #############################################
# todo: check these
# todo: use in plotting
xform_recon_pix2coords = params2xform([self.dy_us, 0, self.y_us[0],
self.dx_us, 0, self.x_us[0]])
xform_raw2sim = params2xform([self.upsample_fact, 0, (self.y_us[0] - self.y[0]) / self.dy_us,
self.upsample_fact, 0, (self.x_us[0] - self.x[0]) / self.dx_us])
xform_recon2raw = np.linalg.inv(xform_raw2sim)
xform_recon2cam_roi = None
xform_recon2cam = None
if data_roi is not None:
xform_data_roi2cam_roi = params2xform([1, 0, data_roi[0],
1, 0, data_roi[2]])
xform_recon2cam_roi = xform_data_roi2cam_roi.dot(xform_recon2raw)
xform_recon2cam = deepcopy(xform_recon2cam_roi)
if cam_roi is not None:
xform_cam_roi2cam = params2xform([1, 0, cam_roi[0],
1, 0, cam_roi[2]])
xform_recon2cam = xform_cam_roi2cam.dot(xform_recon2cam_roi)
# must be json serializable
self.xform_dict = {"affine_xform_recon_pix2coords": np.asarray(xform_recon_pix2coords).tolist(),
"affine_xform_recon_2_raw_data_roi": np.asarray(xform_recon2raw).tolist(),
"affine_xform_recon_2_raw_camera_roi": np.asarray(xform_recon2cam_roi).tolist(),
"affine_xform_recon_2_raw_camera": np.asarray(xform_recon2cam).tolist(),
"data_roi": np.array(data_roi).tolist(),
"camera_roi": np.array(cam_roi).tolist(),
"coordinate_order": "yx"
}
def update_recon_settings(self,
wiener_parameter: float = 0.1,
frq_estimation_mode: str = "band-correlation",
phase_estimation_mode: str = "wicker-iterative",
combine_bands_mode: str = "fairSIM",
fmax_exclude_band0: float = 0,
use_fixed_mod_depths: bool = False,
mod_depth_otf_mask_threshold: float = 0.1,
minimum_mod_depth: float = 0.5,
determine_amplitudes: bool = False,
max_phase_err: float = 10 * np.pi / 180,
min_p2nr: float = 1.,
trim_negative_values: bool = False,
):
"""
Set flags and settings for SIM reconstruction
:param wiener_parameter:
:param frq_estimation_mode:
:param phase_estimation_mode:
:param combine_bands_mode:
:param fmax_exclude_band0:
:param use_fixed_mod_depths:
:param mod_depth_otf_mask_threshold:
:param minimum_mod_depth:
:param determine_amplitudes:
:param max_phase_err:
:param min_p2nr:
:param trim_negative_values:
:return:
"""
# todo: argument checking
reconstruction_mode = "wiener-filter"
if reconstruction_mode not in self.allowed_reconstruction_modes:
raise ValueError(f"reconstruction_mode must be one of {self.allowed_reconstruction_modes},"
f" but was {reconstruction_mode:s}")
if phase_estimation_mode not in self.allowed_phase_estimation_modes:
raise ValueError(f"phase_estimation_mode must be one of {self.allowed_phase_estimation_modes},"
f" but was {phase_estimation_mode:s}")
# mod depth estimation mode
if use_fixed_mod_depths:
mod_depth_estimation_mode = "fixed"
else:
mod_depth_estimation_mode = "band-correlation"
if mod_depth_estimation_mode not in self.allowed_mod_depth_estimation_modes:
raise ValueError(f"mod_depth_estimation_mode must be one of {self.allowed_mod_depth_estimation_modes},"
f"but was {mod_depth_estimation_mode}")
if wiener_parameter <= 0 or wiener_parameter > 1:
raise ValueError(f"Wiener parameter must be between 0 and 1, but was {wiener_parameter:.3f}")
if frq_estimation_mode not in self.allowed_frq_estimation_modes:
raise ValueError(f"frq_estimation must be one of {self.allowed_frq_estimation_modes},"
f" but was {frq_estimation_mode:s}")
self._recon_settings = {"reconstruction_mode": reconstruction_mode,
"phase_estimation_mode": phase_estimation_mode,
"frq_estimation_mode": frq_estimation_mode,
"combine_bands_mode": combine_bands_mode,
"mod_depth_estimation_mode": mod_depth_estimation_mode,
"wiener_parameter": wiener_parameter,
"determine_amplitudes": determine_amplitudes,
"max_phase_error": max_phase_err,
"min_p2nr": min_p2nr,
"enforce_positivity": trim_negative_values,
"fmax_exclude_band0": fmax_exclude_band0,
"otf_mask_threshold": mod_depth_otf_mask_threshold,
"minimum_mod_depth": minimum_mod_depth
}
def update_otf(self,
otf: Optional[array] = None):
"""
Set OTF
:param otf:
"""
# #############################################
# OTF
# #############################################
if self.use_gpu:
xp = cp
else:
xp = np
if otf is None:
otf = circ_aperture_otf(xp.expand_dims(self.fx, axis=0),
xp.expand_dims(self.fy, axis=1),
self.na,
self.wavelength)
if np.any(otf < 0) or np.any(otf > 1):
raise ValueError("OTF values must fall in [0, 1]")
otf = xp.asarray(otf)
# otf is stored as nangles x ny x nx array to allow for possibly different OTF's along directions (e.g. OPM-SIM)
# todo: can I rely on broadcasting instead of tiling?
if otf.ndim == 2:
otf = xp.tile(otf, [self.nangles, 1, 1])
if otf.shape[-2:] != self.imgs_raw.shape[-2:]:
raise ValueError(f"OTF shape {otf.shape} and image shape {self.imgs_raw.shape} are not compatible")
self.otf = otf
def update_parameter_guesses(self,
frq_guess: Optional[np.ndarray] = None,
phases_guess: Optional[np.ndarray] = None,
mod_depths_guess: Optional[np.ndarray] = None,
):
"""
Set SIM parameter guess values
:param frq_guess:
:param phases_guess:
:param mod_depths_guess:
:return:
"""
if frq_guess is not None:
self.frqs_guess = np.array(frq_guess)
else:
self.frqs_guess = None
if phases_guess is not None:
self.phases_guess = np.array(phases_guess)
else:
self.phases_guess = None
self.bands_unmixed_ft_guess = da.map_blocks(unmix_bands,
self.imgs_ft,
self.phases_guess,
mod_depths=np.ones(self.nangles),
dtype=complex,
)
# todo: compute cross-correlations so can guess frequencies from them
if mod_depths_guess is not None:
self.mod_depths_guess = np.array(mod_depths_guess)
else:
self.mod_depths_guess = np.ones(self.nangles)
def delete(self):
"""
Delete data on GPU, otherwise will be retained and look like memory leak
:return:
"""
if self.use_gpu:
for attr_name in dir(self):
if attr_name in self.__dict__.keys():
del self.__dict__[attr_name]
def estimate_parameters(self,
slices: Optional[tuple] = None,
frq_max_shift: Optional[float] = None,
frq_search_bounds: Sequence[float] = (0., np.inf)):
"""
Estimate SIM parameters from chosen slice
:param slices:
:param frq_max_shift:
:param frq_search_bounds:
:return:
"""
if frq_max_shift is None:
frq_max_shift = 5 * self.dfx
tstart_param_est = perf_counter()
if self.phases_guess is None and self._recon_settings["frq_estimation_mode"] == "band-correlation":
raise ValueError(f"frq_estimation_mode=`band-correlation`, but this requires phase guesses,"
f"and no phase guesses were provided")
if self.use_gpu:
mempool = cp.get_default_memory_pool()
memory_start = mempool.used_bytes()
self.print_log("starting parameter estimation...")
if self.use_gpu:
xp = cp
else:
xp = np
if self._recon_settings["frq_estimation_mode"] != "fixed" or \
self._recon_settings["phase_estimation_mode"] != "fixed" or \
self._recon_settings["mod_depth_estimation_mode"] != "fixed":
# get slice of image stack to estimate SIM parameters from
if slices is None:
slices = tuple([slice(None) for _ in range(self.n_extra_dims)])
if self.imgs[slices].size == 0:
raise ValueError(f"After slicing, imgs array had size zero and shape {self.imgs[slices].shape}")
# always average over first dims after slicing...
imgs = da.mean(self.imgs[slices],
axis=tuple(range(self.n_extra_dims))).compute()
imgs_ft = da.mean(self.imgs_ft[slices],
axis=tuple(range(self.n_extra_dims))).compute()
if imgs_ft.shape[0] != self.nangles or imgs_ft.shape[1] != self.nphases or imgs_ft.ndim != 4:
raise ValueError("sliced image incorrect size for parameter estimation")
# #############################################
# estimate frequencies
# #############################################
if self._recon_settings["frq_estimation_mode"] == "fixed":
self.frqs = self.frqs_guess
else:
tstart = perf_counter()
if self._recon_settings["frq_estimation_mode"] == "fourier-transform":
# determine SIM frequency directly from Fourier transform
band0 = imgs_ft[:, 0]
band1 = imgs_ft[:, 0]
elif self._recon_settings["frq_estimation_mode"] == "band-correlation":
# determine SIM frequency from separated frequency bands using guess phases
bands_unmixed_ft_temp = unmix_bands(imgs_ft,
self.phases_guess,
mod_depths=np.ones(self.nangles))
band0 = bands_unmixed_ft_temp[:, 0]
band1 = bands_unmixed_ft_temp[:, 1]
else:
raise ValueError(f"frq_estimation_mode must be one of {self.allowed_frq_estimation_modes}"
f" but was '{self._recon_settings['frq_estimation_mode']:s}'")
# do frequency guess (note this is not done on GPU because scipy.optimize not supported by CuPy)
if self.frqs_guess is not None:
frq_guess = self.frqs_guess
else:
frq_guess = [None] * self.nangles
if self.use_gpu:
band0 = band0.get()
band1 = band1.get()
self.band0_frq_fit = band0
self.band1_frq_fit = band1
r = []
for ii in range(self.nangles):
r.append(delayed(fit_modulation_frq)(
self.band0_frq_fit[ii],
self.band1_frq_fit[ii],
self.dx,
frq_guess=frq_guess[ii],
max_frq_shift=frq_max_shift,
fbounds=frq_search_bounds,
otf=self.otf[ii])
)
results = compute(*r)
frqs, _, _ = zip(*results)
self.frqs = np.array(frqs).reshape((self.nangles, 2))
self.print_log(f"estimating {self.nangles:d} frequencies "
f"using mode {self._recon_settings['frq_estimation_mode']:s} "
f"took {perf_counter() - tstart:.2f}s")
# #############################################
# estimate peak heights
# #############################################
if self._recon_settings["frq_estimation_mode"] != "fixed":
tstart = perf_counter()
noise = np.sqrt(get_noise_power(imgs_ft,
(self.dy, self.dx),
self.fmax))
peak_phases = xp.zeros((self.nangles, self.nphases))
peak_heights = xp.zeros((self.nangles, self.nphases))
p2nr = xp.zeros((self.nangles, self.nphases))
for ii in range(self.nangles):
peak_val = get_peak_value(imgs_ft[ii],
self.fx,
self.fy,
self.frqs[ii],
peak_pixel_size=1)
peak_heights[ii] = xp.abs(peak_val)
peak_phases[ii] = xp.angle(peak_val)
p2nr[ii] = peak_heights[ii] / noise[ii]
# if p2nr is too low use guess values instead
if np.min(p2nr[ii]) < self._recon_settings["min_p2nr"] and self.frqs_guess is not None:
self.frqs[ii] = self.frqs_guess[ii]
self.print_log(f"SIM peak-to-noise ratio for angle={ii:d} is"
f" {np.min(p2nr[ii]):.2f} < {self._recon_settings['min_p2nr']:.2f}, "
f"the so frequency fit will be ignored "
f"and the guess value will be used instead.")
peak_val = get_peak_value(imgs_ft[ii],
self.fx,
self.fy,
self.frqs[ii],
peak_pixel_size=1)
peak_heights[ii] = np.abs(peak_val)
peak_phases[ii] = np.angle(peak_val)
p2nr[ii] = peak_heights[ii] / noise[ii]
if self.use_gpu:
self.p2nr = p2nr.get()
self.peak_phases = peak_phases.get()
else:
self.p2nr = p2nr
self.peak_phases = peak_phases
self.print_log(f"estimated peak-to-noise ratio in {perf_counter() - tstart:.2f}s")
# #############################################
# estimate phases
# todo: as with frqs since cannot easily go on GPU ...
# #############################################
tstart = perf_counter()
if self._recon_settings["phase_estimation_mode"] == "fixed":
phases = self.phases_guess
amps = np.ones((self.nangles, self.nphases))
elif self._recon_settings["phase_estimation_mode"] == "naive":
phases = self.peak_phases
elif self._recon_settings["phase_estimation_mode"] == "wicker-iterative":
phase_guess = self.phases_guess
if phase_guess is None:
phase_guess = [None] * self.nangles
imft = imgs_ft
otfs = self.otf
if self.use_gpu:
imft = imft.get()
otfs = otfs.get()
r = []
for ii in range(self.nangles):
r.append(delayed(get_phase_wicker_iterative)(
imft[ii],
otfs[ii],
self.frqs[ii],
self.dx,
self.fmax,
phases_guess=phase_guess[ii],
fit_amps=self._recon_settings["determine_amplitudes"]
))
results = compute(*r)
phases, amps, _ = zip(*results)
phases = np.array(phases)
amps = np.array(amps)
if self.use_gpu:
# find this is necessary, else mempool gets too big for 8GB GPU's
mempool.free_all_blocks()
elif self._recon_settings["phase_estimation_mode"] == "real-space":
phase_guess = self.phases_guess
if phase_guess is None:
phase_guess = np.zeros((self.nangles, self.nphases))
im = imgs
if self.use_gpu:
im = im.get()
r = []
for ii in range(self.nangles):
for jj in range(self.nphases):
r.append(delayed(get_phase_realspace)(
im[ii, jj],
self.frqs[ii],
self.dx,
phase_guess=phase_guess[ii, jj],
use_fft_origin=True
))
results = compute(*r)
phases = np.array(results).reshape((self.nangles, self.nphases))
amps = np.ones((self.nangles, self.nphases))
if self.use_gpu:
# find this is necessary, else mempool gets too big for 8GB GPU's
mempool.free_all_blocks()
else:
raise ValueError(f"phase_estimation_mode must be one of {self.allowed_phase_estimation_modes}"
f" but was '{self._recon_settings['phase_estimation_mode']:s}'")
self.phases = np.array(phases)
self.amps = np.array(amps)
self.print_log(f"estimated {self.nangles * self.nphases:d} phases"
f" using mode {self._recon_settings['phase_estimation_mode']:s} "
f"in {perf_counter() - tstart:.2f}s")
# #############################################
# check if phase fit was too bad, and default to guess values
# #############################################
if self.phases_guess is not None and self._recon_settings["phase_estimation_mode"] != "fixed":
phase_guess_diffs = np.mod(self.phases_guess - self.phases_guess[:, 0][:, None], 2 * np.pi)
phase_diffs = np.mod(self.phases - self.phases[:, 0][:, None], 2 * np.pi)
for ii in range(self.nangles):
diffs = np.mod(phase_guess_diffs[ii] - phase_diffs[ii], 2 * np.pi)
condition = np.abs(diffs - 2 * np.pi) < diffs
diffs[condition] = diffs[condition] - 2 * np.pi
if np.any(np.abs(diffs) > self._recon_settings["max_phase_error"]):
self.phases[ii] = self.phases_guess[ii]
strv = f"Angle {ii:d} phase guesses have more than the maximum allowed" \
f" phase error={self._recon_settings['max_phase_error'] * 180 / np.pi:.2f}deg." \
f" Defaulting to guess values"
strv += "\nfit phase diffs="
for jj in range(self.nphases):
strv += f"{phase_diffs[ii, jj] * 180 / np.pi:.2f}deg, "
self.print_log(strv)
# #############################################
# estimate global phase shifts/modulation depths
# #############################################
if self._recon_settings["phase_estimation_mode"] != "fixed" or \
self._recon_settings["mod_depth_estimation_mode"] != "fixed":
tstart_mod_depth = perf_counter()
# do band separation
bands_shifted_ft = shift_bands(unmix_bands(imgs_ft, self.phases, amps=self.amps),
self.frqs,
(self.dy, self.dx),
self.upsample_fact)