def test_no_band(self):
        """
        test raise statements if band is not evaluated

        """
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # cutout pixel size
        deltaPix = 0.5  # pixel size in arcsec (area per pixel = deltaPix**2)
        fwhm = 0.5  # full width half max of PSF

        kwargs_data = sim_util.data_configure_simple(numPix, deltaPix,
                                                     exp_time, sigma_bkg)
        kwargs_data['image_data'] = np.ones((numPix, numPix))
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'truncation': 5,
            'pixel_size': deltaPix
        }
        kwargs_numerics = {}
        multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics]]
        multi_band = MultiBandImageReconstruction(
            multi_band_list, {}, {},
            multi_band_type='single-band',
            kwargs_likelihood={'bands_compute': [False]})
        with self.assertRaises(ValueError):
            multi_band.band_setup(band_index=0)
    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 test_error_map_source(self):
        sourceModel = LightModel(light_model_list=['UNIFORM', 'UNIFORM'])

        kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                     deltaPix=1,
                                                     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 = ImageLinearFit(data_class=data_class,
                                    psf_class=psf_class,
                                    lens_model_class=None,
                                    point_source_class=None,
                                    source_model_class=sourceModel)

        x_grid, y_grid = util.make_grid(numPix=10, deltapix=1)
        error_map = imageModel.error_map_source(kwargs_source=[{
            'amp': 1
        }, {
            'amp': 1
        }],
                                                x_grid=x_grid,
                                                y_grid=y_grid,
                                                cov_param=np.array([[1, 0],
                                                                    [0, 1]]))
        assert error_map[0] == 2
    def test_force_positive_source_surface_brightness(self):
        kwargs_likelihood = {'force_minimum_source_surface_brightness': True}
        kwargs_model = {'source_light_model_list': ['SERSIC']}

        kwargs_constraints = {}
        param_class = Param(kwargs_model, **kwargs_constraints)

        kwargs_data = sim_util.data_configure_simple(numPix=10, deltaPix=0.1, exposure_time=1, sigma_bkg=0.1)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {'psf_type': 'NONE'}
        psf_class = PSF(**kwargs_psf)
        kwargs_sersic = {'amp': -1., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0}
        source_model_list = ['SERSIC']
        kwargs_source = [kwargs_sersic]
        source_model_class = LightModel(light_model_list=source_model_list)

        imageModel = ImageModel(data_class, psf_class, lens_model_class=None, source_model_class=source_model_class)

        image_sim = sim_util.simulate_simple(imageModel, [], kwargs_source)

        kwargs_data['image_data'] = image_sim
        kwargs_data_joint = {'multi_band_list': [[kwargs_data, kwargs_psf, {}]], 'multi_band_type': 'single-band'}
        likelihood = LikelihoodModule(kwargs_data_joint=kwargs_data_joint, kwargs_model=kwargs_model, param_class=param_class, **kwargs_likelihood)

        logL, _ = likelihood.logL(args=param_class.kwargs2args(kwargs_source=kwargs_source), verbose=True)
        assert logL <= -10**10
Example #5
0
    def sepc_kwargs_data(self,
                         supersampling_factor=2,
                         psf_data=None,
                         psf_error_map=None):
        import lenstronomy.Util.simulation_util as sim_util
        kwargs_data = sim_util.data_configure_simple(self.numPix,
                                                     self.deltaPix,
                                                     inverse=True)
        kwargs_data['image_data'] = self.data_process_class.target_stamp
        kwargs_data['noise_map'] = self.data_process_class.noise_map

        if psf_data is None:
            psf_data = self.data_process_class.PSF_list[
                self.data_process_class.psf_id_for_fitting]
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf_data,
            'pixel_size': self.deltaPix
        }
        if psf_error_map is not None:
            kwargs_psf['psf_error_map'] = psf_error_map

        kwargs_numerics = {
            'supersampling_factor': supersampling_factor,
            'supersampling_convolution': False
        }
        image_band = [kwargs_data, kwargs_psf, kwargs_numerics]
        multi_band_list = [image_band]
        self.kwargs_data = kwargs_data
        self.kwargs_psf = kwargs_psf
        self.kwargs_numerics = kwargs_numerics
        self.kwargs_data_joint = {
            'multi_band_list': multi_band_list,
            'multi_band_type': 'multi-linear'
        }  # 'single-band', 'multi-linear', 'joint-linear'
 def test_extinction_map(self):
     kwargs_data = sim_util.data_configure_simple(numPix=10, deltaPix=1, exposure_time=1, background_rms=1)
     data_class = ImageData(**kwargs_data)
     extinction_class = DifferentialExtinction(optical_depth_model=['UNIFORM'], tau0_index=0)
     imageModel = ImageModel(data_class, PSF(), extinction_class=extinction_class)
     extinction = imageModel.extinction_map(kwargs_extinction=[{'amp': 1}], kwargs_special={'tau0_list': [1, 0, 0]})
     npt.assert_almost_equal(extinction, np.exp(-1))
    def test_create_empty(self):
        kwargs_data = sim_util.data_configure_simple(numPix=10, deltaPix=1, exposure_time=1, background_rms=1)
        data_class = ImageData(**kwargs_data)
        imageModel_empty = ImageModel(data_class, PSF())
        assert imageModel_empty._psf_error_map == False

        flux = imageModel_empty.lens_surface_brightness(kwargs_lens_light=None)
        assert flux.all() == 0
Example #8
0
 def test_update_data(self):
     kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                  deltaPix=1,
                                                  exposure_time=1,
                                                  background_rms=1,
                                                  inverse=True)
     data_class = ImageData(**kwargs_data)
     self.imageModel.update_data(data_class)
     assert self.imageModel.Data.num_pixel == 100
    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)
Example #10
0
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, coord_center_ra=0, coord_center_dec=0,
                    coord_inverse=False):
    """
    plots a lens model (convergence) and the critical curves and caustics

    :param ax:
    :param kwargs_lens:
    :param numPix:
    :param deltaPix:
    :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)
    #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_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.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.autoscale(False)
    return ax
Example #11
0
    def test_data_configure_simple(self):

        # data specifics
        sigma_bkg = 1.  # background noise per pixel
        exp_time = 10  # 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)
        assert data_class.pixel_width == deltaPix
    def test_force_positive_source_surface_brightness(self):
        kwargs_likelihood = {
            'force_positive_source_surface_brightness': True,
            'numPix_source': 10,
            'deltaPix_source': 0.1
        }
        kwargs_model = {'source_light_model_list': ['SERSIC']}

        kwargs_constraints = {}
        param_class = Param(kwargs_model, **kwargs_constraints)

        kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                     deltaPix=0.1,
                                                     exposure_time=1,
                                                     sigma_bkg=0.1)
        data_class = Data(kwargs_data)
        kwargs_psf = {'psf_type': 'NONE'}
        psf_class = PSF(kwargs_psf)
        kwargs_sersic = {
            'amp': -1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        source_model_list = ['SERSIC']
        kwargs_source = [kwargs_sersic]
        source_model_class = LightModel(light_model_list=source_model_list)

        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class=None,
                                source_model_class=source_model_class)

        image_sim = sim_util.simulate_simple(imageModel, [], kwargs_source)

        data_class.update_data(image_sim)
        likelihood = LikelihoodModule(imSim_class=imageModel,
                                      param_class=param_class,
                                      **kwargs_likelihood)
        logL, _ = likelihood.logL(args=param_class.kwargs2args(
            kwargs_source=kwargs_source))
        assert logL <= -10**10
    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)
Example #14
0
def distortions(lensModel,
                kwargs_lens,
                num_pix=100,
                delta_pix=0.05,
                center_ra=0,
                center_dec=0,
                differential_scale=0.0001,
                smoothing_scale=None,
                **kwargs):
    """

    :param lensModel: LensModel instance
    :param kwargs_lens: lens model keyword argument list
    :param num_pix: number of pixels per axis
    :param delta_pix: pixel scale per axis
    :param center_ra: center of the grid
    :param center_dec: center of the grid
    :param differential_scale: scale of the finite derivative length in units of angles
    :param smoothing_scale: float or None, Gaussian FWHM of a smoothing kernel applied before plotting
    :return: matplotlib instance with different panels
    """
    kwargs_grid = sim_util.data_configure_simple(num_pix,
                                                 delta_pix,
                                                 center_ra=center_ra,
                                                 center_dec=center_dec)
    _coords = ImageData(**kwargs_grid)
    _frame_size = num_pix * delta_pix
    ra_grid, dec_grid = _coords.pixel_coordinates

    extensions = LensModelExtensions(lensModel=lensModel)
    ra_grid1d = util.image2array(ra_grid)
    dec_grid1d = util.image2array(dec_grid)
    lambda_rad, lambda_tan, orientation_angle, dlambda_tan_dtan, dlambda_tan_drad, dlambda_rad_drad, dlambda_rad_dtan, dphi_tan_dtan, dphi_tan_drad, dphi_rad_drad, dphi_rad_dtan = extensions.radial_tangential_differentials(
        ra_grid1d,
        dec_grid1d,
        kwargs_lens=kwargs_lens,
        center_x=center_ra,
        center_y=center_dec,
        smoothing_3rd=differential_scale,
        smoothing_2nd=None)

    lambda_rad2d, lambda_tan2d, orientation_angle2d, dlambda_tan_dtan2d, dlambda_tan_drad2d, dlambda_rad_drad2d, dlambda_rad_dtan2d, dphi_tan_dtan2d, dphi_tan_drad2d, dphi_rad_drad2d, dphi_rad_dtan2d = util.array2image(lambda_rad), \
                                            util.array2image(lambda_tan), util.array2image(orientation_angle), util.array2image(dlambda_tan_dtan), util.array2image(dlambda_tan_drad), util.array2image(dlambda_rad_drad), util.array2image(dlambda_rad_dtan), \
                                            util.array2image(dphi_tan_dtan), util.array2image(dphi_tan_drad), util.array2image(dphi_rad_drad), util.array2image(dphi_rad_dtan)

    if smoothing_scale is not None:
        lambda_rad2d = ndimage.gaussian_filter(lambda_rad2d,
                                               sigma=smoothing_scale /
                                               delta_pix)
        dlambda_rad_drad2d = ndimage.gaussian_filter(dlambda_rad_drad2d,
                                                     sigma=smoothing_scale /
                                                     delta_pix)
        lambda_tan2d = np.abs(lambda_tan2d)
        # the magnification cut is made to make a stable integral/convolution
        lambda_tan2d[lambda_tan2d > 100] = 100
        lambda_tan2d = ndimage.gaussian_filter(lambda_tan2d,
                                               sigma=smoothing_scale /
                                               delta_pix)
        # the magnification cut is made to make a stable integral/convolution
        dlambda_tan_dtan2d[dlambda_tan_dtan2d > 100] = 100
        dlambda_tan_dtan2d[dlambda_tan_dtan2d < -100] = -100
        dlambda_tan_dtan2d = ndimage.gaussian_filter(dlambda_tan_dtan2d,
                                                     sigma=smoothing_scale /
                                                     delta_pix)
        orientation_angle2d = ndimage.gaussian_filter(orientation_angle2d,
                                                      sigma=smoothing_scale /
                                                      delta_pix)
        dphi_tan_dtan2d = ndimage.gaussian_filter(dphi_tan_dtan2d,
                                                  sigma=smoothing_scale /
                                                  delta_pix)

    def _plot_frame(ax, map, vmin, vmax, text_string):
        """

        :param ax: matplotlib.axis instance
        :param map: 2d array
        :param vmin: minimum plotting scale
        :param vmax: maximum plotting scale
        :param text_string: string to describe the label
        :return:
        """
        font_size = 10
        _arrow_size = 0.02
        im = ax.matshow(map,
                        extent=[0, _frame_size, 0, _frame_size],
                        vmin=vmin,
                        vmax=vmax)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.autoscale(False)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cb = plt.colorbar(im, cax=cax, orientation='vertical')
        #cb.set_label(text_string, fontsize=10)
        #plot_util.scale_bar(ax, _frame_size, dist=1, text='1"', font_size=font_size)
        plot_util.text_description(ax,
                                   _frame_size,
                                   text=text_string,
                                   color="k",
                                   backgroundcolor='w',
                                   font_size=font_size)
        #if 'no_arrow' not in kwargs or not kwargs['no_arrow']:
        #    plot_util.coordinate_arrows(ax, _frame_size, _coords,
        #                                color='w', arrow_size=_arrow_size,
        #                                font_size=font_size)

    f, axes = plt.subplots(3, 4, figsize=(12, 8))
    _plot_frame(axes[0, 0],
                lambda_rad2d,
                vmin=0.6,
                vmax=1.4,
                text_string=r"$\lambda_{rad}$")
    _plot_frame(axes[0, 1],
                lambda_tan2d,
                vmin=-20,
                vmax=20,
                text_string=r"$\lambda_{tan}$")
    _plot_frame(axes[0, 2],
                orientation_angle2d,
                vmin=-np.pi / 10,
                vmax=np.pi / 10,
                text_string=r"$\phi$")
    _plot_frame(axes[0, 3],
                util.array2image(lambda_tan * lambda_rad),
                vmin=-20,
                vmax=20,
                text_string='magnification')
    _plot_frame(axes[1, 0],
                dlambda_rad_drad2d / lambda_rad2d,
                vmin=-.1,
                vmax=.1,
                text_string='dlambda_rad_drad')
    _plot_frame(axes[1, 1],
                dlambda_tan_dtan2d / lambda_tan2d,
                vmin=-20,
                vmax=20,
                text_string='dlambda_tan_dtan')
    _plot_frame(axes[1, 2],
                dlambda_tan_drad2d / lambda_tan2d,
                vmin=-20,
                vmax=20,
                text_string='dlambda_tan_drad')
    _plot_frame(axes[1, 3],
                dlambda_rad_dtan2d / lambda_rad2d,
                vmin=-.1,
                vmax=.1,
                text_string='dlambda_rad_dtan')

    _plot_frame(axes[2, 0],
                dphi_rad_drad2d,
                vmin=-.1,
                vmax=.1,
                text_string='dphi_rad_drad')
    _plot_frame(axes[2, 1],
                dphi_tan_dtan2d,
                vmin=0,
                vmax=20,
                text_string='dphi_tan_dtan: curvature radius')
    _plot_frame(axes[2, 2],
                dphi_tan_drad2d,
                vmin=-.1,
                vmax=.1,
                text_string='dphi_tan_drad')
    _plot_frame(axes[2, 3],
                dphi_rad_dtan2d,
                vmin=0,
                vmax=20,
                text_string='dphi_rad_dtan')

    return f, axes
Example #15
0
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
Example #16
0
    def setup(self):
        np.random.seed(42)

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 50  # cutout pixel size
        deltaPix = 0.1  # pixel size in arcsec (area per pixel = deltaPix**2)
        fwhm = 0.5  # full width half max of PSF

        kwargs_model = {'lens_model_list': ['SPEP'],
                        'lens_light_model_list': ['SERSIC'],
                        'source_light_model_list': ['SERSIC'],
                        'point_source_model_list': ['SOURCE_POSITION'],
                        'fixed_magnification_list': [True]}

        # PSF specification
        kwargs_band = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_band)
        kwargs_psf = {'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'pixel_size': deltaPix}
        psf_class = PSF(**kwargs_psf)
        print(np.shape(psf_class.kernel_point_source), 'test kernel shape -')
        kwargs_spep = {'theta_E': 1., 'gamma': 1.95, 'center_x': 0, 'center_y': 0, 'e1': 0.1, 'e2': 0.1}

        self.kwargs_lens = [kwargs_spep]
        kwargs_sersic = {'amp': 1/0.05**2., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0}
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {'amp': 1., 'R_sersic': .6, 'n_sersic': 3, 'center_x': 0, 'center_y': 0}

        self.kwargs_lens_light = [kwargs_sersic]
        self.kwargs_source = [kwargs_sersic_ellipse]
        self.kwargs_ps = [{'ra_source': 0.55, 'dec_source': 0.02,
                           'source_amp': 1.}]  # quasar point source position in the source plane and intrinsic brightness
        self.kwargs_cosmo = {'D_dt': 1000}
        kwargs_numerics = {'supersampling_factor': 1, 'supersampling_convolution': False}
        lens_model_class, source_model_class, lens_light_model_class, point_source_class, extinction_class = class_creator.create_class_instances(**kwargs_model)
        imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class,
                                lens_light_model_class, point_source_class, extinction_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)
        ra_pos, dec_pos = imageModel.PointSource.image_position(kwargs_ps=self.kwargs_ps, kwargs_lens=self.kwargs_lens)

        data_class.update_data(image_sim)
        kwargs_band['image_data'] = image_sim
        self.data_class = data_class
        self.psf_class = psf_class

        self.kwargs_model = kwargs_model
        self.kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False}

        kwargs_constraints = {
                                   'num_point_source_list': [4],
                                   'solver_type': 'NONE',  # 'PROFILE', 'PROFILE_SHEAR', 'ELLIPSE', 'CENTER'
                                   'Ddt_sampling': True
                                   }

        def condition_definition(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps=None, kwargs_special=None, kwargs_extinction=None):
            logL = 0
            if kwargs_lens_light[0]['R_sersic'] > kwargs_source[0]['R_sersic']:
                logL -= 10**15
            return logL

        kwargs_likelihood = {'force_no_add_image': True,
                             'source_marg': True,
                             'astrometric_likelihood': True,
                             'image_position_uncertainty': 0.004,
                             'check_matched_source_position': False,
                             'source_position_tolerance': 0.001,
                             'source_position_sigma': 0.001,
                             'check_positive_flux': True,
                             'flux_ratio_likelihood': True,
                             'prior_lens': [[0, 'theta_E', 1, 0.1]],
                             'custom_logL_addition': condition_definition,
                             'image_position_likelihood': True
                             }
        self.kwargs_data = {'multi_band_list': [[kwargs_band, kwargs_psf, kwargs_numerics]], 'multi_band_type': 'single-band',
                            'time_delays_measured': np.ones(4),
                            'time_delays_uncertainties': np.ones(4),
                            'flux_ratios': np.ones(4),
                            'flux_ratio_errors': np.ones(4),
                            'ra_image_list': ra_pos,
                            'dec_image_list': dec_pos
                            }
        self.param_class = Param(self.kwargs_model, **kwargs_constraints)
        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.Likelihood = LikelihoodModule(kwargs_data_joint=self.kwargs_data, kwargs_model=kwargs_model, param_class=self.param_class, **kwargs_likelihood)
        self.kwargs_band = kwargs_band
        self.kwargs_psf = kwargs_psf
        self.numPix = numPix
Example #17
0
    def setup(self):

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # cutout pixel size
        deltaPix = 0.1  # 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_gaussian = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix
        }
        psf = PSF(**kwargs_psf_gaussian)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf.kernel_point_source
        }
        psf_class = PSF(**kwargs_psf)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_model_list = ['SPEP']
        self.kwargs_lens = [kwargs_spemd]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {
            'amp': 1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        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)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False,
            'compute_mode': 'regular'
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                kwargs_numerics=kwargs_numerics)
        image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens,
                                             self.kwargs_source,
                                             self.kwargs_lens_light)

        data_class.update_data(image_sim)
        kwargs_data['image_data'] = image_sim
        kwargs_data_joint = {
            'multi_band_list': [[kwargs_data, kwargs_psf, kwargs_numerics]],
            'multi_band_type': 'single-band'
        }
        self.data_class = data_class
        self.psf_class = psf_class

        kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'lens_light_model_list': lens_light_model_list,
            'fixed_magnification_list': [False],
        }
        self.kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}

        kwargs_constraints = {
            'image_plane_source_list': [False] * len(source_model_list)
        }

        kwargs_likelihood = {
            'source_marg': False,
            'position_uncertainty': 0.004,
            'check_solver': False,
            'solver_tolerance': 0.001,
        }
        self.param_class = Param(kwargs_model, **kwargs_constraints)
        self.Likelihood = LikelihoodModule(kwargs_data_joint=kwargs_data_joint,
                                           kwargs_model=kwargs_model,
                                           param_class=self.param_class,
                                           **kwargs_likelihood)

        prior_means = self.param_class.kwargs2args(
            kwargs_lens=self.kwargs_lens,
            kwargs_source=self.kwargs_source,
            kwargs_lens_light=self.kwargs_lens_light)
        prior_sigmas = np.ones_like(prior_means) * 0.1
        self.output_dir = 'test_nested_out'
        self.sampler = MultiNestSampler(self.Likelihood,
                                        prior_type='uniform',
                                        prior_means=prior_means,
                                        prior_sigmas=prior_sigmas,
                                        output_dir=self.output_dir,
                                        remove_output_dir=True)
    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)
        # vgrad = np.gradient(lens_data)
        # fulgrad = np.sqrt(vgrad[0]**2 + vgrad[1]**2)
        # len_std = (abs(lens_data/exp_time)+stdd**2)**0.5
        # len_std = len_std + fulgrad/fulgrad.max() * len_std.max()

        deltaPix = 0.08

        psf = pyfits.getdata(folder + 'Drz_PSF.fits')
        psf_fsize = 77
        psf_half_r = int(psf_fsize / 2)
        psf_peak = np.where(psf == psf.max())
        psf_peak = [psf_peak[0][0], psf_peak[1][0]]
        psf = psf[psf_peak[0] - psf_half_r:psf_peak[0] + psf_half_r + 1,
                  psf_peak[1] - psf_half_r:psf_peak[1] + psf_half_r + 1]

        kwargs_data = sim_util.data_configure_simple(
            numPix=framesize, deltaPix=deltaPix)  #,inverse=True)
        kwargs_data['image_data'] = lens_data
        kwargs_data['noise_map'] = len_std

        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf,
            'pixel_size': deltaPix
        }
        psf_class = PSF(**kwargs_psf)

        #%%
        # lens model choicers
        fixed_lens = []
        kwargs_lens_init = []
Example #20
0
numPix = int( 240 * 0.13/0.05 ) + 1  #  pixel size  #!!!
deltaPix = 0.05/4 #  pixel size in arcsec (area per pixel = deltaPix**2)

psf = pyfits.open('psf_{0}_sub4.fits'.format(filt))
psf_data = psf[0].data
cut =25 
# psf_data = psf_data[1+cut:-cut,1+cut:-cut]+ 0  #shave PSF to singular size, as max in the middle
plt.imshow(psf_data, origin='lower',cmap='gist_heat', norm=LogNorm())
plt.colorbar()
plt.close()

kwargs_psf_high_res = {'psf_type': 'PIXEL', 'kernel_point_source': psf_data, 'pixel_size': deltaPix}
psf_class = PSF(**kwargs_psf_high_res)

zp= 25.9463   #Assuming it same as F160W
kwargs_data_high_res = sim_util.data_configure_simple(numPix, deltaPix) #,inverse=True)
data_class = Data(**kwargs_data_high_res)
kwargs_numerics = {'supersampling_factor': 12, 'supersampling_convolution': False}

import sys
sys.path.insert(0,'../../share_tools/')
from gene_para import gene_para
for seed in range(702, 799):
    print(seed)
    para=gene_para(seed=seed,fixh0=102)
    #==============================================================================
    # #######lens light 
    #==============================================================================
    from lenstronomy.LightModel.light_model import LightModel
    lens_light_para=para.lens_light()
    np.random.seed(seed)
Example #21
0
    def __init__(self, *args, **kwargs):
        super(TestRaise, self).__init__(*args, **kwargs)
        # data specifics
        sigma_bkg = .05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 100  # cutout pixel size
        deltaPix = 0.05  # pixel size in arcsec (area per pixel = deltaPix**2)
        fwhm = 0.5  # full width half max of PSF

        # PSF specification

        kwargs_data = sim_util.data_configure_simple(numPix,
                                                     deltaPix,
                                                     exp_time,
                                                     sigma_bkg,
                                                     inverse=True)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'truncation': 5,
            'pixel_size': deltaPix
        }
        psf_class = PSF(**kwargs_psf)
        kernel = psf_class.kernel_point_source
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel,
            'psf_error_map': np.ones_like(kernel) * 0.001
        }
        psf_class = PSF(**kwargs_psf)

        # 'EXERNAL_SHEAR': external shear
        kwargs_shear = {
            'gamma1': 0.01,
            'gamma2': 0.01
        }  # gamma_ext: shear strength, psi_ext: shear angel (in radian)
        phi, q = 0.2, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': e1,
            'e2': e2
        }

        lens_model_list = ['SPEP', 'SHEAR']
        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']
        kwargs_lens_light = [kwargs_sersic]
        lens_light_model_class = LightModel(
            light_model_list=lens_light_model_list)
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_source = [kwargs_sersic_ellipse]
        source_model_class = LightModel(light_model_list=source_model_list)
        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 = {'supersampling_factor': 2}
        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, kwargs_lens,
                                             kwargs_source, kwargs_lens_light,
                                             kwargs_ps)
        data_class.update_data(image_sim)

        self.imageModel = imageModel
        self.kwargs_sparse_solver = {}
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]
    }
Example #23
0
    def __init__(self, *args, **kwargs):
        super(TestRaise, self).__init__(*args, **kwargs)
        # data specifics
        sigma_bkg = .05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 100  # cutout pixel size
        deltaPix = 0.05  # pixel size in arcsec (area per pixel = deltaPix**2)
        fwhm = 0.5  # full width half max of PSF

        # PSF specification

        kwargs_data = sim_util.data_configure_simple(numPix,
                                                     deltaPix,
                                                     exp_time,
                                                     sigma_bkg,
                                                     inverse=True)
        self.data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'truncation': 5,
            'pixel_size': deltaPix
        }
        psf_class = PSF(**kwargs_psf)
        kernel = psf_class.kernel_point_source
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel,
            'psf_error_map': np.ones_like(kernel) * 0.001
        }
        self.psf_class = PSF(**kwargs_psf)

        # 'EXERNAL_SHEAR': external shear
        kwargs_shear = {
            'gamma1': 0.01,
            'gamma2': 0.01
        }  # gamma_ext: shear strength, psi_ext: shear angel (in radian)
        phi, q = 0.2, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': e1,
            'e2': e2
        }

        lens_model_list = ['SPEP', 'SHEAR']
        self.kwargs_lens = [kwargs_spemd, kwargs_shear]
        self.lens_model_class = LensModel(lens_model_list=lens_model_list)
        # list of light profiles (for lens and source)
        # 'SERSIC': spherical Sersic profile
        kwargs_sersic = {
            'amp': 1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        phi, q = 0.2, 0.9
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 7,
            'center_x': 0,
            'center_y': 0,
            'e1': e1,
            'e2': e2
        }

        lens_light_model_list = ['SERSIC']
        kwargs_lens_light_base = [kwargs_sersic]
        lens_light_model_class_base = LightModel(
            light_model_list=lens_light_model_list)
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_source_base = [kwargs_sersic_ellipse]
        source_model_class_base = LightModel(
            light_model_list=source_model_list)
        self.kwargs_ps = [
            {
                'ra_source': 0.01,
                'dec_source': 0.0,
                'source_amp': 1.
            }
        ]  # quasar point source position in the source plane and intrinsic brightness
        point_source_class_base = PointSource(
            point_source_type_list=['SOURCE_POSITION'],
            fixed_magnification_list=[True])
        kwargs_numerics_base = {
            'supersampling_factor': 2,
            'supersampling_convolution': False
        }
        imageModel_base = ImageModel(self.data_class,
                                     self.psf_class,
                                     self.lens_model_class,
                                     source_model_class_base,
                                     lens_light_model_class_base,
                                     point_source_class_base,
                                     kwargs_numerics=kwargs_numerics_base)
        image_sim = sim_util.simulate_simple(imageModel_base, self.kwargs_lens,
                                             kwargs_source_base,
                                             kwargs_lens_light_base,
                                             self.kwargs_ps)
        self.data_class.update_data(image_sim)

        # create a starlet light distributions
        n_scales = 6
        source_map = imageModel_base.source_surface_brightness(
            kwargs_source_base, de_lensed=True, unconvolved=True)
        starlets_class = SLIT_Starlets(force_no_pysap=_force_no_pysap)
        source_map_starlets = starlets_class.decomposition_2d(
            source_map, n_scales)
        self.kwargs_source = [{
            'amp': source_map_starlets,
            'n_scales': n_scales,
            'n_pixels': numPix,
            'scale': deltaPix,
            'center_x': 0,
            'center_y': 0
        }]
        self.source_model_class = LightModel(
            light_model_list=['SLIT_STARLETS'])
        lens_light_map = imageModel_base.lens_surface_brightness(
            kwargs_lens_light_base, unconvolved=True)
        starlets_class = SLIT_Starlets(force_no_pysap=_force_no_pysap,
                                       second_gen=True)
        lens_light_starlets = starlets_class.decomposition_2d(
            lens_light_map, n_scales)
        self.kwargs_lens_light = [{
            'amp': lens_light_starlets,
            'n_scales': n_scales,
            'n_pixels': numPix,
            'scale': deltaPix,
            'center_x': 0,
            'center_y': 0
        }]
        self.lens_light_model_class = LightModel(
            light_model_list=['SLIT_STARLETS_GEN2'])

        self.kwargs_numerics = {'supersampling_factor': 1}
        self.kwargs_pixelbased = {
            'supersampling_factor_source':
            2,  # supersampling of pixelated source grid

            # following choices are to minimize pixel solver runtime (not to get accurate reconstruction!)
            'threshold_decrease_type': 'none',
            'num_iter_source': 2,
            'num_iter_lens': 2,
            'num_iter_global': 2,
            'num_iter_weights': 2,
        }
    def setup(self):

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # 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

        self.kwargs_data = sim_util.data_configure_simple(
            numPix, deltaPix, exp_time, sigma_bkg)
        data_class = ImageData(**self.kwargs_data)
        kwargs_psf_gaussian = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_gaussian = PSF(**kwargs_psf_gaussian)
        self.kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf_gaussian.kernel_point_source,
            'psf_error_map': np.zeros_like(psf_gaussian.kernel_point_source)
        }
        psf_class = PSF(**self.kwargs_psf)
        # 'EXTERNAL_SHEAR': external shear
        kwargs_shear = {
            'gamma1': 0.01,
            'gamma2': 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,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_model_list = ['SPEP', 'SHEAR']
        self.kwargs_lens = [kwargs_spemd, kwargs_shear]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {
            'amp': 1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        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_list = ['SOURCE_POSITION']
        point_source_class = PointSource(
            point_source_type_list=point_source_list,
            fixed_magnification_list=[True])
        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False,
            'compute_mode': 'regular',
            'point_source_supersampling_factor': 1
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class,
                                kwargs_numerics=kwargs_numerics)
        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.data_class = data_class
        self.psf_class = psf_class
        self.kwargs_data['image_data'] = image_sim
        self.kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'lens_light_model_list': lens_light_model_list,
            'point_source_model_list': point_source_list,
            'fixed_magnification_list': [False],
            'index_lens_model_list': [[0, 1]],
        }
        self.kwargs_numerics = kwargs_numerics

        num_source_model = len(source_model_list)

        self.kwargs_constraints = {
            'num_point_source_list': [4],
            'image_plane_source_list': [False] * num_source_model,
            'solver_type':
            'NONE',  # 'PROFILE', 'PROFILE_SHEAR', 'ELLIPSE', 'CENTER'
        }

        self.kwargs_likelihood = {
            'force_no_add_image': True,
            'source_marg': True,
            'linear_prior': [1],
            'image_position_uncertainty': 0.004,
            'check_matched_source_position': False,
            'source_position_tolerance': 0.001,
            'source_position_sigma': 0.001,
            'check_positive_flux': True,
        }

        lens_sigma = [{
            'theta_E': 0.1,
            'gamma': 0.1,
            'e1': 0.1,
            'e2': 0.1,
            'center_x': 0.1,
            'center_y': 0.1
        }, {
            'gamma1': 0.1,
            'gamma2': 0.1
        }]
        lens_lower = [{
            'theta_E': 0.,
            'gamma': 1.5,
            'center_x': -2,
            'center_y': -2,
            'e1': -0.4,
            'e2': -0.4
        }, {
            'gamma1': -0.3,
            'gamma2': -0.3
        }]
        lens_upper = [{
            'theta_E': 10.,
            'gamma': 2.5,
            'center_x': 2,
            'center_y': 2,
            'e1': 0.4,
            'e2': 0.4
        }, {
            'gamma1': 0.3,
            'gamma2': 0.3
        }]
        source_sigma = [{
            'R_sersic': 0.05,
            'n_sersic': 0.5,
            'center_x': 0.1,
            'center_y': 0.1,
            'e1': 0.1,
            'e2': 0.1
        }]
        source_lower = [{
            'R_sersic': 0.01,
            'n_sersic': 0.5,
            'center_x': -2,
            'center_y': -2,
            'e1': -0.4,
            'e2': -0.4
        }]
        source_upper = [{
            'R_sersic': 10,
            'n_sersic': 5.5,
            'center_x': 2,
            'center_y': 2,
            'e1': 0.4,
            'e2': 0.4
        }]

        lens_light_sigma = [{
            'R_sersic': 0.05,
            'n_sersic': 0.5,
            'center_x': 0.1,
            'center_y': 0.1
        }]
        lens_light_lower = [{
            'R_sersic': 0.01,
            'n_sersic': 0.5,
            'center_x': -2,
            'center_y': -2
        }]
        lens_light_upper = [{
            'R_sersic': 10,
            'n_sersic': 5.5,
            'center_x': 2,
            'center_y': 2
        }]
        ps_sigma = [{'ra_source': 1, 'dec_source': 1, 'point_amp': 1}]

        lens_param = self.kwargs_lens, lens_sigma, [{}, {
            'ra_0': 0,
            'dec_0': 0
        }], lens_lower, lens_upper
        source_param = self.kwargs_source, source_sigma, [
            {}
        ], source_lower, source_upper
        lens_light_param = self.kwargs_lens_light, lens_light_sigma, [{
            'center_x':
            0
        }], lens_light_lower, lens_light_upper
        ps_param = self.kwargs_ps, ps_sigma, [{}
                                              ], self.kwargs_ps, self.kwargs_ps

        self.kwargs_params = {
            'lens_model': lens_param,
            'source_model': source_param,
            'lens_light_model': lens_light_param,
            'point_source_model': ps_param,
            # 'cosmography': cosmo_param
        }
        image_band = [self.kwargs_data, self.kwargs_psf, self.kwargs_numerics]
        multi_band_list = [image_band]
        self.kwargs_data_joint = {
            'multi_band_list': multi_band_list,
            'multi_band_type': 'multi-linear'
        }
Example #25
0
import lenstronomy.Util.simulation_util as sim_util
import lenstronomy.Util.image_util as image_util
from lenstronomy.Data.imaging_data import ImageData
from lenstronomy.Data.psf import PSF

# data specifics
background_rms = .05  # background noise per pixel
exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
numPix = 50  # cutout pixel size
deltaPix = 0.3  # pixel size in arcsec (area per pixel = deltaPix**2)
fwhm = 0.8  # full width half max of PSF

kwargs_data = sim_util.data_configure_simple(numPix,
                                             deltaPix,
                                             exp_time,
                                             background_rms,
                                             inverse=True)
data_class = ImageData(**kwargs_data)
# PSF specification
kwargs_psf = {
    'psf_type': 'GAUSSIAN',
    'fwhm': fwhm,
    'pixel_size': deltaPix,
    'truncation': 6
}
psf_class = PSF(**kwargs_psf)
# create a model with three Sersic profiles
# all the models are part of 'lens_light_model_list', meaning that their surface brightness profile are not lensed
lens_light_model_list = ['SERSIC_ELLIPSE']
from lenstronomy.LightModel.light_model import LightModel
    def test_zeus(self):
        # we make a very basic lens+source model to feed to check zeus can be run through fitting sequence
        # we don't use the kwargs defined in setup() as those are modified during the tests; using unique kwargs here is safer

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # 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_gaussian = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_gaussian = PSF(**kwargs_psf_gaussian)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf_gaussian.kernel_point_source,
            'psf_error_map': np.zeros_like(psf_gaussian.kernel_point_source)
        }
        psf_class = PSF(**kwargs_psf)

        # make a lens
        lens_model_list = ['EPL']
        kwargs_epl = {
            'theta_E': 0.6,
            'gamma': 2.6,
            'center_x': 0.0,
            'center_y': 0.0,
            'e1': 0.1,
            'e2': 0.1
        }
        kwargs_lens = [kwargs_epl]
        lens_model_class = LensModel(lens_model_list=lens_model_list)

        # make a source
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': 0.6,
            'n_sersic': 3,
            'center_x': 0.0,
            'center_y': 0.0,
            'e1': 0.1,
            'e2': 0.1
        }
        kwargs_source = [kwargs_sersic_ellipse]
        source_model_class = LightModel(light_model_list=source_model_list)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False
        }

        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                kwargs_numerics=kwargs_numerics)
        image_sim = sim_util.simulate_simple(imageModel, kwargs_lens,
                                             kwargs_source)

        data_class.update_data(image_sim)

        kwargs_data['image_data'] = image_sim

        kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list
        }

        lens_fixed = [{}]
        lens_sigma = [{
            'theta_E': 0.1,
            'gamma': 0.1,
            'e1': 0.1,
            'e2': 0.1,
            'center_x': 0.1,
            'center_y': 0.1
        }]
        lens_lower = [{
            'theta_E': 0.,
            'gamma': 1.5,
            'center_x': -2,
            'center_y': -2,
            'e1': -0.4,
            'e2': -0.4
        }]
        lens_upper = [{
            'theta_E': 10.,
            'gamma': 2.5,
            'center_x': 2,
            'center_y': 2,
            'e1': 0.4,
            'e2': 0.4
        }]

        source_fixed = [{}]
        source_sigma = [{
            'R_sersic': 0.05,
            'n_sersic': 0.5,
            'center_x': 0.1,
            'center_y': 0.1,
            'e1': 0.1,
            'e2': 0.1
        }]
        source_lower = [{
            'R_sersic': 0.01,
            'n_sersic': 0.5,
            'center_x': -2,
            'center_y': -2,
            'e1': -0.4,
            'e2': -0.4
        }]
        source_upper = [{
            'R_sersic': 10,
            'n_sersic': 5.5,
            'center_x': 2,
            'center_y': 2,
            'e1': 0.4,
            'e2': 0.4
        }]

        lens_param = [
            kwargs_lens, lens_sigma, lens_fixed, lens_lower, lens_upper
        ]
        source_param = [
            kwargs_source, source_sigma, source_fixed, source_lower,
            source_upper
        ]

        kwargs_params = {
            'lens_model': lens_param,
            'source_model': source_param
        }

        kwargs_constraints = {}

        multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics]]

        kwargs_data_joint = {
            'multi_band_list': multi_band_list,
            'multi_band_type': 'multi-linear'
        }

        kwargs_likelihood = {'source_marg': True}

        fittingSequence = FittingSequence(kwargs_data_joint, kwargs_model,
                                          kwargs_constraints,
                                          kwargs_likelihood, kwargs_params)

        fitting_list = []
        kwargs_zeus = {
            'sampler_type': 'ZEUS',
            'n_burn': 2,
            'n_run': 2,
            'walkerRatio': 4
        }

        fitting_list.append(['MCMC', kwargs_zeus])

        chain_list = fittingSequence.fit_sequence(fitting_list)
Example #27
0
    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)
Example #28
0
    def test_raise(self):
        with self.assertRaises(ValueError):
            kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                         deltaPix=1,
                                                         background_rms=1)
            #kwargs_data['image_data'] = np.zeros((10, 10))
            kwargs_model = {'source_light_model_list': ['GAUSSIAN']}
            kwargs_params = {
                'kwargs_lens': [],
                'kwargs_source': [{
                    'amp': 1,
                    'sigma': 1,
                    'center_x': 0,
                    'center_y': 0
                }],
                'kwargs_ps': [],
                'kwargs_lens_light': []
            }
            lensPlot = ModelPlot(
                multi_band_list=[[kwargs_data, {
                    'psf_type': 'NONE'
                }, {}]],
                kwargs_model=kwargs_model,
                kwargs_params=kwargs_params,
                arrow_size=0.02,
                cmap_string="gist_heat")
        with self.assertRaises(ValueError):
            kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                         deltaPix=1,
                                                         background_rms=1)
            # kwargs_data['image_data'] = np.zeros((10, 10))
            kwargs_model = {'source_light_model_list': ['GAUSSIAN']}
            kwargs_params = {
                'kwargs_lens': [],
                'kwargs_source': [{
                    'amp': 1,
                    'sigma': 1,
                    'center_x': 0,
                    'center_y': 0
                }],
                'kwargs_ps': [],
                'kwargs_lens_light': []
            }
            lensPlot = ModelPlot(multi_band_list=[[kwargs_data, {}, {}]],
                                 kwargs_model=kwargs_model,
                                 kwargs_params=kwargs_params,
                                 arrow_size=0.02,
                                 cmap_string="gist_heat")
            f, ax = plt.subplots(1, 1, figsize=(4, 4))
            ax = lensPlot.source_plot(ax=ax,
                                      numPix=10,
                                      deltaPix_source=0.1,
                                      v_min=None,
                                      v_max=None,
                                      with_caustics=False,
                                      caustic_color='yellow',
                                      fsize=15,
                                      plot_scale='bad')
            plt.close()
        with self.assertRaises(ValueError):
            kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                         deltaPix=1,
                                                         background_rms=1)
            # kwargs_data['image_data'] = np.zeros((10, 10))
            kwargs_model = {'source_light_model_list': ['GAUSSIAN']}
            kwargs_params = {
                'kwargs_lens': [],
                'kwargs_source': [{
                    'amp': 1,
                    'sigma': 1,
                    'center_x': 0,
                    'center_y': 0
                }],
                'kwargs_ps': [],
                'kwargs_lens_light': []
            }
            lensPlot = ModelPlot(
                multi_band_list=[[kwargs_data, {
                    'psf_type': 'NONE'
                }, {}]],
                kwargs_model=kwargs_model,
                kwargs_params=kwargs_params,
                bands_compute=[False],
                arrow_size=0.02,
                cmap_string="gist_heat")
            lensPlot._select_band(band_index=0)

        with self.assertRaises(ValueError):
            kwargs_data = sim_util.data_configure_simple(numPix=10,
                                                         deltaPix=1,
                                                         background_rms=1,
                                                         exposure_time=1)
            # kwargs_data['image_data'] = np.zeros((10, 10))
            kwargs_model = {'source_light_model_list': ['GAUSSIAN']}
            kwargs_params = {
                'kwargs_lens': [],
                'kwargs_source': [{
                    'amp': 1,
                    'sigma': 1,
                    'center_x': 0,
                    'center_y': 0
                }],
                'kwargs_ps': [],
                'kwargs_lens_light': []
            }
            lensPlot = ModelPlot(
                multi_band_list=[[kwargs_data, {
                    'psf_type': 'NONE'
                }, {}]],
                kwargs_model=kwargs_model,
                kwargs_params=kwargs_params,
                bands_compute=[True],
                arrow_size=0.02,
                cmap_string="gist_heat")

            f, ax = plt.subplots(1, 1, figsize=(4, 4))
            ax = lensPlot.source_plot(ax=ax,
                                      numPix=10,
                                      deltaPix_source=0.1,
                                      v_min=None,
                                      v_max=None,
                                      with_caustics=False,
                                      caustic_color='yellow',
                                      fsize=15,
                                      plot_scale='wrong')
            plt.close()
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 = .05  # background noise per pixel (Gaussian)
        exp_time = 100.  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 100  # cutout pixel size
        deltaPix = 0.05  # pixel size in arcsec (area per pixel = deltaPix**2)
        fwhm = 0.1  # full width half max of PSF (only valid when psf_type='gaussian')
        psf_type = 'GAUSSIAN'  # 'GAUSSIAN', 'PIXEL', 'NONE'

        # generate the coordinate grid and image properties
        kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg)
        kwargs_data['exposure_time'] = exp_time * np.ones_like(kwargs_data['image_data'])
        data_class = ImageData(**kwargs_data)
        # generate the psf variables

        kwargs_psf = {'psf_type': psf_type, 'pixel_size': deltaPix, 'fwhm': fwhm}
        # kwargs_psf = sim_util.psf_configure_simple(psf_type=psf_type, fwhm=fwhm, kernelsize=kernel_size, deltaPix=deltaPix, kernel=kernel)
        psf_class = PSF(**kwargs_psf)

        # lensing quantities
        kwargs_shear = {'gamma1': 0.02, 'gamma2': -0.04}  # shear values to the source plane
        kwargs_spemd = {'theta_E': 1.26, 'gamma': 2., 'center_x': 0.0, 'center_y': 0.0, 'e1': -0.1,
                        'e2': 0.05}  # parameters of the deflector lens model

        # the lens model is a supperposition of an elliptical lens model with external shear
        lens_model_list = ['EPL', 'SHEAR']
        kwargs_lens_true = [kwargs_spemd, kwargs_shear]
        lens_model_class = LensModel(lens_model_list=lens_model_list)

        # choice of source type
        source_type = 'SERSIC'  # 'SERSIC' or 'SHAPELETS'

        source_x = 0.
        source_y = 0.05

        # Sersic parameters in the initial simulation
        phi_G, q = 0.5, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_sersic_source = {'amp': 1000, 'R_sersic': 0.05, 'n_sersic': 1, 'e1': e1, 'e2': e2, 'center_x': source_x,
                                'center_y': source_y}
        # kwargs_else = {'sourcePos_x': source_x, 'sourcePos_y': source_y, 'quasar_amp': 400., 'gamma1_foreground': 0.0, 'gamma2_foreground':-0.0}
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_source_true = [kwargs_sersic_source]
        source_model_class = LightModel(light_model_list=source_model_list)

        lensEquationSolver = LensEquationSolver(lens_model_class)
        x_image, y_image = lensEquationSolver.findBrightImage(source_x, source_y, kwargs_lens_true, numImages=4,
                                                              min_distance=deltaPix, search_window=numPix * deltaPix)
        mag = lens_model_class.magnification(x_image, y_image, kwargs=kwargs_lens_true)

        kwargs_numerics = {'supersampling_factor': 1}

        imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class,
                                kwargs_numerics=kwargs_numerics)

        # generate image
        model = imageModel.image(kwargs_lens_true, kwargs_source_true)
        poisson = image_util.add_poisson(model, exp_time=exp_time)
        bkg = image_util.add_background(model, sigma_bkd=sigma_bkg)
        image_sim = model + bkg + poisson

        data_class.update_data(image_sim)
        kwargs_data['image_data'] = image_sim

        kwargs_model = {'lens_model_list': lens_model_list,
                        'source_light_model_list': source_model_list,
                        }

        # make cutous and data instances of them
        x_pos, y_pos = data_class.map_coord2pix(x_image, y_image)
        ra_grid, dec_grid = data_class.pixel_coordinates

        multi_band_list = []
        for i in range(len(x_pos)):
            n_cut = 12
            x_c = int(x_pos[i])
            y_c = int(y_pos[i])
            image_cut = image_sim[int(y_c - n_cut):int(y_c + n_cut), int(x_c - n_cut):int(x_c + n_cut)]
            exposure_map_cut = data_class.exposure_map[int(y_c - n_cut):int(y_c + n_cut),
                               int(x_c - n_cut):int(x_c + n_cut)]
            kwargs_data_i = {
                'background_rms': data_class.background_rms,
                'exposure_time': exposure_map_cut,
                'ra_at_xy_0': ra_grid[y_c - n_cut, x_c - n_cut], 'dec_at_xy_0': dec_grid[y_c - n_cut, x_c - n_cut],
                'transform_pix2angle': data_class.transform_pix2angle
                , 'image_data': image_cut
            }
            multi_band_list.append([kwargs_data_i, kwargs_psf, kwargs_numerics])

        kwargs_params = {'kwargs_lens': kwargs_lens_true, 'kwargs_source': kwargs_source_true}
        self.multiPatch = MultiPatchPlot(multi_band_list, kwargs_model, kwargs_params, multi_band_type='joint-linear',
                 kwargs_likelihood=None, verbose=True, cmap_string="gist_heat")
        self.data_class = data_class
        self.model = model
        self.lens_model_class = lens_model_class
        self.kwargs_lens = kwargs_lens_true