def __init__(self,
              image,
              sigma,
              poisson,
              sampling_option,
              deltaPix=1,
              mask=None,
              subgrid_res=1,
              x_grid=None,
              y_grid=None):
     """
     initializes all the classes needed for the chain
     """
     self.image = util.image2array(image)
     self.numPix = len(image)
     self.deltaPix = deltaPix
     self.subgrid_res = subgrid_res
     self.background = sigma
     self.poisson = poisson
     if x_grid is None or y_grid is None:
         self.x_grid, self.y_grid = util.make_grid(self.numPix, deltaPix,
                                                   subgrid_res)
     else:
         self.x_grid, self.y_grid = util.make_subgrid(
             x_grid, y_grid, subgrid_res)
     self.gaussian = Gaussian()
     self.moffat = Moffat()
     self.sampling_option = sampling_option
     if not mask is None:
         self.mask = util.image2array(mask)
     else:
         self.mask = np.ones((self.numPix, self.numPix))
    def test_delete_interpol_caches(self):
        x, y = util.make_grid(numPix=20, deltapix=1.)
        gauss = Gaussian()
        flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.)
        image = util.array2image(flux)

        light_model_list = ['INTERPOL', 'INTERPOL']
        kwargs_list = [{
            'image': image,
            'scale': 1,
            'phi_G': 0,
            'center_x': 0,
            'center_y': 0
        }, {
            'image': image,
            'scale': 1,
            'phi_G': 0,
            'center_x': 0,
            'center_y': 0
        }]
        lightModel = LightModel(light_model_list=light_model_list)
        output = lightModel.surface_brightness(x, y, kwargs_list)
        for func in lightModel.func_list:
            assert hasattr(func, '_image_interp')
        lightModel.delete_interpol_caches()
        for func in lightModel.func_list:
            assert not hasattr(func, '_image_interp')
Exemple #3
0
    def test_update_psf(self):
        fwhm = 0.3
        sigma = util.fwhm2sigma(fwhm)
        x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05)
        from lenstronomy.LightModel.Profiles.gaussian import Gaussian
        gaussian = Gaussian()
        kernel_point_source = gaussian.function(x_grid,
                                                y_grid,
                                                amp=1.,
                                                sigma_x=sigma,
                                                sigma_y=sigma,
                                                center_x=0,
                                                center_y=0)
        kernel_point_source /= np.sum(kernel_point_source)
        kernel_point_source = util.array2image(kernel_point_source)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel_point_source
        }

        kwargs_psf_return, improved_bool = self.psf_fitting.update_psf(
            kwargs_psf,
            self.kwargs_lens,
            self.kwargs_source,
            self.kwargs_lens_light,
            self.kwargs_ps,
            factor=0.1,
            symmetry=1)
        assert improved_bool
        kernel_new = kwargs_psf_return['kernel_point_source']
        kernel_true = self.kwargs_psf['kernel_point_source']
        kernel_old = kwargs_psf['kernel_point_source']
        diff_old = np.sum((kernel_old - kernel_true)**2)
        diff_new = np.sum((kernel_new - kernel_true)**2)
        assert diff_old > diff_new
Exemple #4
0
def test_subgrid_rebin():
    kernel_size = 11
    subgrid_res = 3

    sigma = 1
    from lenstronomy.LightModel.Profiles.gaussian import Gaussian
    gaussian = Gaussian()
    x_grid, y_gird = Util.make_grid(kernel_size, 1. / subgrid_res, subgrid_res)
    flux = gaussian.function(x_grid,
                             y_gird,
                             amp=1,
                             sigma_x=sigma,
                             sigma_y=sigma)
    kernel = Util.array2image(flux)
    print(np.shape(kernel))
    kernel = util.averaging(kernel,
                            numGrid=kernel_size * subgrid_res,
                            numPix=kernel_size)
    kernel = kernel_util.kernel_norm(kernel)

    subgrid_kernel = kernel_util.subgrid_kernel(kernel,
                                                subgrid_res=subgrid_res,
                                                odd=True)
    kernel_pixel = util.averaging(subgrid_kernel,
                                  numGrid=kernel_size * subgrid_res,
                                  numPix=kernel_size)
    kernel_pixel = kernel_util.kernel_norm(kernel_pixel)
    assert np.sum((kernel_pixel - kernel)**2) < 0.1
Exemple #5
0
 def test_gaussian_ellipse(self):
     gaussianEllipse = GaussianEllipse()
     gaussian = Gaussian()
     sigma = 1
     flux = gaussianEllipse.function(1, 1, amp=1, sigma=sigma, e1=0, e2=0)
     flux_spherical = gaussian.function(1, 1, amp=1, sigma=sigma)
     npt.assert_almost_equal(flux, flux_spherical, decimal=8)
Exemple #6
0
    def test_update_iterative(self):
        fwhm = 0.5
        sigma = util.fwhm2sigma(fwhm)
        x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05)
        from lenstronomy.LightModel.Profiles.gaussian import Gaussian
        gaussian = Gaussian()
        kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma_x=sigma, sigma_y=sigma,
                                              center_x=0, center_y=0)
        kernel_point_source /= np.sum(kernel_point_source)
        kernel_point_source = util.array2image(kernel_point_source)
        kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source}
        kwargs_psf_iter = {'stacking_method': 'median'}
        kwargs_psf_new = self.psf_fitting.update_iterative(kwargs_psf, self.kwargs_lens, self.kwargs_source,
                                                                       self.kwargs_lens_light, self.kwargs_ps,
                                                           **kwargs_psf_iter)
        kernel_new = kwargs_psf_new['kernel_point_source']
        kernel_true = self.kwargs_psf['kernel_point_source']
        kernel_old = kwargs_psf['kernel_point_source']
        diff_old = np.sum((kernel_old - kernel_true) ** 2)
        diff_new = np.sum((kernel_new - kernel_true) ** 2)
        assert diff_old > diff_new
        assert diff_new < 0.01

        kwargs_psf_new = self.psf_fitting.update_iterative(kwargs_psf, self.kwargs_lens, self.kwargs_source,
                                                           self.kwargs_lens_light, self.kwargs_ps, num_iter=3,
                                                           no_break=True)
        kernel_new = kwargs_psf_new['kernel_point_source']
        kernel_true = self.kwargs_psf['kernel_point_source']
        kernel_old = kwargs_psf['kernel_point_source']
        diff_old = np.sum((kernel_old - kernel_true) ** 2)
        diff_new = np.sum((kernel_new - kernel_true) ** 2)
        assert diff_old > diff_new
        assert diff_new < 0.01
Exemple #7
0
    def test_update_psf(self):
        fwhm = 0.5
        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)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel_point_source
        }

        kwargs_psf_iter = {'stacking_method': 'median'}
        #mag = np.ones_like(x_pos)

        kwargs_psf_return, improved_bool, error_map = self.psf_fitting.update_psf(
            kwargs_psf, self.kwargs_params, **kwargs_psf_iter)
        assert improved_bool
        kernel_new = kwargs_psf_return['kernel_point_source']
        kernel_true = self.kwargs_psf['kernel_point_source']
        kernel_old = kwargs_psf['kernel_point_source']
        diff_old = np.sum((kernel_old - kernel_true)**2)
        diff_new = np.sum((kernel_new - kernel_true)**2)
        assert diff_old > diff_new
    def test_update_iterative(self):
        fwhm = 0.5
        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)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel_point_source,
            'kernel_point_source_init': kernel_point_source
        }
        kwargs_psf_iter = {
            'stacking_method': 'median',
            'psf_symmetry': 2,
            'psf_iter_factor': 0.2,
            'block_center_neighbour': 0.1,
            'error_map_radius': 0.5,
            'new_procedure': False,
            'no_break': False,
            'verbose': True,
            'keep_psf_error_map': False
        }

        kwargs_params = copy.deepcopy(self.kwargs_params)
        kwargs_ps = kwargs_params['kwargs_ps']
        del kwargs_ps[0]['source_amp']
        print(kwargs_params['kwargs_ps'])
        kwargs_psf_new = self.psf_fitting.update_iterative(
            kwargs_psf, kwargs_params, **kwargs_psf_iter)
        kernel_new = kwargs_psf_new['kernel_point_source']
        kernel_true = self.kwargs_psf['kernel_point_source']
        kernel_old = kwargs_psf['kernel_point_source']
        diff_old = np.sum((kernel_old - kernel_true)**2)
        diff_new = np.sum((kernel_new - kernel_true)**2)
        assert diff_old > diff_new
        assert diff_new < 0.01
        assert 'psf_error_map' in kwargs_psf_new

        kwargs_psf_new = self.psf_fitting.update_iterative(
            kwargs_psf,
            kwargs_params,
            num_iter=3,
            no_break=True,
            keep_psf_error_map=True)
        kernel_new = kwargs_psf_new['kernel_point_source']
        kernel_true = self.kwargs_psf['kernel_point_source']
        kernel_old = kwargs_psf['kernel_point_source']
        diff_old = np.sum((kernel_old - kernel_true)**2)
        diff_new = np.sum((kernel_new - kernel_true)**2)
        assert diff_old > diff_new
        assert diff_new < 0.01
Exemple #9
0
 def test_total_flux(self):
     gauss = Gaussian()
     deltapix = 0.1
     amp = 1
     x_grid, y_gird = util.make_grid(100, deltapix=deltapix)
     flux = gauss.function(x_grid, y_gird, amp=amp, sigma=1)
     flux_integral = np.sum(flux) * deltapix**2
     npt.assert_almost_equal(flux_integral, amp, decimal=3)
Exemple #10
0
def test_radial_profile():
    from lenstronomy.LightModel.Profiles.gaussian import Gaussian
    gauss = Gaussian()
    x, y = util.make_grid(11, 1)
    flux = gauss.function(x, y, sigma=10, amp=1)
    data = util.array2image(flux)
    profile_r = image_util.radial_profile(data, center=[5, 5])
    profile_r_true = gauss.function(np.linspace(0, stop=7, num=8), 0, sigma=10, amp=1)
    npt.assert_almost_equal(profile_r, profile_r_true, decimal=3)
Exemple #11
0
def kernel_gaussian(kernel_numPix, deltaPix, fwhm):
    sigma = util.fwhm2sigma(fwhm)
    #if kernel_numPix % 2 == 0:
    #    kernel_numPix += 1
    x_grid, y_grid = util.make_grid(kernel_numPix, deltaPix)
    gaussian = Gaussian()
    kernel = gaussian.function(x_grid, y_grid, amp=1., sigma=sigma, center_x=0, center_y=0)
    kernel /= np.sum(kernel)
    kernel = util.array2image(kernel)
    return kernel
Exemple #12
0
    def test_function(self):
        """

        :return:
        """
        x, y = util.make_grid(numPix=20, deltapix=1.)
        gauss = Gaussian()
        flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.)
        image = util.array2image(flux)
        interp = Interpol()
        kwargs_interp = {
            'image': image,
            'scale': 1.,
            'phi_G': 0.,
            'center_x': 0.,
            'center_y': 0.
        }
        output = interp.function(x, y, **kwargs_interp)
        npt.assert_almost_equal(output, flux, decimal=0)

        flux = gauss.function(x - 1.,
                              y,
                              amp=1.,
                              center_x=0.,
                              center_y=0.,
                              sigma=1.)
        kwargs_interp = {
            'image': image,
            'scale': 1.,
            'phi_G': 0.,
            'center_x': 1.,
            'center_y': 0.
        }
        output = interp.function(x, y, **kwargs_interp)
        npt.assert_almost_equal(output, flux, decimal=0)

        flux = gauss.function(x - 1.,
                              y - 1.,
                              amp=1,
                              center_x=0.,
                              center_y=0.,
                              sigma=1.)
        kwargs_interp = {
            'image': image,
            'scale': 1.,
            'phi_G': 0.,
            'center_x': 1.,
            'center_y': 1.
        }
        output = interp.function(x, y, **kwargs_interp)
        npt.assert_almost_equal(output, flux, decimal=0)

        out = interp.function(x=1000, y=0, **kwargs_interp)
        assert out == 0
Exemple #13
0
 def test_radial_profile(self):
     x_grid, y_grid = util.make_grid(numPix=20, deltapix=1)
     profile = Gaussian()
     light_grid = profile.function(x_grid, y_grid, amp=1., sigma=5)
     I_r, r = analysis_util.radial_profile(light_grid,
                                           x_grid,
                                           y_grid,
                                           center_x=0,
                                           center_y=0,
                                           n=None)
     assert I_r[0] == 0
Exemple #14
0
def test_kernel_average_pixel():
    gaussian = Gaussian()
    subgrid_res = 3
    x_grid, y_gird = Util.make_grid(9, 1., subgrid_res)
    sigma = 2
    flux = gaussian.function(x_grid, y_gird, amp=1, sigma=sigma)
    kernel_super = Util.array2image(flux)
    kernel_pixel = kernel_util.kernel_average_pixel(kernel_super, supersampling_factor=subgrid_res)
    npt.assert_almost_equal(np.sum(kernel_pixel), np.sum(kernel_super))

    kernel_pixel = kernel_util.kernel_average_pixel(kernel_super, supersampling_factor=2)
    npt.assert_almost_equal(np.sum(kernel_pixel), np.sum(kernel_super))
Exemple #15
0
    def magnification_finite(self,
                             x_pos,
                             y_pos,
                             kwargs_lens,
                             source_sigma=0.003,
                             window_size=0.1,
                             grid_number=100,
                             polar_grid=False,
                             aspect_ratio=0.5):
        """
        returns the magnification of an extended source with Gaussian light profile
        :param x_pos: x-axis positons of point sources
        :param y_pos: y-axis position of point sources
        :param kwargs_lens: lens model kwargs
        :param source_sigma: Gaussian sigma in arc sec in source
        :param window_size: size of window to compute the finite flux
        :param grid_number: number of grid cells per axis in the window to numerically compute the flux
        :return: numerically computed brightness of the sources
        """

        mag_finite = np.zeros_like(x_pos)
        deltaPix = float(window_size) / grid_number
        from lenstronomy.LightModel.Profiles.gaussian import Gaussian
        quasar = Gaussian()
        x_grid, y_grid = util.make_grid(numPix=grid_number,
                                        deltapix=deltaPix,
                                        subgrid_res=1)

        if polar_grid is True:
            a = window_size * 0.5
            b = window_size * 0.5 * aspect_ratio
            ellipse_inds = (x_grid * a**-1)**2 + (y_grid * b**-1)**2 <= 1
            x_grid, y_grid = x_grid[ellipse_inds], y_grid[ellipse_inds]

        for i in range(len(x_pos)):
            ra, dec = x_pos[i], y_pos[i]

            center_x, center_y = self._lensModel.ray_shooting(
                ra, dec, kwargs_lens)

            if polar_grid is True:
                theta = np.arctan2(dec, ra)
                xcoord, ycoord = util.rotate(x_grid, y_grid, theta)
            else:
                xcoord, ycoord = x_grid, y_grid

            betax, betay = self._lensModel.ray_shooting(
                xcoord + ra, ycoord + dec, kwargs_lens)

            I_image = quasar.function(betax, betay, 1., source_sigma, center_x,
                                      center_y)
            mag_finite[i] = np.sum(I_image) * deltaPix**2
        return mag_finite
Exemple #16
0
def test_fwhm_kernel():
    x_grid, y_gird = Util.make_grid(101, 1)
    sigma = 20
    from lenstronomy.LightModel.Profiles.gaussian import Gaussian
    gaussian = Gaussian()
    flux = gaussian.function(x_grid,
                             y_gird,
                             amp=1,
                             sigma_x=sigma,
                             sigma_y=sigma)
    kernel = Util.array2image(flux)
    kernel = kernel_util.kernel_norm(kernel)
    fwhm_kernel = kernel_util.fwhm_kernel(kernel)
    fwhm = Util.sigma2fwhm(sigma)
    npt.assert_almost_equal(fwhm / fwhm_kernel, 1, 2)
    def zoom_source(self, x_pos, y_pos, kwargs_lens, source_sigma=0.003, window_size=0.1, grid_number=100,
                    shape="GAUSSIAN"):
        """
        computes the surface brightness on an image with a zoomed window

        :param x_pos: angular coordinate of center of image
        :param y_pos: angular coordinate of center of image
        :param kwargs_lens: lens model parameter list
        :param source_sigma: source size (in angular units)
        :param window_size: window size in angular units
        :param grid_number: number of grid points per axis
        :param shape: string, shape of source, supports 'GAUSSIAN' and 'TORUS
        :return: 2d numpy array
        """
        deltaPix = float(window_size) / grid_number
        if shape == 'GAUSSIAN':
            from lenstronomy.LightModel.Profiles.gaussian import Gaussian
            quasar = Gaussian()
        elif shape == 'TORUS':
            import lenstronomy.LightModel.Profiles.ellipsoid as quasar
        else:
            raise ValueError("shape %s not valid for finite magnification computation!" % shape)
        x_grid, y_grid = util.make_grid(numPix=grid_number, deltapix=deltaPix, subgrid_res=1)
        center_x, center_y = self._lensModel.ray_shooting(x_pos, y_pos, kwargs_lens)
        betax, betay = self._lensModel.ray_shooting(x_grid + x_pos, y_grid + y_pos, kwargs_lens)
        image = quasar.function(betax, betay, 1., source_sigma, center_x, center_y)
        return util.array2image(image)
class TestGaussianKappa(object):
    """
    test the Gaussian with Gaussian kappa
    """
    def setup(self):
        self.gaussian_kappa = MultiGaussian_kappa()
        self.gaussian = Gaussian()
        self.g_kappa = GaussianKappa()

    def test_derivatives(self):
        x = np.linspace(0, 5, 10)
        y = np.linspace(0, 5, 10)
        amp = [1. * 2 * np.pi]
        center_x = 0.
        center_y = 0.
        sigma = [1.]
        f_x, f_y = self.gaussian_kappa.derivatives(x, y, amp, sigma, center_x,
                                                   center_y)
        npt.assert_almost_equal(f_x[2], 0.63813558702212059, decimal=8)
        npt.assert_almost_equal(f_y[2], 0.63813558702212059, decimal=8)

    def test_hessian(self):
        x = np.linspace(0, 5, 10)
        y = np.linspace(0, 5, 10)
        amp = [1. * 2 * np.pi]
        center_x = 0.
        center_y = 0.
        sigma = [1.]
        f_xx, f_yy, f_xy = self.gaussian_kappa.hessian(x, y, amp, sigma,
                                                       center_x, center_y)
        kappa = 1. / 2 * (f_xx + f_yy)
        kappa_true = self.gaussian.function(x, y, amp[0], sigma[0], sigma[0],
                                            center_x, center_y)
        print(kappa_true)
        print(kappa)
        npt.assert_almost_equal(kappa[0], kappa_true[0], decimal=5)
        npt.assert_almost_equal(kappa[1], kappa_true[1], decimal=5)

    def test_density_2d(self):
        x = np.linspace(0, 5, 10)
        y = np.linspace(0, 5, 10)
        amp = [1. * 2 * np.pi]
        center_x = 0.
        center_y = 0.
        sigma = [1.]
        f_xx, f_yy, f_xy = self.gaussian_kappa.hessian(x, y, amp, sigma,
                                                       center_x, center_y)
        kappa = 1. / 2 * (f_xx + f_yy)
        amp_3d = self.g_kappa._amp2d_to_3d(amp, sigma[0], sigma[0])
        density_2d = self.gaussian_kappa.density_2d(x, y, amp_3d, sigma,
                                                    center_x, center_y)
        npt.assert_almost_equal(kappa[1], density_2d[1], decimal=5)
        npt.assert_almost_equal(kappa[2], density_2d[2], decimal=5)

    def test_density(self):
        amp = [1. * 2 * np.pi]

        sigma = [1.]
        density = self.gaussian_kappa.density(1., amp, sigma)
        npt.assert_almost_equal(density, 0.6065306597126334, decimal=8)
Exemple #19
0
    def magnification_finite(self, x_pos, y_pos, kwargs_lens, source_sigma=0.003, window_size=0.1, grid_number=100,
                             shape="GAUSSIAN"):
        """
        returns the magnification of an extended source with Gaussian light profile
        :param x_pos: x-axis positons of point sources
        :param y_pos: y-axis position of point sources
        :param kwargs_lens: lens model kwargs
        :param source_sigma: Gaussian sigma in arc sec in source
        :param window_size: size of window to compute the finite flux
        :param grid_number: number of grid cells per axis in the window to numerically comute the flux
        :return: numerically computed brightness of the sources
        """

        mag_finite = np.zeros_like(x_pos)
        deltaPix = float(window_size)/grid_number
        if shape == 'GAUSSIAN':
            from lenstronomy.LightModel.Profiles.gaussian import Gaussian
            quasar = Gaussian()
        elif shape == 'TORUS':
            import lenstronomy.LightModel.Profiles.torus as quasar
        else:
            raise ValueError("shape %s not valid for finite magnification computation!" % shape)
        x_grid, y_grid = util.make_grid(numPix=grid_number, deltapix=deltaPix, subgrid_res=1)
        for i in range(len(x_pos)):
            ra, dec = x_pos[i], y_pos[i]
            center_x, center_y = self.ray_shooting(ra, dec, kwargs_lens)
            x_source, y_source = self.ray_shooting(x_grid + ra, y_grid + dec, kwargs_lens)
            I_image = quasar.function(x_source, y_source, 1., source_sigma, source_sigma, center_x, center_y)
            mag_finite[i] = np.sum(I_image) * deltaPix**2
        return mag_finite
 def test_delete_cache(self):
     x, y = util.make_grid(numPix=20, deltapix=1.)
     gauss = Gaussian()
     flux = gauss.function(x, y, amp=1., center_x=0., center_y=0., sigma=1.)
     image = util.array2image(flux)
     interp = Interpol()
     kwargs_interp = {
         'image': image,
         'scale': 1.,
         'phi_G': 0.,
         'center_x': 0.,
         'center_y': 0.
     }
     output = interp.function(x, y, **kwargs_interp)
     assert hasattr(interp, '_image_interp')
     interp.delete_cache()
     assert not hasattr(interp, '_image_interp')
Exemple #21
0
 def __init__(self, light_model_list, smoothing=0.0000001):
     self.profile_type_list = light_model_list
     self.func_list = []
     for profile_type in light_model_list:
         valid = True
         if profile_type == 'GAUSSIAN':
             from lenstronomy.LightModel.Profiles.gaussian import Gaussian
             self.func_list.append(Gaussian())
         elif profile_type == 'GAUSSIAN_ELLIPSE':
             from lenstronomy.LightModel.Profiles.gaussian import GaussianEllipse
             self.func_list.append(GaussianEllipse())
         elif profile_type == 'MULTI_GAUSSIAN':
             from lenstronomy.LightModel.Profiles.gaussian import MultiGaussian
             self.func_list.append(MultiGaussian())
         elif profile_type == 'MULTI_GAUSSIAN_ELLIPSE':
             from lenstronomy.LightModel.Profiles.gaussian import MultiGaussianEllipse
             self.func_list.append(MultiGaussianEllipse())
         elif profile_type == 'SERSIC':
             from lenstronomy.LightModel.Profiles.sersic import Sersic
             self.func_list.append(Sersic(smoothing=smoothing))
         elif profile_type == 'SERSIC_ELLIPSE':
             from lenstronomy.LightModel.Profiles.sersic import Sersic_elliptic
             self.func_list.append(Sersic_elliptic(smoothing=smoothing))
         elif profile_type == 'CORE_SERSIC':
             from lenstronomy.LightModel.Profiles.sersic import CoreSersic
             self.func_list.append(CoreSersic(smoothing=smoothing))
         elif profile_type == 'SHAPELETS':
             from lenstronomy.LightModel.Profiles.shapelets import ShapeletSet
             self.func_list.append(ShapeletSet())
         elif profile_type == 'HERNQUIST':
             from lenstronomy.LightModel.Profiles.hernquist import Hernquist
             self.func_list.append(Hernquist())
         elif profile_type == 'HERNQUIST_ELLIPSE':
             from lenstronomy.LightModel.Profiles.hernquist import Hernquist_Ellipse
             self.func_list.append(Hernquist_Ellipse())
         elif profile_type == 'PJAFFE':
             from lenstronomy.LightModel.Profiles.p_jaffe import PJaffe
             self.func_list.append(PJaffe())
         elif profile_type == 'PJAFFE_ELLIPSE':
             from lenstronomy.LightModel.Profiles.p_jaffe import PJaffe_Ellipse
             self.func_list.append(PJaffe_Ellipse())
         elif profile_type == 'UNIFORM':
             from lenstronomy.LightModel.Profiles.uniform import Uniform
             self.func_list.append(Uniform())
         elif profile_type == 'POWER_LAW':
             from lenstronomy.LightModel.Profiles.power_law import PowerLaw
             self.func_list.append(PowerLaw())
         elif profile_type == 'NIE':
             from lenstronomy.LightModel.Profiles.nie import NIE
             self.func_list.append(NIE())
         elif profile_type == 'CHAMELEON':
             from lenstronomy.LightModel.Profiles.chameleon import Chameleon
             self.func_list.append(Chameleon())
         elif profile_type == 'DOUBLE_CHAMELEON':
             from lenstronomy.LightModel.Profiles.chameleon import DoubleChameleon
             self.func_list.append(DoubleChameleon())
         else:
             raise ValueError('Warning! No light model of type', profile_type, ' found!')
Exemple #22
0
    def test_light_3d(self):
        gaussianEllipse = GaussianEllipse()
        gaussian = Gaussian()

        sigma = 1
        r = 1.
        amp = 1.
        flux_spherical = gaussian.light_3d(r, amp, sigma)
        flux = gaussianEllipse.light_3d(r, amp, sigma)
        npt.assert_almost_equal(flux, flux_spherical, decimal=8)

        multiGaussian = MultiGaussian()
        multiGaussianEllipse = MultiGaussianEllipse()
        amp = [1, 2]
        sigma = [1., 2]
        flux_spherical = multiGaussian.light_3d(r, amp, sigma)
        flux = multiGaussianEllipse.light_3d(r, amp, sigma)
        npt.assert_almost_equal(flux, flux_spherical, decimal=8)
Exemple #23
0
    def setup(self):
        # different versions of Starlet transforms
        self.starlets = SLIT_Starlets(fast_inverse=False,
                                      second_gen=False,
                                      force_no_pysap=_force_no_pysap)
        self.starlets_fast = SLIT_Starlets(fast_inverse=True,
                                           second_gen=False,
                                           force_no_pysap=_force_no_pysap)
        self.starlets_2nd = SLIT_Starlets(second_gen=True,
                                          force_no_pysap=_force_no_pysap)

        # define a test image with gaussian components
        self.num_pix = 50
        self.n_scales = 3
        self.n_pixels = self.num_pix**2
        self.x, self.y = util.make_grid(self.num_pix, 1)

        # build a non-trivial positive image from sum of gaussians
        gaussian = Gaussian()
        gaussian1 = gaussian.function(self.x,
                                      self.y,
                                      amp=100,
                                      sigma=1,
                                      center_x=-7,
                                      center_y=-7)
        gaussian2 = gaussian.function(self.x,
                                      self.y,
                                      amp=500,
                                      sigma=3,
                                      center_x=-3,
                                      center_y=-3)
        gaussian3 = gaussian.function(self.x,
                                      self.y,
                                      amp=2000,
                                      sigma=5,
                                      center_x=+5,
                                      center_y=+5)
        self.test_image = util.array2image(gaussian1 + gaussian2 + gaussian3)

        self.test_coeffs = np.zeros(
            (self.n_scales, self.num_pix, self.num_pix))
        self.test_coeffs[0, :, :] = util.array2image(gaussian1)
        self.test_coeffs[1, :, :] = util.array2image(gaussian2)
        self.test_coeffs[2, :, :] = util.array2image(gaussian3)
Exemple #24
0
def test_center_kernel():
    x_grid, y_gird = Util.make_grid(31, 1)
    sigma = 2
    from lenstronomy.LightModel.Profiles.gaussian import Gaussian
    gaussian = Gaussian()
    flux = gaussian.function(x_grid,
                             y_gird,
                             amp=1,
                             sigma_x=sigma,
                             sigma_y=sigma)
    kernel = Util.array2image(flux)
    kernel = kernel_util.kernel_norm(kernel)

    # kernel being centered
    kernel_new = kernel_util.center_kernel(kernel, iterations=20)
    kernel_new = kernel_util.kernel_norm(kernel_new)
    npt.assert_almost_equal(kernel_new / kernel, 1, decimal=8)
    # kernel shifted in x
    kernel_shifted = interp.shift(kernel, [-.1, 0], order=1)
    kernel_new = kernel_util.center_kernel(kernel_shifted, iterations=5)
    kernel_new = kernel_util.kernel_norm(kernel_new)
    npt.assert_almost_equal((kernel_new + 0.00001) / (kernel + 0.00001),
                            1,
                            decimal=4)
    # kernel shifted in y
    kernel_shifted = interp.shift(kernel, [0, -0.4], order=1)
    kernel_new = kernel_util.center_kernel(kernel_shifted, iterations=5)
    kernel_new = kernel_util.kernel_norm(kernel_new)
    npt.assert_almost_equal((kernel_new + 0.01) / (kernel + 0.01),
                            1,
                            decimal=3)
    # kernel shifted in x and y
    kernel_shifted = interp.shift(kernel, [0.2, -0.3], order=1)
    kernel_new = kernel_util.center_kernel(kernel_shifted, iterations=5)
    kernel_new = kernel_util.kernel_norm(kernel_new)
    npt.assert_almost_equal((kernel_new + 0.01) / (kernel + 0.01),
                            1,
                            decimal=3)
Exemple #25
0
    def setup(self):

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

        # PSF specification

        kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, sigma_bkg)
        data_class = Data(kwargs_data)
        sigma = util.fwhm2sigma(fwhm)
        x_grid, y_grid = util.make_grid(numPix=31, deltapix=0.05)
        from lenstronomy.LightModel.Profiles.gaussian import Gaussian
        gaussian = Gaussian()
        kernel_point_source = gaussian.function(x_grid, y_grid, amp=1., sigma_x=sigma, sigma_y=sigma,
                                                center_x=0, center_y=0)
        kernel_point_source /= np.sum(kernel_point_source)
        kernel_point_source = util.array2image(kernel_point_source)
        self.kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source}

        psf_class = PSF(kwargs_psf=self.kwargs_psf)

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

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

        lens_light_model_list = ['SERSIC']
        self.kwargs_lens_light = [kwargs_sersic]
        lens_light_model_class = LightModel(light_model_list=lens_light_model_list)
        source_model_list = ['SERSIC_ELLIPSE']
        self.kwargs_source = [kwargs_sersic_ellipse]
        source_model_class = LightModel(light_model_list=source_model_list)
        self.kwargs_ps = [{'ra_source': 0.0, 'dec_source': 0.0,
                           'source_amp': 10.}]  # quasar point source position in the source plane and intrinsic brightness
        point_source_class = PointSource(point_source_type_list=['SOURCE_POSITION'], fixed_magnification_list=[True])
        kwargs_numerics = {'subgrid_res': 3, 'psf_subgrid': True}
        imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class,
                                     lens_light_model_class,
                                     point_source_class, kwargs_numerics=kwargs_numerics)
        image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens, self.kwargs_source,
                                         self.kwargs_lens_light, self.kwargs_ps)
        data_class.update_data(image_sim)
        self.imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class,
                                lens_light_model_class,
                                point_source_class, kwargs_numerics=kwargs_numerics)

        self.psf_fitting = PsfFitting(self.imageModel)
Exemple #26
0
    def __init__(self, light_model_list, smoothing=0.001):
        """

        :param light_model_list: list of light models
        :param smoothing: smoothing factor for certain models (deprecated)
        """
        self.profile_type_list = light_model_list
        self.func_list = []
        for profile_type in light_model_list:
            if profile_type == 'GAUSSIAN':
                from lenstronomy.LightModel.Profiles.gaussian import Gaussian
                self.func_list.append(Gaussian())
            elif profile_type == 'GAUSSIAN_ELLIPSE':
                from lenstronomy.LightModel.Profiles.gaussian import GaussianEllipse
                self.func_list.append(GaussianEllipse())
            elif profile_type == 'ELLIPSOID':
                from lenstronomy.LightModel.Profiles.ellipsoid import Ellipsoid
                self.func_list.append(Ellipsoid())
            elif profile_type == 'MULTI_GAUSSIAN':
                from lenstronomy.LightModel.Profiles.gaussian import MultiGaussian
                self.func_list.append(MultiGaussian())
            elif profile_type == 'MULTI_GAUSSIAN_ELLIPSE':
                from lenstronomy.LightModel.Profiles.gaussian import MultiGaussianEllipse
                self.func_list.append(MultiGaussianEllipse())
            elif profile_type == 'SERSIC':
                from lenstronomy.LightModel.Profiles.sersic import Sersic
                self.func_list.append(Sersic(smoothing=smoothing))
            elif profile_type == 'SERSIC_ELLIPSE':
                from lenstronomy.LightModel.Profiles.sersic import SersicElliptic
                self.func_list.append(
                    SersicElliptic(smoothing=smoothing,
                                   sersic_major_axis=sersic_major_axis_conf))
            elif profile_type == 'CORE_SERSIC':
                from lenstronomy.LightModel.Profiles.sersic import CoreSersic
                self.func_list.append(CoreSersic(smoothing=smoothing))
            elif profile_type == 'SHAPELETS':
                from lenstronomy.LightModel.Profiles.shapelets import ShapeletSet
                self.func_list.append(ShapeletSet())
            elif profile_type == 'SHAPELETS_POLAR':
                from lenstronomy.LightModel.Profiles.shapelets_polar import ShapeletSetPolar
                self.func_list.append(ShapeletSetPolar(exponential=False))
            elif profile_type == 'SHAPELETS_POLAR_EXP':
                from lenstronomy.LightModel.Profiles.shapelets_polar import ShapeletSetPolar
                self.func_list.append(ShapeletSetPolar(exponential=True))
            elif profile_type == 'HERNQUIST':
                from lenstronomy.LightModel.Profiles.hernquist import Hernquist
                self.func_list.append(Hernquist())
            elif profile_type == 'HERNQUIST_ELLIPSE':
                from lenstronomy.LightModel.Profiles.hernquist import HernquistEllipse
                self.func_list.append(HernquistEllipse())
            elif profile_type == 'PJAFFE':
                from lenstronomy.LightModel.Profiles.p_jaffe import PJaffe
                self.func_list.append(PJaffe())
            elif profile_type == 'PJAFFE_ELLIPSE':
                from lenstronomy.LightModel.Profiles.p_jaffe import PJaffe_Ellipse
                self.func_list.append(PJaffe_Ellipse())
            elif profile_type == 'UNIFORM':
                from lenstronomy.LightModel.Profiles.uniform import Uniform
                self.func_list.append(Uniform())
            elif profile_type == 'POWER_LAW':
                from lenstronomy.LightModel.Profiles.power_law import PowerLaw
                self.func_list.append(PowerLaw())
            elif profile_type == 'NIE':
                from lenstronomy.LightModel.Profiles.nie import NIE
                self.func_list.append(NIE())
            elif profile_type == 'CHAMELEON':
                from lenstronomy.LightModel.Profiles.chameleon import Chameleon
                self.func_list.append(Chameleon())
            elif profile_type == 'DOUBLE_CHAMELEON':
                from lenstronomy.LightModel.Profiles.chameleon import DoubleChameleon
                self.func_list.append(DoubleChameleon())
            elif profile_type == 'TRIPLE_CHAMELEON':
                from lenstronomy.LightModel.Profiles.chameleon import TripleChameleon
                self.func_list.append(TripleChameleon())
            elif profile_type == 'INTERPOL':
                from lenstronomy.LightModel.Profiles.interpolation import Interpol
                self.func_list.append(Interpol())
            elif profile_type == 'SLIT_STARLETS':
                from lenstronomy.LightModel.Profiles.starlets import SLIT_Starlets
                self.func_list.append(
                    SLIT_Starlets(fast_inverse=True, second_gen=False))
            elif profile_type == 'SLIT_STARLETS_GEN2':
                from lenstronomy.LightModel.Profiles.starlets import SLIT_Starlets
                self.func_list.append(SLIT_Starlets(second_gen=True))
            else:
                raise ValueError(
                    'No light model of type %s found! Supported are the following models: %s'
                    % (profile_type, _MODELS_SUPPORTED))
        self._num_func = len(self.func_list)
__author__ = "ajshajib", "sibirrer"
"""
Multi-Gaussian expansion fitting, based on Capellari 2002, http://adsabs.harvard.edu/abs/2002MNRAS.333..400C
"""

import numpy as np
from scipy.optimize import nnls
import warnings
from lenstronomy.LightModel.Profiles.gaussian import Gaussian
gaussian_func = Gaussian()


def gaussian(R, sigma, amp):
    """

    :param R: radius
    :param sigma: gaussian sigma
    :param amp: normalization
    :return: Gaussian function
    """
    c = amp / (2 * np.pi * sigma**2)
    return c * np.exp(-(R/float(sigma))**2/2.)


def mge_1d(r_array, flux_r, N=20, linspace=False):
    """

    :param r_array: list or radii (numpy array)
    :param flux_r: list of flux values (numpy array)
    :param N: number of Gaussians
    :return: amplitudes and Gaussian sigmas for the best 1d flux profile
 def setup(self):
     self.gaussian_kappa = MultiGaussian_kappa()
     self.gaussian = Gaussian()
     self.g_kappa = GaussianKappa()
Exemple #29
0
    def setup(self):
        self.num_pix = 20  # cutout pixel size
        delta_pix = 0.2
        _, _, 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)
        # imaging data class
        gaussian = Gaussian()
        x, y = l_util.make_grid(self.num_pix, 1)
        gaussian1 = gaussian.function(x,
                                      y,
                                      amp=5,
                                      sigma=1,
                                      center_x=-7,
                                      center_y=-7)
        gaussian2 = gaussian.function(x,
                                      y,
                                      amp=20,
                                      sigma=2,
                                      center_x=-3,
                                      center_y=-3)
        gaussian3 = gaussian.function(x,
                                      y,
                                      amp=60,
                                      sigma=4,
                                      center_x=+5,
                                      center_y=+5)
        image_data = util.array2image(gaussian1 + gaussian2 + gaussian3)
        background_rms = 0.1
        image_data += background_rms * np.random.randn(self.num_pix,
                                                       self.num_pix)
        kwargs_data = {
            'ra_at_xy_0': ra_at_xy_0,
            'dec_at_xy_0': dec_at_xy_0,
            'transform_pix2angle': Mpix2coord,
            'image_data': image_data,
            'background_rms': background_rms,
            'noise_map': background_rms * np.ones_like(image_data),
        }
        data_class = ImageData(**kwargs_data)

        # lens mass class
        lens_model_class = LensModel(['SPEP'])
        self.kwargs_lens = [{
            'theta_E': 1,
            'gamma': 2,
            'center_x': 0,
            'center_y': 0,
            'e1': -0.05,
            'e2': 0.05
        }]

        # source light class
        source_model_class = LightModel(['SLIT_STARLETS'])
        self.kwargs_source = [{
            'coeffs': 0,
            'n_scales': 3,
            'n_pixels': self.num_pix**2
        }]

        # define numerics classes
        image_numerics_class = NumericsSubFrame(pixel_grid=data_class,
                                                psf=PSF(psf_type='NONE'))
        source_numerics_class = NumericsSubFrame(pixel_grid=data_class,
                                                 psf=PSF(psf_type='NONE'),
                                                 supersampling_factor=1)

        # init sparse solver
        self.solver = SparseSolverSource(data_class,
                                         lens_model_class,
                                         image_numerics_class,
                                         source_numerics_class,
                                         source_model_class,
                                         num_iter_source=10)

        # init the plotter
        self.plotter = SolverPlotter(self.solver, show_now=False)
Exemple #30
0
import lenstronomy.Util.util as Util
import lenstronomy.Util.kernel_util as kernel_util
import lenstronomy.Util.image_util as image_util
import lenstronomy.Util.util as util
from lenstronomy.LightModel.Profiles.gaussian import Gaussian
gaussian = Gaussian()
import pytest
import unittest
import numpy as np
import numpy.testing as npt
import scipy.ndimage.interpolation as interp


def test_fwhm_kernel():
    x_grid, y_gird = Util.make_grid(101, 1)
    sigma = 20

    flux = gaussian.function(x_grid, y_gird, amp=1, sigma=sigma)
    kernel = Util.array2image(flux)
    kernel = kernel_util.kernel_norm(kernel)
    fwhm_kernel = kernel_util.fwhm_kernel(kernel)
    fwhm = Util.sigma2fwhm(sigma)
    npt.assert_almost_equal(fwhm/fwhm_kernel, 1, 2)


def test_center_kernel():
    x_grid, y_gird = Util.make_grid(31, 1)
    sigma = 2
    flux = gaussian.function(x_grid, y_gird, amp=1, sigma=sigma)
    kernel = Util.array2image(flux)
    kernel = kernel_util.kernel_norm(kernel)