def test_create_empty(self): kwargs_data = sim_util.data_configure_simple(numPix=10, deltaPix=1, exposure_time=1, background_rms=1) data_class = ImageData(**kwargs_data) imageModel_empty = ImageModel(data_class, PSF()) assert imageModel_empty._psf_error_map == False flux = imageModel_empty.lens_surface_brightness(kwargs_lens_light=None) assert flux.all() == 0
def __init__(self, *args, **kwargs): super(TestRaise, self).__init__(*args, **kwargs) # 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 = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg, inverse=True) self.data_class = ImageData(**kwargs_data) kwargs_psf = { 'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncation': 5, 'pixel_size': deltaPix } 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 } self.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_base = [kwargs_sersic] lens_light_model_class_base = LightModel( light_model_list=lens_light_model_list) source_model_list = ['SERSIC_ELLIPSE'] kwargs_source_base = [kwargs_sersic_ellipse] source_model_class_base = 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_base = PointSource( point_source_type_list=['SOURCE_POSITION'], fixed_magnification_list=[True]) kwargs_numerics_base = { 'supersampling_factor': 2, 'supersampling_convolution': False } imageModel_base = ImageModel(self.data_class, self.psf_class, self.lens_model_class, source_model_class_base, lens_light_model_class_base, point_source_class_base, kwargs_numerics=kwargs_numerics_base) image_sim = sim_util.simulate_simple(imageModel_base, self.kwargs_lens, kwargs_source_base, kwargs_lens_light_base, self.kwargs_ps) self.data_class.update_data(image_sim) # create a starlet light distributions n_scales = 6 source_map = imageModel_base.source_surface_brightness( kwargs_source_base, de_lensed=True, unconvolved=True) starlets_class = SLIT_Starlets(force_no_pysap=_force_no_pysap) source_map_starlets = starlets_class.decomposition_2d( source_map, n_scales) self.kwargs_source = [{ 'amp': source_map_starlets, 'n_scales': n_scales, 'n_pixels': numPix, 'scale': deltaPix, 'center_x': 0, 'center_y': 0 }] self.source_model_class = LightModel( light_model_list=['SLIT_STARLETS']) lens_light_map = imageModel_base.lens_surface_brightness( kwargs_lens_light_base, unconvolved=True) starlets_class = SLIT_Starlets(force_no_pysap=_force_no_pysap, second_gen=True) lens_light_starlets = starlets_class.decomposition_2d( lens_light_map, n_scales) self.kwargs_lens_light = [{ 'amp': lens_light_starlets, 'n_scales': n_scales, 'n_pixels': numPix, 'scale': deltaPix, 'center_x': 0, 'center_y': 0 }] self.lens_light_model_class = LightModel( light_model_list=['SLIT_STARLETS_GEN2']) self.kwargs_numerics = {'supersampling_factor': 1} self.kwargs_pixelbased = { 'supersampling_factor_source': 2, # supersampling of pixelated source grid # following choices are to minimize pixel solver runtime (not to get accurate reconstruction!) 'threshold_decrease_type': 'none', 'num_iter_source': 2, 'num_iter_lens': 2, 'num_iter_global': 2, 'num_iter_weights': 2, }
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)
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