def test_analytical_lens_equation_solver(self): lensModel = LensModel(['EPL_NUMBA', 'SHEAR']) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.03 sourcePos_y = 0.0 kwargs_lens = [{ 'theta_E': 1., 'gamma': 2.2, 'center_x': 0.01, 'center_y': 0.02, 'e1': 0.01, 'e2': 0.05 }, { 'gamma1': -0.04, 'gamma2': -0.1, 'ra_0': 0.01, 'dec_0': 0.02 }] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, solver='analytical') source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) assert len(source_x) == len(source_y) >= 4 npt.assert_almost_equal(sourcePos_x, source_x, decimal=10) npt.assert_almost_equal(sourcePos_y, source_y, decimal=10) x_pos_ls, y_pos_ls = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, solver='analytical') for x, y in zip( x_pos_ls, y_pos_ls): # Check if it found all solutions lenstronomy found assert np.sqrt((x - x_pos)**2 + (y - y_pos)**2).min() < 1e-8
def test_example(self): lens_model_list = ['SPEP', 'SHEAR'] lensModel = LensModel(lens_model_list) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.03 sourcePos_y = 0.0 min_distance = 0.05 search_window = 10 gamma = 2. e1, e2 = -0.04, -0.1 kwargs_shear = {'e1': e1, 'e2': e2} # shear values to the source plane kwargs_spemd = { 'theta_E': 1., 'gamma': gamma, 'center_x': 0.0, 'center_y': 0.0, 'e1': 0.01, 'e2': 0.05 } # parameters of the deflector lens model kwargs_lens = [kwargs_spemd, kwargs_shear] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10, arrival_time_sort=True) x_pos_non_linear, y_pos_non_linear = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10, arrival_time_sort=True, non_linear=True) x_pos_stoch, y_pos_stoch = lensEquationSolver.image_position_stochastic( sourcePos_x, sourcePos_y, kwargs_lens, search_window=search_window, precision_limit=10**(-10), arrival_time_sort=True, x_center=0, y_center=0, num_random=100, ) assert len(x_pos) == 4 assert len(x_pos_stoch) == 4 assert len(x_pos_non_linear) == 4 npt.assert_almost_equal(x_pos, x_pos_stoch, decimal=5) npt.assert_almost_equal(x_pos, x_pos_non_linear, decimal=5)
def test_central_image(self): lens_model_list = ['SPEP', 'SIS', 'SHEAR'] kwargs_spep = { 'theta_E': 1, 'gamma': 2, 'e1': 0.2, 'e2': -0.03, 'center_x': 0, 'center_y': 0 } kwargs_sis = {'theta_E': 1, 'center_x': 1.5, 'center_y': 0} kwargs_shear = {'e1': 0.01, 'e2': 0} kwargs_lens = [kwargs_spep, kwargs_sis, kwargs_shear] lensModel = LensModel(lens_model_list) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.1 sourcePos_y = -0.1 min_distance = 0.05 search_window = 10 x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10) source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) npt.assert_almost_equal(sourcePos_x, source_x, decimal=10) print(x_pos, y_pos) assert len(x_pos) == 4
def test_foreground_shear(self): lens_model_list = ['SPEP', 'FOREGROUND_SHEAR'] lensModel = LensModel(lens_model_list) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.1 sourcePos_y = -0.1 min_distance = 0.05 search_window = 10 gamma = 1.9 kwargs_lens = [{ 'theta_E': 1., 'gamma': gamma, 'e1': 0.2, 'e2': -0.03, 'center_x': 0.1, 'center_y': -0.1 }, { 'e1': 0.01, 'e2': -0.05 }] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10) source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) npt.assert_almost_equal(sourcePos_x, source_x, decimal=10)
def solve_leq(self, xsrc, ysrc, lensmodel, lens_model_params, brightimg, precision_lim=10**(-10), nitermax=10): lensEquationSolver = LensEquationSolver(lensModel=lensmodel) if brightimg: x_image, y_image = lensEquationSolver.findBrightImage( xsrc, ysrc, lens_model_params, arrival_time_sort=False, min_distance=0.02, search_window=3.5, precision_limit=precision_lim, num_iter_max=nitermax) else: x_image, y_image = lensEquationSolver.image_position_from_source( kwargs_lens=lens_model_params, sourcePos_x=xsrc, sourcePos_y=ysrc, min_distance=self.min_distance, search_window=self.search_window, precision_limit=self.precision_limit, num_iter_max=self.num_iter_max, arrival_time_sort=False) return x_image, y_image
def setup(self): lens_model_list = ['SPEP', 'SHEAR'] lensModel = LensModel(lens_model_list=lens_model_list) lensModelExtensions = LensModelExtensions(lensModel=lensModel) lensEquationSolver = LensEquationSolver(lensModel=lensModel) x_source, y_source = 0.02, 0.01 kwargs_lens = [{'theta_E': 1., 'e1': 0.1, 'e2': 0.1, 'gamma': 2., 'center_x': 0, 'center_y': 0}, {'gamma1': 0.06, 'gamma2': -0.03}] x_img, y_img = lensEquationSolver.image_position_from_source(kwargs_lens=kwargs_lens, sourcePos_x=x_source, sourcePos_y=y_source) print('image positions are: ', x_img, y_img) mag_inf = lensModel.magnification(x_img, y_img, kwargs_lens) print('point source magnification: ', mag_inf) source_size_arcsec = 0.001 window_size = 0.1 grid_number = 100 print('source size in arcsec: ', source_size_arcsec) mag_finite = lensModelExtensions.magnification_finite(x_pos=x_img, y_pos=y_img, kwargs_lens=kwargs_lens, source_sigma=source_size_arcsec, window_size=window_size, grid_number=grid_number) flux_ratios = mag_finite[1:] / mag_finite[0] flux_ratio_errors = [0.1, 0.1, 0.1] self.flux_likelihood = FluxRatioLikelihood(lens_model_class=lensModel, flux_ratios=flux_ratios, flux_ratio_errors=flux_ratio_errors, source_type='GAUSSIAN', window_size=window_size, grid_number=grid_number) self.flux_likelihood_inf = FluxRatioLikelihood(lens_model_class=lensModel, flux_ratios=flux_ratios, flux_ratio_errors=flux_ratio_errors, source_type='INF', window_size=window_size, grid_number=grid_number) self.kwargs_cosmo = {'source_size': source_size_arcsec} self.x_img, self.y_img = x_img, y_img self.kwargs_lens = kwargs_lens
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_analytical_sie(self): sourcePos_x = 0.03 sourcePos_y = 0.0 lensModel = LensModel(['SIE']) lensEquationSolver = LensEquationSolver(lensModel) kwargs_lens = [ { 'theta_E': 1., 'center_x': 0.0, 'center_y': 0.0, 'e1': 0.5, 'e2': 0.05 }, ] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, solver='analytical', magnification_limit=1e-3) source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) assert len(source_x) == len(source_y) == 4 npt.assert_almost_equal(sourcePos_x, source_x, decimal=10) npt.assert_almost_equal(sourcePos_y, source_y, decimal=10)
def test_zoom_source(self): lens_model_list = ['SPEMD', 'SHEAR'] lensModel = LensModel(lens_model_list=lens_model_list) lensModelExtensions = LensModelExtensions(lensModel=lensModel) lensEquationSolver = LensEquationSolver(lensModel=lensModel) x_source, y_source = 0.02, 0.01 kwargs_lens = [{ 'theta_E': 1, 'e1': 0.1, 'e2': 0.1, 'gamma': 2, 'center_x': 0, 'center_y': 0 }, { 'gamma1': 0.05, 'gamma2': -0.03 }] x_img, y_img = lensEquationSolver.image_position_from_source( kwargs_lens=kwargs_lens, sourcePos_x=x_source, sourcePos_y=y_source) image = lensModelExtensions.zoom_source(x_img[0], y_img[0], kwargs_lens, source_sigma=0.003, window_size=0.1, grid_number=100, shape="GAUSSIAN") assert len(image) == 100
def test_spep_sis(self): lens_model_list = ['SPEP', 'SIS'] lensModel = LensModel(lens_model_list) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.1 sourcePos_y = -0.1 min_distance = 0.05 search_window = 10 gamma = 1.9 kwargs_lens = [{ 'theta_E': 1., 'gamma': gamma, 'q': 0.8, 'phi_G': 0.5, 'center_x': 0.1, 'center_y': -0.1 }, { 'theta_E': 0.1, 'center_x': 0.5, 'center_y': 0 }] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10) source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) npt.assert_almost_equal(sourcePos_x, source_x, decimal=10)
def test_multiplane(self): lens_model_list = ['SPEP', 'SIS'] lensModel = LensModel(lens_model_list, z_source=1., lens_redshift_list=[0.5, 0.3], multi_plane=True) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.1 sourcePos_y = -0.1 min_distance = 0.05 search_window = 10 gamma = 1.9 kwargs_lens = [{ 'theta_E': 1., 'gamma': gamma, 'e1': 0.2, 'e2': -0.03, 'center_x': 0.1, 'center_y': -0.1 }, { 'theta_E': 0.1, 'center_x': 0.5, 'center_y': 0 }] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10) source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) npt.assert_almost_equal(sourcePos_x, source_x, decimal=10)
def test_nfw(self): lens_model_list = ['NFW_ELLIPSE', 'SIS'] lensModel = LensModel(lens_model_list) lensEquationSolver = LensEquationSolver(lensModel) sourcePos_x = 0.1 sourcePos_y = -0.1 min_distance = 0.05 search_window = 10 Rs = 4. kwargs_lens = [{ 'alpha_Rs': 1., 'Rs': Rs, 'e1': 0.2, 'e2': -0.03, 'center_x': 0.1, 'center_y': -0.1 }, { 'theta_E': 1, 'center_x': 0, 'center_y': 0 }] x_pos, y_pos = lensEquationSolver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=10**(-10), num_iter_max=10, verbose=True, magnification_limit=1) source_x, source_y = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens) npt.assert_almost_equal(sourcePos_x, source_x, decimal=10)
def point_source_plot(ax, pixel_grid, lens_model, kwargs_lens, source_x, source_y, **kwargs): """ plots and illustrates images of a point source The plotting routine orders the image labels according to the arrival time and illustrates a diamond shape of the size of the magnification. The coordinates are chosen in pixel coordinates :param ax: matplotlib axis instance :param pixel_grid: lenstronomy PixelGrid() instance (or class with inheritance of PixelGrid() :param lens_model: LensModel() class instance :param kwargs_lens: lens model keyword argument list :param source_x: x-position of source :param source_y: y-position of source :param kwargs: additional plotting keyword arguments :return: matplotlib axis instance with figure """ from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver solver = LensEquationSolver(lens_model) x_center, y_center = pixel_grid.center delta_pix = pixel_grid.pixel_width ra0, dec0 = pixel_grid.radec_at_xy_0 tranform = pixel_grid.transform_angle2pix if np.linalg.det( tranform ) < 0: # if coordiate transform has negative parity (#TODO temporary fix) delta_pix_x = -delta_pix else: delta_pix_x = delta_pix origin = [ra0, dec0] theta_x, theta_y = solver.image_position_from_source( source_x, source_y, kwargs_lens, search_window=np.max(pixel_grid.width), x_center=x_center, y_center=y_center, min_distance=pixel_grid.pixel_width) mag_images = lens_model.magnification(theta_x, theta_y, kwargs_lens) #ax = plot_util.image_position_plot(ax=ax, coords=pixel_grid, ra_image=theta_x, dec_image=theta_y, color='w', image_name_list=None) x_image, y_image = pixel_grid.map_coord2pix(theta_x, theta_y) abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] for i in range(len(x_image)): x_ = (x_image[i] + 0.5) * delta_pix_x + origin[0] y_ = (y_image[i] + 0.5) * delta_pix + origin[1] ax.plot(x_, y_, 'dk', markersize=4 * (1 + np.log(np.abs(mag_images[i]))), alpha=0.5) ax.text(x_, y_, abc_list[i], fontsize=20, color='k') x_source, y_source = pixel_grid.map_coord2pix(source_x, source_y) ax.plot((x_source + 0.5) * delta_pix_x + origin[0], (y_source + 0.5) * delta_pix + origin[1], '*k', markersize=10) return ax
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 test_caustics(self): lm = LensModel(['EPL_NUMBA', 'SHEAR']) leqs = LensEquationSolver(lm) kwargs = [{ 'theta_E': 1., 'e1': 0.5, 'e2': 0.1, 'center_x': 0.0, 'center_y': 0.0, 'gamma': 1.9 }, { 'gamma1': 0.03, 'gamma2': 0.01, 'ra_0': 0.0, 'dec_0': 0.0 }] # Calculate the caustics and a few critical curves. caus = caustics_epl_shear(kwargs, return_which='caustic') lensplane_caus = caustics_epl_shear(kwargs, return_which='caustic', sourceplane=False) cut = caustics_epl_shear(kwargs, return_which='cut') lensplane_cut = caustics_epl_shear(kwargs, return_which='cut', sourceplane=False) twoimg = caustics_epl_shear(kwargs, return_which='double') fourimg = caustics_epl_shear(kwargs, return_which='quad') assert np.abs(lm.magnification(*lensplane_caus, kwargs)).min() > 1e12 assert np.abs(lm.magnification(*lensplane_cut, kwargs)).min() > 1e12 # Test whether the caustics indeed the number of images they say N = 20 xpl, ypl = np.linspace(-1, 1, N), np.linspace(-1, 1, N) xgr, ygr = np.meshgrid(xpl, ypl, indexing='ij') xf, yf = xgr.flatten(), ygr.flatten() sols = [ leqs.image_position_from_source(x, y, kwargs, solver='analytical') for x, y in zip(xf, yf) ] numsols = np.array([len(p[0]) for p in sols]) from matplotlib.path import Path points = np.vstack((xf, yf)).T p = Path(twoimg.T) # make a polygon grid2img = p.contains_points(points) assert np.all(numsols[grid2img] >= 2) p = Path(fourimg.T) # make a polygon grid4img = p.contains_points(points) assert np.all(numsols[grid4img] >= 4)
def test_with_solver(self): kwargs_model = { 'lens_model_list': ['SPEP'], 'source_light_model_list': ['SERSIC'], 'point_source_model_list': ['LENSED_POSITION'] } i_lens_light, k_ps = 0, 0 kwargs_constraints = { 'solver_type': 'PROFILE', 'num_point_source_list': [4] } kwargs_lens = [{ 'theta_E': 1, 'gamma': 2, 'e1': 0.1, 'e2': 0.1, 'center_x': 0, 'center_y': 0 }] kwargs_source = [{ 'amp': 1, 'n_sersic': 2, 'R_sersic': 0.3, 'center_x': 1, 'center_y': 1 }] kwargs_lens_light = [{ 'amp': 1, 'n_sersic': 2, 'R_sersic': 0.3, 'center_x': 0.2, 'center_y': 0.2 }] lensModel = LensModel(lens_model_list=['SPEP']) lensEquationSlover = LensEquationSolver(lensModel=lensModel) x_image, y_image = lensEquationSlover.image_position_from_source( sourcePos_x=0.0, sourcePos_y=0.01, kwargs_lens=kwargs_lens) print(x_image, y_image, 'test') kwargs_ps = [{'ra_image': x_image, 'dec_image': y_image}] param = Param(kwargs_model=kwargs_model, kwargs_lens_init=kwargs_lens, **kwargs_constraints) args = param.kwargs2args(kwargs_lens=kwargs_lens, kwargs_source=kwargs_source, kwargs_lens_light=kwargs_lens_light, kwargs_ps=kwargs_ps) #kwargs_lens_out, kwargs_source_out, kwargs_lens_light_out, kwargs_ps_out, _ = param.args2kwargs(args) kwargs_return = param.args2kwargs(args) kwargs_lens_out = kwargs_return['kwargs_lens'] kwargs_ps_out = kwargs_return['kwargs_ps'] dist = param.check_solver(kwargs_lens=kwargs_lens_out, kwargs_ps=kwargs_ps_out) npt.assert_almost_equal(dist, 0, decimal=10)
def lens_model_plot(ax, lensModel, kwargs_lens, numPix=500, deltaPix=0.01, sourcePos_x=0, sourcePos_y=0, point_source=False, with_caustics=False): """ plots a lens model (convergence) and the critical curves and caustics :param ax: :param kwargs_lens: :param numPix: :param deltaPix: :return: """ from lenstronomy.SimulationAPI.simulations import Simulation simAPI = Simulation() kwargs_data = simAPI.data_configure(numPix, deltaPix) data = Data(kwargs_data) _frame_size = numPix * deltaPix _coords = data._coords x_grid, y_grid = data.coordinates lensModelExt = LensModelExtensions(lensModel) #ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExt.critical_curve_caustics( # kwargs_lens, compute_window=_frame_size, grid_scale=deltaPix/2.) x_grid1d = util.image2array(x_grid) y_grid1d = util.image2array(y_grid) kappa_result = lensModel.kappa(x_grid1d, y_grid1d, kwargs_lens) kappa_result = util.array2image(kappa_result) im = ax.matshow(np.log10(kappa_result), origin='lower', extent=[0, _frame_size, 0, _frame_size], cmap='Greys', vmin=-1, vmax=1) #, cmap=self._cmap, vmin=v_min, vmax=v_max) if with_caustics is True: ra_crit_list, dec_crit_list = lensModelExt.critical_curve_tiling(kwargs_lens, compute_window=_frame_size, start_scale=deltaPix, max_order=10) ra_caustic_list, dec_caustic_list = lensModel.ray_shooting(ra_crit_list, dec_crit_list, kwargs_lens) plot_line_set(ax, _coords, ra_caustic_list, dec_caustic_list, color='g') plot_line_set(ax, _coords, ra_crit_list, dec_crit_list, color='r') if point_source: from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver solver = LensEquationSolver(lensModel) theta_x, theta_y = solver.image_position_from_source(sourcePos_x, sourcePos_y, kwargs_lens) mag_images = lensModel.magnification(theta_x, theta_y, kwargs_lens) x_image, y_image = _coords.map_coord2pix(theta_x, theta_y) abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] for i in range(len(x_image)): x_ = (x_image[i] + 0.5) * deltaPix y_ = (y_image[i] + 0.5) * deltaPix ax.plot(x_, y_, 'dk', markersize=4*(1 + np.log(np.abs(mag_images[i]))), alpha=0.5) ax.text(x_, y_, abc_list[i], fontsize=20, color='k') x_source, y_source = _coords.map_coord2pix(sourcePos_x, sourcePos_y) ax.plot((x_source + 0.5) * deltaPix, (y_source + 0.5) * deltaPix, '*k', markersize=10) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.autoscale(False) #image_position_plot(ax, _coords, self._kwargs_else) #source_position_plot(ax, self._coords, self._kwargs_source) return ax
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 test_assertions(self): lensModel = LensModel(['SPEP']) lensEquationSolver = LensEquationSolver(lensModel) kwargs_lens = [{ 'theta_E': 1, 'gamma': 2, 'e1': 0.2, 'e2': -0.03, 'center_x': 0, 'center_y': 0 }] with pytest.raises(ValueError): lensEquationSolver.image_position_from_source(0.1, 0., kwargs_lens, solver='analytical') lensModel = LensModel(['EPL_NUMBA', 'SHEAR']) lensEquationSolver = LensEquationSolver(lensModel) kwargs_lens = [{ 'theta_E': 1., 'gamma': 2.2, 'center_x': 0.0, 'center_y': 0.0, 'e1': 0.01, 'e2': 0.05 }, { 'gamma1': -0.04, 'gamma2': -0.1, 'ra_0': 0.0, 'dec_0': 0.0 }] with pytest.raises(ValueError): lensEquationSolver.image_position_from_source(0.1, 0., kwargs_lens, solver='nonexisting') with pytest.raises(ValueError): kwargs_lens[1]['ra_0'] = 0.1 lensEquationSolver.image_position_from_source(0.1, 0., kwargs_lens, solver='analytical')
def _find_point_sources(self, kwargs_options, kwargs_lens, kwargs_else): lensModel = LensModel(kwargs_options.get('lens_model_list', [])) imPos = LensEquationSolver(lensModel) if kwargs_options.get('point_source', False): min_distance = 0.05 search_window = 10 sourcePos_x = kwargs_else['sourcePos_x'] sourcePos_y = kwargs_else['sourcePos_y'] x_mins, y_mins = imPos.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=min_distance, search_window=search_window) n = len(x_mins) mag_list = np.zeros(n) for i in range(n): mag = lensModel.magnification(x_mins[i], y_mins[i], kwargs_lens) mag_list[i] = abs(mag) kwargs_else['ra_pos'] = x_mins kwargs_else['dec_pos'] = y_mins kwargs_else['point_amp'] = mag_list * kwargs_else['quasar_amp'] return kwargs_else
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_type = 'PIXEL' # 'gaussian', 'pixel', 'NONE' # PSF specification data_class = self.SimAPI.data_configure(numPix, deltaPix, exp_time, sigma_bkg) psf_class = self.SimAPI.psf_configure(psf_type='GAUSSIAN', fwhm=fwhm, kernelsize=31, deltaPix=deltaPix, truncate=5) # 'EXERNAL_SHEAR': external shear kwargs_shear = {'e1': 0.01, 'e2': 0.01} # gamma_ext: shear strength, psi_ext: shear angel (in radian) kwargs_spemd = {'theta_E': 1., 'gamma': 1.8, 'center_x': 0, 'center_y': 0, 'q': 0.8, 'phi_G': 0.2} 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 = {'I0_sersic': 1., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0} # 'SERSIC_ELLIPSE': elliptical Sersic profile kwargs_sersic_ellipse = {'I0_sersic': 1., 'R_sersic': .6, 'n_sersic': 7, 'center_x': 0, 'center_y': 0, 'phi_G': 0.2, 'q': 0.9} 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': 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) kwargs_data = data_class.constructor_kwargs() kwargs_psf = psf_class.constructor_kwargs() self.solver = LensEquationSolver(lensModel=lens_model_class) multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics]] self.imageModel = Multiband(multi_band_list, lens_model_class, source_model_class, lens_light_model_class, point_source_class) 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[0]) == 100 npt.assert_almost_equal(source_model[0][10, 10], 0.1370014246240874, decimal=8) source_model = self.imageModel.source_surface_brightness(self.kwargs_source, self.kwargs_lens, unconvolved=True, de_lensed=False) assert len(source_model[0]) == 100 npt.assert_almost_equal(source_model[0][10, 10], 0.13164547458291054, decimal=8) 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[0][50, 50], 0.4415194068014886, decimal=8) lens_flux = self.imageModel.lens_surface_brightness(self.kwargs_lens_light, unconvolved=True) npt.assert_almost_equal(lens_flux[0][50, 50], 4.7310552067454452, decimal=8) 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._imageModel_list[0].reduced_chi2(model[0], error_map[0]) npt.assert_almost_equal(chi2_reduced, 1, decimal=1) def test_image(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._imageModel_list[0].reduced_chi2(model[0], error_map[0]) npt.assert_almost_equal(chi2_reduced, 1, decimal=1) 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] 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, -5100, 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=-2) 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) phi_fermat = phi_fermat[0] npt.assert_almost_equal(phi_fermat[0], -0.2719737, decimal=3) npt.assert_almost_equal(phi_fermat[1], -0.2719737, decimal=3) npt.assert_almost_equal(phi_fermat[2], -0.51082354, decimal=3) npt.assert_almost_equal(phi_fermat[3], -0.51082354, decimal=3)
class TestImageModel(object): """ tests the source model routines """ 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 = Data(kwargs_data) kwargs_psf = sim_util.psf_configure_simple(psf_type='GAUSSIAN', fwhm=fwhm, kernelsize=31, deltaPix=deltaPix, truncate=5) psf_class = PSF(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', 'SERSIC'] self.kwargs_lens_light = [kwargs_sersic, kwargs_sersic] lens_light_model_class = LightModel(light_model_list=['SERSIC']) source_model_list = ['SERSIC_ELLIPSE', 'SERSIC_ELLIPSE'] self.kwargs_source = [kwargs_sersic_ellipse, kwargs_sersic_ellipse] source_model_class = LightModel(light_model_list=['SERSIC_ELLIPSE']) 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 = {'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 = sim_util.simulate_simple(imageModel, self.kwargs_lens, [kwargs_sersic_ellipse], [kwargs_sersic], self.kwargs_ps) data_class.update_data(image_sim) kwargs_data['image_data'] = image_sim self.solver = LensEquationSolver(lensModel=lens_model_class) kwargs_model_bool = { 'index_source_light_model': [0], 'index_lens_light_model': [0] } multi_band_list = [[ kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model_bool ]] self.imageModel = MultiBandMultiModel(multi_band_list, lens_model_class, source_model_list, lens_light_model_list, point_source_class) 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._imageModel_list[0].reduced_chi2( model[0], error_map[0]) npt.assert_almost_equal(chi2_reduced, 1, decimal=1) 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] 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, -5100, 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=-2) 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) phi_fermat = phi_fermat[0] npt.assert_almost_equal(phi_fermat[0], -0.2719737, decimal=3) npt.assert_almost_equal(phi_fermat[1], -0.2719737, decimal=3) npt.assert_almost_equal(phi_fermat[2], -0.51082354, decimal=3) npt.assert_almost_equal(phi_fermat[3], -0.51082354, decimal=3)
class LensedPositions(object): """ class of a single point source in the image plane, aka star parameters: ra_image, dec_image, point_amp """ def __init__(self, lensModel, fixed_magnification=False, additional_image=False): self._lensModel = lensModel self._solver = LensEquationSolver(lensModel) self._fixed_magnification = fixed_magnification self._additional_image = additional_image def image_position(self, kwargs_ps, kwargs_lens, min_distance=0.01, search_window=5, precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0): """ :param ra_image: :param dec_image: :param point_amp: :return: """ if self._additional_image: ra_source, dec_source = self.source_position( kwargs_ps, kwargs_lens) ra_image, dec_image = self._solver.image_position_from_source( ra_source, dec_source, kwargs_lens, min_distance=min_distance, search_window=search_window, precision_limit=precision_limit, num_iter_max=num_iter_max, x_center=x_center, y_center=y_center) else: ra_image = kwargs_ps['ra_image'] dec_image = kwargs_ps['dec_image'] return np.array(ra_image), np.array(dec_image) def source_position(self, kwargs_ps, kwargs_lens): ra_image = kwargs_ps['ra_image'] dec_image = kwargs_ps['dec_image'] x_source, y_source = self._lensModel.ray_shooting( ra_image, dec_image, kwargs_lens) x_source = np.mean(x_source) y_source = np.mean(y_source) return np.array(x_source), np.array(y_source) def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, min_distance=0.01, search_window=5, precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0): if self._fixed_magnification: ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens) mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens) point_amp = kwargs_ps['source_amp'] * np.abs(mag) else: point_amp = kwargs_ps['point_amp'] return np.array(point_amp) def source_amplitude(self, kwargs_ps, kwargs_lens=None): if self._fixed_magnification: source_amp = kwargs_ps['source_amp'] else: ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens) mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens) point_amp = kwargs_ps['point_amp'] source_amp = np.mean(np.array(point_amp) / np.array(np.abs(mag))) return np.array(source_amp) def update_lens_model(self, lens_model_class): self._lensModel = lens_model_class self._solver = LensEquationSolver(lens_model_class)
class LensedPositions(object): """ class of a a lensed point source parameterized as the (multiple) observed image positions Name within the PointSource module: 'LENSED_POSITION' parameters: ra_image, dec_image, point_amp If fixed_magnification=True, than 'source_amp' is a parameter instead of 'point_amp' """ def __init__(self, lensModel, fixed_magnification=False, additional_image=False): """ :param lensModel: instance of the LensModel() class :param fixed_magnification: bool. If True, magnification ratio of point sources is fixed to the one given by the lens model :param additional_image: bool. If True, search for additional images of the same source is conducted. """ self._lensModel = lensModel self._solver = LensEquationSolver(lensModel) self._fixed_magnification = fixed_magnification self._additional_image = additional_image if fixed_magnification is True and additional_image is True: Warning( 'The combination of fixed_magnification=True and additional_image=True is not optimal for the ' 'current computation. If you see this warning, please approach the developers.' ) def image_position(self, kwargs_ps, kwargs_lens, magnification_limit=None, kwargs_lens_eqn_solver={}): """ on-sky image positions :param kwargs_ps: keyword arguments of the point source model :param kwargs_lens: keyword argument list of the lens model(s), only used when requiring the lens equation solver :param magnification_limit: float >0 or None, if float is set and additional images are computed, only those images will be computed that exceed the lensing magnification (absolute value) limit :param kwargs_lens_eqn_solver: keyword arguments specifying the numerical settings for the lens equation solver see LensEquationSolver() class for details :return: image positions in x, y as arrays """ if self._additional_image is True: ra_source, dec_source = self.source_position( kwargs_ps, kwargs_lens) ra_image, dec_image = self._solver.image_position_from_source( ra_source, dec_source, kwargs_lens, magnification_limit=magnification_limit, **kwargs_lens_eqn_solver) else: ra_image = kwargs_ps['ra_image'] dec_image = kwargs_ps['dec_image'] return np.array(ra_image), np.array(dec_image) def source_position(self, kwargs_ps, kwargs_lens): """ original source position (prior to lensing) :param kwargs_ps: point source keyword arguments :param kwargs_lens: lens model keyword argument list (required to ray-trace back in the source plane) :return: x, y position (as numpy arrays) """ ra_image = kwargs_ps['ra_image'] dec_image = kwargs_ps['dec_image'] x_source, y_source = self._lensModel.ray_shooting( ra_image, dec_image, kwargs_lens) x_source = np.mean(x_source) y_source = np.mean(y_source) return np.array(x_source), np.array(y_source) def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, magnification_limit=None, kwargs_lens_eqn_solver={}): """ image brightness amplitudes :param kwargs_ps: keyword arguments of the point source model :param kwargs_lens: keyword argument list of the lens model(s), only used when requiring the lens equation solver :param x_pos: pre-computed image position (no lens equation solver applied) :param y_pos: pre-computed image position (no lens equation solver applied) :param magnification_limit: float >0 or None, if float is set and additional images are computed, only those images will be computed that exceed the lensing magnification (absolute value) limit :param kwargs_lens_eqn_solver: keyword arguments specifying the numerical settings for the lens equation solver see LensEquationSolver() class for details :return: array of image amplitudes """ if self._fixed_magnification: if x_pos is not None and y_pos is not None: ra_image, dec_image = x_pos, y_pos else: ra_image, dec_image = self.image_position( kwargs_ps, kwargs_lens, magnification_limit=magnification_limit, kwargs_lens_eqn_solver=kwargs_lens_eqn_solver) mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens) point_amp = kwargs_ps['source_amp'] * np.abs(mag) else: point_amp = kwargs_ps['point_amp'] if x_pos is not None: point_amp = _expand_to_array(point_amp, len(x_pos)) return np.array(point_amp) def source_amplitude(self, kwargs_ps, kwargs_lens=None): """ intrinsic brightness amplitude of point source When brightnesses are defined in magnified on-sky positions, the intrinsic brightness is computed as the mean in the magnification corrected image position brightnesses. :param kwargs_ps: keyword arguments of the point source model :param kwargs_lens: keyword argument list of the lens model(s), used when brightness are defined in magnified on-sky positions :return: brightness amplitude (as numpy array) """ if self._fixed_magnification: source_amp = kwargs_ps['source_amp'] else: ra_image, dec_image = kwargs_ps['ra_image'], kwargs_ps['dec_image'] mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens) point_amp = kwargs_ps['point_amp'] source_amp = np.mean(np.array(point_amp) / np.array(np.abs(mag))) return np.array(source_amp) def update_lens_model(self, lens_model_class): """ update LensModel() and LensEquationSolver() instance :param lens_model_class: LensModel() class instance :return: internal lensModel class updated """ self._lensModel = lens_model_class self._solver = LensEquationSolver(lens_model_class)
def __init__(self, source_x, source_y, variability_func, numpix, kwargs_single_band, kwargs_model, kwargs_numerics, kwargs_lens, kwargs_source_mag=None, kwargs_lens_light_mag=None, kwargs_ps_mag=None): """ :param source_x: RA of source position :param source_y: DEC of source position :param variability_func: function that returns a brightness (in magnitude) as a function of time t :param numpix: number of pixels per axis :param kwargs_single_band: :param kwargs_model: :param kwargs_numerics: :param kwargs_lens: :param kwargs_source_mag: :param kwargs_lens_light_mag: :param kwargs_ps_mag: """ # create background SimAPI class instance sim_api_bkg = SimAPI(numpix, kwargs_single_band, kwargs_model) image_model_bkg = sim_api_bkg.image_model_class(kwargs_numerics) kwargs_lens_light, kwargs_source, kwargs_ps = sim_api_bkg.magnitude2amplitude( kwargs_lens_light_mag, kwargs_source_mag, kwargs_ps_mag) self._image_bkg = image_model_bkg.image(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps) # compute image positions of point source x_center, y_center = sim_api_bkg.data_class.center search_window = np.max(sim_api_bkg.data_class.width) lensModel = image_model_bkg.LensModel solver = LensEquationSolver(lensModel=lensModel) image_x, image_y = solver.image_position_from_source( source_x, source_y, kwargs_lens, min_distance=0.1, search_window=search_window, precision_limit=10**(-10), num_iter_max=100, arrival_time_sort=True, x_center=x_center, y_center=y_center) mag = lensModel.magnification(image_x, image_y, kwargs_lens) dt_days = lensModel.arrival_time(image_x, image_y, kwargs_lens) dt_days -= np.min( dt_days ) # shift the arrival times such that the first image arrives at t=0 and the other # times at t>=0 # add image plane source model kwargs_model_ps = {'point_source_model_list': ['LENSED_POSITION']} self.sim_api_ps = SimAPI(numpix, kwargs_single_band, kwargs_model_ps) self._image_model_ps = self.sim_api_ps.image_model_class( kwargs_numerics) self._kwargs_lens = kwargs_lens self._dt_days = dt_days self._mag = mag self._image_x, self._image_y = image_x, image_y self._variability_func = variability_func
class SourcePositions(object): """ class of a single point source defined in the original source coordinate position that is lensed. The lens equation is solved to compute the image positions for the specified source position. Name within the PointSource module: 'SOURCE_POSITION' parameters: ra_source, dec_source, source_amp If fixed_magnification=True, than 'source_amp' is a parameter instead of 'point_amp' """ def __init__(self, lensModel, fixed_magnification=True): """ :param lensModel: instance of the LensModel() class :param fixed_magnification: bool. If True, magnification ratio of point sources is fixed to the one given by the lens model """ self._lensModel = lensModel self._solver = LensEquationSolver(lensModel) self._fixed_magnification = fixed_magnification def image_position(self, kwargs_ps, kwargs_lens, magnification_limit=None, kwargs_lens_eqn_solver={}): """ on-sky image positions :param kwargs_ps: keyword arguments of the point source model :param kwargs_lens: keyword argument list of the lens model(s), only used when requiring the lens equation solver :param magnification_limit: float >0 or None, if float is set and additional images are computed, only those images will be computed that exceed the lensing magnification (absolute value) limit :param kwargs_lens_eqn_solver: keyword arguments specifying the numerical settings for the lens equation solver see LensEquationSolver() class for details :return: image positions in x, y as arrays """ ra_source, dec_source = self.source_position(kwargs_ps) ra_image, dec_image = self._solver.image_position_from_source( ra_source, dec_source, kwargs_lens, magnification_limit=magnification_limit, **kwargs_lens_eqn_solver) return ra_image, dec_image def source_position(self, kwargs_ps, **kwargs): """ original source position (prior to lensing) :param kwargs_ps: point source keyword arguments :return: x, y position (as numpy arrays) """ ra_source = kwargs_ps['ra_source'] dec_source = kwargs_ps['dec_source'] return np.array(ra_source), np.array(dec_source) def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, magnification_limit=None, kwargs_lens_eqn_solver={}): """ image brightness amplitudes :param kwargs_ps: keyword arguments of the point source model :param kwargs_lens: keyword argument list of the lens model(s), only ignored when providing image positions directly :param x_pos: pre-computed image position (no lens equation solver applied) :param y_pos: pre-computed image position (no lens equation solver applied) :param magnification_limit: float >0 or None, if float is set and additional images are computed, only those images will be computed that exceed the lensing magnification (absolute value) limit :param kwargs_lens_eqn_solver: keyword arguments specifying the numerical settings for the lens equation solver see LensEquationSolver() class for details :return: array of image amplitudes """ if self._fixed_magnification: if x_pos is not None and y_pos is not None: ra_image, dec_image = x_pos, y_pos else: ra_image, dec_image = self.image_position( kwargs_ps, kwargs_lens, magnification_limit=magnification_limit, **kwargs_lens_eqn_solver) mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens) point_amp = kwargs_ps['source_amp'] * np.abs(mag) else: point_amp = kwargs_ps['point_amp'] if x_pos is not None: point_amp = _expand_to_array(point_amp, len(x_pos)) return np.array(point_amp) def source_amplitude(self, kwargs_ps, kwargs_lens=None): """ intrinsic brightness amplitude of point source When brightnesses are defined in magnified on-sky positions, the intrinsic brightness is computed as the mean in the magnification corrected image position brightnesses. :param kwargs_ps: keyword arguments of the point source model :param kwargs_lens: keyword argument list of the lens model(s), used when brightness are defined in magnified on-sky positions :return: brightness amplitude (as numpy array) """ if self._fixed_magnification: source_amp = kwargs_ps['source_amp'] else: ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens) mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens) point_amp = kwargs_ps['point_amp'] source_amp = np.mean(np.array(point_amp) / np.array(mag)) return np.array(source_amp) def update_lens_model(self, lens_model_class): """ update LensModel() and LensEquationSolver() instance :param lens_model_class: LensModel() class instance :return: internal lensModel class updated """ self._lensModel = lens_model_class self._solver = LensEquationSolver(lens_model_class)
def lens_model_plot(ax, lensModel, kwargs_lens, numPix=500, deltaPix=0.01, sourcePos_x=0, sourcePos_y=0, point_source=False, with_caustics=False, with_convergence=True, coord_center_ra=0, coord_center_dec=0, coord_inverse=False, fast_caustic=False): """ plots a lens model (convergence) and the critical curves and caustics :param ax: :param kwargs_lens: :param numPix: :param deltaPix: :param fast_caustic: boolean, if True, uses faster but less precise caustic calculation (might have troubles for the outer caustic (inner critical curve) :param with_convergence: boolean, if True, plots the convergence of the deflector :return: """ kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, center_ra=coord_center_ra, center_dec=coord_center_dec, inverse=coord_inverse) data = ImageData(**kwargs_data) _coords = data _frame_size = numPix * deltaPix x_grid, y_grid = data.pixel_coordinates lensModelExt = LensModelExtensions(lensModel) x_grid1d = util.image2array(x_grid) y_grid1d = util.image2array(y_grid) if with_convergence: kappa_result = lensModel.kappa(x_grid1d, y_grid1d, kwargs_lens) kappa_result = util.array2image(kappa_result) im = ax.matshow(np.log10(kappa_result), origin='lower', extent=[0, _frame_size, 0, _frame_size], cmap='Greys', vmin=-1, vmax=1) #, cmap=self._cmap, vmin=v_min, vmax=v_max) if with_caustics is True: if fast_caustic: ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExt.critical_curve_caustics( kwargs_lens, compute_window=_frame_size, grid_scale=deltaPix) plot_util.plot_line_set_list(ax, _coords, ra_caustic_list, dec_caustic_list, color='g') plot_util.plot_line_set_list(ax, _coords, ra_crit_list, dec_crit_list, color='r') else: ra_crit_list, dec_crit_list = lensModelExt.critical_curve_tiling( kwargs_lens, compute_window=_frame_size, start_scale=deltaPix, max_order=10) ra_caustic_list, dec_caustic_list = lensModel.ray_shooting( ra_crit_list, dec_crit_list, kwargs_lens) plot_util.plot_line_set(ax, _coords, ra_caustic_list, dec_caustic_list, color='g') plot_util.plot_line_set(ax, _coords, ra_crit_list, dec_crit_list, color='r') if point_source: from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver solver = LensEquationSolver(lensModel) theta_x, theta_y = solver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=deltaPix, search_window=deltaPix * numPix) mag_images = lensModel.magnification(theta_x, theta_y, kwargs_lens) x_image, y_image = _coords.map_coord2pix(theta_x, theta_y) abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] for i in range(len(x_image)): x_ = (x_image[i] + 0.5) * deltaPix y_ = (y_image[i] + 0.5) * deltaPix ax.plot(x_, y_, 'dk', markersize=4 * (1 + np.log(np.abs(mag_images[i]))), alpha=0.5) ax.text(x_, y_, abc_list[i], fontsize=20, color='k') x_source, y_source = _coords.map_coord2pix(sourcePos_x, sourcePos_y) ax.plot((x_source + 0.5) * deltaPix, (y_source + 0.5) * deltaPix, '*k', markersize=10) ax.set_xlim([0, _frame_size]) ax.set_ylim([0, _frame_size]) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.autoscale(False) return ax
def arrival_time_surface(ax, lensModel, kwargs_lens, numPix=500, deltaPix=0.01, sourcePos_x=0, sourcePos_y=0, with_caustics=False, point_source=False, n_levels=10, kwargs_contours={}, image_color_list=None, letter_font_size=20): """ :param ax: :param lensModel: :param kwargs_lens: :param numPix: :param deltaPix: :param sourcePos_x: :param sourcePos_y: :param with_caustics: :return: """ kwargs_data = sim_util.data_configure_simple(numPix, deltaPix) data = ImageData(**kwargs_data) _frame_size = numPix * deltaPix _coords = data x_grid, y_grid = data.pixel_coordinates lensModelExt = LensModelExtensions(lensModel) #ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExt.critical_curve_caustics( # kwargs_lens, compute_window=_frame_size, grid_scale=deltaPix/2.) x_grid1d = util.image2array(x_grid) y_grid1d = util.image2array(y_grid) fermat_surface = lensModel.fermat_potential(x_grid1d, y_grid1d, kwargs_lens, sourcePos_x, sourcePos_y) fermat_surface = util.array2image(fermat_surface) #, cmap='Greys', vmin=-1, vmax=1) #, cmap=self._cmap, vmin=v_min, vmax=v_max) if with_caustics is True: ra_crit_list, dec_crit_list = lensModelExt.critical_curve_tiling( kwargs_lens, compute_window=_frame_size, start_scale=deltaPix / 5, max_order=10) ra_caustic_list, dec_caustic_list = lensModel.ray_shooting( ra_crit_list, dec_crit_list, kwargs_lens) plot_util.plot_line_set(ax, _coords, ra_caustic_list, dec_caustic_list, shift=_frame_size / 2., color='g') plot_util.plot_line_set(ax, _coords, ra_crit_list, dec_crit_list, shift=_frame_size / 2., color='r') if point_source is True: from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver solver = LensEquationSolver(lensModel) theta_x, theta_y = solver.image_position_from_source( sourcePos_x, sourcePos_y, kwargs_lens, min_distance=deltaPix, search_window=deltaPix * numPix) fermat_pot_images = lensModel.fermat_potential(theta_x, theta_y, kwargs_lens) im = ax.contour( x_grid, y_grid, fermat_surface, origin='lower', # extent=[0, _frame_size, 0, _frame_size], levels=np.sort(fermat_pot_images), **kwargs_contours) mag_images = lensModel.magnification(theta_x, theta_y, kwargs_lens) x_image, y_image = _coords.map_coord2pix(theta_x, theta_y) abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] for i in range(len(x_image)): x_ = (x_image[i] + 0.5) * deltaPix - _frame_size / 2 y_ = (y_image[i] + 0.5) * deltaPix - _frame_size / 2 if image_color_list is None: color = 'k' else: color = image_color_list[i] ax.plot(x_, y_, 'x', markersize=10, alpha=1, color=color ) # markersize=8*(1 + np.log(np.abs(mag_images[i]))) ax.text(x_ + deltaPix, y_ + deltaPix, abc_list[i], fontsize=letter_font_size, color='k') x_source, y_source = _coords.map_coord2pix(sourcePos_x, sourcePos_y) ax.plot((x_source + 0.5) * deltaPix - _frame_size / 2, (y_source + 0.5) * deltaPix - _frame_size / 2, '*k', markersize=20) else: vmin = np.min(fermat_surface) vmax = np.max(fermat_surface) levels = np.linspace(start=vmin, stop=vmax, num=n_levels) im = ax.contour( x_grid, y_grid, fermat_surface, origin='lower', # extent=[0, _frame_size, 0, _frame_size], levels=levels, **kwargs_contours) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.autoscale(False) return ax
def make_lensmodel(lens_info, theta_E, source_info, box_f): # lens data specifics lens_image = lens_info['image'] psf_lens = lens_info['psf'] background_rms = background_rms_image(5, lens_image) exposure_time = 100 kwargs_data_lens = sim_util.data_configure_simple(len(lens_image), lens_info['deltapix'], exposure_time, background_rms) kwargs_data_lens['image_data'] = lens_image data_class_lens = ImageData(**kwargs_data_lens) #PSF kwargs_psf_lens = { 'psf_type': 'PIXEL', 'pixel_size': lens_info['deltapix'], 'kernel_point_source': psf_lens } psf_class_lens = PSF(**kwargs_psf_lens) # lens light model lens_light_model_list = ['SERSIC_ELLIPSE'] lens_light_model_class = LightModel(light_model_list=lens_light_model_list) kwargs_model = {'lens_light_model_list': lens_light_model_list} kwargs_numerics_galfit = {'supersampling_factor': 1} kwargs_constraints = {} kwargs_likelihood = {'check_bounds': True} image_band = [kwargs_data_lens, kwargs_psf_lens, kwargs_numerics_galfit] multi_band_list = [image_band] kwargs_data_joint = { 'multi_band_list': multi_band_list, 'multi_band_type': 'multi-linear' } # Sersic component fixed_lens_light = [{}] kwargs_lens_light_init = [{ 'R_sersic': .1, 'n_sersic': 4, 'e1': 0, 'e2': 0, 'center_x': 0, 'center_y': 0 }] kwargs_lens_light_sigma = [{ 'n_sersic': 0.5, 'R_sersic': 0.2, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1 }] kwargs_lower_lens_light = [{ 'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.01, 'n_sersic': 0.5, 'center_x': -10, 'center_y': -10 }] kwargs_upper_lens_light = [{ 'e1': 0.5, 'e2': 0.5, 'R_sersic': 10, 'n_sersic': 8, 'center_x': 10, 'center_y': 10 }] lens_light_params = [ kwargs_lens_light_init, kwargs_lens_light_sigma, fixed_lens_light, kwargs_lower_lens_light, kwargs_upper_lens_light ] kwargs_params = {'lens_light_model': lens_light_params} fitting_seq = FittingSequence(kwargs_data_joint, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params) fitting_kwargs_list = [[ 'PSO', { 'sigma_scale': 1., 'n_particles': 50, 'n_iterations': 50 } ]] chain_list = fitting_seq.fit_sequence(fitting_kwargs_list) kwargs_result = fitting_seq.best_fit() modelPlot = ModelPlot(multi_band_list, kwargs_model, kwargs_result) # Lens light best result kwargs_light_lens = kwargs_result['kwargs_lens_light'][0] #Lens model kwargs_lens_list = [{ 'theta_E': theta_E, 'e1': kwargs_light_lens['e1'], 'e2': kwargs_light_lens['e2'], 'center_x': kwargs_light_lens['center_x'], 'center_y': kwargs_light_lens['center_y'] }] lensModel = LensModel(['SIE']) lme = LensModelExtensions(lensModel) #random position for the source x_crit_list, y_crit_list = lme.critical_curve_tiling( kwargs_lens_list, compute_window=(len(source_info['image'])) * (source_info['deltapix']), start_scale=source_info['deltapix'], max_order=10) if len(x_crit_list) > 2 and len(y_crit_list) > 2: x_caustic_list, y_caustic_list = lensModel.ray_shooting( x_crit_list, y_crit_list, kwargs_lens_list) xsamp0 = np.arange( min(x_caustic_list) - min(x_caustic_list) * box_f[0], max(x_caustic_list) + max(x_caustic_list) * box_f[1], 0.1) xsamp = xsamp0[abs(xsamp0.round(1)) != 0.1] ysamp0 = np.arange( min(y_caustic_list) - min(y_caustic_list) * box_f[0], max(y_caustic_list) + max(y_caustic_list) * box_f[1], 0.1) ysamp = ysamp0[abs(ysamp0.round(1)) != 0.1] if len(xsamp) == 0 or len(ysamp) == 0: x_shift, y_shift = 0.15, 0.15 #arcseconds else: y_shift = rand.sample(list(ysamp), 1)[0] x_shift = rand.sample(list(xsamp), 1)[0] else: x_shift, y_shift = -0.15, 0.15 #arcseconds x_caustic_list = [0] y_caustic_list = [0] solver = LensEquationSolver(lensModel) theta_ra, theta_dec = solver.image_position_from_source( x_shift, y_shift, kwargs_lens_list) if len(theta_ra) <= 1: x_shift, y_shift = -0.2, -0.2 #arcseconds1 if abs(x_shift) >= int(theta_E) or abs(y_shift) >= int(theta_E): x_shift, y_shift = 0.3, -0.3 print('BLABLA') print('HERE', min(x_caustic_list) - min(x_caustic_list) * box_f[0], max(x_caustic_list) + max(x_caustic_list) * box_f[1], min(y_caustic_list) - min(y_caustic_list) * box_f[0], max(y_caustic_list) + max(y_caustic_list) * box_f[1]) return { 'lens_light_model_list': ['SERSIC_ELLIPSE'], 'kwargs_light_lens': [kwargs_light_lens], 'lens_light_model_class': lens_light_model_class, 'kwargs_lens_list': kwargs_lens_list, 'kwargs_data_lens': kwargs_data_lens, 'source_shift': [x_shift, y_shift] }