def test_radial_profile(): from lenstronomy.LightModel.Profiles.gaussian import Gaussian gauss = Gaussian() x, y = util.make_grid(11, 1) flux = gauss.function(x, y, sigma=10, amp=1) data = util.array2image(flux) profile_r = image_util.radial_profile(data, center=[5, 5]) profile_r_true = gauss.function(np.linspace(0, stop=7, num=8), 0, sigma=10, amp=1) npt.assert_almost_equal(profile_r, profile_r_true, decimal=3)
def test_function(self): """ :return: """ x, y = util.make_grid(numPix=20, deltapix=1.) gauss = Gaussian() flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.) image = util.array2image(flux) interp = Interpol() kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 0., 'center_y': 0. } output = interp.function(x, y, **kwargs_interp) npt.assert_almost_equal(output, flux, decimal=0) flux = gauss.function(x - 1., y, amp=1., center_x=0., center_y=0., sigma=1.) kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 1., 'center_y': 0. } output = interp.function(x, y, **kwargs_interp) npt.assert_almost_equal(output, flux, decimal=0) flux = gauss.function(x - 1., y - 1., amp=1, center_x=0., center_y=0., sigma=1.) kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 1., 'center_y': 1. } output = interp.function(x, y, **kwargs_interp) npt.assert_almost_equal(output, flux, decimal=0) out = interp.function(x=1000, y=0, **kwargs_interp) assert out == 0
def test_subgrid_rebin(): kernel_size = 11 subgrid_res = 3 sigma = 1 from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() x_grid, y_gird = Util.make_grid(kernel_size, 1. / subgrid_res, subgrid_res) flux = gaussian.function(x_grid, y_gird, amp=1, sigma_x=sigma, sigma_y=sigma) kernel = Util.array2image(flux) print(np.shape(kernel)) kernel = util.averaging(kernel, numGrid=kernel_size * subgrid_res, numPix=kernel_size) kernel = kernel_util.kernel_norm(kernel) subgrid_kernel = kernel_util.subgrid_kernel(kernel, subgrid_res=subgrid_res, odd=True) kernel_pixel = util.averaging(subgrid_kernel, numGrid=kernel_size * subgrid_res, numPix=kernel_size) kernel_pixel = kernel_util.kernel_norm(kernel_pixel) assert np.sum((kernel_pixel - kernel)**2) < 0.1
def test_update_psf(self): fwhm = 0.3 sigma = util.fwhm2sigma(fwhm) x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma_x=sigma, sigma_y=sigma, center_x=0, center_y=0) kernel_point_source /= np.sum(kernel_point_source) kernel_point_source = util.array2image(kernel_point_source) kwargs_psf = { 'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source } kwargs_psf_return, improved_bool = self.psf_fitting.update_psf( kwargs_psf, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, factor=0.1, symmetry=1) assert improved_bool kernel_new = kwargs_psf_return['kernel_point_source'] kernel_true = self.kwargs_psf['kernel_point_source'] kernel_old = kwargs_psf['kernel_point_source'] diff_old = np.sum((kernel_old - kernel_true)**2) diff_new = np.sum((kernel_new - kernel_true)**2) assert diff_old > diff_new
def test_gaussian_ellipse(self): gaussianEllipse = GaussianEllipse() gaussian = Gaussian() sigma = 1 flux = gaussianEllipse.function(1, 1, amp=1, sigma=sigma, e1=0, e2=0) flux_spherical = gaussian.function(1, 1, amp=1, sigma=sigma) npt.assert_almost_equal(flux, flux_spherical, decimal=8)
def test_update_psf(self): fwhm = 0.5 sigma = util.fwhm2sigma(fwhm) x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma=sigma, center_x=0, center_y=0) kernel_point_source /= np.sum(kernel_point_source) kernel_point_source = util.array2image(kernel_point_source) kwargs_psf = { 'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source } kwargs_psf_iter = {'stacking_method': 'median'} #mag = np.ones_like(x_pos) kwargs_psf_return, improved_bool, error_map = self.psf_fitting.update_psf( kwargs_psf, self.kwargs_params, **kwargs_psf_iter) assert improved_bool kernel_new = kwargs_psf_return['kernel_point_source'] kernel_true = self.kwargs_psf['kernel_point_source'] kernel_old = kwargs_psf['kernel_point_source'] diff_old = np.sum((kernel_old - kernel_true)**2) diff_new = np.sum((kernel_new - kernel_true)**2) assert diff_old > diff_new
def test_update_iterative(self): fwhm = 0.5 sigma = util.fwhm2sigma(fwhm) x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma_x=sigma, sigma_y=sigma, center_x=0, center_y=0) kernel_point_source /= np.sum(kernel_point_source) kernel_point_source = util.array2image(kernel_point_source) kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source} kwargs_psf_iter = {'stacking_method': 'median'} kwargs_psf_new = self.psf_fitting.update_iterative(kwargs_psf, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, **kwargs_psf_iter) kernel_new = kwargs_psf_new['kernel_point_source'] kernel_true = self.kwargs_psf['kernel_point_source'] kernel_old = kwargs_psf['kernel_point_source'] diff_old = np.sum((kernel_old - kernel_true) ** 2) diff_new = np.sum((kernel_new - kernel_true) ** 2) assert diff_old > diff_new assert diff_new < 0.01 kwargs_psf_new = self.psf_fitting.update_iterative(kwargs_psf, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, num_iter=3, no_break=True) kernel_new = kwargs_psf_new['kernel_point_source'] kernel_true = self.kwargs_psf['kernel_point_source'] kernel_old = kwargs_psf['kernel_point_source'] diff_old = np.sum((kernel_old - kernel_true) ** 2) diff_new = np.sum((kernel_new - kernel_true) ** 2) assert diff_old > diff_new assert diff_new < 0.01
def test_delete_interpol_caches(self): x, y = util.make_grid(numPix=20, deltapix=1.) gauss = Gaussian() flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.) image = util.array2image(flux) light_model_list = ['INTERPOL', 'INTERPOL'] kwargs_list = [{ 'image': image, 'scale': 1, 'phi_G': 0, 'center_x': 0, 'center_y': 0 }, { 'image': image, 'scale': 1, 'phi_G': 0, 'center_x': 0, 'center_y': 0 }] lightModel = LightModel(light_model_list=light_model_list) output = lightModel.surface_brightness(x, y, kwargs_list) for func in lightModel.func_list: assert hasattr(func, '_image_interp') lightModel.delete_interpol_caches() for func in lightModel.func_list: assert not hasattr(func, '_image_interp')
class TestGaussianKappa(object): """ test the Gaussian with Gaussian kappa """ def setup(self): self.gaussian_kappa = MultiGaussian_kappa() self.gaussian = Gaussian() self.g_kappa = GaussianKappa() def test_derivatives(self): x = np.linspace(0, 5, 10) y = np.linspace(0, 5, 10) amp = [1. * 2 * np.pi] center_x = 0. center_y = 0. sigma = [1.] f_x, f_y = self.gaussian_kappa.derivatives(x, y, amp, sigma, center_x, center_y) npt.assert_almost_equal(f_x[2], 0.63813558702212059, decimal=8) npt.assert_almost_equal(f_y[2], 0.63813558702212059, decimal=8) def test_hessian(self): x = np.linspace(0, 5, 10) y = np.linspace(0, 5, 10) amp = [1. * 2 * np.pi] center_x = 0. center_y = 0. sigma = [1.] f_xx, f_yy, f_xy = self.gaussian_kappa.hessian(x, y, amp, sigma, center_x, center_y) kappa = 1. / 2 * (f_xx + f_yy) kappa_true = self.gaussian.function(x, y, amp[0], sigma[0], sigma[0], center_x, center_y) print(kappa_true) print(kappa) npt.assert_almost_equal(kappa[0], kappa_true[0], decimal=5) npt.assert_almost_equal(kappa[1], kappa_true[1], decimal=5) def test_density_2d(self): x = np.linspace(0, 5, 10) y = np.linspace(0, 5, 10) amp = [1. * 2 * np.pi] center_x = 0. center_y = 0. sigma = [1.] f_xx, f_yy, f_xy = self.gaussian_kappa.hessian(x, y, amp, sigma, center_x, center_y) kappa = 1. / 2 * (f_xx + f_yy) amp_3d = self.g_kappa._amp2d_to_3d(amp, sigma[0], sigma[0]) density_2d = self.gaussian_kappa.density_2d(x, y, amp_3d, sigma, center_x, center_y) npt.assert_almost_equal(kappa[1], density_2d[1], decimal=5) npt.assert_almost_equal(kappa[2], density_2d[2], decimal=5) def test_density(self): amp = [1. * 2 * np.pi] sigma = [1.] density = self.gaussian_kappa.density(1., amp, sigma) npt.assert_almost_equal(density, 0.6065306597126334, decimal=8)
def test_update_iterative(self): fwhm = 0.5 sigma = util.fwhm2sigma(fwhm) x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma=sigma, center_x=0, center_y=0) kernel_point_source /= np.sum(kernel_point_source) kernel_point_source = util.array2image(kernel_point_source) kwargs_psf = { 'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source, 'kernel_point_source_init': kernel_point_source } kwargs_psf_iter = { 'stacking_method': 'median', 'psf_symmetry': 2, 'psf_iter_factor': 0.2, 'block_center_neighbour': 0.1, 'error_map_radius': 0.5, 'new_procedure': False, 'no_break': False, 'verbose': True, 'keep_psf_error_map': False } kwargs_params = copy.deepcopy(self.kwargs_params) kwargs_ps = kwargs_params['kwargs_ps'] del kwargs_ps[0]['source_amp'] print(kwargs_params['kwargs_ps']) kwargs_psf_new = self.psf_fitting.update_iterative( kwargs_psf, kwargs_params, **kwargs_psf_iter) kernel_new = kwargs_psf_new['kernel_point_source'] kernel_true = self.kwargs_psf['kernel_point_source'] kernel_old = kwargs_psf['kernel_point_source'] diff_old = np.sum((kernel_old - kernel_true)**2) diff_new = np.sum((kernel_new - kernel_true)**2) assert diff_old > diff_new assert diff_new < 0.01 assert 'psf_error_map' in kwargs_psf_new kwargs_psf_new = self.psf_fitting.update_iterative( kwargs_psf, kwargs_params, num_iter=3, no_break=True, keep_psf_error_map=True) kernel_new = kwargs_psf_new['kernel_point_source'] kernel_true = self.kwargs_psf['kernel_point_source'] kernel_old = kwargs_psf['kernel_point_source'] diff_old = np.sum((kernel_old - kernel_true)**2) diff_new = np.sum((kernel_new - kernel_true)**2) assert diff_old > diff_new assert diff_new < 0.01
def test_total_flux(self): gauss = Gaussian() deltapix = 0.1 amp = 1 x_grid, y_gird = util.make_grid(100, deltapix=deltapix) flux = gauss.function(x_grid, y_gird, amp=amp, sigma=1) flux_integral = np.sum(flux) * deltapix**2 npt.assert_almost_equal(flux_integral, amp, decimal=3)
def setup(self): # different versions of Starlet transforms self.starlets = SLIT_Starlets(fast_inverse=False, second_gen=False, force_no_pysap=_force_no_pysap) self.starlets_fast = SLIT_Starlets(fast_inverse=True, second_gen=False, force_no_pysap=_force_no_pysap) self.starlets_2nd = SLIT_Starlets(second_gen=True, force_no_pysap=_force_no_pysap) # define a test image with gaussian components self.num_pix = 50 self.n_scales = 3 self.n_pixels = self.num_pix**2 self.x, self.y = util.make_grid(self.num_pix, 1) # build a non-trivial positive image from sum of gaussians gaussian = Gaussian() gaussian1 = gaussian.function(self.x, self.y, amp=100, sigma=1, center_x=-7, center_y=-7) gaussian2 = gaussian.function(self.x, self.y, amp=500, sigma=3, center_x=-3, center_y=-3) gaussian3 = gaussian.function(self.x, self.y, amp=2000, sigma=5, center_x=+5, center_y=+5) self.test_image = util.array2image(gaussian1 + gaussian2 + gaussian3) self.test_coeffs = np.zeros( (self.n_scales, self.num_pix, self.num_pix)) self.test_coeffs[0, :, :] = util.array2image(gaussian1) self.test_coeffs[1, :, :] = util.array2image(gaussian2) self.test_coeffs[2, :, :] = util.array2image(gaussian3)
def kernel_gaussian(kernel_numPix, deltaPix, fwhm): sigma = util.fwhm2sigma(fwhm) #if kernel_numPix % 2 == 0: # kernel_numPix += 1 x_grid, y_grid = util.make_grid(kernel_numPix, deltaPix) gaussian = Gaussian() kernel = gaussian.function(x_grid, y_grid, amp=1., sigma=sigma, center_x=0, center_y=0) kernel /= np.sum(kernel) kernel = util.array2image(kernel) return kernel
def test_radial_profile(self): x_grid, y_grid = util.make_grid(numPix=20, deltapix=1) profile = Gaussian() light_grid = profile.function(x_grid, y_grid, amp=1., sigma=5) I_r, r = analysis_util.radial_profile(light_grid, x_grid, y_grid, center_x=0, center_y=0, n=None) assert I_r[0] == 0
def test_kernel_average_pixel(): gaussian = Gaussian() subgrid_res = 3 x_grid, y_gird = Util.make_grid(9, 1., subgrid_res) sigma = 2 flux = gaussian.function(x_grid, y_gird, amp=1, sigma=sigma) kernel_super = Util.array2image(flux) kernel_pixel = kernel_util.kernel_average_pixel(kernel_super, supersampling_factor=subgrid_res) npt.assert_almost_equal(np.sum(kernel_pixel), np.sum(kernel_super)) kernel_pixel = kernel_util.kernel_average_pixel(kernel_super, supersampling_factor=2) npt.assert_almost_equal(np.sum(kernel_pixel), np.sum(kernel_super))
def magnification_finite(self, x_pos, y_pos, kwargs_lens, source_sigma=0.003, window_size=0.1, grid_number=100, polar_grid=False, aspect_ratio=0.5): """ returns the magnification of an extended source with Gaussian light profile :param x_pos: x-axis positons of point sources :param y_pos: y-axis position of point sources :param kwargs_lens: lens model kwargs :param source_sigma: Gaussian sigma in arc sec in source :param window_size: size of window to compute the finite flux :param grid_number: number of grid cells per axis in the window to numerically compute the flux :return: numerically computed brightness of the sources """ mag_finite = np.zeros_like(x_pos) deltaPix = float(window_size) / grid_number from lenstronomy.LightModel.Profiles.gaussian import Gaussian quasar = Gaussian() x_grid, y_grid = util.make_grid(numPix=grid_number, deltapix=deltaPix, subgrid_res=1) if polar_grid is True: a = window_size * 0.5 b = window_size * 0.5 * aspect_ratio ellipse_inds = (x_grid * a**-1)**2 + (y_grid * b**-1)**2 <= 1 x_grid, y_grid = x_grid[ellipse_inds], y_grid[ellipse_inds] for i in range(len(x_pos)): ra, dec = x_pos[i], y_pos[i] center_x, center_y = self._lensModel.ray_shooting( ra, dec, kwargs_lens) if polar_grid is True: theta = np.arctan2(dec, ra) xcoord, ycoord = util.rotate(x_grid, y_grid, theta) else: xcoord, ycoord = x_grid, y_grid betax, betay = self._lensModel.ray_shooting( xcoord + ra, ycoord + dec, kwargs_lens) I_image = quasar.function(betax, betay, 1., source_sigma, center_x, center_y) mag_finite[i] = np.sum(I_image) * deltaPix**2 return mag_finite
def test_fwhm_kernel(): x_grid, y_gird = Util.make_grid(101, 1) sigma = 20 from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() flux = gaussian.function(x_grid, y_gird, amp=1, sigma_x=sigma, sigma_y=sigma) kernel = Util.array2image(flux) kernel = kernel_util.kernel_norm(kernel) fwhm_kernel = kernel_util.fwhm_kernel(kernel) fwhm = Util.sigma2fwhm(sigma) npt.assert_almost_equal(fwhm / fwhm_kernel, 1, 2)
def test_delete_cache(self): x, y = util.make_grid(numPix=20, deltapix=1.) gauss = Gaussian() flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.) image = util.array2image(flux) interp = Interpol() kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 0., 'center_y': 0. } output = interp.function(x, y, **kwargs_interp) assert hasattr(interp, '_image_interp') interp.delete_cache() assert not hasattr(interp, '_image_interp')
def test_center_kernel(): x_grid, y_gird = Util.make_grid(31, 1) sigma = 2 from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() flux = gaussian.function(x_grid, y_gird, amp=1, sigma_x=sigma, sigma_y=sigma) kernel = Util.array2image(flux) kernel = kernel_util.kernel_norm(kernel) # kernel being centered kernel_new = kernel_util.center_kernel(kernel, iterations=20) kernel_new = kernel_util.kernel_norm(kernel_new) npt.assert_almost_equal(kernel_new / kernel, 1, decimal=8) # kernel shifted in x kernel_shifted = interp.shift(kernel, [-.1, 0], order=1) kernel_new = kernel_util.center_kernel(kernel_shifted, iterations=5) kernel_new = kernel_util.kernel_norm(kernel_new) npt.assert_almost_equal((kernel_new + 0.00001) / (kernel + 0.00001), 1, decimal=4) # kernel shifted in y kernel_shifted = interp.shift(kernel, [0, -0.4], order=1) kernel_new = kernel_util.center_kernel(kernel_shifted, iterations=5) kernel_new = kernel_util.kernel_norm(kernel_new) npt.assert_almost_equal((kernel_new + 0.01) / (kernel + 0.01), 1, decimal=3) # kernel shifted in x and y kernel_shifted = interp.shift(kernel, [0.2, -0.3], order=1) kernel_new = kernel_util.center_kernel(kernel_shifted, iterations=5) kernel_new = kernel_util.kernel_norm(kernel_new) npt.assert_almost_equal((kernel_new + 0.01) / (kernel + 0.01), 1, decimal=3)
def setup(self): self.num_pix = 49 # cutout pixel size self.subgrid_res_source = 2 self.num_pix_source = self.num_pix * self.subgrid_res_source self.background_rms = 0.05 self.noise_map = self.background_rms * np.ones( (self.num_pix, self.num_pix)) delta_pix = 0.24 _, _, ra_at_xy_0, dec_at_xy_0, _, _, Mpix2coord, _ \ = l_util.make_grid_with_coordtransform(numPix=self.num_pix, deltapix=delta_pix, subgrid_res=1, inverse=False, left_lower=False) self.image_data = np.random.rand(self.num_pix, self.num_pix) kwargs_data = { 'ra_at_xy_0': ra_at_xy_0, 'dec_at_xy_0': dec_at_xy_0, 'transform_pix2angle': Mpix2coord, 'image_data': self.image_data, 'background_rms': self.background_rms, 'noise_map': self.noise_map, } data = ImageData(**kwargs_data) gaussian_func = Gaussian() x, y = l_util.make_grid(41, 1) gaussian = gaussian_func.function(x, y, amp=1, sigma=0.02, center_x=0, center_y=0) self.psf_kernel = gaussian / gaussian.sum() lens_model = LensModel(['SPEP']) self.kwargs_lens = [{ 'theta_E': 1, 'gamma': 2, 'center_x': 0, 'center_y': 0, 'e1': -0.05, 'e2': 0.05 }] # wavelets scales for lens and source self.n_scales_source = 4 self.n_scales_lens = 3 # list of source light profiles self.source_model = LightModel(['SLIT_STARLETS']) self.kwargs_source = [{'n_scales': self.n_scales_source}] # list of lens light profiles self.lens_light_model = LightModel(['SLIT_STARLETS']) self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}] # get grid classes image_grid_class = NumericsSubFrame(data, PSF('NONE')).grid_class source_grid_class = NumericsSubFrame( data, PSF('NONE'), supersampling_factor=self.subgrid_res_source).grid_class # get a lensing operator self.lensing_op = LensingOperator(lens_model, image_grid_class, source_grid_class, self.num_pix) self.noise_class = NoiseLevels( data, subgrid_res_source=self.subgrid_res_source, include_regridding_error=False) self.noise_class_regrid = NoiseLevels( data, subgrid_res_source=self.subgrid_res_source, include_regridding_error=True)
def setup(self): # data specifics sigma_bkg = 0.01 # background noise per pixel exp_time = 100 # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit) numPix = 100 # cutout pixel size deltaPix = 0.05 # pixel size in arcsec (area per pixel = deltaPix**2) fwhm = 0.3 # full width half max of PSF # PSF specification kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) data_class = Data(kwargs_data) sigma = util.fwhm2sigma(fwhm) x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma_x=sigma, sigma_y=sigma, center_x=0, center_y=0) kernel_point_source /= np.sum(kernel_point_source) kernel_point_source = util.array2image(kernel_point_source) self.kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source} psf_class = PSF(kwargs_psf=self.kwargs_psf) # 'EXERNAL_SHEAR': external shear kwargs_shear = {'e1': 0.01, 'e2': 0.01} # gamma_ext: shear strength, psi_ext: shear angel (in radian) phi, q = 0.2, 0.8 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_spemd = {'theta_E': 1., 'gamma': 1.8, 'center_x': 0, 'center_y': 0, 'e1': e1, 'e2': e2} lens_model_list = ['SPEP', 'SHEAR'] self.kwargs_lens = [kwargs_spemd, kwargs_shear] lens_model_class = LensModel(lens_model_list=lens_model_list) # list of light profiles (for lens and source) # 'SERSIC': spherical Sersic profile kwargs_sersic = {'amp': 1., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0} # 'SERSIC_ELLIPSE': elliptical Sersic profile phi, q = 0.2, 0.9 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_sersic_ellipse = {'amp': 1., 'R_sersic': .6, 'n_sersic': 7, 'center_x': 0, 'center_y': 0, 'e1': e1, 'e2': e2} lens_light_model_list = ['SERSIC'] self.kwargs_lens_light = [kwargs_sersic] lens_light_model_class = LightModel(light_model_list=lens_light_model_list) source_model_list = ['SERSIC_ELLIPSE'] self.kwargs_source = [kwargs_sersic_ellipse] source_model_class = LightModel(light_model_list=source_model_list) self.kwargs_ps = [{'ra_source': 0.0, 'dec_source': 0.0, 'source_amp': 10.}] # quasar point source position in the source plane and intrinsic brightness point_source_class = PointSource(point_source_type_list=['SOURCE_POSITION'], fixed_magnification_list=[True]) kwargs_numerics = {'subgrid_res': 3, 'psf_subgrid': True} imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps) data_class.update_data(image_sim) self.imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) self.psf_fitting = PsfFitting(self.imageModel)
class Chain(object): """ contains the routines to be fitted by a mcmc, meant for PSF estimations/re-center """ def __init__(self, image, sigma, poisson, sampling_option, deltaPix=1, mask=None, subgrid_res=1, x_grid=None, y_grid=None): """ initializes all the classes needed for the chain """ self.image = util.image2array(image) self.numPix = len(image) self.deltaPix = deltaPix self.subgrid_res = subgrid_res self.background = sigma self.poisson = poisson if x_grid is None or y_grid is None: self.x_grid, self.y_grid = util.make_grid(self.numPix, deltaPix, subgrid_res) else: self.x_grid, self.y_grid = util.make_subgrid( x_grid, y_grid, subgrid_res) self.gaussian = Gaussian() self.moffat = Moffat() self.sampling_option = sampling_option if not mask is None: self.mask = util.image2array(mask) else: self.mask = np.ones((self.numPix, self.numPix)) def X2_chain_gaussian(self, args): """ routine to compute X2 given variable parameters for a MCMC/PSO chain """ amp = args[0] sigma = np.exp(args[1]) center_x = args[2] center_y = args[3] model = self.gaussian.function(self.x_grid, self.y_grid, amp, sigma, sigma, center_x, center_y) X2 = self.compare(model, self.image, self.background, self.poisson) return -X2, None def X2_chain_moffat(self, args): """ routine to compute X2 given variable parameters for a MCMC/PSO chain """ amp = args[0] alpha = args[1] beta = args[2] center_x = args[3] center_y = args[4] model = self.moffat.function(self.x_grid, self.y_grid, amp, alpha, beta, center_x, center_y) X2 = self.compare(model, self.image, self.background, self.poisson) return -X2, None def compare(self, model, data, sigma, poisson): """ :param model: model 2d image :param data: data 2d image :param sigma: minimal noise level of background (float>0 or as image) :return: X^2 value if images have same size """ deltaIm = (data - model)**2 relDeltaIm = deltaIm / (sigma**2 + np.abs(model) / poisson) X2_estimate = np.sum(relDeltaIm) return X2_estimate def __call__(self, a): if self.sampling_option == 'psf_gaussian': return self.X2_chain_gaussian(a) if self.sampling_option == 'psf_moffat': return self.X2_chain_moffat(a) def computeLikelihood(self, ctx): if self.sampling_option == 'psf_gaussian': likelihood, _ = self.X2_chain_gaussian(ctx.getParams()) elif self.sampling_option == 'psf_moffat': likelihood, _ = self.X2_chain_moffat(ctx.getParams()) else: raise ValueError('sampling option %s not valid!') return likelihood def setup(self): pass
def test_supersampling_simple(): """ :return: """ from lenstronomy.Data.psf import PSF from lenstronomy.SimulationAPI.data_api import DataAPI detector_pixel_scale = 0.04 numpix = 64 supersampling_factor = 2 # generate a Gaussian image x, y = util.make_grid(numPix=numpix * supersampling_factor, deltapix=detector_pixel_scale / supersampling_factor) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() image_1d = gaussian.function(x, y, amp=1, sigma=0.1) image = util.array2image(image_1d) # generate psf kernal supersampled kernel_super = kernel_util.kernel_gaussian( kernel_numPix=21 * supersampling_factor + 1, deltaPix=detector_pixel_scale / supersampling_factor, fwhm=0.2) psf_parameters = { 'psf_type': 'PIXEL', 'kernel_point_source': kernel_super, 'point_source_supersampling_factor': supersampling_factor } kwargs_detector = { 'pixel_scale': detector_pixel_scale, 'ccd_gain': 2.5, 'read_noise': 4.0, 'magnitude_zero_point': 25.0, 'exposure_time': 5400.0, 'sky_brightness': 22, 'num_exposures': 1, 'background_noise': None } kwargs_numerics = { 'supersampling_factor': 2, 'supersampling_convolution': True, 'point_source_supersampling_factor': 2, 'supersampling_kernel_size': 21 } psf_model = PSF(**psf_parameters) data_class = DataAPI(numpix=numpix, **kwargs_detector).data_class from lenstronomy.ImSim.Numerics.numerics_subframe import NumericsSubFrame image_numerics = NumericsSubFrame(pixel_grid=data_class, psf=psf_model, **kwargs_numerics) conv_class = image_numerics.convolution_class conv_flat = conv_class.convolution2d(image) print(np.shape(conv_flat), 'shape of output') # psf_helper = lenstronomy_utils.PSFHelper(data_class, psf_model, kwargs_numerics) # Convolve with lenstronomy and with scipy # helper_image = psf_helper.psf_model(image) from scipy import signal scipy_image = signal.fftconvolve(image, kernel_super, mode='same') from lenstronomy.Util import image_util image_scipy_resized = image_util.re_size(scipy_image, supersampling_factor) image_unconvolved = image_util.re_size(image, supersampling_factor) # Compare the outputs # low res convolution as comparison kwargs_numerics_low_res = { 'supersampling_factor': 2, 'supersampling_convolution': False, 'point_source_supersampling_factor': 2, } image_numerics_low_res = NumericsSubFrame(pixel_grid=data_class, psf=psf_model, **kwargs_numerics_low_res) conv_class_low_res = image_numerics_low_res.convolution_class conv_flat_low_res = conv_class_low_res.convolution2d(image_unconvolved) #import matplotlib.pyplot as plt #plt.matshow(image_scipy_resized - image_unconvolved) #plt.colorbar() #plt.show() #plt.matshow(image_scipy_resized - conv_flat) #plt.colorbar() #plt.show() #plt.matshow(image_scipy_resized - conv_flat_low_res) #plt.colorbar() #plt.show() np.testing.assert_almost_equal(conv_flat, image_scipy_resized)
def test_function(self): """ :return: """ for len_x, len_y in [(20, 20), (14, 20)]: x, y = util.make_grid(numPix=(len_x, len_y), deltapix=1.) gauss = Gaussian() flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.) image = util.array2image(flux, nx=len_y, ny=len_x) interp = Interpol() kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 0., 'center_y': 0. } output = interp.function(x, y, **kwargs_interp) npt.assert_equal(output, flux) flux = gauss.function(x - 1., y, amp=1., center_x=0., center_y=0., sigma=1.) kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 1., 'center_y': 0. } output = interp.function(x, y, **kwargs_interp) npt.assert_almost_equal(output, flux, decimal=0) flux = gauss.function(x - 1., y - 1., amp=1, center_x=0., center_y=0., sigma=1.) kwargs_interp = { 'image': image, 'scale': 1., 'phi_G': 0., 'center_x': 1., 'center_y': 1. } output = interp.function(x, y, **kwargs_interp) npt.assert_almost_equal(output, flux, decimal=0) out = interp.function(x=1000, y=0, **kwargs_interp) assert out == 0 # test change of center without re-doing interpolation out = interp.function(x=0, y=0, image=image, scale=1., phi_G=0, center_x=0, center_y=0) out_shift = interp.function(x=1, y=0, image=image, scale=1., phi_G=0, center_x=1, center_y=0) assert out_shift == out # function must give a single value when evaluated at a single point assert isinstance(out, float) # test change of scale without re-doing interpolation out = interp.function(x=1., y=0, image=image, scale=1., phi_G=0, center_x=0, center_y=0) out_scaled = interp.function(x=2., y=0, image=image, scale=2, phi_G=0, center_x=0, center_y=0) assert out_scaled == out
def test_raise(self): with self.assertRaises(ValueError): # try to set decomposition scale to higher than maximal value starlets = SLIT_Starlets(force_no_pysap=True) # define a test image with gaussian components num_pix = 50 x, y = util.make_grid(num_pix, 1) # build a non-trivial positive image from sum of gaussians gaussian = Gaussian() gaussian1 = gaussian.function(x, y, amp=100, sigma=1, center_x=-7, center_y=-7) gaussian2 = gaussian.function(x, y, amp=500, sigma=3, center_x=-3, center_y=-3) gaussian3 = gaussian.function(x, y, amp=2000, sigma=5, center_x=+5, center_y=+5) test_image = util.array2image(gaussian1 + gaussian2 + gaussian3) n_scales = 100 _ = starlets.decomposition_2d(test_image, n_scales) with self.assertRaises(ValueError): # try to set decomposition scale to negative value starlets = SLIT_Starlets(force_no_pysap=True) # define a test image with gaussian components num_pix = 50 x, y = util.make_grid(num_pix, 1) # build a non-trivial positive image from sum of gaussians gaussian = Gaussian() gaussian1 = gaussian.function(x, y, amp=100, sigma=1, center_x=-7, center_y=-7) gaussian2 = gaussian.function(x, y, amp=500, sigma=3, center_x=-3, center_y=-3) gaussian3 = gaussian.function(x, y, amp=2000, sigma=5, center_x=+5, center_y=+5) test_image = util.array2image(gaussian1 + gaussian2 + gaussian3) n_scales = -1 _ = starlets.decomposition_2d(test_image, n_scales) with self.assertRaises(ValueError): # function_split is not supported/defined for pixel-based profiles light_model = LightModel(['SLIT_STARLETS']) num_pix = 20 x, y = util.make_grid(num_pix, 1) kwargs_list = [{ 'amp': np.ones((3, num_pix, num_pix)), 'n_scales': 3, 'n_pixels': 20**2, 'center_x': 0, 'center_y': 0, 'scale': 1 }] _ = light_model.functions_split(x, y, kwargs_list) with self.assertRaises(ValueError): # provided a wrong shape for starlet coefficients starlet_class = SLIT_Starlets() num_pix = 20 x, y = util.make_grid(num_pix, 1) coeffs_wrong = np.ones((3, num_pix**2)) kwargs_list = { 'amp': coeffs_wrong, 'n_scales': 3, 'n_pixels': 20**2, 'center_x': 0, 'center_y': 0, 'scale': 1 } _ = starlet_class.function(x, y, **kwargs_list) image_wrong = np.ones((1, num_pix, num_pix)) _ = starlet_class.decomposition(image_wrong, 3) with self.assertRaises(ValueError): # provided a wrong shape for image to be decomposed starlet_class = SLIT_Starlets() num_pix = 20 image_wrong = np.ones((2, num_pix, num_pix)) _ = starlet_class.decomposition(image_wrong, 3)
def setup(self): self.num_pix = 20 # cutout pixel size delta_pix = 0.2 _, _, ra_at_xy_0, dec_at_xy_0, _, _, Mpix2coord, _ \ = l_util.make_grid_with_coordtransform(numPix=self.num_pix, deltapix=delta_pix, subgrid_res=1, inverse=False, left_lower=False) # imaging data class gaussian = Gaussian() x, y = l_util.make_grid(self.num_pix, 1) gaussian1 = gaussian.function(x, y, amp=5, sigma=1, center_x=-7, center_y=-7) gaussian2 = gaussian.function(x, y, amp=20, sigma=2, center_x=-3, center_y=-3) gaussian3 = gaussian.function(x, y, amp=60, sigma=4, center_x=+5, center_y=+5) image_data = util.array2image(gaussian1 + gaussian2 + gaussian3) background_rms = 0.1 image_data += background_rms * np.random.randn(self.num_pix, self.num_pix) kwargs_data = { 'ra_at_xy_0': ra_at_xy_0, 'dec_at_xy_0': dec_at_xy_0, 'transform_pix2angle': Mpix2coord, 'image_data': image_data, 'background_rms': background_rms, 'noise_map': background_rms * np.ones_like(image_data), } data_class = ImageData(**kwargs_data) # lens mass class lens_model_class = LensModel(['SPEP']) self.kwargs_lens = [{ 'theta_E': 1, 'gamma': 2, 'center_x': 0, 'center_y': 0, 'e1': -0.05, 'e2': 0.05 }] # source light class source_model_class = LightModel(['SLIT_STARLETS']) self.kwargs_source = [{ 'coeffs': 0, 'n_scales': 3, 'n_pixels': self.num_pix**2 }] # define numerics classes image_numerics_class = NumericsSubFrame(pixel_grid=data_class, psf=PSF(psf_type='NONE')) source_numerics_class = NumericsSubFrame(pixel_grid=data_class, psf=PSF(psf_type='NONE'), supersampling_factor=1) # init sparse solver self.solver = SparseSolverSource(data_class, lens_model_class, image_numerics_class, source_numerics_class, source_model_class, num_iter_source=10) # init the plotter self.plotter = SolverPlotter(self.solver, show_now=False)