def test_create_solver_class(self): from slitronomy.Optimization.solver_source import SparseSolverSource source_model_class = LightModel(['SLIT_STARLETS']) lens_light_model_class = LightModel([]) point_source_class = PointSource(point_source_type_list=[]) source_numerics_class = NumericsSubFrame(self.imageModel.Data, self.imageModel.PSF, supersampling_factor=2) solver_class = class_util.create_solver_class( self.imageModel.Data, self.imageModel.PSF, self.imageModel.ImageNumerics, source_numerics_class, self.imageModel.LensModel, source_model_class, lens_light_model_class, point_source_class, self.imageModel._extinction, self.kwargs_sparse_solver) assert isinstance(solver_class, SparseSolverSource) from slitronomy.Optimization.solver_source_lens import SparseSolverSourceLens source_model_class = LightModel(['SLIT_STARLETS']) lens_light_model_class = LightModel(['SLIT_STARLETS']) point_source_class = PointSource(point_source_type_list=[]) source_numerics_class = NumericsSubFrame(self.imageModel.Data, self.imageModel.PSF, supersampling_factor=2) solver_class = class_util.create_solver_class( self.imageModel.Data, self.imageModel.PSF, self.imageModel.ImageNumerics, source_numerics_class, self.imageModel.LensModel, source_model_class, lens_light_model_class, point_source_class, self.imageModel._extinction, self.kwargs_sparse_solver) assert isinstance(solver_class, SparseSolverSourceLens)
def test_source_position_plot(self): from lenstronomy.PointSource.point_source import PointSource from lenstronomy.LensModel.lens_model import LensModel lensModel = LensModel(lens_model_list=['SIS']) ps = PointSource(point_source_type_list=[ 'UNLENSED', 'LENSED_POSITION', 'SOURCE_POSITION' ], lensModel=lensModel) kwargs_lens = [{'theta_E': 1., 'center_x': 0, 'center_y': 0}] kwargs_ps = [{ 'ra_image': [1., 1.], 'dec_image': [0, 1], 'point_amp': [1, 1] }, { 'ra_image': [1.], 'dec_image': [1.], 'point_amp': [10] }, { 'ra_source': 0.1, 'dec_source': 0, 'point_amp': 1. }] ra_source, dec_source = ps.source_position(kwargs_ps, kwargs_lens) from lenstronomy.Data.coord_transforms import Coordinates coords_source = Coordinates( transform_pix2angle=np.array([[1, 0], [0, 1]]) * 0.1, ra_at_xy_0=-2, dec_at_xy_0=-2) f, ax = plt.subplots(1, 1, figsize=(4, 4)) plot_util.source_position_plot(ax, coords_source, ra_source, dec_source) plt.close()
def __init__(self, kwargs_model): self.LensLightModel = LightModel(kwargs_model.get('lens_light_model_list', ['NONE'])) self.SourceModel = LightModel(kwargs_model.get('source_light_model_list', ['NONE'])) self.LensModel = LensModelExtensions(lens_model_list=kwargs_model['lens_model_list']) self.PointSource = PointSource(point_source_type_list=kwargs_model.get('point_source_model_list', ['NONE'])) self.kwargs_model = kwargs_model self.NumLensModel = NumericLens(lens_model_list=kwargs_model['lens_model_list']) self.gaussian = Gaussian()
def test_point_source(self): kwargs_model = { 'lens_model_list': ['SPEMD', 'SHEAR_GAMMA_PSI'], 'point_source_model_list': ['SOURCE_POSITION'] } lensAnalysis = LensAnalysis(kwargs_model=kwargs_model) source_x, source_y = 0.02, 0.1 kwargs_ps = [{ 'dec_source': source_y, 'ra_source': source_x, 'point_amp': 75.155 }] kwargs_lens = [{ 'e2': 0.1, 'center_x': 0, 'theta_E': 1.133, 'e1': 0.1, 'gamma': 2.063, 'center_y': 0 }, { 'gamma_ext': 0.026, 'psi_ext': 1.793 }] x_image, y_image = lensAnalysis.PointSource.image_position( kwargs_ps=kwargs_ps, kwargs_lens=kwargs_lens) from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver from lenstronomy.LensModel.lens_model import LensModel lensModel = LensModel(lens_model_list=['SPEMD', 'SHEAR_GAMMA_PSI']) from lenstronomy.PointSource.point_source import PointSource ps = PointSource(point_source_type_list=['SOURCE_POSITION'], lensModel=lensModel) x_image_new, y_image_new = ps.image_position(kwargs_ps, kwargs_lens) npt.assert_almost_equal(x_image_new[0], x_image[0], decimal=7) solver = LensEquationSolver(lensModel=lensModel) x_image_true, y_image_true = solver.image_position_from_source( source_x, source_y, kwargs_lens, min_distance=0.01, search_window=5, precision_limit=10**(-10), num_iter_max=100, arrival_time_sort=True, initial_guess_cut=False, verbose=False, x_center=0, y_center=0, num_random=0, non_linear=False, magnification_limit=None) print(x_image[0], y_image[0], x_image_true, y_image_true) npt.assert_almost_equal(x_image_true, x_image[0], decimal=7)
def setup(self): lensModel = LensModel(lens_model_list=['SPEP']) solver = LensEquationSolver(lensModel=lensModel) self.kwargs_lens = [{'theta_E': 1., 'center_x': 0, 'center_y': 0, 'q': 0.7, 'phi_G': 0, 'gamma': 2}] self.sourcePos_x, self.sourcePos_y = 0.01, -0.01 self.x_pos, self.y_pos = solver.image_position_from_source(sourcePos_x=self.sourcePos_x, sourcePos_y=self.sourcePos_y, kwargs_lens=self.kwargs_lens) self.PointSource = PointSource(point_source_type_list=['LENSED_POSITION', 'UNLENSED', 'SOURCE_POSITION', 'NONE'], lensModel=lensModel, fixed_magnification_list=[True]*4, additional_images_list=[False]*4) self.kwargs_ps = [{'ra_image': self.x_pos, 'dec_image': self.y_pos, 'source_amp': 1}, {'ra_image': [1.], 'dec_image': [1.], 'point_amp': [10]}, {'ra_source': self.sourcePos_x, 'dec_source': self.sourcePos_y, 'source_amp': 1.}, {}]
def setup(self): lensModel = LensModel(lens_model_list=['SPEP']) solver = LensEquationSolver(lensModel=lensModel) e1, e2 = param_util.phi_q2_ellipticity(0, 0.7) self.kwargs_lens = [{'theta_E': 1., 'center_x': 0, 'center_y': 0, 'e1': e1, 'e2': e2, 'gamma': 2}] self.sourcePos_x, self.sourcePos_y = 0.01, -0.01 self.x_pos, self.y_pos = solver.image_position_from_source(sourcePos_x=self.sourcePos_x, sourcePos_y=self.sourcePos_y, kwargs_lens=self.kwargs_lens) self.PointSource = PointSource(point_source_type_list=['LENSED_POSITION', 'UNLENSED', 'SOURCE_POSITION'], lensModel=lensModel, fixed_magnification_list=[False]*3, additional_images_list=[False]*4) self.kwargs_ps = [{'ra_image': self.x_pos, 'dec_image': self.y_pos, 'point_amp': np.ones_like(self.x_pos)}, {'ra_image': [1.], 'dec_image': [1.], 'point_amp': [10]}, {'ra_source': self.sourcePos_x, 'dec_source': self.sourcePos_y, 'point_amp': np.ones_like(self.x_pos)}, {}]
def __init__(self, kwargs_model): self.LensLightModel = LightModel( kwargs_model.get('lens_light_model_list', [])) self.SourceModel = LightModel( kwargs_model.get('source_light_model_list', [])) self.LensModel = LensModel( lens_model_list=kwargs_model.get('lens_model_list', []), z_source=kwargs_model.get('z_source', None), redshift_list=kwargs_model.get('redshift_list', None), multi_plane=kwargs_model.get('multi_plane', False)) self._lensModelExtensions = LensModelExtensions(self.LensModel) self.PointSource = PointSource(point_source_type_list=kwargs_model.get( 'point_source_model_list', [])) self.kwargs_model = kwargs_model self.NumLensModel = NumericLens( lens_model_list=kwargs_model.get('lens_model_list', []))
def sepc_imageModel(self): from lenstronomy.ImSim.image_model import ImageModel from lenstronomy.Data.imaging_data import ImageData from lenstronomy.Data.psf import PSF data_class = ImageData(**self.kwargs_data) from lenstronomy.PointSource.point_source import PointSource pointSource = PointSource( point_source_type_list=self.point_source_list) psf_class = PSF(**self.kwargs_psf) from lenstronomy.LightModel.light_model import LightModel lightModel = LightModel(light_model_list=self.light_model_list) if self.light_model_list is None: imageModel = ImageModel(data_class, psf_class, point_source_class=pointSource, kwargs_numerics=self.kwargs_numerics) else: imageModel = ImageModel(data_class, psf_class, source_model_class=lightModel, point_source_class=pointSource, kwargs_numerics=self.kwargs_numerics) self.data_class = data_class self.psf_class = psf_class self.lightModel = lightModel self.imageModel = imageModel self.pointSource = pointSource
def create_image_model(kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model): """ :param kwargs_data: :param kwargs_psf: :param kwargs_options: :return: """ data_class = Data(kwargs_data) psf_class = PSF(kwargs_psf) lens_model_class = LensModel( lens_model_list=kwargs_model.get('lens_model_list', []), z_source=kwargs_model.get('z_source', None), redshift_list=kwargs_model.get('redshift_list', None), multi_plane=kwargs_model.get('multi_plane', False)) source_model_class = LightModel( light_model_list=kwargs_model.get('source_light_model_list', [])) lens_light_model_class = LightModel( light_model_list=kwargs_model.get('lens_light_model_list', [])) point_source_class = PointSource( point_source_type_list=kwargs_model.get('point_source_model_list', []), lensModel=lens_model_class, fixed_magnification_list=kwargs_model.get('fixed_magnification_list', None), additional_images_list=kwargs_model.get('additional_images_list', None), min_distance=kwargs_model.get('min_distance', 0.01), search_window=kwargs_model.get('search_window', 5), precision_limit=kwargs_model.get('precision_limit', 10**(-10)), num_iter_max=kwargs_model.get('num_iter_max', 100)) imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics) return imageModel
def setup(self): # compute image positions lensModel = LensModel(lens_model_list=['SIE']) solver = LensEquationSolver(lensModel=lensModel) self._kwargs_lens = [{ 'theta_E': 1, 'e1': 0.1, 'e2': -0.03, 'center_x': 0, 'center_y': 0 }] x_pos, y_pos = solver.image_position_from_source( sourcePos_x=0.01, sourcePos_y=-0.01, kwargs_lens=self._kwargs_lens) point_source_class = PointSource( point_source_type_list=['LENSED_POSITION'], lensModel=lensModel) self.likelihood = PositionLikelihood(point_source_class, position_uncertainty=0.005, astrometric_likelihood=True, image_position_likelihood=True, ra_image_list=[x_pos], dec_image_list=[y_pos], source_position_likelihood=True, check_solver=False, solver_tolerance=0.001, force_no_add_image=False, restrict_image_number=False, max_num_images=None) self._x_pos, self._y_pos = x_pos, y_pos
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 __init__(self, data_class, psf_class, lens_model_class=None, source_model_class=None, lens_light_model_class=None, point_source_class=None, extinction_class=None, kwargs_numerics=None): """ :param data_class: instance of ImageData() or PixelGrid() class :param psf_class: instance of PSF() class :param lens_model_class: instance of LensModel() class :param source_model_class: instance of LightModel() class describing the source parameters :param lens_light_model_class: instance of LightModel() class describing the lens light parameters :param point_source_class: instance of PointSource() class describing the point sources :param kwargs_numerics: keyword argument with various numeric description (see ImageNumerics class for options) """ self.type = 'single-band' self.PSF = psf_class self.Data = data_class self.PSF.set_pixel_size(self.Data.pixel_width) if kwargs_numerics is None: kwargs_numerics = {} self.ImageNumerics = NumericsSubFrame(pixel_grid=self.Data, psf=self.PSF, **kwargs_numerics) if lens_model_class is None: lens_model_class = LensModel(lens_model_list=[]) self.LensModel = lens_model_class if point_source_class is None: point_source_class = PointSource(point_source_type_list=[]) self.PointSource = point_source_class self.PointSource.update_lens_model(lens_model_class=lens_model_class) x_center, y_center = self.Data.center self.PointSource.update_search_window( search_window=np.max(self.Data.width), x_center=x_center, y_center=y_center, min_distance=self.Data.pixel_width, only_from_unspecified=True) self._psf_error_map = self.PSF.psf_error_map_bool if source_model_class is None: source_model_class = LightModel(light_model_list=[]) self.SourceModel = source_model_class if lens_light_model_class is None: lens_light_model_class = LightModel(light_model_list=[]) self.LensLightModel = lens_light_model_class self.source_mapping = Image2SourceMapping( lensModel=lens_model_class, sourceModel=source_model_class) self.num_bands = 1 self._kwargs_numerics = kwargs_numerics if extinction_class is None: extinction_class = DifferentialExtinction(optical_depth_model=[]) self._extinction = extinction_class
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 create_image_model(kwargs_data, kwargs_psf, kwargs_numerics, lens_model_list=[], z_lens=None, z_source=None, lens_redshift_list=None, multi_plane=False, source_light_model_list=[], lens_light_model_list=[], point_source_model_list=[], fixed_magnification_list=None, additional_images_list=None, min_distance=0.01, search_window=5, precision_limit=10**(-10), num_iter_max=100, multi_band_type=None, source_deflection_scaling_list=None, source_redshift_list=None, cosmo=None): """ :param kwargs_data: :param kwargs_psf: :param kwargs_options: :return: """ data_class = Data(kwargs_data) psf_class = PSF(kwargs_psf) lens_model_class = LensModel(lens_model_list=lens_model_list, z_lens=z_lens, z_source=z_source, lens_redshift_list=lens_redshift_list, multi_plane=multi_plane, cosmo=cosmo) source_model_class = LightModel( light_model_list=source_light_model_list, deflection_scaling_list=source_deflection_scaling_list, source_redshift_list=source_redshift_list) lens_light_model_class = LightModel(light_model_list=lens_light_model_list) point_source_class = PointSource( point_source_type_list=point_source_model_list, lensModel=lens_model_class, fixed_magnification_list=fixed_magnification_list, additional_images_list=additional_images_list, min_distance=min_distance, search_window=search_window, precision_limit=precision_limit, num_iter_max=num_iter_max) imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics) return imageModel
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) 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) data_class = ImageData(**kwargs_data) kwargs_psf = {'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncation': 5, 'pixel_size': deltaPix} psf_class = PSF(**kwargs_psf) # 'EXTERNAL_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.0001, '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 = {'supersampling_factor': 2, 'supersampling_convolution': True, 'compute_mode': 'gaussian'} imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps) data_class.update_data(image_sim) kwargs_data['image_data'] = image_sim self.solver = LensEquationSolver(lensModel=lens_model_class) multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics]] kwargs_model = {'lens_model_list': lens_model_list, 'source_light_model_list': source_model_list, 'point_source_model_list': ['SOURCE_POSITION'], 'fixed_magnification_list': [True]} self.imageModel = MultiLinear(multi_band_list, kwargs_model, likelihood_mask_list=None, compute_bool=None)
def test_positive_flux(self): bool = PointSource.check_positive_flux( kwargs_ps=[{ 'point_amp': np.array([1, -1]) }]) assert bool is False bool = PointSource.check_positive_flux(kwargs_ps=[{'point_amp': -1}]) assert bool is False bool = PointSource.check_positive_flux( kwargs_ps=[{ 'point_amp': np.array([0, 1]) }]) assert bool is True bool = PointSource.check_positive_flux(kwargs_ps=[{'point_amp': 1}]) assert bool is True bool = PointSource.check_positive_flux( kwargs_ps=[{ 'point_amp': np.array([0, 1]), 'source_amp': 1 }]) assert bool is True bool = PointSource.check_positive_flux(kwargs_ps=[{ 'point_amp': 1, 'source_amp': -1 }]) assert bool is False
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 normalize_flux(self, kwargs_options, kwargs_source, kwargs_lens_light, kwargs_ps, norm_factor_source=1, norm_factor_lens_light=1, norm_factor_point_source=1.): """ multiplies the surface brightness amplitudes with a norm_factor aim: mimic different telescopes photon collection area or colours for different imaging bands :param kwargs_source: :param kwargs_lens_light: :param norm_factor: :return: """ lensLightModel = LightModel(kwargs_options.get('lens_light_model_list', ['NONE'])) sourceModel = LightModel(kwargs_options.get('source_light_model_list', ['NONE'])) lensModel = LensModel(lens_model_list=kwargs_options.get('lens_model_list', ['NONE'])) pointSource = PointSource(point_source_type_list=kwargs_options.get('point_source_list', ['NONE']), lensModel=lensModel, fixed_magnification_list=kwargs_options.get('fixed_magnification_list', [False]), additional_images_list=kwargs_options.get('additional_images_list', [False])) kwargs_source_updated = copy.deepcopy(kwargs_source) kwargs_lens_light_updated = copy.deepcopy(kwargs_lens_light) kwargs_ps_updated = copy.deepcopy(kwargs_ps) kwargs_source_updated = sourceModel.re_normalize_flux(kwargs_source_updated, norm_factor_source) kwargs_lens_light_updated = lensLightModel.re_normalize_flux(kwargs_lens_light_updated, norm_factor_lens_light) kwargs_ps_updated = pointSource.re_normalize_flux(kwargs_ps_updated, norm_factor_point_source) return kwargs_source_updated, kwargs_lens_light_updated, kwargs_ps_updated
def get_img_pos(self, ps_dict, kwargs_lens): """Sets the kwargs_ps class attribute as those coresponding to the point source model `LENSED_POSITION` Parameters ---------- ps_dict : dict point source parameters definitions, either of `SOURCE_POSITION` or `LENSED_POSITION` """ if 'ra_source' in ps_dict: # If the user provided ps_dict in terms of the source position, we precompute the corresponding image positions before we enter the sampling loop. lens_model_class = LensModel(self.kwargs_model['lens_model_list']) ps_class = PointSource(['SOURCE_POSITION'], lens_model_class) kwargs_ps_source = [ps_dict] ra_image, dec_image = ps_class.image_position( kwargs_ps_source, kwargs_lens) kwargs_image = [dict(ra_image=ra_image[0], dec_image=dec_image[0])] requires_reordering = True # Since the ra_image is coming out of lenstronomy, we need to reorder it to agree with TDLMC else: kwargs_image = [ps_dict] requires_reordering = False # If the user is providing `ra_image` inside `ps_dict`, the order is required to agree with `measured_time_delays`. return kwargs_image, requires_reordering
def __init__(self, lens_model_list=[], z_lens=None, z_source=None, lens_redshift_list=None, multi_plane=False, source_light_model_list=[], lens_light_model_list=[], point_source_model_list=[], source_redshift_list=None, cosmo=None): """ :param lens_model_list: list of strings with lens model names :param z_lens: redshift of the deflector (only considered when operating in single plane mode). Is only needed for specific functions that require a cosmology. :param z_source: redshift of the source: Needed in multi_plane option only, not required for the core functionalities in the single plane mode. :param lens_redshift_list: list of deflector redshift (corresponding to the lens model list), only applicable in multi_plane mode. :param source_light_model_list: list of strings with source light model names (lensed light profiles) :param lens_light_model_list: list of strings with lens light model names (not lensed light profiles) :param point_source_model_list: list of strings with point source model names :param source_redshift_list: list of redshifts of the source profiles (optional) :param cosmo: instance of the astropy cosmology class. If not specified, uses the default cosmology. """ self._lens_model_class = LensModel( lens_model_list=lens_model_list, z_source=z_source, z_lens=z_lens, lens_redshift_list=lens_redshift_list, multi_plane=multi_plane, cosmo=cosmo) self._source_model_class = LightModel( light_model_list=source_light_model_list, source_redshift_list=source_redshift_list) self._lens_light_model_class = LightModel( light_model_list=lens_light_model_list) fixed_magnification = [False] * len(point_source_model_list) for i, ps_type in enumerate(point_source_model_list): if ps_type == 'SOURCE_POSITION': fixed_magnification[i] = True self._point_source_model_class = PointSource( point_source_type_list=point_source_model_list, lensModel=self._lens_model_class, fixed_magnification_list=fixed_magnification)
def test_check_additional_images(self): point_source_class = PointSource( point_source_type_list=['LENSED_POSITION'], additional_images_list=[True], lensModel=LensModel(lens_model_list=['SIE'])) likelihood = PositionLikelihood(point_source_class) kwargs_ps = [{'ra_image': self._x_pos, 'dec_image': self._y_pos}] bool = likelihood.check_additional_images(kwargs_ps, self._kwargs_lens) assert bool is False kwargs_ps = [{ 'ra_image': self._x_pos[1:], 'dec_image': self._y_pos[1:] }] bool = likelihood.check_additional_images(kwargs_ps, self._kwargs_lens) assert bool is True
class TestPointSource_fixed_mag(object): def setup(self): lensModel = LensModel(lens_model_list=['SPEP']) solver = LensEquationSolver(lensModel=lensModel) e1, e2 = param_util.phi_q2_ellipticity(0, 0.7) self.kwargs_lens = [{'theta_E': 1., 'center_x': 0, 'center_y': 0, 'e1': e1, 'e2': e2, 'gamma': 2}] self.sourcePos_x, self.sourcePos_y = 0.01, -0.01 self.x_pos, self.y_pos = solver.image_position_from_source(sourcePos_x=self.sourcePos_x, sourcePos_y=self.sourcePos_y, kwargs_lens=self.kwargs_lens) self.PointSource = PointSource(point_source_type_list=['LENSED_POSITION', 'UNLENSED', 'SOURCE_POSITION'], lensModel=lensModel, fixed_magnification_list=[True]*4, additional_images_list=[False]*4) self.kwargs_ps = [{'ra_image': self.x_pos, 'dec_image': self.y_pos, 'source_amp': 1}, {'ra_image': [1.], 'dec_image': [1.], 'point_amp': [10]}, {'ra_source': self.sourcePos_x, 'dec_source': self.sourcePos_y, 'source_amp': 1.}, {}] def test_image_position(self): x_image_list, y_image_list = self.PointSource.image_position(kwargs_ps=self.kwargs_ps, kwargs_lens=self.kwargs_lens) npt.assert_almost_equal(x_image_list[0][0], self.x_pos[0], decimal=8) npt.assert_almost_equal(x_image_list[1], 1, decimal=8) npt.assert_almost_equal(x_image_list[2][0], self.x_pos[0], decimal=8) def test_source_position(self): x_source_list, y_source_list = self.PointSource.source_position(kwargs_ps=self.kwargs_ps, kwargs_lens=self.kwargs_lens) npt.assert_almost_equal(x_source_list[0], self.sourcePos_x, decimal=8) npt.assert_almost_equal(x_source_list[1], 1, decimal=8) npt.assert_almost_equal(x_source_list[2], self.sourcePos_x, decimal=8) def test_num_basis(self): num_basis = self.PointSource.num_basis(self.kwargs_ps, self.kwargs_lens) assert num_basis == 3 def test_linear_response_set(self): ra_pos, dec_pos, amp, n = self.PointSource.linear_response_set(self.kwargs_ps, kwargs_lens=self.kwargs_lens, with_amp=False, k=None) num_basis = self.PointSource.num_basis(self.kwargs_ps, self.kwargs_lens) assert n == num_basis assert ra_pos[0][0] == self.x_pos[0] assert ra_pos[1][0] == 1 npt.assert_almost_equal(ra_pos[2][0], self.x_pos[0], decimal=8) def test_point_source_list(self): ra_list, dec_list, amp_list = self.PointSource.point_source_list(self.kwargs_ps, self.kwargs_lens) assert ra_list[0] == self.x_pos[0] assert len(ra_list) == 9 def test_check_image_positions(self): bool = self.PointSource.check_image_positions(self.kwargs_ps, self.kwargs_lens, tolerance=0.001) assert bool == True
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 creat_image_model(kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model): """ :param kwargs_data: :param kwargs_psf: :param kwargs_options: :return: """ data_class = Data(kwargs_data) psf_class = PSF(kwargs_psf) if 'lens_model_list' in kwargs_model: lens_model_class = LensModel( lens_model_list=kwargs_model.get('lens_model_list', None), z_source=kwargs_model.get('z_source', None), redshift_list=kwargs_model.get('redshift_list', None), multi_plane=kwargs_model.get('multi_plane', False)) else: lens_model_class = None if 'source_light_model_list' in kwargs_model: source_model_class = LightModel(light_model_list=kwargs_model.get( 'source_light_model_list', ['NONE'])) else: source_model_class = None if 'lens_light_model_list' in kwargs_model: lens_light_model_class = LightModel(light_model_list=kwargs_model.get( 'lens_light_model_list', ['NONE'])) else: lens_light_model_class = None if 'point_source_model_list' in kwargs_model: point_source_class = PointSource( point_source_type_list=kwargs_model.get('point_source_model_list', ['NONE']), fixed_magnification_list=kwargs_model.get( 'fixed_magnification_list', None), additional_images_list=kwargs_model.get('additional_images_list', None)) else: point_source_class = None imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics) return imageModel
def creat_multiband(multi_band_list, kwargs_model): """ :param kwargs_data: :param kwargs_psf: :param kwargs_options: :return: """ if 'lens_model_list' in kwargs_model: lens_model_class = LensModel( lens_model_list=kwargs_model.get('lens_model_list', None), z_source=kwargs_model.get('z_source', None), redshift_list=kwargs_model.get('redshift_list', None), multi_plane=kwargs_model.get('multi_plane', False)) else: lens_model_class = None if 'source_light_model_list' in kwargs_model: source_model_class = LightModel(light_model_list=kwargs_model.get( 'source_light_model_list', ['NONE'])) else: source_model_class = None if 'lens_light_model_list' in kwargs_model: lens_light_model_class = LightModel(light_model_list=kwargs_model.get( 'lens_light_model_list', ['NONE'])) else: lens_light_model_class = None if 'point_source_model_list' in kwargs_model: point_source_class = PointSource( point_source_type_list=kwargs_model.get('point_source_model_list', ['NONE']), fixed_magnification_list=kwargs_model.get( 'fixed_magnification_list', None), additional_images_list=kwargs_model.get('additional_images_list', None)) else: point_source_class = None multiband = Multiband(multi_band_list, lens_model_class, source_model_class, lens_light_model_class, point_source_class) return multiband
def __init__(self, data_class, psf_class, lens_model_class=None, source_model_class=None, lens_light_model_class=None, point_source_class=None, extinction_class=None, kwargs_numerics=None, kwargs_pixelbased=None): """ :param data_class: instance of ImageData() or PixelGrid() class :param psf_class: instance of PSF() class :param lens_model_class: instance of LensModel() class :param source_model_class: instance of LightModel() class describing the source parameters :param lens_light_model_class: instance of LightModel() class describing the lens light parameters :param point_source_class: instance of PointSource() class describing the point sources :param kwargs_numerics: keyword arguments with various numeric description (see ImageNumerics class for options) :param kwargs_pixelbased: keyword arguments with various settings related to the pixel-based solver (see SLITronomy documentation) """ self.type = 'single-band' self.num_bands = 1 self.PSF = psf_class self.Data = data_class self.PSF.set_pixel_size(self.Data.pixel_width) if kwargs_numerics is None: kwargs_numerics = {} self.ImageNumerics = NumericsSubFrame(pixel_grid=self.Data, psf=self.PSF, **kwargs_numerics) if lens_model_class is None: lens_model_class = LensModel(lens_model_list=[]) self.LensModel = lens_model_class if point_source_class is None: point_source_class = PointSource(point_source_type_list=[]) self.PointSource = point_source_class self.PointSource.update_lens_model(lens_model_class=lens_model_class) x_center, y_center = self.Data.center self.PointSource.update_search_window( search_window=np.max(self.Data.width), x_center=x_center, y_center=y_center, min_distance=self.Data.pixel_width, only_from_unspecified=True) self._psf_error_map = self.PSF.psf_error_map_bool if source_model_class is None: source_model_class = LightModel(light_model_list=[]) self.SourceModel = source_model_class if lens_light_model_class is None: lens_light_model_class = LightModel(light_model_list=[]) self.LensLightModel = lens_light_model_class self._kwargs_numerics = kwargs_numerics if extinction_class is None: extinction_class = DifferentialExtinction(optical_depth_model=[]) self._extinction = extinction_class if kwargs_pixelbased is None: kwargs_pixelbased = {} else: kwargs_pixelbased = kwargs_pixelbased.copy() self._pixelbased_bool = self._detect_pixelbased_models() if self._pixelbased_bool is True: from slitronomy.Util.class_util import create_solver_class # requirement on SLITronomy is exclusively here self.SourceNumerics = self._setup_pixelbased_source_numerics( kwargs_numerics, kwargs_pixelbased) self.PixelSolver = create_solver_class( self.Data, self.PSF, self.ImageNumerics, self.SourceNumerics, self.LensModel, self.SourceModel, self.LensLightModel, self.PointSource, self._extinction, kwargs_pixelbased) self.source_mapping = None # handled with pixelated operator else: self.source_mapping = Image2SourceMapping( lensModel=lens_model_class, sourceModel=source_model_class)
def main(): args = parse_args() version_id = args.version_id prec_version_id = args.prec_version_id is_prec_ceiling = bool(version_id == prec_version_id) n_test = args.n_test version_dir = '/home/jwp/stage/sl/h0rton/experiments/v{:d}'.format(version_id) if is_prec_ceiling: test_cfg_path = os.path.join(version_dir, 'simple_mc_default.json') else: test_cfg_path = os.path.join(version_dir, 'mcmc_default.json') test_cfg = TestConfig.from_file(test_cfg_path) baobab_cfg = BaobabConfig.from_file(test_cfg.data.test_baobab_cfg_path) #train_val_cfg = TrainValConfig.from_file(test_cfg.train_val_config_file_path) # Read in truth metadata metadata = pd.read_csv(os.path.join(baobab_cfg.out_dir, 'metadata.csv'), index_col=None, nrows=n_test) # Read in summary summary = pd.read_csv(os.path.join(version_dir, 'summary.csv'), index_col=None, nrows=n_test) summary['id'] = summary.index true_Om0 = 0.3 # Drop irrelevant lenses summary.drop(summary[summary['id']>(n_test - 1)].index, inplace=True) outside_rung = summary[summary['inference_time'] == 0].index summary.drop(outside_rung, inplace=True) print("Number of lenses being combined: {:d}".format(summary.shape[0])) print("Lenses that were discarded: ", set(np.arange(n_test)) - set(summary['id'].values)) # Assign doubles vs quads summary['is_quad'] = (summary['n_img'] == 4) print("Doubles: ", len(summary[~summary['is_quad']])) print("Quads: ", len(summary[summary['is_quad']])) min_doubles_quads = np.min([len(summary[~summary['is_quad']]), len(summary[summary['is_quad']])]) doubles = summary[~summary['is_quad']].iloc[:min_doubles_quads] quads = summary[summary['is_quad']].iloc[:min_doubles_quads] #################### # Lens combination # #################### if False: # 1. Gaussian D_dt print("Gaussian D_dt parameterization:") # Combine all lenses print("Combining all lenses...") combined_path_all = os.path.join(version_dir, 'combined_H0_summary.npy') _ = h0_utils.combine_lenses('DdtGaussian', ddt_mean=summary['D_dt_mean'].values, ddt_sigma=summary['D_dt_std'].values, z_lens=summary['z_lens'].values, z_src=summary['z_src'].values, samples_save_path=combined_path_all, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) # Combine all doubles print("Combining the {:d} doubles...".format(min_doubles_quads)) combined_path_doubles = os.path.join(version_dir, 'combined_H0_doubles.npy') _ = h0_utils.combine_lenses('DdtGaussian', ddt_mean=doubles['D_dt_mean'].values, ddt_sigma=doubles['D_dt_std'].values, z_lens=doubles['z_lens'].values, z_src=doubles['z_src'].values, samples_save_path=combined_path_doubles, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) # Combine all quads print("Combining the {:d} quads...".format(min_doubles_quads)) combined_path_quads = os.path.join(version_dir, 'combined_H0_quads.npy') _ = h0_utils.combine_lenses('DdtGaussian', ddt_mean=quads['D_dt_mean'].values, ddt_sigma=quads['D_dt_std'].values, z_lens=quads['z_lens'].values, z_src=quads['z_src'].values, samples_save_path=combined_path_quads, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) # 2. Lognormal D_dt print("Lognormal D_dt parameterization:") # Combine all lenses print("Combining all lenses...") combined_path_all_lognormal = os.path.join(version_dir, 'combined_H0_summary_lognormal.npy') _ = h0_utils.combine_lenses('DdtLogNorm', ddt_mu=summary['D_dt_mu'].values, ddt_sigma=summary['D_dt_sigma'].values, z_lens=summary['z_lens'].values, z_src=summary['z_src'].values, samples_save_path=combined_path_all_lognormal, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) # Combine all doubles print("Combining the {:d} doubles...".format(min_doubles_quads)) combined_path_doubles_lognormal = os.path.join(version_dir, 'combined_H0_doubles_lognormal.npy') _ = h0_utils.combine_lenses('DdtLogNorm', ddt_mu=doubles['D_dt_mu'].values, ddt_sigma=doubles['D_dt_sigma'].values, z_lens=doubles['z_lens'].values, z_src=doubles['z_src'].values, samples_save_path=combined_path_doubles_lognormal, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) # Combine all quads print("Combining the {:d} quads...".format(min_doubles_quads)) combined_path_quads_lognormal = os.path.join(version_dir, 'combined_H0_quads_lognormal.npy') _ = h0_utils.combine_lenses('DdtLogNorm', ddt_mu=quads['D_dt_mu'].values, ddt_sigma=quads['D_dt_sigma'].values, z_lens=quads['z_lens'].values, z_src=quads['z_src'].values, samples_save_path=combined_path_quads_lognormal, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) # 2. KDE print("KDE D_dt:") # Combine all lenses print("Combining all lenses...") combined_path_all_kde = os.path.join(version_dir, 'combined_H0_summary_kde.npy') _ = h0_utils.combine_lenses('DdtHistKDE', lens_ids=summary['id'].values, samples_dir=os.path.join(version_dir, 'mcmc_default'), z_lens=summary['z_lens'].values, z_src=summary['z_src'].values, samples_save_path=combined_path_all_kde, corner_save_path=None, n_run=100, n_burn=200, n_walkers=20, true_Om0=true_Om0, binning_method='scott') # Combine all doubles print("Combining the {:d} doubles...".format(min_doubles_quads)) combined_path_doubles_kde = os.path.join(version_dir, 'combined_H0_doubles_kde.npy') _ = h0_utils.combine_lenses('DdtHistKDE', lens_ids=doubles['id'].values, samples_dir=os.path.join(version_dir, 'mcmc_default'), z_lens=doubles['z_lens'].values, z_src=doubles['z_src'].values, samples_save_path=combined_path_doubles_kde, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0, binning_method='scott') # Combine all quads print("Combining the {:d} quads...".format(min_doubles_quads)) combined_path_quads_kde = os.path.join(version_dir, 'combined_H0_quads_kde.npy') _ = h0_utils.combine_lenses('DdtHistKDE', lens_ids=quads['id'].values, samples_dir=os.path.join(version_dir, 'mcmc_default'), z_lens=quads['z_lens'].values, z_src=quads['z_src'].values, samples_save_path=combined_path_quads_kde, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0, binning_method='scott') # Combine for each Einstein brightness bin if is_prec_ceiling: # If this version is the precision ceiling, compute the Einstein ring brightness for the first time. print("Computing Einstein ring brightness...") summary['lensed_E_ring_flux'] = 0.0 summary['lensed_E_ring_mag'] = 0.0 lens_mass_model = LensModel(lens_model_list=['PEMD', 'SHEAR_GAMMA_PSI']) src_light_model = LightModel(light_model_list=['SERSIC_ELLIPSE']) lens_light_model = LightModel(light_model_list=['SERSIC_ELLIPSE']) ps_model = PointSource(point_source_type_list=['LENSED_POSITION'], fixed_magnification_list=[False]) components = ['lens_mass', 'src_light', 'agn_light', 'lens_light'] for lens_i in range(n_test): imager = Imager(components, lens_mass_model, src_light_model, lens_light_model=lens_light_model, ps_model=ps_model, kwargs_numerics={'supersampling_factor': 1}, min_magnification=0.0, for_cosmography=True) imager._set_sim_api(num_pix=64, kwargs_detector=baobab_cfg.survey_object_dict[baobab_cfg.survey_info.bandpass_list[0]].kwargs_single_band(), psf_kernel_size=99, which_psf_maps=[101]) # TODO: read from BaobabConfig rather than hardcode imager.kwargs_src_light = metadata_utils.get_kwargs_src_light(metadata.iloc[lens_i]) imager.kwargs_src_light = flux_utils.mag_to_amp_extended(imager.kwargs_src_light, imager.src_light_model, imager.data_api) imager.kwargs_lens_mass = metadata_utils.get_kwargs_lens_mass(metadata.iloc[lens_i]) sample_ps = metadata_utils.get_nested_ps(metadata.iloc[lens_i]) imager.for_cosmography = False imager._load_agn_light_kwargs(sample_ps) lensed_total_flux, lensed_src_img = flux_utils.get_lensed_total_flux(imager.kwargs_lens_mass, imager.kwargs_src_light, None, imager.image_model, return_image=True) lensed_ring_total_flux = np.sum(lensed_src_img) summary.loc[lens_i, 'lensed_E_ring_flux'] = lensed_ring_total_flux summary.loc[lens_i, 'lensed_E_ring_mag'] = data_util.cps2magnitude(lensed_ring_total_flux, baobab_cfg.survey_object_dict[baobab_cfg.survey_info.bandpass_list[0]].kwargs_single_band()['magnitude_zero_point']) lensed_ring_bins = np.quantile(summary['lensed_E_ring_mag'].values, [0.25, 0.5, 0.75, 1]) lensed_ring_bins[-1] += 0.1 # buffer summary['lensed_ring_bin'] = np.digitize(summary['lensed_E_ring_mag'].values, lensed_ring_bins) summary.to_csv(os.path.join(version_dir, 'ering_summary.csv'), index=False) else: # Simply read in the preciously computed Einstein ring brightness prec_version_dir = '/home/jwp/stage/sl/h0rton/experiments/v{:d}'.format(prec_version_id) prec_summary = pd.read_csv(os.path.join(prec_version_dir, 'ering_summary.csv'), index_col=None, nrows=n_test) summary['lensed_E_ring_mag'] = prec_summary['lensed_E_ring_mag'].values lensed_ring_bins = np.quantile(summary['lensed_E_ring_mag'].values, [0.25, 0.5, 0.75, 1]) lensed_ring_bins[-1] += 0.1 # buffer summary['lensed_ring_bin'] = np.digitize(summary['lensed_E_ring_mag'].values, lensed_ring_bins) for bin_i in range(len(lensed_ring_bins)): take_bin_i = (summary['lensed_ring_bin'] == bin_i) print("Combining {:d} lenses in bin {:d}...".format(len(summary[take_bin_i]), bin_i)) if False: if is_prec_ceiling: combined_path_ering_i = os.path.join(version_dir, 'combined_H0_ering_{:d}.npy'.format(bin_i)) _ = h0_utils.combine_lenses(likelihood_type='DdtGaussian', ddt_mean=summary['D_dt_mean'][take_bin_i].values, ddt_sigma=summary['D_dt_std'][take_bin_i].values, z_lens=summary['z_lens'][take_bin_i].values, z_src=summary['z_src'][take_bin_i].values, samples_save_path=combined_path_ering_i, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) combined_path_ering_i_lognormal = os.path.join(version_dir, 'combined_H0_ering_{:d}_lognormal.npy'.format(bin_i)) _ = h0_utils.combine_lenses(likelihood_type='DdtLogNorm', ddt_mu=summary['D_dt_mu'][take_bin_i].values, ddt_sigma=summary['D_dt_sigma'][take_bin_i].values, z_lens=summary['z_lens'][take_bin_i].values, z_src=summary['z_src'][take_bin_i].values, samples_save_path=combined_path_ering_i_lognormal, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0) combined_path_ering_i_kde = os.path.join(version_dir, 'combined_H0_ering_{:d}_kde.npy'.format(bin_i)) _ = h0_utils.combine_lenses(likelihood_type='DdtHistKDE', lens_ids=summary['id'][take_bin_i].values, samples_dir=os.path.join(version_dir, 'mcmc_default'), z_lens=summary['z_lens'][take_bin_i].values, z_src=summary['z_src'][take_bin_i].values, samples_save_path=combined_path_ering_i_kde, corner_save_path=None, n_run=100, n_burn=500, n_walkers=20, true_Om0=true_Om0, binning_method='scott')
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 setup(self): # data specifics sigma_bkg = 0.01 # background noise per pixel exp_time = 100 # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit) numPix = 100 # cutout pixel size deltaPix = 0.05 # pixel size in arcsec (area per pixel = deltaPix**2) fwhm = 0.3 # full width half max of PSF # PSF specification kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg) data_class = Data(kwargs_data) sigma = util.fwhm2sigma(fwhm) x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05) from lenstronomy.LightModel.Profiles.gaussian import Gaussian gaussian = Gaussian() kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma_x=sigma, sigma_y=sigma, center_x=0, center_y=0) kernel_point_source /= np.sum(kernel_point_source) kernel_point_source = util.array2image(kernel_point_source) self.kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source} psf_class = PSF(kwargs_psf=self.kwargs_psf) # 'EXERNAL_SHEAR': external shear kwargs_shear = {'e1': 0.01, 'e2': 0.01} # gamma_ext: shear strength, psi_ext: shear angel (in radian) phi, q = 0.2, 0.8 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_spemd = {'theta_E': 1., 'gamma': 1.8, 'center_x': 0, 'center_y': 0, 'e1': e1, 'e2': e2} lens_model_list = ['SPEP', 'SHEAR'] self.kwargs_lens = [kwargs_spemd, kwargs_shear] lens_model_class = LensModel(lens_model_list=lens_model_list) # list of light profiles (for lens and source) # 'SERSIC': spherical Sersic profile kwargs_sersic = {'amp': 1., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0} # 'SERSIC_ELLIPSE': elliptical Sersic profile phi, q = 0.2, 0.9 e1, e2 = param_util.phi_q2_ellipticity(phi, q) kwargs_sersic_ellipse = {'amp': 1., 'R_sersic': .6, 'n_sersic': 7, 'center_x': 0, 'center_y': 0, 'e1': e1, 'e2': e2} lens_light_model_list = ['SERSIC'] self.kwargs_lens_light = [kwargs_sersic] lens_light_model_class = LightModel(light_model_list=lens_light_model_list) source_model_list = ['SERSIC_ELLIPSE'] self.kwargs_source = [kwargs_sersic_ellipse] source_model_class = LightModel(light_model_list=source_model_list) self.kwargs_ps = [{'ra_source': 0.0, 'dec_source': 0.0, 'source_amp': 10.}] # quasar point source position in the source plane and intrinsic brightness point_source_class = PointSource(point_source_type_list=['SOURCE_POSITION'], fixed_magnification_list=[True]) kwargs_numerics = {'subgrid_res': 3, 'psf_subgrid': True} imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens, self.kwargs_source, self.kwargs_lens_light, self.kwargs_ps) data_class.update_data(image_sim) self.imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class, lens_light_model_class, point_source_class, kwargs_numerics=kwargs_numerics) self.psf_fitting = PsfFitting(self.imageModel)