Example #1
0
 def test_update_data(self):
     kwargs_data = {'image_data': np.zeros((self.numPix, self.numPix)),
                    'noise_map': None, 'exposure_time': 1, 'background_rms': 1}
     data = ImageData(**kwargs_data)
     C_D = data.C_D
     data.update_data(image_data=np.ones((self.numPix, self.numPix)))
     C_D_new = data.C_D
     assert C_D_new[0,0] > C_D[0, 0]
     data_new = data.data
     npt.assert_almost_equal(data_new, np.ones((self.numPix, self.numPix)))
    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 #3
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 = ImageData(**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=sigma,
                                                center_x=0,
                                                center_y=0)
        kernel_point_source /= np.sum(kernel_point_source)
        kernel_point_source = util.array2image(kernel_point_source)
        psf_error_map = np.zeros_like(kernel_point_source)
        self.kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel_point_source,
            'psf_error_map': psf_error_map
        }

        psf_class = PSF(**self.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]
        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 = {
            'supersampling_factor': 3,
            'supersampling_convolution': False,
            'compute_mode': 'regular',
            'point_source_supersampling_factor': 3
        }
        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 = ImageLinearFit(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)
        self.kwargs_params = {
            'kwargs_lens': self.kwargs_lens,
            'kwargs_source': self.kwargs_source,
            'kwargs_lens_light': self.kwargs_lens_light,
            'kwargs_ps': self.kwargs_ps
        }
Example #4
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 = {}
Example #5
0
class TestRaise(unittest.TestCase):
    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 test_raise(self):
        with self.assertRaises(ValueError):
            # test various numerics that are not supported by the pixelbased solver
            kwargs_numerics = {
                'supersampling_factor': 2,
                'supersampling_convolution': True
            }
            imageModel = ImageLinearFit(
                self.data_class,
                self.psf_class,
                self.lens_model_class,
                source_model_class=self.source_model_class,
                lens_light_model_class=self.lens_light_model_class,
                kwargs_numerics=kwargs_numerics,
                kwargs_pixelbased=self.kwargs_pixelbased)
        with self.assertRaises(ValueError):
            # test various numerics that are not supported by the pixelbased solver
            kwargs_numerics = {'compute_mode': 'adaptive'}
            imageModel = ImageLinearFit(
                self.data_class,
                self.psf_class,
                self.lens_model_class,
                source_model_class=self.source_model_class,
                lens_light_model_class=self.lens_light_model_class,
                kwargs_numerics=kwargs_numerics,
                kwargs_pixelbased=self.kwargs_pixelbased)
        with self.assertRaises(ValueError):
            # test unsupported gaussian PSF type
            kwargs_psf = {
                'psf_type': 'GAUSSIAN',
                'fwhm': 0.5,
                'truncation': 5,
                'pixel_size': 0.05
            }
            psf_class = PSF(**kwargs_psf)
            imageModel = ImageLinearFit(
                self.data_class,
                psf_class,
                self.lens_model_class,
                source_model_class=self.source_model_class,
                lens_light_model_class=self.lens_light_model_class,
                kwargs_numerics=self.kwargs_numerics,
                kwargs_pixelbased=self.kwargs_pixelbased)
        with self.assertRaises(ValueError):
            kwargs_numerics = {'supersampling_factor': 1}
            # test more than a single pixel-based light profile
            source_model_class = LightModel(['SLIT_STARLETS', 'SLIT_STARLETS'])
            imageModel = ImageLinearFit(
                self.data_class,
                self.psf_class,
                self.lens_model_class,
                source_model_class=source_model_class,
                lens_light_model_class=self.lens_light_model_class,
                kwargs_numerics=self.kwargs_numerics,
                kwargs_pixelbased=self.kwargs_pixelbased)
        with self.assertRaises(ValueError):
            # test access to unconvolved lens light surface brightness
            imageModel = ImageLinearFit(
                self.data_class,
                self.psf_class,
                self.lens_model_class,
                source_model_class=self.source_model_class,
                lens_light_model_class=self.lens_light_model_class,
                kwargs_numerics=self.kwargs_numerics,
                kwargs_pixelbased=self.kwargs_pixelbased)
            imageModel.lens_surface_brightness(self.kwargs_lens_light,
                                               unconvolved=True)
    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
Example #7
0
            point_source_list = ['LENSED_POSITION']
            point_source_class = PointSource(point_source_type_list=point_source_list, fixed_magnification_list=[False])

            kwargs_numerics = {'supersampling_factor': 1}

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

            # generate image
            image_sim = imageModel.image(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps)
            poisson = image_util.add_poisson(image_sim, exp_time=exp_time)
            bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg)
            image_sim = image_sim + bkg + poisson
            #image_sim = add_noise(image_sim, kwargs_band =DES_survey_noise)#image_sim# + bkg + poisson

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


            kwargs_model = {'lens_model_list': lens_model_list,
                             'lens_light_model_list': lens_light_model_list,
                             'source_light_model_list': source_model_list,
                            'point_source_model_list': point_source_list
                             }
            full_band_images[:, :, color_idx] += image_sim



        ##### saving files
        #np.save(file_path + "lens" + "_" + "%07d" % (i+1) + ".npy", image_sim)
        np.save(file_path + "full_band_lens" + "_" + "%07d" % (i+1) + ".npy", full_band_images)
Example #8
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)
Example #9
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 #10
0
def sim_lens(data,
             numPix=101,
             sigma_bkg=8.0,
             exp_time=100.0,
             deltaPix=0.263,
             psf_type='GAUSSIAN',
             kernel_size=91):

    flux_g = mag_to_flux(data['mag_g'], 27.5)
    flux_r = mag_to_flux(data['mag_r'], 27.5)
    flux_i = mag_to_flux(data['mag_i'], 27.5)
    flux_z = mag_to_flux(data['mag_z'], 27.5)
    flux_source = mag_to_flux(data['source_mag'], 27.5)
    flux_lens = mag_to_flux(data['lens_mag'], 27.5)

    color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3}

    cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.)

    full_band_images = np.zeros((numPix, numPix, 4))

    ### Set kwargs based on input data file
    #shear
    kwargs_shear = {
        'gamma_ext': data['lens_shear_gamma_ext'],
        'psi_ext': data['lens_shear_psi_ext']
    }
    #lens potential
    kwargs_spemd = {
        'theta_E': data['lens_theta_E'],
        'gamma': data['lens_gamma'],
        'center_x': data['lens_center_x'],
        'center_y': data['lens_center_y'],
        'e1': data['lens_e1'],
        'e2': data['lens_e2']
    }
    #lens light
    kwargs_sersic_lens = {
        'amp': flux_lens,
        'R_sersic': data['lens_R_sersic'],
        'n_sersic': data['lens_n_sersic'],
        'e1': data['lens_e1'],
        'e2': data['lens_e2'],
        'center_x': data['lens_center_x'],
        'center_y': data['lens_center_y']
    }
    #source
    kwargs_sersic_source = {
        'amp': flux_source,
        'R_sersic': data['source_R_sersic'],
        'n_sersic': data['source_n_sersic'],
        'e1': data['source_e1'],
        'e2': data['source_e2'],
        'center_x': data['source_center_x'],
        'center_y': data['source_center_y']
    }

    ###set model parameters based on kwargs
    #lens potential
    lens_model_list = ['SPEP', 'SHEAR_GAMMA_PSI']
    kwargs_lens = [kwargs_spemd, kwargs_shear]
    lens_model_class = LensModel(lens_model_list=lens_model_list)
    #lens light
    lens_light_model_list = ['SERSIC_ELLIPSE']
    kwargs_lens_light = [kwargs_sersic_lens]
    lens_light_model_class = LightModel(light_model_list=lens_light_model_list)
    #source
    source_model_list = ['SERSIC_ELLIPSE']
    kwargs_source = [kwargs_sersic_source]
    source_model_class = LightModel(light_model_list=source_model_list)

    ###configure image based on data properties
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time,
                                                 sigma_bkg)
    data_class = ImageData(**kwargs_data)

    ###solve lens equation
    lensEquationSolver = LensEquationSolver(lens_model_class)
    x_image, y_image = lensEquationSolver.findBrightImage(
        kwargs_sersic_source['center_x'],
        kwargs_sersic_source['center_y'],
        kwargs_lens,
        numImages=4,
        min_distance=deltaPix,
        search_window=numPix * deltaPix)
    magnification = lens_model_class.magnification(x_image,
                                                   y_image,
                                                   kwargs=kwargs_lens)

    ###iterate through bands to simulate images
    for band in ['g', 'r', 'i', 'z']:

        #psf info
        kwargs_psf = {
            'psf_type': psf_type,
            'fwhm': data['psf_%s' % band],
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_class = PSF(**kwargs_psf)

        #quasar info
        kwargs_ps = [{
            'ra_image':
            x_image,
            'dec_image':
            y_image,
            'point_amp':
            np.abs(magnification) * eval('flux_%s' % band)
        }]
        point_source_list = ['LENSED_POSITION']
        point_source_class = PointSource(
            point_source_type_list=point_source_list,
            fixed_magnification_list=[False])

        #build image model
        kwargs_numerics = {'supersampling_factor': 1}
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class,
                                kwargs_numerics=kwargs_numerics)

        #generate image
        image_sim = imageModel.image(kwargs_lens, kwargs_source,
                                     kwargs_lens_light, kwargs_ps)
        poisson = image_util.add_poisson(image_sim, exp_time=exp_time)
        bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg)
        image_sim = image_sim + bkg + poisson

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

        kwargs_model = {
            'lens_model_list': lens_model_list,
            'lens_light_model_list': lens_light_model_list,
            'source_light_model_list': source_model_list,
            'point_source_model_list': point_source_list
        }
        #build up an array with one slice for each band
        full_band_images[:, :, color_idx[band]] += image_sim

    return full_band_images
class TestLensingOperator(object):
    """
    tests the Lensing Operator class
    """
    def setup(self):
        self.num_pix = 25  # cutout pixel size
        delta_pix = 0.24
        _, _, ra_at_xy_0, dec_at_xy_0, _, _, Mpix2coord, _ \
            = l_util.make_grid_with_coordtransform(numPix=self.num_pix, deltapix=delta_pix, subgrid_res=1,
                                                   inverse=False, left_lower=False)
        kwargs_data = {
            #'background_rms': background_rms,
            #'exposure_time': np.ones((self.num_pix, self.num_pix)) * exp_time,  # individual exposure time/weight per pixel
            'ra_at_xy_0': ra_at_xy_0,
            'dec_at_xy_0': dec_at_xy_0,
            'transform_pix2angle': Mpix2coord,
            'image_data': np.zeros((self.num_pix, self.num_pix))
        }
        self.data = ImageData(**kwargs_data)

        self.lens_model = LensModel(['SPEP'])
        self.kwargs_lens = [{
            'theta_E': 1,
            'gamma': 2,
            'center_x': 0,
            'center_y': 0,
            'e1': -0.05,
            'e2': 0.05
        }]
        self.kwargs_lens_null = [{
            'theta_E': 0,
            'gamma': 2,
            'center_x': 0,
            'center_y': 0,
            'e1': 0,
            'e2': 0
        }]

        # PSF specification
        kwargs_psf = {'psf_type': 'NONE'}
        self.psf = PSF(**kwargs_psf)

        # list of source light profiles
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_sersic_ellipse_source = {
            'amp': 2000,
            'R_sersic': 0.6,
            'n_sersic': 1,
            'e1': 0.1,
            'e2': 0.1,
            'center_x': 0.3,
            'center_y': 0.3
        }
        kwargs_source = [kwargs_sersic_ellipse_source]
        source_model = LightModel(light_model_list=source_model_list)

        # list of lens light profiles
        lens_light_model_list = []
        kwargs_lens_light = [{}]
        lens_light_model = LightModel(light_model_list=lens_light_model_list)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False
        }
        self.image_model = ImageModel(self.data,
                                      self.psf,
                                      self.lens_model,
                                      source_model,
                                      lens_light_model,
                                      point_source_class=None,
                                      kwargs_numerics=kwargs_numerics)
        self.image_grid_class = self.image_model.ImageNumerics.grid_class
        self.source_grid_class_default = NumericsSubFrame(self.data,
                                                          self.psf).grid_class

        # create simulated image
        image_sim_no_noise = self.image_model.image(self.kwargs_lens,
                                                    kwargs_source,
                                                    kwargs_lens_light)
        self.source_light_lensed = image_sim_no_noise
        self.data.update_data(image_sim_no_noise)

        # source only, in source plane, on same grid as data
        self.source_light_delensed = self.image_model.source_surface_brightness(
            kwargs_source, unconvolved=False, de_lensed=True)

        # define some auto mask for tests
        self.likelihood_mask = np.zeros_like(self.source_light_lensed)
        self.likelihood_mask[self.source_light_lensed > 0.1 *
                             self.source_light_lensed.max()] = 1

    def test_matrix_product(self):
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='nearest_legacy')
        lensing_op.update_mapping(self.kwargs_lens)

        lensing_op_mat = LensingOperator(self.lens_model,
                                         self.image_grid_class,
                                         self.source_grid_class_default,
                                         self.num_pix,
                                         source_interpolation='nearest')
        lensing_op_mat.update_mapping(self.kwargs_lens)

        source_1d = util.image2array(self.source_light_delensed)
        image_1d = util.image2array(self.source_light_lensed)

        npt.assert_equal(lensing_op.source2image(source_1d),
                         lensing_op_mat.source2image(source_1d))
        npt.assert_equal(lensing_op.image2source(image_1d),
                         lensing_op_mat.image2source(image_1d))

    def test_minimal_source_plane(self):
        source_1d = util.image2array(self.source_light_delensed)

        # test with no mask
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='nearest',
                                     minimal_source_plane=True)
        lensing_op.update_mapping(self.kwargs_lens)
        image_1d = util.image2array(self.source_light_lensed)
        assert lensing_op.image2source(image_1d).size < source_1d.size

        # test with mask
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='nearest',
                                     minimal_source_plane=True)
        lensing_op.set_likelihood_mask(self.likelihood_mask)
        lensing_op.update_mapping(self.kwargs_lens)
        image_1d = util.image2array(self.source_light_lensed)
        assert lensing_op.image2source(image_1d).size < source_1d.size

        # for 'bilinear' operator, only works with no mask (for now)
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='bilinear',
                                     minimal_source_plane=True)
        lensing_op.update_mapping(self.kwargs_lens)
        image_1d = util.image2array(self.source_light_lensed)
        assert lensing_op.image2source(image_1d).size < source_1d.size

    def test_legacy_mapping(self):
        """testing than image2source / source2image are close to the parametric mapping"""
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='nearest_legacy')
        lensing_op.update_mapping(self.kwargs_lens)

        source_1d = util.image2array(self.source_light_delensed)
        image_1d = util.image2array(self.source_light_lensed)

        source_1d_lensed = lensing_op.source2image(source_1d)
        image_1d_delensed = lensing_op.image2source(image_1d)
        assert source_1d_lensed.shape == image_1d.shape
        assert image_1d_delensed.shape == source_1d.shape

        npt.assert_almost_equal(source_1d_lensed / source_1d_lensed.max(),
                                image_1d / image_1d.max(),
                                decimal=0.6)
        npt.assert_almost_equal(image_1d_delensed / image_1d_delensed.max(),
                                source_1d / source_1d.max(),
                                decimal=0.6)

    def test_simple_mapping(self):
        """testing than image2source / source2image are close to the parametric mapping"""
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='nearest')
        lensing_op.update_mapping(self.kwargs_lens)

        source_1d = util.image2array(self.source_light_delensed)
        image_1d = util.image2array(self.source_light_lensed)

        source_1d_lensed = lensing_op.source2image(source_1d)
        image_1d_delensed = lensing_op.image2source(image_1d)
        assert source_1d_lensed.shape == image_1d.shape
        assert image_1d_delensed.shape == source_1d.shape

        npt.assert_almost_equal(source_1d_lensed / source_1d_lensed.max(),
                                image_1d / image_1d.max(),
                                decimal=0.6)
        npt.assert_almost_equal(image_1d_delensed / image_1d_delensed.max(),
                                source_1d / source_1d.max(),
                                decimal=0.6)

    def test_interpol_mapping(self):
        """testing than image2source / source2image are close to the parametric mapping"""
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='bilinear')
        lensing_op.update_mapping(self.kwargs_lens)

        source_1d = util.image2array(self.source_light_delensed)
        image_1d = util.image2array(self.source_light_lensed)

        source_1d_lensed = lensing_op.source2image(source_1d)
        image_1d_delensed = lensing_op.image2source(image_1d)
        assert source_1d_lensed.shape == image_1d.shape
        assert image_1d_delensed.shape == source_1d.shape

        npt.assert_almost_equal(source_1d_lensed / source_1d_lensed.max(),
                                image_1d / image_1d.max(),
                                decimal=0.8)
        npt.assert_almost_equal(image_1d_delensed / image_1d_delensed.max(),
                                source_1d / source_1d.max(),
                                decimal=0.8)

    def test_source2image(self):
        lensing_op = LensingOperator(self.lens_model, self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix)
        source_1d = util.image2array(self.source_light_delensed)
        source_1d_lensed = lensing_op.source2image(
            source_1d, kwargs_lens=self.kwargs_lens)
        assert len(source_1d_lensed.shape) == 1

        source_2d = self.source_light_delensed
        source_2d_lensed = lensing_op.source2image_2d(
            source_2d, kwargs_lens=self.kwargs_lens, update_mapping=True)
        assert len(source_2d_lensed.shape) == 2

    def test_image2source(self):
        lensing_op = LensingOperator(self.lens_model, self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix)
        image_1d = util.image2array(self.source_light_lensed)
        image_1d_delensed = lensing_op.image2source(
            image_1d, kwargs_lens=self.kwargs_lens)
        assert len(image_1d_delensed.shape) == 1

        image_2d = self.source_light_lensed
        image_2d_delensed = lensing_op.image2source_2d(
            image_2d, kwargs_lens=self.kwargs_lens, update_mapping=True)
        assert len(image_2d_delensed.shape) == 2

    def test_source_plane_coordinates(self):
        lensing_op = LensingOperator(self.lens_model, self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix)
        theta_x, theta_y = lensing_op.source_plane_coordinates
        assert theta_x.size == self.num_pix**2
        assert theta_y.size == self.num_pix**2

        subgrid_res = 2
        source_grid_class = NumericsSubFrame(
            self.data, self.psf, supersampling_factor=subgrid_res).grid_class
        lensing_op = LensingOperator(self.lens_model, self.image_grid_class,
                                     source_grid_class, self.num_pix)
        theta_x, theta_y = lensing_op.source_plane_coordinates
        assert theta_x.size == self.num_pix**2 * subgrid_res**2
        assert theta_y.size == self.num_pix**2 * subgrid_res**2

    def test_image_plane_coordinates(self):
        lensing_op = LensingOperator(self.lens_model, self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix)
        theta_x, theta_y = lensing_op.image_plane_coordinates
        assert theta_x.size == self.num_pix**2
        assert theta_y.size == self.num_pix**2

    def test_find_source_pixel(self):
        lensing_op = LensingOperator(self.lens_model,
                                     self.image_grid_class,
                                     self.source_grid_class_default,
                                     self.num_pix,
                                     source_interpolation='nearest')
        beta_x, beta_y = self.lens_model.ray_shooting(
            lensing_op.imagePlane.theta_x, lensing_op.imagePlane.theta_y,
            self.kwargs_lens)
        i = 10
        j = lensing_op._find_source_pixel_nearest_legacy(i, beta_x, beta_y)
        assert (isinstance(j, int) or isinstance(j, np.int64))
Example #12
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 = simulation_util.data_configure_simple(
            numPix, deltaPix, exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix
        }
        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']
        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']
        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)

        # Point Source
        point_source_model_list = ['UNLENSED']
        kwargs_ps = [{
            'ra_image': [0.4],
            'dec_image': [-0.2],
            'point_amp': [2]
        }]
        point_source_class = PointSource(
            point_source_type_list=point_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,
                                point_source_class=point_source_class,
                                kwargs_numerics=kwargs_numerics)
        image_sim = simulation_util.simulate_simple(imageModel, kwargs_lens,
                                                    kwargs_source,
                                                    kwargs_lens_light,
                                                    kwargs_ps)

        data_class.update_data(image_sim)
        kwargs_data['image_data'] = image_sim
        self.multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics]]

        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_model_list,
            'fixed_magnification_list': [False],
            'index_lens_model_list': [[0]],
            'index_lens_light_model_list': [[0]],
            'index_source_light_model_list': [[0]],
            'index_point_source_model_list': [[0]],
        }

        self.kwargs_params = {
            'kwargs_lens': kwargs_lens,
            'kwargs_source': kwargs_source,
            'kwargs_lens_light': kwargs_lens_light,
            'kwargs_ps': kwargs_ps
        }

        self.single_band = SingleBandMultiModel(
            multi_band_list=self.multi_band_list,
            kwargs_model=self.kwargs_model,
            linear_solver=True)
        self.single_band_no_linear = SingleBandMultiModel(
            multi_band_list=self.multi_band_list,
            kwargs_model=self.kwargs_model,
            linear_solver=False)
Example #13
0
def simple_einstein_ring_likelihood_2d():

    # 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']
    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']
    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_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, kwargs_lens,
                                         kwargs_source, 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'
    }

    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],
    }

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

    kwargs_likelihood = {
        'source_marg': False,
        'image_position_uncertainty': 0.004,
        'check_matched_source_position': False,
        'source_position_tolerance': 0.001,
        'source_position_sigma': 0.001,
    }

    # reduce number of param to sample (for runtime)
    kwargs_fixed_lens = [{'gamma': 1.8, 'center_y': 0, 'e1': 0.1, 'e2': 0.1}]
    kwargs_lower_lens = [{'theta_E': 0.8, 'center_x': -0.1}]
    kwargs_upper_lens = [{'theta_E': 1.2, 'center_x': 0.1}]
    kwargs_fixed_source = [{
        'R_sersic': 0.6,
        'n_sersic': 3,
        'center_x': 0,
        'center_y': 0,
        'e1': 0.1,
        'e2': 0.1
    }]
    kwargs_fixed_lens_light = [{
        'R_sersic': 0.1,
        'n_sersic': 2,
        'center_x': 0,
        'center_y': 0
    }]

    param_class = Param(kwargs_model,
                        kwargs_fixed_lens=kwargs_fixed_lens,
                        kwargs_fixed_source=kwargs_fixed_source,
                        kwargs_fixed_lens_light=kwargs_fixed_lens_light,
                        kwargs_lower_lens=kwargs_lower_lens,
                        kwargs_upper_lens=kwargs_upper_lens,
                        **kwargs_constraints)

    likelihood = LikelihoodModule(kwargs_data_joint=kwargs_data_joint,
                                  kwargs_model=kwargs_model,
                                  param_class=param_class,
                                  **kwargs_likelihood)
    kwargs_truths = {
        'kwargs_lens': kwargs_lens,
        'kwargs_source': kwargs_source,
        'kwargs_lens_light': kwargs_lens_light
    }
    return likelihood, kwargs_truths
Example #14
0
def fit_qso(QSO_im, psf_ave, psf_std=None, source_params=None,ps_param=None, background_rms=0.04, pix_sz = 0.168,
            exp_time = 300., fix_n=None, image_plot = True, corner_plot=True, supersampling_factor = 2, 
            flux_ratio_plot=False, deep_seed = False, fixcenter = False, QSO_msk=None, QSO_std=None,
            tag = None, no_MCMC= False, pltshow = 1, return_Chisq = False, dump_result = False, pso_diag=False):
    '''
    A quick fit for the QSO image with (so far) single sersice + one PSF. The input psf noise is optional.
    
    Parameter
    --------
        QSO_im: An array of the QSO image.
        psf_ave: The psf image.
        psf_std: The psf noise, optional.
        source_params: The prior for the source. Default is given. If [], means no Sersic light.
        background_rms: default as 0.04
        exp_time: default at 2400.
        deep_seed: if Ture, more mcmc steps will be performed.
        tag: The name tag for save the plot
            
    Return
    --------
        Will output the fitted image (Set image_plot = True), the corner_plot and the flux_ratio_plot.
        source_result, ps_result, image_ps, image_host
    
    To do
    --------
        
    '''
    # data specifics need to set up based on the data situation
    background_rms = background_rms  #  background noise per pixel (Gaussian)
    exp_time = exp_time  #  exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
    numPix = len(QSO_im)  #  cutout pixel size
    deltaPix = pix_sz
    psf_type = 'PIXEL'  # 'gaussian', 'pixel', 'NONE'
    kernel = psf_ave

    kwargs_numerics = {'supersampling_factor': supersampling_factor, 'supersampling_convolution': False} 
    
    if source_params is None:
        # here are the options for the host galaxy fitting
        fixed_source = []
        kwargs_source_init = []
        kwargs_source_sigma = []
        kwargs_lower_source = []
        kwargs_upper_source = []
        
        if fix_n == None:
            fixed_source.append({})  # we fix the Sersic index to n=1 (exponential)
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': 2., 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.5, 'R_sersic': 0.5, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.1, 'n_sersic': 0.3, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3., 'n_sersic': 7., 'center_x': 10, 'center_y': 10})
        elif fix_n is not None:
            fixed_source.append({'n_sersic': fix_n})
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': fix_n, 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.001, 'R_sersic': 0.5, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.1, 'n_sersic': fix_n, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3, 'n_sersic': fix_n, 'center_x': 10, 'center_y': 10})
        source_params = [kwargs_source_init, kwargs_source_sigma, fixed_source, kwargs_lower_source, kwargs_upper_source]
    else:
        source_params = source_params
    
    if ps_param is None:
        center_x = 0.0
        center_y = 0.0
        point_amp = QSO_im.sum()/2.
        fixed_ps = [{}]
        kwargs_ps = [{'ra_image': [center_x], 'dec_image': [center_y], 'point_amp': [point_amp]}]
        kwargs_ps_init = kwargs_ps
        kwargs_ps_sigma = [{'ra_image': [0.05], 'dec_image': [0.05]}]
        kwargs_lower_ps = [{'ra_image': [-0.6], 'dec_image': [-0.6]}]
        kwargs_upper_ps = [{'ra_image': [0.6], 'dec_image': [0.6]}]
        ps_param = [kwargs_ps_init, kwargs_ps_sigma, fixed_ps, kwargs_lower_ps, kwargs_upper_ps]
    else:
        ps_param = ps_param
    
    #==============================================================================
    #Doing the QSO fitting 
    #==============================================================================
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, background_rms, inverse=True)
    data_class = ImageData(**kwargs_data)
    kwargs_psf = {'psf_type': psf_type, 'kernel_point_source': kernel}
    psf_class = PSF(**kwargs_psf)
    data_class.update_data(QSO_im)
    
    point_source_list = ['UNLENSED'] * len(ps_param[0])
    pointSource = PointSource(point_source_type_list=point_source_list)
    
    if fixcenter == False:
        kwargs_constraints = {'num_point_source_list': [1] * len(ps_param[0])
                              }
    elif fixcenter == True:
        kwargs_constraints = {'joint_source_with_point_source': [[i, i] for i in range(len(ps_param[0]))],
                              'num_point_source_list': [1] * len(ps_param[0])
                              }
    
    
    if source_params == []:   #fitting image as Point source only.
        kwargs_params = {'point_source_model': ps_param}
        lightModel = None
        kwargs_model = {'point_source_model_list': point_source_list }
        imageModel = ImageModel(data_class, psf_class, point_source_class=pointSource, kwargs_numerics=kwargs_numerics)
        kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                             'image_likelihood_mask_list': [QSO_msk]
                     }
    elif source_params != []:
        kwargs_params = {'source_model': source_params,
                 'point_source_model': ps_param}

        light_model_list = ['SERSIC_ELLIPSE'] * len(source_params[0])
        lightModel = LightModel(light_model_list=light_model_list)
        kwargs_model = { 'source_light_model_list': light_model_list,
                        'point_source_model_list': point_source_list
                        }
        imageModel = ImageModel(data_class, psf_class, source_model_class=lightModel,
                                point_source_class=pointSource, kwargs_numerics=kwargs_numerics)
        # numerical options and fitting sequences
        kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                             'source_marg': False,  #In likelihood_module.LikelihoodModule -- whether to fully invert the covariance matrix for marginalization
                              'check_positive_flux': True, 
                              'image_likelihood_mask_list': [QSO_msk]
                             }
    
    kwargs_data['image_data'] = QSO_im
    if QSO_std is not None:
        kwargs_data['noise_map'] = QSO_std
    
    if psf_std is not None:
        kwargs_psf['psf_error_map'] = psf_std
    image_band = [kwargs_data, kwargs_psf, kwargs_numerics]
    multi_band_list = [image_band]

    kwargs_data_joint = {'multi_band_list': multi_band_list, 'multi_band_type': 'multi-linear'}  # 'single-band', 'multi-linear', 'joint-linear'
    fitting_seq = FittingSequence(kwargs_data_joint, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params)
    
    if deep_seed == False:
        fitting_kwargs_list = [
             ['PSO', {'sigma_scale': 0.8, 'n_particles': 100, 'n_iterations': 60}],
             ['MCMC', {'n_burn': 10, 'n_run': 10, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]
    elif deep_seed == True:
         fitting_kwargs_list = [
             ['PSO', {'sigma_scale': 0.8, 'n_particles': 250, 'n_iterations': 250}],
             ['MCMC', {'n_burn': 100, 'n_run': 200, 'walkerRatio': 10, 'sigma_scale': .1}]
            ]
    if no_MCMC == True:
        fitting_kwargs_list = [fitting_kwargs_list[0],
                               ]        

    start_time = time.time()
    chain_list = fitting_seq.fit_sequence(fitting_kwargs_list)
    kwargs_result = fitting_seq.best_fit()
    ps_result = kwargs_result['kwargs_ps']
    source_result = kwargs_result['kwargs_source']
    if no_MCMC == False:
        sampler_type, samples_mcmc, param_mcmc, dist_mcmc  = chain_list[1]    
    
    end_time = time.time()
    print(end_time - start_time, 'total time needed for computation')
    print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
    imageLinearFit = ImageLinearFit(data_class=data_class, psf_class=psf_class,
                                    source_model_class=lightModel,
                                    point_source_class=pointSource, 
                                    kwargs_numerics=kwargs_numerics)    
    image_reconstructed, error_map, _, _ = imageLinearFit.image_linear_solve(kwargs_source=source_result, kwargs_ps=ps_result)
    # this is the linear inversion. The kwargs will be updated afterwards
    modelPlot = ModelPlot(multi_band_list, kwargs_model, kwargs_result,
                          arrow_size=0.02, cmap_string="gist_heat", likelihood_mask_list=[QSO_msk])
    image_host = []  #!!! The linear_solver before and after LensModelPlot could have different result for very faint sources.
    for i in range(len(source_result)):
        image_host.append(imageModel.source_surface_brightness(source_result, de_lensed=True,unconvolved=False,k=i))
    
    image_ps = []
    for i in range(len(ps_result)):
        image_ps.append(imageModel.point_source(ps_result, k = i))
    
    if pso_diag == True:
        f, axes = chain_plot.plot_chain_list(chain_list,0)
        if pltshow == 0:
            plt.close()
        else:
            plt.show()

    # let's plot the output of the PSO minimizer
    reduced_Chisq =  imageLinearFit.reduced_chi2(image_reconstructed, error_map)
    if image_plot:
        f, axes = plt.subplots(3, 3, figsize=(16, 16), sharex=False, sharey=False)
        modelPlot.data_plot(ax=axes[0,0], text="Data")
        modelPlot.model_plot(ax=axes[0,1])
        modelPlot.normalized_residual_plot(ax=axes[0,2], v_min=-6, v_max=6)
        
        modelPlot.decomposition_plot(ax=axes[1,0], text='Host galaxy', source_add=True, unconvolved=True)
        modelPlot.decomposition_plot(ax=axes[1,1], text='Host galaxy convolved', source_add=True)
        modelPlot.decomposition_plot(ax=axes[1,2], text='All components convolved', source_add=True, lens_light_add=True, point_source_add=True)
        
        modelPlot.subtract_from_data_plot(ax=axes[2,0], text='Data - Point Source', point_source_add=True)
        modelPlot.subtract_from_data_plot(ax=axes[2,1], text='Data - host galaxy', source_add=True)
        modelPlot.subtract_from_data_plot(ax=axes[2,2], text='Data - host galaxy - Point Source', source_add=True, point_source_add=True)
        
        f.tight_layout()
        #f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05)
        if tag is not None:
            f.savefig('{0}_fitted_image.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
        
    if corner_plot==True and no_MCMC==False:
        # here the (non-converged) MCMC chain of the non-linear parameters
        if not samples_mcmc == []:
           n, num_param = np.shape(samples_mcmc)
           plot = corner.corner(samples_mcmc, labels=param_mcmc, show_titles=True)
           if tag is not None:
               plot.savefig('{0}_para_corner.pdf'.format(tag))
           plt.close()               
           # if pltshow == 0:
           #     plt.close()
           # else:
           #     plt.show()
        
    if flux_ratio_plot==True and no_MCMC==False:
        param = Param(kwargs_model, kwargs_fixed_source=source_params[2], kwargs_fixed_ps=ps_param[2], **kwargs_constraints)
        mcmc_new_list = []
        if len(ps_param[2]) == 1:
            labels_new = ["Quasar flux"] +  ["host{0} flux".format(i) for i in range(len(source_params[0]))]
        else:
            labels_new = ["Quasar{0} flux".format(i) for i in range(len(ps_param[2]))] +  ["host{0} flux".format(i) for i in range(len(source_params[0]))]
        if len(samples_mcmc) > 10000:
            trans_steps = [len(samples_mcmc)-10000, len(samples_mcmc)]
        else:
            trans_steps = [0, len(samples_mcmc)]
        for i in range(trans_steps[0], trans_steps[1]):
            kwargs_out = param.args2kwargs(samples_mcmc[i])
            kwargs_light_source_out = kwargs_out['kwargs_source']
            kwargs_ps_out =  kwargs_out['kwargs_ps']
            image_reconstructed, _, _, _ = imageLinearFit.image_linear_solve(kwargs_source=kwargs_light_source_out, kwargs_ps=kwargs_ps_out)
            flux_quasar = []
            if len(ps_param[0]) == 1:
                image_ps_j = imageModel.point_source(kwargs_ps_out)
                flux_quasar.append(np.sum(image_ps_j))  
            else:    
                for j in range(len(ps_param[0])):
                    image_ps_j = imageModel.point_source(kwargs_ps_out, k=j)
                    flux_quasar.append(np.sum(image_ps_j))
            fluxs = []
            for j in range(len(source_params[0])):
                image_j = imageModel.source_surface_brightness(kwargs_light_source_out,unconvolved= False, k=j)
                fluxs.append(np.sum(image_j))
            mcmc_new_list.append(flux_quasar + fluxs )
            if int(i/1000) > int((i-1)/1000) :
                print(len(samples_mcmc), "MCMC samplers in total, finished translate:", i )
        plot = corner.corner(mcmc_new_list, labels=labels_new, show_titles=True)
        if tag is not None:
            plot.savefig('{0}_HOSTvsQSO_corner.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
    if QSO_std is None:
        noise_map = np.sqrt(data_class.C_D+np.abs(error_map))
    else:
        noise_map = np.sqrt(QSO_std**2+np.abs(error_map))
    if dump_result == True:
        if flux_ratio_plot==True and no_MCMC==False:
            trans_paras = [mcmc_new_list, labels_new, 'mcmc_new_list, labels_new']
        else:
            trans_paras = []
        picklename= tag + '.pkl'
        best_fit = [source_result, image_host, ps_result, image_ps,'source_result, image_host, ps_result, image_ps']
        chain_list_result = [chain_list, 'chain_list']
        kwargs_fixed_source=source_params[2]
        kwargs_fixed_ps=ps_param[2]
        classes = data_class, psf_class, lightModel, pointSource
        material = multi_band_list, kwargs_model, kwargs_result, QSO_msk, kwargs_fixed_source, kwargs_fixed_ps, kwargs_constraints, kwargs_numerics, classes
        pickle.dump([best_fit, chain_list_result, trans_paras, material], open(picklename, 'wb'))
    if return_Chisq == False:
        return source_result, ps_result, image_ps, image_host, noise_map
    elif return_Chisq == True:
        return source_result, ps_result, image_ps, image_host, noise_map, reduced_Chisq
Example #15
0
def fit_galaxy(galaxy_im, psf_ave, psf_std=None, source_params=None, background_rms=0.04, pix_sz = 0.08,
            exp_time = 300., fix_n=None, image_plot = True, corner_plot=True,
            deep_seed = False, galaxy_msk=None, galaxy_std=None, flux_corner_plot = False,
            tag = None, no_MCMC= False, pltshow = 1, return_Chisq = False, dump_result = False, pso_diag=False):
    '''
    A quick fit for the QSO image with (so far) single sersice + one PSF. The input psf noise is optional.
    
    Parameter
    --------
        galaxy_im: An array of the QSO image.
        psf_ave: The psf image.
        psf_std: The psf noise, optional.
        source_params: The prior for the source. Default is given.
        background_rms: default as 0.04
        exp_time: default at 2400.
        deep_seed: if Ture, more mcmc steps will be performed.
        tag: The name tag for save the plot
            
    Return
    --------
        Will output the fitted image (Set image_plot = True), the corner_plot and the flux_ratio_plot.
        source_result, ps_result, image_ps, image_host
    
    To do
    --------
        
    '''
    # data specifics need to set up based on the data situation
    background_rms = background_rms  #  background noise per pixel (Gaussian)
    exp_time = exp_time  #  exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
    numPix = len(galaxy_im)  #  cutout pixel size
    deltaPix = pix_sz
    if psf_ave is not None:
        psf_type = 'PIXEL'  # 'gaussian', 'pixel', 'NONE'
        kernel = psf_ave
    
#    if psf_std is not None:
#        kwargs_numerics = {'subgrid_res': 1, 'psf_error_map': True}     #Turn on the PSF error map
#    else: 
    kwargs_numerics = {'supersampling_factor': 1, 'supersampling_convolution': False}
        
    if source_params is None:
        # here are the options for the host galaxy fitting
        fixed_source = []
        kwargs_source_init = []
        kwargs_source_sigma = []
        kwargs_lower_source = []
        kwargs_upper_source = []
        # Disk component, as modelled by an elliptical Sersic profile
        if fix_n == None:
            fixed_source.append({})  # we fix the Sersic index to n=1 (exponential)
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': 2., 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.5, 'R_sersic': 0.1, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.01, 'n_sersic': 0.3, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3., 'n_sersic': 7., 'center_x': 10, 'center_y': 10})
        elif fix_n is not None:
            fixed_source.append({'n_sersic': fix_n})
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': fix_n, 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.001, 'R_sersic': 0.1, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.01, 'n_sersic': fix_n, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3, 'n_sersic': fix_n, 'center_x': 10, 'center_y': 10})
        source_params = [kwargs_source_init, kwargs_source_sigma, fixed_source, kwargs_lower_source, kwargs_upper_source]
    else:
        source_params = source_params
    kwargs_params = {'source_model': source_params}
    
    #==============================================================================
    #Doing the QSO fitting 
    #==============================================================================
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, background_rms, inverse=True)
    data_class = ImageData(**kwargs_data)
    if psf_ave is not None:
        kwargs_psf = {'psf_type': psf_type, 'kernel_point_source': kernel}
    else:
        kwargs_psf =  {'psf_type': 'NONE'}
    
    psf_class = PSF(**kwargs_psf)
    data_class.update_data(galaxy_im)
    
    light_model_list = ['SERSIC_ELLIPSE'] * len(source_params[0])
    lightModel = LightModel(light_model_list=light_model_list)
    
    kwargs_model = { 'source_light_model_list': light_model_list}
    # numerical options and fitting sequences
    kwargs_constraints = {}
    
    kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                         'source_marg': False,  #In likelihood_module.LikelihoodModule -- whether to fully invert the covariance matrix for marginalization
                          'check_positive_flux': True,       
                          'image_likelihood_mask_list': [galaxy_msk]
                         }
    kwargs_data['image_data'] = galaxy_im
    if galaxy_std is not None:
        kwargs_data['noise_map'] = galaxy_std
    if psf_std is not None:
        kwargs_psf['psf_error_map'] = psf_std
                  
    image_band = [kwargs_data, kwargs_psf, kwargs_numerics]
    multi_band_list = [image_band]
    
    kwargs_data_joint = {'multi_band_list': multi_band_list, 'multi_band_type': 'multi-linear'}  # 'single-band', 'multi-linear', 'joint-linear'
    fitting_seq = FittingSequence(kwargs_data_joint, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params)
    
    if deep_seed == False:
        fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 50, 'n_iterations': 50}],
            ['MCMC', {'n_burn': 10, 'n_run': 10, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]            
    elif deep_seed == True:
         fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 100, 'n_iterations': 80}],
            ['MCMC', {'n_burn': 10, 'n_run': 15, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]
    elif deep_seed == 'very_deep':
         fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 150, 'n_iterations': 150}],
            ['MCMC', {'n_burn': 10, 'n_run': 20, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]
    if no_MCMC == True:
        fitting_kwargs_list = [fitting_kwargs_list[0],
                               ]        
    
    start_time = time.time()
    chain_list = fitting_seq.fit_sequence(fitting_kwargs_list)
    kwargs_result = fitting_seq.best_fit()
    ps_result = kwargs_result['kwargs_ps']
    source_result = kwargs_result['kwargs_source']
    
    if no_MCMC == False:
        sampler_type, samples_mcmc, param_mcmc, dist_mcmc  = chain_list[1]      
    
#    chain_list, param_list, samples_mcmc, param_mcmc, dist_mcmc = fitting_seq.fit_sequence(fitting_kwargs_list)
#    lens_result, source_result, lens_light_result, ps_result, cosmo_temp = fitting_seq.best_fit()
    end_time = time.time()
    print(end_time - start_time, 'total time needed for computation')
    print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
    # this is the linear inversion. The kwargs will be updated afterwards
    imageModel = ImageModel(data_class, psf_class, source_model_class=lightModel,kwargs_numerics=kwargs_numerics)
    imageLinearFit = ImageLinearFit(data_class=data_class, psf_class=psf_class,
                                       source_model_class=lightModel,
                                       kwargs_numerics=kwargs_numerics)    
    image_reconstructed, error_map, _, _ = imageLinearFit.image_linear_solve(kwargs_source=source_result, kwargs_ps=ps_result)
#    image_host = []   #!!! The linear_solver before and after could have different result for very faint sources.
#    for i in range(len(source_result)):
#        image_host_i = imageModel.source_surface_brightness(source_result,de_lensed=True,unconvolved=False, k=i)
#        print("image_host_i", source_result[i])
#        print("total flux", image_host_i.sum())
#        image_host.append(image_host_i)  
        
    # let's plot the output of the PSO minimizer
    modelPlot = ModelPlot(multi_band_list, kwargs_model, kwargs_result,
                          arrow_size=0.02, cmap_string="gist_heat", likelihood_mask_list=[galaxy_msk])  
    
    if pso_diag == True:
        f, axes = chain_plot.plot_chain_list(chain_list,0)
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
                
    reduced_Chisq =  imageLinearFit.reduced_chi2(image_reconstructed, error_map)
    if image_plot:
        f, axes = plt.subplots(1, 3, figsize=(16, 16), sharex=False, sharey=False)
        modelPlot.data_plot(ax=axes[0])
        modelPlot.model_plot(ax=axes[1])
        modelPlot.normalized_residual_plot(ax=axes[2], v_min=-6, v_max=6)
        f.tight_layout()
        #f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05)
        if tag is not None:
            f.savefig('{0}_fitted_image.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
    image_host = []    
    for i in range(len(source_result)):
        image_host_i = imageModel.source_surface_brightness(source_result,de_lensed=True,unconvolved=False, k=i)
#        print("image_host_i", source_result[i])
#        print("total flux", image_host_i.sum())
        image_host.append(image_host_i)  
        
    if corner_plot==True and no_MCMC==False:
        # here the (non-converged) MCMC chain of the non-linear parameters
        if not samples_mcmc == []:
           n, num_param = np.shape(samples_mcmc)
           plot = corner.corner(samples_mcmc, labels=param_mcmc, show_titles=True)
           if tag is not None:
               plot.savefig('{0}_para_corner.pdf'.format(tag))
           if pltshow == 0:
               plt.close()
           else:
               plt.show()
    if flux_corner_plot ==True and no_MCMC==False:
        param = Param(kwargs_model, kwargs_fixed_source=source_params[2], **kwargs_constraints)
        mcmc_new_list = []
        labels_new = ["host{0} flux".format(i) for i in range(len(source_params[0]))]
        for i in range(len(samples_mcmc)):
            kwargs_out = param.args2kwargs(samples_mcmc[i])
            kwargs_light_source_out = kwargs_out['kwargs_source']
            kwargs_ps_out =  kwargs_out['kwargs_ps']
            image_reconstructed, _, _, _ = imageLinearFit.image_linear_solve(kwargs_source=kwargs_light_source_out, kwargs_ps=kwargs_ps_out)
            fluxs = []
            for j in range(len(source_params[0])):
                image_j = imageModel.source_surface_brightness(kwargs_light_source_out,unconvolved= False, k=j)
                fluxs.append(np.sum(image_j))
            mcmc_new_list.append( fluxs )
            if int(i/1000) > int((i-1)/1000) :
                print(len(samples_mcmc), "MCMC samplers in total, finished translate:", i    )
        plot = corner.corner(mcmc_new_list, labels=labels_new, show_titles=True)
        if tag is not None:
            plot.savefig('{0}_HOSTvsQSO_corner.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show() 

    if galaxy_std is None:
        noise_map = np.sqrt(data_class.C_D+np.abs(error_map))
    else:
        noise_map = np.sqrt(galaxy_std**2+np.abs(error_map))   
        
    if dump_result == True:
        if flux_corner_plot==True and no_MCMC==False:
            trans_paras = [source_params[2], mcmc_new_list, labels_new, 'source_params[2], mcmc_new_list, labels_new']
        else:
            trans_paras = []
        picklename= tag + '.pkl'
        best_fit = [source_result, image_host, 'source_result, image_host']
#        pso_fit = [chain_list, param_list, 'chain_list, param_list']
#        mcmc_fit = [samples_mcmc, param_mcmc, dist_mcmc, 'samples_mcmc, param_mcmc, dist_mcmc']
        chain_list_result = [chain_list, 'chain_list']
        pickle.dump([best_fit, chain_list_result, trans_paras], open(picklename, 'wb'))
        
    if return_Chisq == False:
        return source_result, image_host, noise_map
    elif return_Chisq == True:
        return source_result, image_host, noise_map, reduced_Chisq
Example #16
0
 def test_raise(self):
     kwargs_data = {'image_data': np.zeros((10, 10))}
     Data = ImageData(**kwargs_data)
     image_data_new = np.zeros((5, 5))
     with self.assertRaises(ValueError):
         out = Data.update_data(image_data_new)
    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'
        }
    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)
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
Example #20
0
    def setup(self):

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

        # supersampling factor for source plane
        self.subgrid_res_source = 1
        self.num_pix_source = self.num_pix * self.subgrid_res_source

        # wavelets scales for lens and source
        self.n_scales_source = 4
        self.n_scales_lens = 3

        # prepare data simulation
        kwargs_data = sim_util.data_configure_simple(self.num_pix,
                                                     delta_pix,
                                                     exp_time,
                                                     sigma_bkg,
                                                     inverse=True)
        data_class = ImageData(**kwargs_data)

        # generate sa pixelated gaussian PSF kernel
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'truncation': 5,
            'pixel_size': delta_pix
        }
        psf_class = PSF(**kwargs_psf)
        kernel = psf_class.kernel_point_source
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel,
            'psf_error_map': np.ones_like(kernel) * 0.001
        }
        psf_class = PSF(**kwargs_psf)

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

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

        lens_light_model_list = ['SERSIC']
        kwargs_lens_light = [kwargs_sersic]
        lens_light_model_class = LightModel(
            light_model_list=lens_light_model_list)
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_source = [kwargs_sersic_ellipse]
        source_model_class = LightModel(light_model_list=source_model_list)

        # list of lens light profiles
        point_source_class = PointSource(['LENSED_POSITION'])
        lens_eq_solver = LensEquationSolver(lensModel=self.lens_model_class)
        ra_image, dec_image = lens_eq_solver.image_position_from_source(
            sourcePos_x=kwargs_source[0]['center_x'],
            sourcePos_y=kwargs_source[0]['center_y'],
            kwargs_lens=self.kwargs_lens)
        point_amp = np.ones_like(ra_image)
        kwargs_ps = [{
            'ra_image': ra_image,
            'dec_image': dec_image,
            'point_amp': point_amp
        }]

        # simulate data
        kwargs_numerics = {'supersampling_factor': 1}
        imageModel = ImageModel(data_class,
                                psf_class,
                                self.lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class,
                                kwargs_numerics=kwargs_numerics)
        self.image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens,
                                                  kwargs_source,
                                                  kwargs_lens_light, kwargs_ps)
        data_class.update_data(self.image_sim)

        # retrieve the point source data only (for initial guess for source+PS solver)
        self.ps_sim = imageModel.image(self.kwargs_lens,
                                       kwargs_source,
                                       kwargs_lens_light,
                                       kwargs_ps,
                                       source_add=False,
                                       lens_light_add=False,
                                       point_source_add=True)

        # define some mask
        self.likelihood_mask = np.zeros((self.num_pix, self.num_pix))
        self.likelihood_mask[5:-5, 5:-5] = 1

        # get a numerics classes
        numerics = NumericsSubFrame(pixel_grid=data_class, psf=psf_class)
        source_numerics = NumericsSubFrame(
            pixel_grid=data_class,
            psf=psf_class,
            supersampling_factor=self.subgrid_res_source)

        self.num_iter_source = 20
        self.num_iter_lens = 10
        self.num_iter_global = 7
        self.num_iter_weights = 2

        # source grid offsets
        self.kwargs_special = {
            'delta_x_source_grid': 0,
            'delta_y_source_grid': 0,
        }

        # init the solvers

        # SOLVER SOURCE, with analysis formulation
        self.source_model_class = LightModel(['SLIT_STARLETS'])
        self.kwargs_source = [{'n_scales': self.n_scales_source}]
        self.solver_source_ana = SparseSolverSource(
            data_class,
            self.lens_model_class,
            numerics,
            source_numerics,
            self.source_model_class,
            source_interpolation='bilinear',
            minimal_source_plane=False,
            use_mask_for_minimal_source_plane=True,
            min_num_pix_source=20,
            sparsity_prior_norm=1,
            force_positivity=True,
            formulation='analysis',
            verbose=False,
            show_steps=False,
            min_threshold=5,
            threshold_increment_high_freq=1,
            threshold_decrease_type='exponential',
            num_iter_source=self.num_iter_source,
            num_iter_weights=self.num_iter_weights)
        self.solver_source_ana.set_likelihood_mask(self.likelihood_mask)

        # SOLVER SOURCE + LENS, with synthesis formulation
        self.lens_light_model_class = LightModel(['SLIT_STARLETS'])
        self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}]
        self.solver_lens_syn = SparseSolverSourceLens(
            data_class,
            self.lens_model_class,
            numerics,
            source_numerics,
            self.source_model_class,
            self.lens_light_model_class,
            source_interpolation='bilinear',
            minimal_source_plane=False,
            use_mask_for_minimal_source_plane=True,
            min_num_pix_source=20,
            sparsity_prior_norm=1,
            force_positivity=True,
            formulation='synthesis',
            verbose=False,
            show_steps=False,
            min_threshold=3,
            threshold_increment_high_freq=1,
            threshold_decrease_type='linear',
            num_iter_global=self.num_iter_global,
            num_iter_source=self.num_iter_source,
            num_iter_lens=self.num_iter_lens,
            num_iter_weights=self.num_iter_weights)
        self.solver_lens_syn.set_likelihood_mask(self.likelihood_mask)