def test_point_source(self): pointSource = PointSource(point_source_type_list=['SOURCE_POSITION'], fixed_magnification_list=[True]) kwargs_ps = [{'source_amp': 1000, 'ra_source': 0.1, 'dec_source': 0.1}] lensModel = LensModel(lens_model_list=['SIS']) kwargs_lens = [{'theta_E': 1, 'center_x': 0, 'center_y': 0}] numPix = 64 deltaPix = 0.13 kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exposure_time=1, background_rms=1) data_class = ImageData(**kwargs_data) psf_type = "GAUSSIAN" fwhm = 0.9 kwargs_psf = {'psf_type': psf_type, 'fwhm': fwhm} psf_class = PSF(**kwargs_psf) imageModel = ImageModel(data_class=data_class, psf_class=psf_class, lens_model_class=lensModel, point_source_class=pointSource) image = imageModel.image(kwargs_lens=kwargs_lens, kwargs_ps=kwargs_ps) assert np.sum(image) > 0
def generate_image(kwargs_lens_mass, kwargs_src_light, psf_model, data_api, lens_mass_model, src_light_model): """Generate the image of a lensed extended source from provided model and model parameters Parameters ---------- kwargs_lens_mass : dict lens model parameters kwargs_src_light : dict host light model parameters psf_model : lenstronomy PSF object the PSF kernel point source map data_api : lenstronomy DataAPI object tool that handles detector and observation conditions Returns ------- tuple of (np.array, dict) the lensed image """ img_features = {} kwargs_numerics = {'supersampling_factor': 1} image_data = data_api.data_class # Instantiate image model lensed_image_model = ImageModel(image_data, psf_model, lens_mass_model, src_light_model, None, None, kwargs_numerics=kwargs_numerics) # Compute total magnification lensed_total_flux = get_lensed_total_flux(kwargs_lens_mass, kwargs_src_light, lensed_image_model) img_features['lensed_total_flux'] = lensed_total_flux #try: #unlensed_total_flux = get_unlenseD_total_flux_analytical(kwargs_src_light_list, src_light_model) unlensed_image_model = ImageModel(image_data, psf_model, None, src_light_model, None, None, kwargs_numerics=kwargs_numerics) unlensed_total_flux = get_unlensed_total_flux_numerical( kwargs_src_light, unlensed_image_model ) # analytical only runs for profiles that allow analytic integration img_features[ 'total_magnification'] = lensed_total_flux / unlensed_total_flux img_features['unlensed_total_flux'] = unlensed_total_flux #except: # pass # Generate image for export img = lensed_image_model.image(kwargs_lens_mass, kwargs_src_light, None, None) img = np.maximum(0.0, img) # safeguard against negative pixel values return img, img_features
def test_low_res(self): image_model = ImageModel(self.pixel_grid, self.psf_class, lens_light_model_class=self.lightModel, kwargs_numerics=self.kwargs_numerics_low_res) image_conv = image_model.image(kwargs_lens_light=self.kwargs_light, unconvolved=False) npt.assert_almost_equal( (self.image_true - image_conv) / self.image_true, 0, decimal=1)
def test_sub_frame(self): image_model = ImageModel(self.pixel_grid, self.psf_class, lens_light_model_class=self.lightModel, kwargs_numerics=self.kwargs_numerics_partial) image_conv = image_model.image(kwargs_lens_light=self.kwargs_light, unconvolved=False) delta = (self.image_true - image_conv) / self.image_true npt.assert_almost_equal(delta[self._conv_pixels_partial], 0, decimal=1)
def test_point_source_rendering(self): # initialize data from lenstronomy.SimulationAPI.simulations import Simulation SimAPI = Simulation() numPix = 100 deltaPix = 0.05 kwargs_data = SimAPI.data_configure(numPix, deltaPix, exposure_time=1, sigma_bkg=1) data_class = Data(kwargs_data) kernel = np.zeros((5, 5)) kernel[2, 2] = 1 kwargs_psf = {'kernel_point_source': kernel, 'kernel_pixel': kernel, 'psf_type': 'PIXEL'} psf_class = PSF(kwargs_psf) lens_model_class = LensModel(['SPEP']) source_model_class = LightModel([]) lens_light_model_class = LightModel([]) kwargs_numerics = {'subgrid_res': 2, 'point_source_subgrid': 1} point_source_class = PointSource(point_source_type_list=['LENSED_POSITION'], fixed_magnification_list=[False]) makeImage = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) # chose point source positions x_pix = np.array([10, 5, 10, 90]) y_pix = np.array([40, 50, 60, 50]) ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix) e1, e2 = param_util.phi_q2_ellipticity(0, 0.8) kwargs_lens_init = [{'theta_E': 1, 'gamma': 2, 'e1': e1, 'e2': e2, 'center_x': 0, 'center_y': 0}] kwargs_else = [{'ra_image': ra_pos, 'dec_image': dec_pos, 'point_amp': np.ones_like(ra_pos)}] model = makeImage.image(kwargs_lens_init, kwargs_source={}, kwargs_lens_light={}, kwargs_ps=kwargs_else) image = makeImage.ImageNumerics.array2image(model) for i in range(len(x_pix)): npt.assert_almost_equal(image[y_pix[i], x_pix[i]], 1, decimal=2) x_pix = np.array([10.5, 5.5, 10.5, 90.5]) y_pix = np.array([40, 50, 60, 50]) ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix) phi, q = 0., 0.8 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_lens_init = [{'theta_E': 1, 'gamma': 2, 'e1': e1, 'e2': e2, 'center_x': 0, 'center_y': 0}] kwargs_else = [{'ra_image': ra_pos, 'dec_image': dec_pos, 'point_amp': np.ones_like(ra_pos)}] model = makeImage.image(kwargs_lens_init, kwargs_source={}, kwargs_lens_light={}, kwargs_ps=kwargs_else) image = makeImage.ImageNumerics.array2image(model) for i in range(len(x_pix)): print(int(y_pix[i]), int(x_pix[i]+0.5)) npt.assert_almost_equal(image[int(y_pix[i]), int(x_pix[i])], 0.5, decimal=1) npt.assert_almost_equal(image[int(y_pix[i]), int(x_pix[i]+0.5)], 0.5, decimal=1)
def test_point_source_rendering(self): # initialize data numPix = 100 deltaPix = 0.05 kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exposure_time=1, background_rms=1) data_class = ImageData(**kwargs_data) kernel = np.zeros((5, 5)) kernel[2, 2] = 1 kwargs_psf = {'kernel_point_source': kernel, 'psf_type': 'PIXEL', 'psf_error_map': np.ones_like(kernel) * 0.001} psf_class = PSF(**kwargs_psf) lens_model_class = LensModel(['SPEP']) source_model_class = LightModel([]) lens_light_model_class = LightModel([]) kwargs_numerics = {'supersampling_factor': 2, 'supersampling_convolution': True, 'point_source_supersampling_factor': 1} point_source_class = PointSource(point_source_type_list=['LENSED_POSITION'], fixed_magnification_list=[False]) makeImage = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) # chose point source positions x_pix = np.array([10, 5, 10, 90]) y_pix = np.array([40, 50, 60, 50]) ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix) e1, e2 = param_util.phi_q2_ellipticity(0, 0.8) kwargs_lens_init = [{'theta_E': 1, 'gamma': 2, 'e1': e1, 'e2': e2, 'center_x': 0, 'center_y': 0}] kwargs_else = [{'ra_image': ra_pos, 'dec_image': dec_pos, 'point_amp': np.ones_like(ra_pos)}] image = makeImage.image(kwargs_lens_init, kwargs_source={}, kwargs_lens_light={}, kwargs_ps=kwargs_else) #print(np.shape(model), 'test') #image = makeImage.ImageNumerics.array2image(model) for i in range(len(x_pix)): npt.assert_almost_equal(image[y_pix[i], x_pix[i]], 1, decimal=2) x_pix = np.array([10.5, 5.5, 10.5, 90.5]) y_pix = np.array([40, 50, 60, 50]) ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix) phi, q = 0., 0.8 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_lens_init = [{'theta_E': 1, 'gamma': 2, 'e1': e1, 'e2': e2, 'center_x': 0, 'center_y': 0}] kwargs_else = [{'ra_image': ra_pos, 'dec_image': dec_pos, 'point_amp': np.ones_like(ra_pos)}] image = makeImage.image(kwargs_lens_init, kwargs_source={}, kwargs_lens_light={}, kwargs_ps=kwargs_else) #image = makeImage.ImageNumerics.array2image(model) for i in range(len(x_pix)): print(int(y_pix[i]), int(x_pix[i]+0.5)) npt.assert_almost_equal(image[int(y_pix[i]), int(x_pix[i])], 0.5, decimal=1) npt.assert_almost_equal(image[int(y_pix[i]), int(x_pix[i]+0.5)], 0.5, decimal=1)
def test_full(self): image_model_true = ImageModel( self.pixel_grid, self.psf_class, lens_light_model_class=self.lightModel, kwargs_numerics=self.kwargs_numerics_true) image_unconvolved = image_model_true.image( kwargs_lens_light=self.kwargs_light, unconvolved=True) npt.assert_almost_equal(np.sum(self.image_true) / np.sum(image_unconvolved), 1, decimal=2)
def setup(self): # data specifics sigma_bkg = .05 # background noise per pixel exp_time = 100 # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit) self.num_pix = 100 # cutout pixel size delta_pix = 0.05 # pixel size in arcsec (area per pixel = delta_pix**2) fwhm = 0.5 # full width half max of PSF # supersampling factor for source plane self.subgrid_res_source = 1 self.num_pix_source = self.num_pix * self.subgrid_res_source # wavelets scales for lens and source self.n_scales_source = 4 self.n_scales_lens = 3 # prepare data simulation kwargs_data = sim_util.data_configure_simple(self.num_pix, delta_pix, exp_time, sigma_bkg, inverse=True) data_class = ImageData(**kwargs_data) # generate sa pixelated gaussian PSF kernel kwargs_psf = { 'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncation': 5, 'pixel_size': delta_pix } psf_class = PSF(**kwargs_psf) kernel = psf_class.kernel_point_source kwargs_psf = { 'psf_type': 'PIXEL', 'kernel_point_source': kernel, 'psf_error_map': np.ones_like(kernel) * 0.001 } psf_class = PSF(**kwargs_psf) # 'EXERNAL_SHEAR': external shear kwargs_shear = { 'gamma1': 0.01, 'gamma2': 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] self.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'] kwargs_lens_light = [kwargs_sersic] lens_light_model_class = LightModel( light_model_list=lens_light_model_list) source_model_list = ['SERSIC_ELLIPSE'] kwargs_source = [kwargs_sersic_ellipse] source_model_class = LightModel(light_model_list=source_model_list) # list of lens light profiles point_source_class = PointSource(['LENSED_POSITION']) lens_eq_solver = LensEquationSolver(lensModel=self.lens_model_class) ra_image, dec_image = lens_eq_solver.image_position_from_source( sourcePos_x=kwargs_source[0]['center_x'], sourcePos_y=kwargs_source[0]['center_y'], kwargs_lens=self.kwargs_lens) point_amp = np.ones_like(ra_image) kwargs_ps = [{ 'ra_image': ra_image, 'dec_image': dec_image, 'point_amp': point_amp }] # simulate data kwargs_numerics = {'supersampling_factor': 1} imageModel = ImageModel(data_class, psf_class, self.lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) self.image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps) data_class.update_data(self.image_sim) # retrieve the point source data only (for initial guess for source+PS solver) self.ps_sim = imageModel.image(self.kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, source_add=False, lens_light_add=False, point_source_add=True) # define some mask self.likelihood_mask = np.zeros((self.num_pix, self.num_pix)) self.likelihood_mask[5:-5, 5:-5] = 1 # get a numerics classes numerics = NumericsSubFrame(pixel_grid=data_class, psf=psf_class) source_numerics = NumericsSubFrame( pixel_grid=data_class, psf=psf_class, supersampling_factor=self.subgrid_res_source) self.num_iter_source = 20 self.num_iter_lens = 10 self.num_iter_global = 7 self.num_iter_weights = 2 # source grid offsets self.kwargs_special = { 'delta_x_source_grid': 0, 'delta_y_source_grid': 0, } # init the solvers # SOLVER SOURCE, with analysis formulation self.source_model_class = LightModel(['SLIT_STARLETS']) self.kwargs_source = [{'n_scales': self.n_scales_source}] self.solver_source_ana = SparseSolverSource( data_class, self.lens_model_class, numerics, source_numerics, self.source_model_class, source_interpolation='bilinear', minimal_source_plane=False, use_mask_for_minimal_source_plane=True, min_num_pix_source=20, sparsity_prior_norm=1, force_positivity=True, formulation='analysis', verbose=False, show_steps=False, min_threshold=5, threshold_increment_high_freq=1, threshold_decrease_type='exponential', num_iter_source=self.num_iter_source, num_iter_weights=self.num_iter_weights) self.solver_source_ana.set_likelihood_mask(self.likelihood_mask) # SOLVER SOURCE + LENS, with synthesis formulation self.lens_light_model_class = LightModel(['SLIT_STARLETS']) self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}] self.solver_lens_syn = SparseSolverSourceLens( data_class, self.lens_model_class, numerics, source_numerics, self.source_model_class, self.lens_light_model_class, source_interpolation='bilinear', minimal_source_plane=False, use_mask_for_minimal_source_plane=True, min_num_pix_source=20, sparsity_prior_norm=1, force_positivity=True, formulation='synthesis', verbose=False, show_steps=False, min_threshold=3, threshold_increment_high_freq=1, threshold_decrease_type='linear', num_iter_global=self.num_iter_global, num_iter_source=self.num_iter_source, num_iter_lens=self.num_iter_lens, num_iter_weights=self.num_iter_weights) self.solver_lens_syn.set_likelihood_mask(self.likelihood_mask)
def sim_non_lens_gal(data, numPix=101, sigma_bkg=8.0, exp_time=100.0, deltaPix=0.263, psf_type='GAUSSIAN', kernel_size=91): full_band_images = np.zeros((numPix, numPix, 4)) center_x_1 = np.random.uniform(-0.03, 0.03) center_y_1 = np.random.uniform(-0.03, 0.03) flux_1 = mag_to_flux(data['source_mag'], 27.5) flux_2 = mag_to_flux(data['lens_mag'], 27.5) light_model_list = ['SERSIC_ELLIPSE', 'SERSIC'] lightModel = LightModel(light_model_list=light_model_list) kwargs_disk = { 'amp': flux_1, 'R_sersic': data['source_R_sersic'], 'n_sersic': data['source_n_sersic'], 'e1': data['source_e1'], 'e2': data['source_e2'], 'center_x': center_x_1, 'center_y': center_y_1 } kwargs_bulge = { 'amp': flux_2, 'R_sersic': data['lens_R_sersic'], 'n_sersic': data['lens_n_sersic'], 'center_x': center_x_1, 'center_y': center_y_1 } kwargs_host = [kwargs_disk, kwargs_bulge] color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3} for band in ['g', 'r', 'i', 'z']: kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) data_class = ImageData(**kwargs_data) kwargs_psf = { 'psf_type': psf_type, 'fwhm': data['psf_%s' % band], 'pixel_size': deltaPix, 'truncation': 3 } psf_class = PSF(**kwargs_psf) kwargs_numerics = { 'supersampling_factor': 1, 'supersampling_convolution': False } imageModel = ImageModel(data_class, psf_class, lens_light_model_class=lightModel, kwargs_numerics=kwargs_numerics) image_sim = imageModel.image(kwargs_lens_light=kwargs_host) poisson = image_util.add_poisson(image_sim, exp_time=exp_time) bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg) image_sim = image_sim + bkg + poisson full_band_images[:, :, color_idx[band]] += image_sim return full_band_images
def sim_lens(data, numPix=101, sigma_bkg=8.0, exp_time=100.0, deltaPix=0.263, psf_type='GAUSSIAN', kernel_size=91): flux_g = mag_to_flux(data['mag_g'], 27.5) flux_r = mag_to_flux(data['mag_r'], 27.5) flux_i = mag_to_flux(data['mag_i'], 27.5) flux_z = mag_to_flux(data['mag_z'], 27.5) flux_source = mag_to_flux(data['source_mag'], 27.5) flux_lens = mag_to_flux(data['lens_mag'], 27.5) color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3} cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.) full_band_images = np.zeros((numPix, numPix, 4)) ### Set kwargs based on input data file #shear kwargs_shear = { 'gamma_ext': data['lens_shear_gamma_ext'], 'psi_ext': data['lens_shear_psi_ext'] } #lens potential kwargs_spemd = { 'theta_E': data['lens_theta_E'], 'gamma': data['lens_gamma'], 'center_x': data['lens_center_x'], 'center_y': data['lens_center_y'], 'e1': data['lens_e1'], 'e2': data['lens_e2'] } #lens light kwargs_sersic_lens = { 'amp': flux_lens, 'R_sersic': data['lens_R_sersic'], 'n_sersic': data['lens_n_sersic'], 'e1': data['lens_e1'], 'e2': data['lens_e2'], 'center_x': data['lens_center_x'], 'center_y': data['lens_center_y'] } #source kwargs_sersic_source = { 'amp': flux_source, 'R_sersic': data['source_R_sersic'], 'n_sersic': data['source_n_sersic'], 'e1': data['source_e1'], 'e2': data['source_e2'], 'center_x': data['source_center_x'], 'center_y': data['source_center_y'] } ###set model parameters based on kwargs #lens potential lens_model_list = ['SPEP', 'SHEAR_GAMMA_PSI'] kwargs_lens = [kwargs_spemd, kwargs_shear] lens_model_class = LensModel(lens_model_list=lens_model_list) #lens light lens_light_model_list = ['SERSIC_ELLIPSE'] kwargs_lens_light = [kwargs_sersic_lens] lens_light_model_class = LightModel(light_model_list=lens_light_model_list) #source source_model_list = ['SERSIC_ELLIPSE'] kwargs_source = [kwargs_sersic_source] source_model_class = LightModel(light_model_list=source_model_list) ###configure image based on data properties kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) data_class = ImageData(**kwargs_data) ###solve lens equation lensEquationSolver = LensEquationSolver(lens_model_class) x_image, y_image = lensEquationSolver.findBrightImage( kwargs_sersic_source['center_x'], kwargs_sersic_source['center_y'], kwargs_lens, numImages=4, min_distance=deltaPix, search_window=numPix * deltaPix) magnification = lens_model_class.magnification(x_image, y_image, kwargs=kwargs_lens) ###iterate through bands to simulate images for band in ['g', 'r', 'i', 'z']: #psf info kwargs_psf = { 'psf_type': psf_type, 'fwhm': data['psf_%s' % band], 'pixel_size': deltaPix, 'truncation': 3 } psf_class = PSF(**kwargs_psf) #quasar info kwargs_ps = [{ 'ra_image': x_image, 'dec_image': y_image, 'point_amp': np.abs(magnification) * eval('flux_%s' % band) }] point_source_list = ['LENSED_POSITION'] point_source_class = PointSource( point_source_type_list=point_source_list, fixed_magnification_list=[False]) #build image model kwargs_numerics = {'supersampling_factor': 1} imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) #generate image image_sim = imageModel.image(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps) poisson = image_util.add_poisson(image_sim, exp_time=exp_time) bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg) image_sim = image_sim + bkg + poisson data_class.update_data(image_sim) kwargs_data['image_data'] = image_sim kwargs_model = { 'lens_model_list': lens_model_list, 'lens_light_model_list': lens_light_model_list, 'source_light_model_list': source_model_list, 'point_source_model_list': point_source_list } #build up an array with one slice for each band full_band_images[:, :, color_idx[band]] += image_sim return full_band_images
'center_x': source_pos[0], 'center_y': source_pos[1], 'e1': source_para['e1'], 'e2': source_para['e2']} kwargs_source_light['amp']= mva.getAmp_lenstronomy(SERSIC_in_mag=source_para,zp=zp) kwargs_source_light_copy = copy.deepcopy(kwargs_source_light) #kwargs_source_light_copy['mag'] = source_para['mag_sersic'] kwargs_source_list = [kwargs_source_light] source_model_class = LightModel(light_model_list=source_model_list) #============================================================================== # Setup the simulating #============================================================================== from lenstronomy.ImSim.image_model import ImageModel imageModel_arc = ImageModel(data_class, psf_class, lens_model_class=lens_model_class, source_model_class=source_model_class, kwargs_numerics=kwargs_numerics) # generate the arc image image_arc = imageModel_arc.image(kwargs_lens_list, kwargs_source_list, unconvolved=True) #print(image_arc.sum()) #print(10.**(-0.4*(source_para['mag_sersic']-zp))) plt.imshow(np.log10(image_arc),origin='lower') plt.colorbar() plt.show() src_mag=-2.5*np.log10(np.sum(image_arc))+zp pc = int(numPix/2) if image_arc[pc,pc]/image_arc[pc,pc+1]>20: print("Average center arc light for seed:", seed) image_arc[pc,pc]= (image_arc[pc,pc-2] + image_arc[pc,pc+2] + image_arc[pc-2,pc] + image_arc[pc+2,pc])/4 #This makes no sense import scipy.signal as signal image_arc_conv= signal.fftconvolve(image_arc, psf_class.kernel_point_source, mode='same') #convolve the image #image_arc_conv = imageModel_arc.image(kwargs_lens_list, kwargs_source_list, unconvolved=False)
'e1': e1, 'e2': e2, 'center_x': center_x, 'center_y': center_y } kwargs_buldge = { 'amp': 1, 'n_sersic': 4, 'R_sersic': 0.3, 'center_x': center_x, 'center_y': center_y } kwargs_host = [kwargs_disk, kwargs_buldge] from lenstronomy.ImSim.image_model import ImageModel kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False} imageModel = ImageModel(data_class, psf_class, source_model_class=lightModel, point_source_class=pointSource, kwargs_numerics=kwargs_numerics) # simulate image with the parameters we have defined above # image = imageModel.image(kwargs_source=kwargs_host, kwargs_ps=kwargs_ps) imageModel_ps = ImageModel(data_class, psf_class, point_source_class=pointSource, kwargs_numerics=kwargs_numerics) image_ps = imageModel_ps.image(kwargs_ps=kwargs_ps) plt.matshow((image_ps), origin='lower') plt.show()
def setup(self): # we define a model consisting of a singe Sersric profile from lenstronomy.LightModel.light_model import LightModel light_model_list = ['SERSIC_ELLIPSE'] self.lightModel = LightModel(light_model_list=light_model_list) self.kwargs_light = [ {'amp': 100, 'R_sersic': 0.5, 'n_sersic': 3, 'e1': 0, 'e2': 0, 'center_x': 0.02, 'center_y': 0}] # we define a pixel grid and a higher resolution super sampling factor self._supersampling_factor = 5 numPix = 61 # cutout pixel size deltaPix = 0.05 # pixel size in arcsec (area per pixel = deltaPix**2) x, y, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix = util.make_grid_with_coordtransform( numPix=numPix, deltapix=deltaPix, subgrid_res=1, left_lower=False, inverse=False) flux = self.lightModel.surface_brightness(x, y, kwargs_list=self.kwargs_light) flux = util.array2image(flux) flux_max = np.max(flux) conv_pixels_partial = np.zeros((numPix, numPix), dtype=bool) conv_pixels_partial[flux >= flux_max / 20] = True self._conv_pixels_partial = conv_pixels_partial # high resolution ray-tracing and high resolution convolution, the full calculation self.kwargs_numerics_true = {'supersampling_factor': self._supersampling_factor, # super sampling factor of (partial) high resolution ray-tracing 'compute_mode': 'regular', # 'regular' or 'adaptive' 'supersampling_convolution': True, # bool, if True, performs the supersampled convolution (either on regular or adaptive grid) 'supersampling_kernel_size': None, # size of the higher resolution kernel region (can be smaller than the original kernel). None leads to use the full size 'flux_evaluate_indexes': None, # bool mask, if None, it will evaluate all (sub) pixels 'supersampled_indexes': None, # bool mask of pixels to be computed in supersampled grid (only for adaptive mode) 'compute_indexes': None, # bool mask of pixels to be computed the PSF response (flux being added to). Only used for adaptive mode and can be set =likelihood mask. 'point_source_supersampling_factor': 1, # int, supersampling factor when rendering a point source (not used in this script) } # high resolution convolution on a smaller PSF with low resolution convolution on the edges of the PSF and high resolution ray tracing self.kwargs_numerics_high_res_narrow = {'supersampling_factor': self._supersampling_factor, 'compute_mode': 'regular', 'supersampling_convolution': True, 'supersampling_kernel_size': 5, } # low resolution convolution based on high resolution ray-tracing grid self.kwargs_numerics_low_conv_high_grid = {'supersampling_factor': self._supersampling_factor, 'compute_mode': 'regular', 'supersampling_convolution': False, # does not matter for supersampling_factor=1 'supersampling_kernel_size': None, # does not matter for supersampling_factor=1 } # low resolution convolution with a subset of pixels with high resolution ray-tracing self.kwargs_numerics_low_conv_high_adaptive = {'supersampling_factor': self._supersampling_factor, 'compute_mode': 'adaptive', 'supersampling_convolution': False, # does not matter for supersampling_factor=1 'supersampling_kernel_size': None, # does not matter for supersampling_factor=1 'supersampled_indexes': self._conv_pixels_partial, 'convolution_kernel_size': 9, } # low resolution convolution with a subset of pixels with high resolution ray-tracing and high resoluton convolution on smaller kernel size self.kwargs_numerics_high_adaptive = {'supersampling_factor': self._supersampling_factor, 'compute_mode': 'adaptive', 'supersampling_convolution': True, # does not matter for supersampling_factor=1 'supersampling_kernel_size': 5, # does not matter for supersampling_factor=1 'supersampled_indexes': self._conv_pixels_partial, 'convolution_kernel_size': 9, } # low resolution convolution and low resolution ray tracing, the simplest calculation self.kwargs_numerics_low_res = {'supersampling_factor': 1, 'compute_mode': 'regular', 'supersampling_convolution': False, # does not matter for supersampling_factor=1 'supersampling_kernel_size': None, # does not matter for supersampling_factor=1 'convolution_kernel_size': 9, } flux_evaluate_indexes = np.zeros((numPix, numPix), dtype=bool) flux_evaluate_indexes[flux >= flux_max / 1000] = True # low resolution convolution on subframe self.kwargs_numerics_partial = {'supersampling_factor': 1, 'compute_mode': 'regular', 'supersampling_convolution': False, # does not matter for supersampling_factor=1 'supersampling_kernel_size': None, # does not matter for supersampling_factor=1 'flux_evaluate_indexes': flux_evaluate_indexes, 'convolution_kernel_size': 9 } # import PSF file kernel_super = kernel_util.kernel_gaussian(kernel_numPix=11 * self._supersampling_factor, deltaPix=deltaPix / self._supersampling_factor, fwhm=0.1) kernel_size = 9 kernel_super = kernel_util.cut_psf(psf_data=kernel_super, psf_size=kernel_size * self._supersampling_factor) # make instance of the PixelGrid class from lenstronomy.Data.pixel_grid import PixelGrid kwargs_grid = {'nx': numPix, 'ny': numPix, 'transform_pix2angle': Mpix2coord, 'ra_at_xy_0': ra_at_xy_0, 'dec_at_xy_0': dec_at_xy_0} self.pixel_grid = PixelGrid(**kwargs_grid) # make instance of the PSF class from lenstronomy.Data.psf import PSF kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_super, 'point_source_supersampling_factor': self._supersampling_factor} self.psf_class = PSF(**kwargs_psf) # without convolution image_model_true = ImageModel(self.pixel_grid, self.psf_class, lens_light_model_class=self.lightModel, kwargs_numerics=self.kwargs_numerics_true) self.image_true = image_model_true.image(kwargs_lens_light=self.kwargs_light)
def setup(self): # data specifics sigma_bkg = .05 # background noise per pixel (Gaussian) 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.1 # full width half max of PSF (only valid when psf_type='gaussian') psf_type = 'GAUSSIAN' # 'GAUSSIAN', 'PIXEL', 'NONE' # generate the coordinate grid and image properties kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) kwargs_data['exposure_time'] = exp_time * np.ones_like(kwargs_data['image_data']) data_class = ImageData(**kwargs_data) # generate the psf variables kwargs_psf = {'psf_type': psf_type, 'pixel_size': deltaPix, 'fwhm': fwhm} # kwargs_psf = sim_util.psf_configure_simple(psf_type=psf_type, fwhm=fwhm, kernelsize=kernel_size, deltaPix=deltaPix, kernel=kernel) psf_class = PSF(**kwargs_psf) # lensing quantities kwargs_shear = {'gamma1': 0.02, 'gamma2': -0.04} # shear values to the source plane kwargs_spemd = {'theta_E': 1.26, 'gamma': 2., 'center_x': 0.0, 'center_y': 0.0, 'e1': -0.1, 'e2': 0.05} # parameters of the deflector lens model # the lens model is a supperposition of an elliptical lens model with external shear lens_model_list = ['EPL', 'SHEAR'] kwargs_lens_true = [kwargs_spemd, kwargs_shear] lens_model_class = LensModel(lens_model_list=lens_model_list) # choice of source type source_type = 'SERSIC' # 'SERSIC' or 'SHAPELETS' source_x = 0. source_y = 0.05 # Sersic parameters in the initial simulation phi_G, q = 0.5, 0.8 e1, e2 = param_util.phi_q2_ellipticity(phi_G, q) kwargs_sersic_source = {'amp': 1000, 'R_sersic': 0.05, 'n_sersic': 1, 'e1': e1, 'e2': e2, 'center_x': source_x, 'center_y': source_y} # kwargs_else = {'sourcePos_x': source_x, 'sourcePos_y': source_y, 'quasar_amp': 400., 'gamma1_foreground': 0.0, 'gamma2_foreground':-0.0} source_model_list = ['SERSIC_ELLIPSE'] kwargs_source_true = [kwargs_sersic_source] source_model_class = LightModel(light_model_list=source_model_list) lensEquationSolver = LensEquationSolver(lens_model_class) x_image, y_image = lensEquationSolver.findBrightImage(source_x, source_y, kwargs_lens_true, numImages=4, min_distance=deltaPix, search_window=numPix * deltaPix) mag = lens_model_class.magnification(x_image, y_image, kwargs=kwargs_lens_true) kwargs_numerics = {'supersampling_factor': 1} imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, kwargs_numerics=kwargs_numerics) # generate image model = imageModel.image(kwargs_lens_true, kwargs_source_true) poisson = image_util.add_poisson(model, exp_time=exp_time) bkg = image_util.add_background(model, sigma_bkd=sigma_bkg) image_sim = model + bkg + poisson data_class.update_data(image_sim) kwargs_data['image_data'] = image_sim kwargs_model = {'lens_model_list': lens_model_list, 'source_light_model_list': source_model_list, } # make cutous and data instances of them x_pos, y_pos = data_class.map_coord2pix(x_image, y_image) ra_grid, dec_grid = data_class.pixel_coordinates multi_band_list = [] for i in range(len(x_pos)): n_cut = 12 x_c = int(x_pos[i]) y_c = int(y_pos[i]) image_cut = image_sim[int(y_c - n_cut):int(y_c + n_cut), int(x_c - n_cut):int(x_c + n_cut)] exposure_map_cut = data_class.exposure_map[int(y_c - n_cut):int(y_c + n_cut), int(x_c - n_cut):int(x_c + n_cut)] kwargs_data_i = { 'background_rms': data_class.background_rms, 'exposure_time': exposure_map_cut, 'ra_at_xy_0': ra_grid[y_c - n_cut, x_c - n_cut], 'dec_at_xy_0': dec_grid[y_c - n_cut, x_c - n_cut], 'transform_pix2angle': data_class.transform_pix2angle , 'image_data': image_cut } multi_band_list.append([kwargs_data_i, kwargs_psf, kwargs_numerics]) kwargs_params = {'kwargs_lens': kwargs_lens_true, 'kwargs_source': kwargs_source_true} self.multiPatch = MultiPatchPlot(multi_band_list, kwargs_model, kwargs_params, multi_band_type='joint-linear', kwargs_likelihood=None, verbose=True, cmap_string="gist_heat") self.data_class = data_class self.model = model self.lens_model_class = lens_model_class self.kwargs_lens = kwargs_lens_true
def sim_image(self, info_dict): """ Simulate an image based on specifications in sim_dict Args: info_dict (dict): A single element from the list produced interanlly by input_reader.Organizer.breakup(). Contains all the properties of a single image to generate. """ output_image = [] if self.return_planes: output_source, output_lens, output_point_source, output_noise = [], [], [], [] output_metadata = [] #set the cosmology cosmology_info = ['H0', 'Om0', 'Tcmb0', 'Neff', 'm_nu', 'Ob0'] cosmo = FlatLambdaCDM( **dict_select_choose(list(info_dict.values())[0], cosmology_info)) for band, sim_dict in info_dict.items(): # Parse the info dict params = self.parse_single_band_info_dict(sim_dict, cosmo, band=band) kwargs_single_band = params[0] kwargs_model = params[1] kwargs_numerics = params[2] kwargs_lens_light_list = params[3] kwargs_source_list = params[4] kwargs_point_source_list = params[5] kwargs_lens_model_list = params[6] output_metadata += params[7] # Make image # data properties kwargs_data = sim_util.data_configure_simple( sim_dict['numPix'], kwargs_single_band['pixel_scale'], kwargs_single_band['exposure_time']) data_class = ImageData(**kwargs_data) # psf properties kwargs_psf = { 'psf_type': kwargs_single_band['psf_type'], 'pixel_size': kwargs_single_band['pixel_scale'], 'fwhm': kwargs_single_band['seeing'] } psf_class = PSF(**kwargs_psf) # SimAPI instance for conversion to observed quantities sim = SimAPI(numpix=sim_dict['numPix'], kwargs_single_band=kwargs_single_band, kwargs_model=kwargs_model) kwargs_lens_model_list = sim.physical2lensing_conversion( kwargs_mass=kwargs_lens_model_list) kwargs_lens_light_list, kwargs_source_list, _ = sim.magnitude2amplitude( kwargs_lens_light_mag=kwargs_lens_light_list, kwargs_source_mag=kwargs_source_list) # lens model properties lens_model_class = LensModel( lens_model_list=kwargs_model['lens_model_list'], z_lens=kwargs_model['lens_redshift_list'][0], z_source=kwargs_model['z_source'], cosmo=cosmo) # source properties source_model_class = LightModel( light_model_list=kwargs_model['source_light_model_list']) # lens light properties lens_light_model_class = LightModel( light_model_list=kwargs_model['lens_light_model_list']) # solve for PS positions to incorporate time delays lensEquationSolver = LensEquationSolver(lens_model_class) kwargs_ps = [] for ps_idx, ps_mag in enumerate(kwargs_point_source_list): # modify the SimAPI instance to do one point source at a time temp_kwargs_model = {k: v for k, v in kwargs_model.items()} temp_kwargs_model['point_source_model_list'] = [ kwargs_model['point_source_model_list'][ps_idx] ] sim = SimAPI(numpix=sim_dict['numPix'], kwargs_single_band=kwargs_single_band, kwargs_model=temp_kwargs_model) if kwargs_model['point_source_model_list'][ ps_idx] == 'SOURCE_POSITION': # convert each image to an amplitude amplitudes = [] for mag in ps_mag['magnitude']: ps_dict = {k: v for k, v in ps_mag.items()} ps_dict['magnitude'] = mag _, _2, ps = sim.magnitude2amplitude( kwargs_ps_mag=[ps_dict]) amplitudes.append(ps[0]['source_amp']) x_image, y_image = lensEquationSolver.findBrightImage( ps[0]['ra_source'], ps[0]['dec_source'], kwargs_lens_model_list, numImages=4, # max number of images min_distance=kwargs_single_band['pixel_scale'], search_window=sim_dict['numPix'] * kwargs_single_band['pixel_scale']) magnification = lens_model_class.magnification( x_image, y_image, kwargs=kwargs_lens_model_list) #amplitudes = np.array(amplitudes) * np.abs(magnification) amplitudes = np.array( [a * m for a, m in zip(amplitudes, magnification)]) kwargs_ps.append({ 'ra_image': x_image, 'dec_image': y_image, 'point_amp': amplitudes }) else: _, _2, ps = sim.magnitude2amplitude(kwargs_ps_mag=[ps_mag]) kwargs_ps.append(ps[0]) # point source properties point_source_class = PointSource(point_source_type_list=[ x if x != 'SOURCE_POSITION' else 'LENSED_POSITION' for x in kwargs_model['point_source_model_list'] ], fixed_magnification_list=[False] * len(kwargs_ps)) # create an image model image_model = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) # generate image image_sim = image_model.image(kwargs_lens_model_list, kwargs_source_list, kwargs_lens_light_list, kwargs_ps) poisson = image_util.add_poisson( image_sim, exp_time=kwargs_single_band['exposure_time']) sigma_bkg = data_util.bkg_noise( kwargs_single_band['read_noise'], kwargs_single_band['exposure_time'], kwargs_single_band['sky_brightness'], kwargs_single_band['pixel_scale'], num_exposures=kwargs_single_band['num_exposures']) bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg) image = image_sim + bkg + poisson # Save theta_E (and sigma_v if used) for ii in range(len(output_metadata)): output_metadata.append({ 'PARAM_NAME': output_metadata[ii]['PARAM_NAME'].replace( 'sigma_v', 'theta_E'), 'PARAM_VALUE': kwargs_lens_model_list[output_metadata[ii] ['LENS_MODEL_IDX']]['theta_E'], 'LENS_MODEL_IDX': output_metadata[ii]['LENS_MODEL_IDX'] }) # Solve lens equation if desired if self.solve_lens_equation: #solver = lens_equation_solver.LensEquationSolver(imSim.LensModel) #x_mins, y_mins = solver.image_position_from_source(sourcePos_x=kwargs_source_list[0]['center_x'], # sourcePos_y=kwargs_source_list[0]['center_y'], # kwargs_lens=kwargs_lens_model_list) x_mins, y_mins = x_image, y_image num_source_images = len(x_mins) # Add noise image_noise = np.zeros(np.shape(image)) for noise_source_num in range( 1, sim_dict['NUMBER_OF_NOISE_SOURCES'] + 1): image_noise += self._generate_noise( sim_dict['NOISE_SOURCE_{0}-NAME'.format(noise_source_num)], np.shape(image), select_params( sim_dict, 'NOISE_SOURCE_{0}-'.format(noise_source_num))) image += image_noise # Combine with other bands output_image.append(image) # Store plane-separated info if requested if self.return_planes: output_lens.append( image_model.lens_surface_brightness( kwargs_lens_light_list)) output_source.append( image_model.source_surface_brightness( kwargs_source_list, kwargs_lens_model_list)) output_point_source.append( image_model.point_source(kwargs_ps, kwargs_lens_model_list)) output_noise.append(image_noise) # Return the desired information in a dictionary return_dict = { 'output_image': np.array(output_image), 'output_lens_plane': None, 'output_source_plane': None, 'output_point_source_plane': None, 'output_noise_plane': None, 'x_mins': None, 'y_mins': None, 'num_source_images': None, 'additional_metadata': output_metadata } if self.return_planes: return_dict['output_lens_plane'] = np.array(output_lens) return_dict['output_source_plane'] = np.array(output_source) return_dict['output_point_source_plane'] = np.array( output_point_source) return_dict['output_noise_plane'] = np.array(output_noise) if self.solve_lens_equation: return_dict['x_mins'] = x_mins return_dict['y_mins'] = y_mins return_dict['num_source_images'] = num_source_images return return_dict
'amp': 1., 'n_sersic': host_n, 'R_sersic': host_Reff / np.sqrt(q), 'e1': e1, 'e2': e2, 'center_x': center_x, 'center_y': center_y } kwargs_host_medi = [kwargs_sersic_medi] imageModel = ImageModel(data_class, psf_class, lens_light_model_class=lightModel, point_source_class=pointSource, kwargs_numerics=kwargs_numerics) medi_host_flux = np.sum( imageModel.image(kwargs_lens_light=kwargs_host_medi, unconvolved=True)) amp = 1. / medi_host_flux * host_flux kwargs_sersic = { 'amp': amp, 'n_sersic': host_n, 'R_sersic': host_Reff / np.sqrt(q), 'e1': e1, 'e2': e2, 'center_x': center_x, 'center_y': center_y } kwargs_host = [kwargs_sersic] ## simulate image with the parameters we have defined above # total_highres = imageModel.image(kwargs_lens_light=kwargs_host, kwargs_ps=kwargs_ps,
lens_light_model_list = ['SERSIC_ELLIPSE'] lightModel = LightModel(lens_light_model_list) supersampled_indexes = np.zeros((numPix, numPix), dtype=bool) kwargs_numerics = {'supersampling_factor': 4} imageModel = ImageModel(data_class, psf_class, lens_light_model_class=lightModel, kwargs_numerics=kwargs_numerics) flux_mis_list = [] flux_truth_list = [] # for folder in folder_list: for folder in [folder_list[0]]: key = folder kwargs_truth_i = result_dic[key][0] kwargs_truth_light = kwargs_truth_i['kwargs_lens_light'] kwargs_result_i = result_dic[key][1] kwargs_result_light = kwargs_result_i['kwargs_lens_light'] image_truth = imageModel.image(kwargs_lens_light=kwargs_truth_light, unconvolved=True) image_result = imageModel.image(kwargs_lens_light=kwargs_result_light, unconvolved=True) kwargs_truth_ps = kwargs_truth_i['kwargs_ps'] x = kwargs_truth_ps['ra_image'] / 0.04 + int(numPix/2) y = kwargs_truth_ps['dec_image'] / 0.04 + int(numPix/2) plt.imshow(( abs(image_truth -image_result )/image_truth ), origin='lower') for i in range(len(x)): plt.plot(x[i], y[i], 'xr') # ax.text(x, x, 'x', fontsize=20, color='k') flux_turth = np.array([image_truth[int(x[i]), int(y[i])] for i in range(len(x))]) flux_result = np.array([image_result[int(x[i]), int(y[i])] for i in range(len(x))]) flux_mis = flux_result - flux_turth flux_mis_list.append(flux_mis) flux_truth_list.append(flux_turth) plt.colorbar()
def main(): args = parse_args() cfg = Config.fromfile(args.config) if args.n_data is not None: cfg.n_data = args.n_data # Seed for reproducibility np.random.seed(cfg.seed) random.seed(cfg.seed) if not os.path.exists(cfg.out_dir): os.makedirs(cfg.out_dir) print("Destination folder: {:s}".format(cfg.out_dir)) else: raise OSError("Destination folder already exists.") # Instantiate PSF models psf_models = get_PSF_models(cfg.psf, cfg.instrument.pixel_scale) n_psf = len(psf_models) # Instantiate ImageData #kwargs_data = sim_util.data_configure_simple(**cfg.image) #image_data = ImageData(**kwargs_data) # Instantiate density models kwargs_model = dict( lens_model_list=[ cfg.bnn_omega.lens_mass.profile, cfg.bnn_omega.external_shear.profile ], source_light_model_list=[cfg.bnn_omega.src_light.profile], ) lens_mass_model = LensModel( lens_model_list=kwargs_model['lens_model_list']) src_light_model = LightModel( light_model_list=kwargs_model['source_light_model_list']) lens_eq_solver = LensEquationSolver(lens_mass_model) lens_light_model = None ps_model = None if 'lens_light' in cfg.components: kwargs_model['lens_light_model_list'] = [ cfg.bnn_omega.lens_light.profile ] lens_light_model = LightModel( light_model_list=kwargs_model['lens_light_model_list']) if 'agn_light' in cfg.components: kwargs_model['point_source_model_list'] = [ cfg.bnn_omega.agn_light.profile ] ps_model = PointSource( point_source_type_list=kwargs_model['point_source_model_list'], fixed_magnification_list=[False]) # Initialize BNN prior bnn_prior = getattr(bnn_priors, cfg.bnn_prior_class)(cfg.bnn_omega, cfg.components) # Initialize dataframe of labels param_list = [] for comp in cfg.components: param_list += [ '{:s}_{:s}'.format(comp, param) for param in bnn_prior.params[cfg.bnn_omega[comp]['profile']] ] if 'agn_light' in cfg.components: param_list += ['magnification_{:d}'.format(i) for i in range(4)] param_list += ['x_image_{:d}'.format(i) for i in range(4)] param_list += ['y_image_{:d}'.format(i) for i in range(4)] param_list += ['n_img'] param_list += ['img_path', 'total_magnification'] if cfg.bnn_prior_class == 'EmpiricalBNNPrior': param_list += [ 'z_lens', 'z_src', 'vel_disp_iso', 'R_eff_lens', 'R_eff_src', 'abmag_src' ] metadata = pd.DataFrame(columns=param_list) print("Starting simulation...") current_idx = 0 # running idx of dataset pbar = tqdm(total=cfg.n_data) while current_idx < cfg.n_data: psf_model = psf_models[current_idx % n_psf] sample = bnn_prior.sample() # FIXME: sampling in batches if sample['lens_mass']['theta_E'] < cfg.selection.theta_E.min: continue # Instantiate SimAPI (converts mag to amp and wraps around image model) kwargs_detector = util.merge_dicts(cfg.instrument, cfg.bandpass, cfg.observation) kwargs_detector.update( seeing=cfg.psf.fwhm, psf_type=cfg.psf.type, kernel_point_source=psf_model ) # keyword deprecation warning: I asked Simon to change this to data_api = DataAPI(cfg.image.num_pix, **kwargs_detector) image_data = data_api.data_class #sim_api = SimAPI(numpix=cfg.image.num_pix, # kwargs_single_band=kwargs_detector, # kwargs_model=kwargs_model, # kwargs_numerics=cfg.numerics) kwargs_lens_mass = [sample['lens_mass'], sample['external_shear']] kwargs_src_light = [sample['src_light']] kwargs_src_light = amp_to_mag_extended(kwargs_src_light, src_light_model, data_api) kwargs_lens_light = None kwargs_ps = None if 'agn_light' in cfg.components: x_image, y_image = lens_eq_solver.findBrightImage( sample['src_light']['center_x'], sample['src_light']['center_y'], kwargs_lens_mass, numImages=4, min_distance=cfg.instrument.pixel_scale, search_window=cfg.image.num_pix * cfg.instrument.pixel_scale) magnification = np.abs( lens_mass_model.magnification(x_image, y_image, kwargs=kwargs_lens_mass)) unlensed_mag = sample['agn_light']['magnitude'] # unlensed agn mag kwargs_unlensed_mag_ps = [{ 'ra_image': x_image, 'dec_image': y_image, 'magnitude': unlensed_mag }] # note unlensed magnitude kwargs_unlensed_amp_ps = amp_to_mag_point( kwargs_unlensed_mag_ps, ps_model, data_api) # note unlensed amp kwargs_ps = copy.deepcopy(kwargs_unlensed_amp_ps) for kw in kwargs_ps: kw.update(point_amp=kw['point_amp'] * magnification) else: kwargs_unlensed_amp_ps = None if 'lens_light' in cfg.components: kwargs_lens_light = [sample['lens_light']] kwargs_lens_light = amp_to_mag_extended(kwargs_lens_light, lens_light_model, data_api) # Instantiate image model image_model = ImageModel(image_data, psf_model, lens_mass_model, src_light_model, lens_light_model, ps_model, kwargs_numerics=cfg.numerics) # Compute magnification lensed_total_flux = get_lensed_total_flux(kwargs_lens_mass, kwargs_src_light, kwargs_lens_light, kwargs_ps, image_model) unlensed_total_flux = get_unlensed_total_flux(kwargs_src_light, src_light_model, kwargs_unlensed_amp_ps, ps_model) total_magnification = lensed_total_flux / unlensed_total_flux # Apply magnification cut if total_magnification < cfg.selection.magnification.min: continue # Generate image for export img = image_model.image(kwargs_lens_mass, kwargs_src_light, kwargs_lens_light, kwargs_ps) #kwargs_in_amp = sim_api.magnitude2amplitude(kwargs_lens_mass, kwargs_src_light, kwargs_lens_light, kwargs_ps) #imsim_api = sim_api.image_model_class #imsim_api.image(*kwargs_in_amp) # Add noise noise = data_api.noise_for_model(img, background_noise=True, poisson_noise=True, seed=None) img += noise # Save image file img_path = os.path.join(cfg.out_dir, 'X_{0:07d}.npy'.format(current_idx + 1)) np.save(img_path, img) # Save labels meta = {} for comp in cfg.components: for param_name, param_value in sample[comp].items(): meta['{:s}_{:s}'.format(comp, param_name)] = param_value if 'agn_light' in cfg.components: n_img = len(x_image) for i in range(n_img): meta['magnification_{:d}'.format(i)] = magnification[i] meta['x_image_{:d}'.format(i)] = x_image[i] meta['y_image_{:d}'.format(i)] = y_image[i] meta['n_img'] = n_img if cfg.bnn_prior_class == 'EmpiricalBNNPrior': for misc_name, misc_value in sample['misc'].items(): meta['{:s}'.format(misc_name)] = misc_value meta['total_magnification'] = total_magnification meta['img_path'] = img_path metadata = metadata.append(meta, ignore_index=True) # Update progress current_idx += 1 pbar.update(1) pbar.close() # Fix column ordering metadata = metadata[param_list] metadata_path = os.path.join(cfg.out_dir, 'metadata.csv') metadata.to_csv(metadata_path, index=None) print("Labels include: ", metadata.columns.values)
min_distance=deltaPix, search_window=numPix * deltaPix) mag = lens_model_class.magnification(x_image, y_image, kwargs=kwargs_lens) kwargs_ps = [{'ra_image': x_image, 'dec_image': y_image, 'point_amp': np.abs(mag)*mag_agn[mag_agn_seed]}] # quasar point source position in the source plane and intrinsic brightness point_source_list = ['LENSED_POSITION'] point_source_class = PointSource(point_source_type_list=point_source_list, fixed_magnification_list=[False]) kwargs_numerics = {'supersampling_factor': 1} imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) # generate image image_sim = imageModel.image(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps) poisson = image_util.add_poisson(image_sim, exp_time=exp_time) bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg) image_sim = image_sim + bkg + poisson #image_sim = add_noise(image_sim, kwargs_band =DES_survey_noise)#image_sim# + bkg + poisson data_class.update_data(image_sim) kwargs_data['image_data'] = image_sim kwargs_model = {'lens_model_list': lens_model_list, 'lens_light_model_list': lens_light_model_list, 'source_light_model_list': source_model_list, 'point_source_model_list': point_source_list } full_band_images[:, :, color_idx] += image_sim
'R_sersic': disk_reff, 'e1': e1_1, 'e2': e2_1, 'center_x': center_x + np.random.uniform(-0.1, 0.1) * deltaPix, 'center_y': center_y + np.random.uniform(-0.1, 0.1) * deltaPix } #!!! # kwargs_host_medi = [kwargs_bulge, kwargs_disk] imageModel = ImageModel(data_class, psf_class, lens_light_model_class=lightModel, point_source_class=pointSource, kwargs_numerics=kwargs_numerics) medi_bluge_flux = np.sum( imageModel.image(kwargs_lens_light=[kwargs_bulge], unconvolved=True)) medi_disk_flux = np.sum( imageModel.image(kwargs_lens_light=[kwargs_disk], unconvolved=True)) kwargs_bulge['amp'] = 1. / medi_bluge_flux * bulge_flux kwargs_disk['amp'] = 1. / medi_disk_flux * disk_flux # ## simulate image with the parameters we have defined above # bulge_image = imageModel.image(kwargs_lens_light=[kwargs_bulge], kwargs_ps=[{ 'ra_image': [center_x], 'dec_image': [center_y], 'point_amp': [0] }], unconvolved=False) disk_image = imageModel.image(kwargs_lens_light=[kwargs_disk],
class TestImageModel(object): """ tests the source model routines """ def setup(self): self.SimAPI = Simulation() # data specifics sigma_bkg = .05 # 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.5 # full width half max of PSF # PSF specification kwargs_data = self.SimAPI.data_configure(numPix, deltaPix, exp_time, sigma_bkg) data_class = Data(kwargs_data) kwargs_psf = self.SimAPI.psf_configure(psf_type='GAUSSIAN', fwhm=fwhm, kernelsize=31, deltaPix=deltaPix, truncate=3, kernel=None) psf_class = PSF(kwargs_psf) psf_class._psf_error_map = np.zeros_like(psf_class.kernel_point_source) # '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.01, 'dec_source': 0.0, 'source_amp': 1.}] # 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': 2, '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 = self.SimAPI.simulate(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.solver = LensEquationSolver(lensModel=self.imageModel.LensModel) def test_source_surface_brightness(self): source_model = self.imageModel.source_surface_brightness(self.kwargs_source, self.kwargs_lens, unconvolved=False, de_lensed=False) assert len(source_model) == 100 npt.assert_almost_equal(source_model[10, 10], 0.13939841209844345, decimal=4) source_model = self.imageModel.source_surface_brightness(self.kwargs_source, self.kwargs_lens, unconvolved=True, de_lensed=False) assert len(source_model) == 100 npt.assert_almost_equal(source_model[10, 10], 0.13536114618182182, decimal=4) def test_lens_surface_brightness(self): lens_flux = self.imageModel.lens_surface_brightness(self.kwargs_lens_light, unconvolved=False) npt.assert_almost_equal(lens_flux[50, 50], 0.54214440654021534, decimal=4) lens_flux = self.imageModel.lens_surface_brightness(self.kwargs_lens_light, unconvolved=True) npt.assert_almost_equal(lens_flux[50, 50], 4.7310552067454452, decimal=4) def test_image_linear_solve(self): model, error_map, cov_param, param = self.imageModel.image_linear_solve(self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, inv_bool=False) chi2_reduced = self.imageModel.reduced_chi2(model, error_map) npt.assert_almost_equal(chi2_reduced, 1, decimal=1) def test_image_with_params(self): model = self.imageModel.image(self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, unconvolved=False, source_add=True, lens_light_add=True, point_source_add=True) error_map = self.imageModel.error_map(self.kwargs_lens, self.kwargs_ps) chi2_reduced = self.imageModel.reduced_chi2(model, error_map) npt.assert_almost_equal(chi2_reduced, 1, decimal=1) def test_point_sources_list(self): point_source_list = self.imageModel.point_sources_list(self.kwargs_ps, self.kwargs_lens) assert len(point_source_list) == 4 def test_image_positions(self): x_im, y_im = self.imageModel.image_positions(self.kwargs_ps, self.kwargs_lens) ra_pos, dec_pos = self.solver.image_position_from_source(sourcePos_x=self.kwargs_ps[0]['ra_source'], sourcePos_y=self.kwargs_ps[0]['dec_source'], kwargs_lens=self.kwargs_lens) ra_pos_new = x_im[0] print(ra_pos_new, ra_pos) npt.assert_almost_equal(ra_pos_new[0], ra_pos[0], decimal=8) npt.assert_almost_equal(ra_pos_new[1], ra_pos[1], decimal=8) npt.assert_almost_equal(ra_pos_new[2], ra_pos[2], decimal=8) npt.assert_almost_equal(ra_pos_new[3], ra_pos[3], decimal=8) def test_likelihood_data_given_model(self): logL = self.imageModel.likelihood_data_given_model(self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, source_marg=False) npt.assert_almost_equal(logL, -5000, decimal=-3) logLmarg = self.imageModel.likelihood_data_given_model(self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, source_marg=True) npt.assert_almost_equal(logL - logLmarg, 0, decimal=-3) def test_reduced_residuals(self): model = self.SimAPI.simulate(self.imageModel, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps, no_noise=True) residuals = self.imageModel.reduced_residuals(model, error_map=0) npt.assert_almost_equal(np.std(residuals), 1.01, decimal=1) chi2 = self.imageModel.reduced_chi2(model, error_map=0) npt.assert_almost_equal(chi2, 1, decimal=1) def test_numData_evaluate(self): numData = self.imageModel.numData_evaluate() assert numData == 10000 def test_fermat_potential(self): phi_fermat = self.imageModel.fermat_potential(self.kwargs_lens, self.kwargs_ps) print(phi_fermat) npt.assert_almost_equal(phi_fermat[0][0], -0.2630531731871062, decimal=3) npt.assert_almost_equal(phi_fermat[0][1], -0.2809100018126987, decimal=3) npt.assert_almost_equal(phi_fermat[0][2], -0.5086643370512096, decimal=3) npt.assert_almost_equal(phi_fermat[0][3], -0.5131716608238992, decimal=3) def test_add_mask(self): mask = np.array([[0, 1],[1, 0]]) A = np.ones((10, 4)) A_masked = self.imageModel._add_mask(A, mask) assert A[0, 1] == A_masked[0, 1] assert A_masked[0, 3] == 0 def test_point_source_rendering(self): # initialize data from lenstronomy.SimulationAPI.simulations import Simulation SimAPI = Simulation() numPix = 100 deltaPix = 0.05 kwargs_data = SimAPI.data_configure(numPix, deltaPix, exposure_time=1, sigma_bkg=1) data_class = Data(kwargs_data) kernel = np.zeros((5, 5)) kernel[2, 2] = 1 kwargs_psf = {'kernel_point_source': kernel, 'kernel_pixel': kernel, 'psf_type': 'PIXEL'} psf_class = PSF(kwargs_psf) lens_model_class = LensModel(['SPEP']) source_model_class = LightModel([]) lens_light_model_class = LightModel([]) kwargs_numerics = {'subgrid_res': 2, 'point_source_subgrid': 1} point_source_class = PointSource(point_source_type_list=['LENSED_POSITION'], fixed_magnification_list=[False]) makeImage = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) # chose point source positions x_pix = np.array([10, 5, 10, 90]) y_pix = np.array([40, 50, 60, 50]) ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix) e1, e2 = param_util.phi_q2_ellipticity(0, 0.8) kwargs_lens_init = [{'theta_E': 1, 'gamma': 2, 'e1': e1, 'e2': e2, 'center_x': 0, 'center_y': 0}] kwargs_else = [{'ra_image': ra_pos, 'dec_image': dec_pos, 'point_amp': np.ones_like(ra_pos)}] model = makeImage.image(kwargs_lens_init, kwargs_source={}, kwargs_lens_light={}, kwargs_ps=kwargs_else) image = makeImage.ImageNumerics.array2image(model) for i in range(len(x_pix)): npt.assert_almost_equal(image[y_pix[i], x_pix[i]], 1, decimal=2) x_pix = np.array([10.5, 5.5, 10.5, 90.5]) y_pix = np.array([40, 50, 60, 50]) ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix) phi, q = 0., 0.8 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_lens_init = [{'theta_E': 1, 'gamma': 2, 'e1': e1, 'e2': e2, 'center_x': 0, 'center_y': 0}] kwargs_else = [{'ra_image': ra_pos, 'dec_image': dec_pos, 'point_amp': np.ones_like(ra_pos)}] model = makeImage.image(kwargs_lens_init, kwargs_source={}, kwargs_lens_light={}, kwargs_ps=kwargs_else) image = makeImage.ImageNumerics.array2image(model) for i in range(len(x_pix)): print(int(y_pix[i]), int(x_pix[i]+0.5)) npt.assert_almost_equal(image[int(y_pix[i]), int(x_pix[i])], 0.5, decimal=1) npt.assert_almost_equal(image[int(y_pix[i]), int(x_pix[i]+0.5)], 0.5, decimal=1)
class Imager: """Deterministic utility class for imaging the objects on a pixel grid Attributes ---------- bnn_omega : dict copy of `cfg.bnn_omega` components : list list of components, e.g. `lens_mass` """ def __init__(self, components, lens_mass_model, src_light_model, lens_light_model=None, ps_model=None, kwargs_numerics={'supersampling_factor': 1}, min_magnification=0.0, for_cosmography=False, magnification_frac_err=0.0): self.components = components self.kwargs_numerics = kwargs_numerics self.lens_mass_model = lens_mass_model self.src_light_model = src_light_model self.lens_light_model = lens_light_model self.ps_model = ps_model self.unlensed_ps_model = PointSource(point_source_type_list=['SOURCE_POSITION'], fixed_magnification_list=[False]) self.lens_eq_solver = LensEquationSolver(self.lens_mass_model) self.min_magnification = min_magnification self.for_cosmography = for_cosmography self.magnification_frac_err = magnification_frac_err self.img_features = {} # Initialized to store metadata of images, will get updated for each lens def _set_sim_api(self, num_pix, kwargs_detector, psf_kernel_size, which_psf_maps): """Set the simulation API objects """ self.data_api = DataAPI(num_pix, **kwargs_detector) #self.pixel_scale = data_api.pixel_scale pixel_scale = kwargs_detector['pixel_scale'] psf_model = psf_utils.get_PSF_model(kwargs_detector['psf_type'], pixel_scale, seeing=kwargs_detector['seeing'], kernel_size=psf_kernel_size, which_psf_maps=which_psf_maps) # Set the precision level of lens equation solver self.min_distance = 0.05 self.search_window = pixel_scale*num_pix self.image_model = ImageModel(self.data_api.data_class, psf_model, self.lens_mass_model, self.src_light_model, self.lens_light_model, self.ps_model, kwargs_numerics=self.kwargs_numerics) if 'agn_light' in self.components: self.unlensed_image_model = ImageModel(self.data_api.data_class, psf_model, None, self.src_light_model, None, self.unlensed_ps_model, kwargs_numerics=self.kwargs_numerics) else: self.unlensed_image_model = ImageModel(self.data_api.data_class, psf_model, None, self.src_light_model, None, None, kwargs_numerics=self.kwargs_numerics) def _load_kwargs(self, sample): """Generate an image from provided model and model parameters Parameters ---------- sample : dict model parameters sampled by a bnn_prior object """ self._load_lens_mass_kwargs(sample['lens_mass'], sample['external_shear']) self._load_src_light_kwargs(sample['src_light']) if 'lens_light' in self.components: self._load_lens_light_kwargs(sample['lens_light']) else: self.kwargs_lens_light = None if 'agn_light' in self.components: self._load_agn_light_kwargs(sample) else: self.kwargs_ps = None self.kwargs_unlensed_unmagnified_amp_ps = None def _load_lens_mass_kwargs(self, lens_mass_sample, external_shear_sample): self.kwargs_lens_mass = [lens_mass_sample, external_shear_sample] def _load_src_light_kwargs(self, src_light_sample): kwargs_src_light = [src_light_sample] # Convert from mag to amp self.kwargs_src_light = mag_to_amp_extended(kwargs_src_light, self.src_light_model, self.data_api) def _load_lens_light_kwargs(self, lens_light_sample): kwargs_lens_light = [lens_light_sample] # Convert lens magnitude into amp self.kwargs_lens_light = mag_to_amp_extended(kwargs_lens_light, self.lens_light_model, self.data_api) def _load_agn_light_kwargs(self, sample): """Set the point source kwargs to be ingested by Lenstronomy """ # When using the image positions for cosmological parameter recovery, the time delays must be computed by evaluating the Fermat potential at these exact positions. if self.for_cosmography: x_image = sample['misc']['x_image'] y_image = sample['misc']['y_image'] # When the precision of the lens equation solver doesn't have to be matched between image positions and time delays, simply solve for the image positions using whatever desired precision. else: x_image, y_image = self.lens_eq_solver.findBrightImage(self.kwargs_src_light[0]['center_x'], self.kwargs_src_light[0]['center_y'], self.kwargs_lens_mass, min_distance=self.min_distance, search_window=self.search_window, numImages=4, num_iter_max=100, # default is 10 but td_cosmography default is 100 precision_limit=10**(-10) # default for both this and td_cosmography ) agn_light_sample = sample['agn_light'] unlensed_mag = agn_light_sample['magnitude'] # unlensed agn mag # Save the unlensed (source-plane) kwargs in amplitude units kwargs_unlensed_unmagnified_mag_ps = [{'ra_source': self.kwargs_src_light[0]['center_x'], 'dec_source': self.kwargs_src_light[0]['center_y'], 'magnitude': unlensed_mag}] self.kwargs_unlensed_unmagnified_amp_ps = mag_to_amp_point(kwargs_unlensed_unmagnified_mag_ps, self.unlensed_ps_model, self.data_api) # note # Compute the lensed (image-plane), magnified kwargs in amplitude units magnification = self.lens_mass_model.magnification(x_image, y_image, kwargs=self.kwargs_lens_mass) measured_magnification = np.abs(magnification*(1.0 + self.magnification_frac_err*np.random.randn(len(magnification)))) # Add noise to magnification magnification = np.abs(magnification) kwargs_lensed_unmagnified_mag_ps = [{'ra_image': x_image, 'dec_image': y_image, 'magnitude': unlensed_mag}] # note unlensed magnitude kwargs_lensed_unmagnified_amp_ps = mag_to_amp_point(kwargs_lensed_unmagnified_mag_ps, self.ps_model, self.data_api) # note unmagnified amp self.kwargs_ps = copy.deepcopy(kwargs_lensed_unmagnified_amp_ps) for kw in self.kwargs_ps: kw.update(point_amp=kw['point_amp']*measured_magnification) # Log the solved image positions self.img_features.update(x_image=x_image, y_image=y_image, magnification=magnification, measured_magnification=measured_magnification) def generate_image(self, sample, num_pix, survey_object_dict): img_canvas = np.empty([len(survey_object_dict), num_pix, num_pix]) # [n_filters, num_pix, num_pix] # Loop over bands for i, (bp, survey_object) in enumerate(survey_object_dict.items()): self._set_sim_api(num_pix, survey_object.kwargs_single_band(), survey_object.psf_kernel_size, survey_object.which_psf_maps) self._load_kwargs(sample) # Reject nonsensical number of images (due to insufficient numerical precision) if ('y_image' in self.img_features) and (len(self.img_features['y_image']) not in [2, 4]): return None, None # Compute magnification lensed_total_flux = get_lensed_total_flux(self.kwargs_lens_mass, self.kwargs_src_light, self.kwargs_ps, self.image_model) #unlensed_total_flux = get_unlensed_total_flux(self.kwargs_src_light, self.src_light_model, self.kwargs_unlensed_amp_ps, self.ps_model) unlensed_total_flux = get_unlensed_total_flux_numerical(self.kwargs_src_light, self.kwargs_unlensed_unmagnified_amp_ps, self.unlensed_image_model) total_magnification = lensed_total_flux/unlensed_total_flux # Apply magnification cut if (total_magnification < self.min_magnification) or np.isnan(total_magnification): return None, None # Generate image for export img = self.image_model.image(self.kwargs_lens_mass, self.kwargs_src_light, self.kwargs_lens_light, self.kwargs_ps) img = np.maximum(0.0, img) # safeguard against negative pixel values img_canvas[i, :, :] = img # Save remaining image features img_features_single_band = {f'total_magnification_{bp}': total_magnification, f'lensed_total_flux_{bp}': lensed_total_flux, f'unlensed_total_flux_{bp}': unlensed_total_flux} self.img_features.update(img_features_single_band) return img_canvas, self.img_features def add_noise(self, image_array): """Add noise to the image (deprecated; replaced by the data_augmentation package) """ #noise_map = self.data_api.noise_for_model(image_array, background_noise=True, poisson_noise=True, seed=None) #image_array += noise_map #return image_array pass
def generate_image(sample, psf_model, data_api, lens_mass_model, src_light_model, lens_eq_solver, pixel_scale, num_pix, components, kwargs_numerics, min_magnification=0.0, lens_light_model=None, ps_model=None): """Generate an image from provided model and model parameters Parameters ---------- sample : dict sampled model parameters psf_models : lenstronomy PSF object the PSF kernel point source map data_api : lenstronomy DataAPI object tool that handles detector and observation conditions Returns ------- tuple of (np.array, dict) the image and its features """ img_features = dict() image_data = data_api.data_class kwargs_lens_mass = [sample['lens_mass'], sample['external_shear']] kwargs_src_light = [sample['src_light']] kwargs_src_light = amp_to_mag_extended(kwargs_src_light, src_light_model, data_api) img_features['src_light_amp'] = kwargs_src_light[0]['amp'] kwargs_lens_light = None kwargs_ps = None # Add AGN point source metadata if 'agn_light' in components: x_image, y_image = lens_eq_solver.findBrightImage( sample['src_light']['center_x'], sample['src_light']['center_y'], kwargs_lens_mass, numImages=4, min_distance=pixel_scale, search_window=num_pix * pixel_scale) magnification = np.abs( lens_mass_model.magnification(x_image, y_image, kwargs=kwargs_lens_mass)) unlensed_mag = sample['agn_light']['magnitude'] # unlensed agn mag kwargs_unlensed_mag_ps = [{ 'ra_image': x_image, 'dec_image': y_image, 'magnitude': unlensed_mag }] # note unlensed magnitude kwargs_unlensed_amp_ps = amp_to_mag_point( kwargs_unlensed_mag_ps, ps_model, data_api) # note unlensed amp kwargs_ps = copy.deepcopy(kwargs_unlensed_amp_ps) for kw in kwargs_ps: kw.update(point_amp=kw['point_amp'] * magnification) img_features['x_image'] = x_image img_features['y_image'] = y_image else: kwargs_unlensed_amp_ps = None # Add lens light metadata if 'lens_light' in components: kwargs_lens_light = [sample['lens_light']] kwargs_lens_light = amp_to_mag_extended(kwargs_lens_light, lens_light_model, data_api) # Instantiate image model image_model = ImageModel(image_data, psf_model, lens_mass_model, src_light_model, lens_light_model, ps_model, kwargs_numerics=kwargs_numerics) # Compute magnification lensed_total_flux = get_lensed_total_flux(kwargs_lens_mass, kwargs_src_light, kwargs_lens_light, kwargs_ps, image_model) unlensed_total_flux = get_unlensed_total_flux(kwargs_src_light, src_light_model, kwargs_unlensed_amp_ps, ps_model) total_magnification = lensed_total_flux / unlensed_total_flux # Apply magnification cut if total_magnification < min_magnification: return None, None # Generate image for export img = image_model.image(kwargs_lens_mass, kwargs_src_light, kwargs_lens_light, kwargs_ps) # Add noise #if add_noise: # noise = data_api.noise_for_model(img, background_noise=True, poisson_noise=True, seed=None) # img += noise img = np.maximum(0.0, img) # safeguard against negative pixel values # Save remaining image features img_features['total_magnification'] = total_magnification return img, img_features
kwargs_light = [kwargs_1] # here we super-sample the resolution of some of the pixels where the surface brightness profile has a high gradient supersampled_indexes = np.zeros((numPix, numPix), dtype=bool) supersampled_indexes[23:27, 23:27] = True kwargs_numerics = { 'supersampling_factor': 4, 'compute_mode': 'adaptive', 'supersampled_indexes': supersampled_indexes } from lenstronomy.ImSim.image_model import ImageModel imageModel = ImageModel(data_class, psf_class, lens_light_model_class=lightModel, kwargs_numerics=kwargs_numerics) image_sim = imageModel.image(kwargs_lens_light=kwargs_light) poisson = image_util.add_poisson(image_sim, exp_time=exp_time) bkg = image_util.add_background(image_sim, sigma_bkd=background_rms) image_noisy = image_sim + bkg + poisson plt.imshow(image_noisy, origin='lower') plt.show() #%% from galight.data_process import DataProcess from galight.fitting_specify import FittingSpecify from galight.fitting_process import FittingProcess data_process = DataProcess(fov_image=image_noisy, target_pos=[25, 25], pos_type='pixel', exptime=100, rm_bkglight=False,
class TestLensingOperator(object): """ tests the Lensing Operator class """ def setup(self): self.num_pix = 25 # cutout pixel size 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) kwargs_data = { #'background_rms': background_rms, #'exposure_time': np.ones((self.num_pix, self.num_pix)) * exp_time, # individual exposure time/weight per pixel 'ra_at_xy_0': ra_at_xy_0, 'dec_at_xy_0': dec_at_xy_0, 'transform_pix2angle': Mpix2coord, 'image_data': np.zeros((self.num_pix, self.num_pix)) } self.data = ImageData(**kwargs_data) self.lens_model = LensModel(['SPEP']) self.kwargs_lens = [{ 'theta_E': 1, 'gamma': 2, 'center_x': 0, 'center_y': 0, 'e1': -0.05, 'e2': 0.05 }] self.kwargs_lens_null = [{ 'theta_E': 0, 'gamma': 2, 'center_x': 0, 'center_y': 0, 'e1': 0, 'e2': 0 }] # PSF specification kwargs_psf = {'psf_type': 'NONE'} self.psf = PSF(**kwargs_psf) # list of source light profiles source_model_list = ['SERSIC_ELLIPSE'] kwargs_sersic_ellipse_source = { 'amp': 2000, 'R_sersic': 0.6, 'n_sersic': 1, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.3, 'center_y': 0.3 } kwargs_source = [kwargs_sersic_ellipse_source] source_model = LightModel(light_model_list=source_model_list) # list of lens light profiles lens_light_model_list = [] kwargs_lens_light = [{}] lens_light_model = LightModel(light_model_list=lens_light_model_list) kwargs_numerics = { 'supersampling_factor': 1, 'supersampling_convolution': False } self.image_model = ImageModel(self.data, self.psf, self.lens_model, source_model, lens_light_model, point_source_class=None, kwargs_numerics=kwargs_numerics) self.image_grid_class = self.image_model.ImageNumerics.grid_class self.source_grid_class_default = NumericsSubFrame(self.data, self.psf).grid_class # create simulated image image_sim_no_noise = self.image_model.image(self.kwargs_lens, kwargs_source, kwargs_lens_light) self.source_light_lensed = image_sim_no_noise self.data.update_data(image_sim_no_noise) # source only, in source plane, on same grid as data self.source_light_delensed = self.image_model.source_surface_brightness( kwargs_source, unconvolved=False, de_lensed=True) # define some auto mask for tests self.likelihood_mask = np.zeros_like(self.source_light_lensed) self.likelihood_mask[self.source_light_lensed > 0.1 * self.source_light_lensed.max()] = 1 def test_matrix_product(self): lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest_legacy') lensing_op.update_mapping(self.kwargs_lens) lensing_op_mat = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest') lensing_op_mat.update_mapping(self.kwargs_lens) source_1d = util.image2array(self.source_light_delensed) image_1d = util.image2array(self.source_light_lensed) npt.assert_equal(lensing_op.source2image(source_1d), lensing_op_mat.source2image(source_1d)) npt.assert_equal(lensing_op.image2source(image_1d), lensing_op_mat.image2source(image_1d)) def test_minimal_source_plane(self): source_1d = util.image2array(self.source_light_delensed) # test with no mask lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest', minimal_source_plane=True) lensing_op.update_mapping(self.kwargs_lens) image_1d = util.image2array(self.source_light_lensed) assert lensing_op.image2source(image_1d).size < source_1d.size # test with mask lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest', minimal_source_plane=True) lensing_op.set_likelihood_mask(self.likelihood_mask) lensing_op.update_mapping(self.kwargs_lens) image_1d = util.image2array(self.source_light_lensed) assert lensing_op.image2source(image_1d).size < source_1d.size # for 'bilinear' operator, only works with no mask (for now) lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='bilinear', minimal_source_plane=True) lensing_op.update_mapping(self.kwargs_lens) image_1d = util.image2array(self.source_light_lensed) assert lensing_op.image2source(image_1d).size < source_1d.size def test_legacy_mapping(self): """testing than image2source / source2image are close to the parametric mapping""" lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest_legacy') lensing_op.update_mapping(self.kwargs_lens) source_1d = util.image2array(self.source_light_delensed) image_1d = util.image2array(self.source_light_lensed) source_1d_lensed = lensing_op.source2image(source_1d) image_1d_delensed = lensing_op.image2source(image_1d) assert source_1d_lensed.shape == image_1d.shape assert image_1d_delensed.shape == source_1d.shape npt.assert_almost_equal(source_1d_lensed / source_1d_lensed.max(), image_1d / image_1d.max(), decimal=0.6) npt.assert_almost_equal(image_1d_delensed / image_1d_delensed.max(), source_1d / source_1d.max(), decimal=0.6) def test_simple_mapping(self): """testing than image2source / source2image are close to the parametric mapping""" lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest') lensing_op.update_mapping(self.kwargs_lens) source_1d = util.image2array(self.source_light_delensed) image_1d = util.image2array(self.source_light_lensed) source_1d_lensed = lensing_op.source2image(source_1d) image_1d_delensed = lensing_op.image2source(image_1d) assert source_1d_lensed.shape == image_1d.shape assert image_1d_delensed.shape == source_1d.shape npt.assert_almost_equal(source_1d_lensed / source_1d_lensed.max(), image_1d / image_1d.max(), decimal=0.6) npt.assert_almost_equal(image_1d_delensed / image_1d_delensed.max(), source_1d / source_1d.max(), decimal=0.6) def test_interpol_mapping(self): """testing than image2source / source2image are close to the parametric mapping""" lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='bilinear') lensing_op.update_mapping(self.kwargs_lens) source_1d = util.image2array(self.source_light_delensed) image_1d = util.image2array(self.source_light_lensed) source_1d_lensed = lensing_op.source2image(source_1d) image_1d_delensed = lensing_op.image2source(image_1d) assert source_1d_lensed.shape == image_1d.shape assert image_1d_delensed.shape == source_1d.shape npt.assert_almost_equal(source_1d_lensed / source_1d_lensed.max(), image_1d / image_1d.max(), decimal=0.8) npt.assert_almost_equal(image_1d_delensed / image_1d_delensed.max(), source_1d / source_1d.max(), decimal=0.8) def test_source2image(self): lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix) source_1d = util.image2array(self.source_light_delensed) source_1d_lensed = lensing_op.source2image( source_1d, kwargs_lens=self.kwargs_lens) assert len(source_1d_lensed.shape) == 1 source_2d = self.source_light_delensed source_2d_lensed = lensing_op.source2image_2d( source_2d, kwargs_lens=self.kwargs_lens, update_mapping=True) assert len(source_2d_lensed.shape) == 2 def test_image2source(self): lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix) image_1d = util.image2array(self.source_light_lensed) image_1d_delensed = lensing_op.image2source( image_1d, kwargs_lens=self.kwargs_lens) assert len(image_1d_delensed.shape) == 1 image_2d = self.source_light_lensed image_2d_delensed = lensing_op.image2source_2d( image_2d, kwargs_lens=self.kwargs_lens, update_mapping=True) assert len(image_2d_delensed.shape) == 2 def test_source_plane_coordinates(self): lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix) theta_x, theta_y = lensing_op.source_plane_coordinates assert theta_x.size == self.num_pix**2 assert theta_y.size == self.num_pix**2 subgrid_res = 2 source_grid_class = NumericsSubFrame( self.data, self.psf, supersampling_factor=subgrid_res).grid_class lensing_op = LensingOperator(self.lens_model, self.image_grid_class, source_grid_class, self.num_pix) theta_x, theta_y = lensing_op.source_plane_coordinates assert theta_x.size == self.num_pix**2 * subgrid_res**2 assert theta_y.size == self.num_pix**2 * subgrid_res**2 def test_image_plane_coordinates(self): lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix) theta_x, theta_y = lensing_op.image_plane_coordinates assert theta_x.size == self.num_pix**2 assert theta_y.size == self.num_pix**2 def test_find_source_pixel(self): lensing_op = LensingOperator(self.lens_model, self.image_grid_class, self.source_grid_class_default, self.num_pix, source_interpolation='nearest') beta_x, beta_y = self.lens_model.ray_shooting( lensing_op.imagePlane.theta_x, lensing_op.imagePlane.theta_y, self.kwargs_lens) i = 10 j = lensing_op._find_source_pixel_nearest_legacy(i, beta_x, beta_y) assert (isinstance(j, int) or isinstance(j, np.int64))
def generate_lens(sigma_bkg=sigma_bkg, exp_time=exp_time, numPix=numPix, deltaPix=deltaPix, fwhm=fwhm, psf_type=psf_type, kernel_size=kernel_size, z_source=z_source, z_lens=z_lens, phi_ext=phi_ext, gamma_ext=gamma_ext, theta_E=theta_E, gamma_lens=gamma_lens, e1_lens=e1_lens, e2_lens=e2_lens, center_x_lens_light=center_x_lens_light, center_y_lens_light=center_y_lens_light, source_x=source_y, source_y=source_y, q_source=q_source, phi_source=phi_source, center_x=center_x, center_y=center_y, amp_source=amp_source, R_sersic_source=R_sersic_source, n_sersic_source=n_sersic_source, phi_lens_light=phi_lens_light, q_lens_light=q_lens_light, amp_lens=amp_lens, R_sersic_lens=R_sersic_lens, n_sersic_lens=n_sersic_lens, amp_ps=amp_ps, supersampling_factor=supersampling_factor, v_min=v_min, v_max=v_max, cosmo=cosmo, cosmo2=cosmo2, lens_pos_eq_lens_light_pos=True, same_cosmology=True): kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) data_class = ImageData(**kwargs_data) kwargs_psf = {'psf_type': psf_type, 'pixel_size': deltaPix, 'fwhm': fwhm} psf_class = PSF(**kwargs_psf) cosmo = FlatLambdaCDM(H0=75, Om0=0.3, Ob0=0.) cosmo = FlatLambdaCDM(H0=65, Om0=0.3, Ob0=0.) gamma1, gamma2 = param_util.shear_polar2cartesian(phi=phi_ext, gamma=gamma_ext) kwargs_shear = {'gamma1': gamma1, 'gamma2': gamma2} if lens_pos_eq_lens_light_pos: center_x = center_x_lens_light center_y = center_y_lens_light if same_cosmology: cosmo2 = cosmo kwargs_spemd = { 'theta_E': theta_E, 'gamma': gamma_lens, 'center_x': center_x, 'center_y': center_y, 'e1': e1_lens, 'e2': e2_lens } lens_model_list = ['SPEP', 'SHEAR'] kwargs_lens = [kwargs_spemd, kwargs_shear] lens_model_class = LensModel(lens_model_list=lens_model_list, z_lens=z_lens, z_source=z_source, cosmo=cosmo) lens_model_class2 = LensModel(lens_model_list=lens_model_list, z_lens=z_lens, z_source=z_source, cosmo=cosmo2) e1_source, e2_source = param_util.phi_q2_ellipticity(phi_source, q_source) kwargs_sersic_source = { 'amp': amp_source, 'R_sersic': R_sersic_source, 'n_sersic': n_sersic_source, 'e1': e1_source, 'e2': e2_source, 'center_x': source_x, 'center_y': source_y } source_model_list = ['SERSIC_ELLIPSE'] kwargs_source = [kwargs_sersic_source] source_model_class = LightModel(light_model_list=source_model_list) ## e1_lens_light, e2_lens_light = param_util.phi_q2_ellipticity( phi_lens_light, q_lens_light) kwargs_sersic_lens = { 'amp': amp_lens, 'R_sersic': R_sersic_lens, 'n_sersic': n_sersic_lens, 'e1': e1_lens_light, 'e2': e2_lens_light, 'center_x': center_x_lens_light, 'center_y': center_y_lens_light } lens_light_model_list = ['SERSIC_ELLIPSE'] kwargs_lens_light = [kwargs_sersic_lens] lens_light_model_class = LightModel(light_model_list=lens_light_model_list) ## lensEquationSolver = LensEquationSolver(lens_model_class) x_image, y_image = lensEquationSolver.findBrightImage( source_x, source_y, #position of ps kwargs_lens, #lens proporties numImages=4, #expected number of images min_distance=deltaPix, #'resolution' search_window=numPix * deltaPix) #search window limits mag = lens_model_class.magnification( x_image, y_image, #for found above ps positions kwargs=kwargs_lens) # and same lens properties kwargs_ps = [{ 'ra_image': x_image, 'dec_image': y_image, 'point_amp': np.abs(mag) * amp_ps }] point_source_list = ['LENSED_POSITION'] point_source_class = PointSource(point_source_type_list=point_source_list, fixed_magnification_list=[False]) kwargs_numerics = {'supersampling_factor': supersampling_factor} imageModel = ImageModel( data_class, # take generated above data specs psf_class, # same for psf lens_model_class, # lens model (gal+ext) source_model_class, # sourse light model lens_light_model_class, # lens light model point_source_class, # add generated ps images kwargs_numerics=kwargs_numerics) image_sim = imageModel.image(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps) poisson = image_util.add_poisson(image_sim, exp_time=exp_time) bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg) image_sim = image_sim + bkg + poisson data_class.update_data(image_sim) kwargs_data['image_data'] = image_sim cmap_string = 'gray' cmap = plt.get_cmap(cmap_string) cmap.set_bad(color='b', alpha=1.) cmap.set_under('k') f, axes = plt.subplots(1, 1, figsize=(6, 6), sharex=False, sharey=False) ax = axes im = ax.matshow(np.log10(image_sim), origin='lower', vmin=v_min, vmax=v_max, cmap=cmap, extent=[0, 1, 0, 1]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.autoscale(False) plt.show() kwargs_model = { 'lens_model_list': lens_model_list, 'lens_light_model_list': lens_light_model_list, 'source_light_model_list': source_model_list, 'point_source_model_list': point_source_list } from lenstronomy.Analysis.td_cosmography import TDCosmography td_cosmo = TDCosmography(z_lens, z_source, kwargs_model, cosmo_fiducial=cosmo) # time delays, the unit [days] is matched when the lensing angles are in arcsec t_days = td_cosmo.time_delays(kwargs_lens, kwargs_ps, kappa_ext=0) dt_days = t_days[1:] - t_days[0] dt_sigma = [3, 5, 10] # Gaussian errors dt_measured = np.random.normal(dt_days, dt_sigma) print("the measured relative delays are: ", dt_measured) return f, source_model_list, kwargs_data, kwargs_psf, kwargs_numerics, dt_measured, dt_sigma, kwargs_ps, lens_model_list, lens_light_model_list, source_model_list, point_source_list, lens_model_class2
def sim_non_lens_agn(data, center_x_1, center_y_1, center_x_2, center_y_2, numPix=101, sigma_bkg=8.0, exp_time=100.0, deltaPix=0.263, psf_type='GAUSSIAN', kernel_size=91): full_band_images = np.zeros((numPix, numPix, 4)) flux_1 = mag_to_flux(data['source_mag'], 27.5) flux_g_1 = mag_to_flux(data['mag_g'], 27.5) flux_r_1 = mag_to_flux(data['mag_r'], 27.5) flux_i_1 = mag_to_flux(data['mag_i'], 27.5) flux_z_1 = mag_to_flux(data['mag_z'], 27.5) flux_2 = mag_to_flux(data['lens_mag'], 27.5) flux_g_2 = flux_g_1 * flux_2 / flux_1 flux_r_2 = flux_r_1 * flux_2 / flux_1 flux_i_2 = flux_i_1 * flux_2 / flux_1 flux_z_2 = flux_z_1 * flux_2 / flux_1 center_x_list = [center_x_1, center_x_2] center_y_list = [center_y_1, center_y_2] kwargs_gal1 = { 'amp': flux_1, 'R_sersic': data['source_R_sersic'], 'n_sersic': data['source_n_sersic'], 'e1': data['source_e1'], 'e2': data['source_e2'], 'center_x': center_x_1, 'center_y': center_y_1 } kwargs_gal2 = { 'amp': flux_2, 'R_sersic': data['lens_R_sersic'], 'n_sersic': data['lens_n_sersic'], 'center_x': center_x_2, 'center_y': center_y_2 } kwargs_gals = [kwargs_gal1, kwargs_gal2] color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3} cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.) light_model_list = ['SERSIC_ELLIPSE', 'SERSIC'] lightModel = LightModel(light_model_list=light_model_list) ###iterate through bands to simulate images for band in ['g', 'r', 'i', 'z']: #psf info kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) data_class = ImageData(**kwargs_data) kwargs_psf = { 'psf_type': psf_type, 'fwhm': data['psf_%s' % band], 'pixel_size': deltaPix, 'truncation': 3 } psf_class = PSF(**kwargs_psf) point_source_list = ['UNLENSED'] pointSource = PointSource(point_source_type_list=point_source_list) point_amp_list = [eval('flux_%s_1' % band), eval('flux_%s_2' % band)] kwargs_ps = [{ 'ra_image': center_x_list, 'dec_image': center_y_list, 'point_amp': point_amp_list }] kwargs_numerics = { 'supersampling_factor': 1, 'supersampling_convolution': False } imageModel = ImageModel(data_class, psf_class, lens_light_model_class=lightModel, point_source_class=pointSource, kwargs_numerics=kwargs_numerics) # generate image image_sim = imageModel.image(kwargs_lens_light=kwargs_gals, kwargs_ps=kwargs_ps) poisson = image_util.add_poisson(image_sim, exp_time=exp_time) bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg) image_sim = image_sim + bkg + poisson full_band_images[:, :, color_idx[band]] += image_sim return full_band_images