|
| 1 | +import os |
| 2 | +import random |
| 3 | +from tqdm import tqdm |
| 4 | +import numpy as np |
| 5 | +from scipy.signal import convolve |
| 6 | +import astropy.io.fits as fits |
| 7 | +import argparse |
| 8 | +import lib_fits |
| 9 | + |
| 10 | + |
| 11 | +def main(): |
| 12 | + # Parameters |
| 13 | + parser = argparse.ArgumentParser(description='This is PDRL method. Results for all iterations are saved.') |
| 14 | + parser.add_argument('thresh_img', type=str, help='input counts map file for PDRL') |
| 15 | + parser.add_argument('expmap', type=str, help='input exposure map file for PDRL') |
| 16 | + parser.add_argument('psfs', type=str, help='input psf file for each infile position (.npz)') |
| 17 | + parser.add_argument('outdir', type=str, help='output dir for each iteration of PDRL results') |
| 18 | + parser.add_argument('--num_iter', type=int, default=200, help='default:200. the number of iterations for PDRL') |
| 19 | + parser.add_argument('--lambda_tv', type=float, default=0.002, help='default:0.002. the TV regularization lambda') |
| 20 | + parser.add_argument('--data_type', type=str, default='float64', help='default:float64. numpy data type (Note:If `killed` is returned, `float32` is useful to lower the memory.)') |
| 21 | + parser.add_argument("--im_deconv_0_flat", action='store_true', help='default:False. initial value for the 0th iteration of the ldrl method (`False` mean the input file)') |
| 22 | + parser.add_argument("--poisson_err", action='store_true', help='default:False. add a Poisson distribution random number according to the input count file for each iteration') |
| 23 | + parser.add_argument("--boundary_px", type=int, default=1, help='default:1. Randomly select a PSF from `boundary_px` pixels near the boundary of the PSFs') |
| 24 | + args = parser.parse_args() |
| 25 | + |
| 26 | + # Loads the thresh.img and expmap. |
| 27 | + thresh_img, wcs = lib_fits.load_fits(infile=args.thresh_img, data_type=args.data_type) |
| 28 | + expmap, _ = lib_fits.load_fits(infile=args.expmap, data_type=args.data_type) |
| 29 | + |
| 30 | + # Loads all PSFs as numpy array. |
| 31 | + print('PSF loading in progress.') |
| 32 | + psfs, psfs_bins = load_all_psf(args.psfs, args.data_type) |
| 33 | + |
| 34 | + # PDRL method. |
| 35 | + np.random.seed(seed=2023) |
| 36 | + print('PDRL method is start.') |
| 37 | + os.makedirs(args.outdir, exist_ok=True) |
| 38 | + pdrl = Position_Dependent_Richardson_Lucy(args.outdir, thresh_img, expmap, psfs, psfs_bins, args.num_iter, args.lambda_tv, wcs, args.data_type, args.im_deconv_0_flat, args.poisson_err, args.boundary_px) |
| 39 | + deconvs = pdrl.position_dependent_richardson_lucy() |
| 40 | + |
| 41 | + |
| 42 | +def load_all_psf(psfs_infile, data_type): |
| 43 | + repro_psfs = np.load(psfs_infile) |
| 44 | + psfs = np.array(repro_psfs['repro_psfs'], dtype=data_type) |
| 45 | + psfs_bins = repro_psfs['psfs_bins'].tolist() |
| 46 | + return psfs, psfs_bins |
| 47 | + |
| 48 | + |
| 49 | +class Position_Dependent_Richardson_Lucy: |
| 50 | + def __init__(self, outdir, thresh_img, expmap, psfs, psfs_bins, num_iter=200, lambda_tv=0.002, wcs=None, data_type='float64', im_deconv_0_flat=False, poisson_err=False, boundary_px=1): |
| 51 | + self.outdir = outdir |
| 52 | + self.thresh_img = thresh_img |
| 53 | + self.expmap = expmap + 1e-15 # Used to avoid 0 divisions |
| 54 | + self.psfs = psfs |
| 55 | + self.psfs_bins = psfs_bins |
| 56 | + self.num_iter = num_iter |
| 57 | + self.lambda_tv = lambda_tv |
| 58 | + self.wcs = wcs |
| 59 | + self.data_type = data_type |
| 60 | + self.im_deconv_0_flat = im_deconv_0_flat |
| 61 | + self.poisson_err = poisson_err |
| 62 | + self.boundary_px = boundary_px |
| 63 | + |
| 64 | + |
| 65 | + def _convolve_each_kernel(self, image, kernels, kernels_xgrid, kernels_ygrid): |
| 66 | + y_shape, x_shape = image.shape |
| 67 | + *_, k_y_shape, k_x_shape = kernels.shape |
| 68 | + pad_y, pad_x = (k_y_shape // 2, k_x_shape // 2) |
| 69 | + pad_conv = np.zeros([y_shape + pad_y*2, x_shape + pad_x*2], dtype=self.data_type) # For convolution edge works |
| 70 | + y_range = range(self.boundary_px, y_shape-self.boundary_px) |
| 71 | + x_range = range(self.boundary_px, x_shape-self.boundary_px) |
| 72 | + for y in tqdm(y_range): |
| 73 | + for x in x_range: |
| 74 | + pad_conv[y:y+k_y_shape, x:x+k_x_shape] += image[y, x] * kernels[(y+kernels_ygrid[y, x])//self.psfs_bins, (x+kernels_xgrid[y, x])//self.psfs_bins] |
| 75 | + conv = pad_conv[pad_y:-pad_y, pad_x:-pad_x] # Make array size equal to input size |
| 76 | + return conv |
| 77 | + |
| 78 | + |
| 79 | + def _convolve_each_kernel_dependent(self, image, kernels, kernels_xgrid, kernels_ygrid): |
| 80 | + y_shape, x_shape = image.shape |
| 81 | + *_, k_y_shape, k_x_shape = kernels.shape |
| 82 | + k_y_half, k_x_half = (k_y_shape // 2, k_x_shape // 2) |
| 83 | + conv = np.zeros_like(image, dtype=self.data_type) |
| 84 | + y_range = range(k_y_half+1+self.boundary_px, y_shape-k_y_half-1-self.boundary_px) |
| 85 | + x_range = range(k_x_half+1+self.boundary_px, x_shape-k_x_half-1-self.boundary_px) |
| 86 | + for y in tqdm(y_range): |
| 87 | + for x in x_range: |
| 88 | + conv[y, x] = np.sum(image[y-k_y_half:y+k_y_half+1, x-k_x_half:x+k_x_half+1] * kernels[(y+kernels_ygrid[y, x])//self.psfs_bins, (x+kernels_xgrid[y, x])//self.psfs_bins]) |
| 89 | + return conv |
| 90 | + |
| 91 | + def _generate_poisson_img(self, thresh_img): |
| 92 | + poisson_func = lambda x: np.random.poisson(x) |
| 93 | + poisson_thresh_img = poisson_func(thresh_img) |
| 94 | + return poisson_thresh_img |
| 95 | + |
| 96 | + def position_dependent_richardson_lucy(self): |
| 97 | + if self.im_deconv_0_flat: |
| 98 | + im_deconv = np.full(self.thresh_img.shape, 0.5, dtype=self.data_type) |
| 99 | + else: |
| 100 | + im_deconv = np.copy(self.thresh_img) / self.expmap |
| 101 | + |
| 102 | + eps = 1e-15 # Small regularization parameter used to avoid 0 divisions |
| 103 | + |
| 104 | + for _iter in range(1, self.num_iter+1): |
| 105 | + print(f'iter {_iter} start.') |
| 106 | + print('Bottom calculation in progress.') |
| 107 | + psfs_xgrid = np.random.randint(-self.boundary_px, self.boundary_px+1, size=im_deconv.shape) |
| 108 | + psfs_ygrid = np.random.randint(-self.boundary_px, self.boundary_px+1, size=im_deconv.shape) |
| 109 | + conv = self._convolve_each_kernel(im_deconv, self.psfs, psfs_xgrid, psfs_ygrid) + eps |
| 110 | + |
| 111 | + if self.poisson_err: |
| 112 | + relative_blur = self._generate_poisson_img(self.thresh_img) / self.expmap / conv |
| 113 | + else: |
| 114 | + relative_blur = self.thresh_img / self.expmap / conv |
| 115 | + |
| 116 | + # TVregularization |
| 117 | + grad_x = np.gradient(im_deconv, axis=1) |
| 118 | + grad_y = np.gradient(im_deconv, axis=0) |
| 119 | + grad_norm = np.sqrt(grad_x**2+grad_y**2) + eps |
| 120 | + tv_reg = np.gradient(grad_x / grad_norm, axis=1) + np.gradient(grad_y / grad_norm, axis=0) |
| 121 | + |
| 122 | + print('Top calculation in progress.') |
| 123 | + im_deconv = im_deconv/(1-self.lambda_tv*tv_reg)*self._convolve_each_kernel_dependent(relative_blur, self.psfs, psfs_xgrid, psfs_ygrid) |
| 124 | + |
| 125 | + # Save the results of deconvolution for each iteration |
| 126 | + outfile = os.path.join(self.outdir, f'iter_{_iter:0>4}.fits') |
| 127 | + lib_fits.np2fits(np_array=im_deconv, outfile=outfile, wcs=self.wcs) |
| 128 | + |
| 129 | + return |
| 130 | + |
| 131 | + |
| 132 | +if __name__ == '__main__': |
| 133 | + main() |
0 commit comments