示例#1
0
    def convergence_plot(self,
                         ax,
                         text='Convergence',
                         v_min=None,
                         v_max=None,
                         font_size=15,
                         colorbar_label=r'$\log_{10}\ \kappa$',
                         **kwargs):
        """

        :param x_grid:
        :param y_grid:
        :param kwargs_lens:
        :param kwargs_else:
        :return:
        """
        if not 'cmap' in kwargs:
            kwargs['cmap'] = self._cmap

        kappa_result = util.array2image(
            self._lensModel.kappa(self._x_grid, self._y_grid,
                                  self._kwargs_lens_partial))
        im = ax.matshow(np.log10(kappa_result),
                        origin='lower',
                        extent=[0, self._frame_size, 0, self._frame_size],
                        cmap=kwargs['cmap'],
                        vmin=v_min,
                        vmax=v_max)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.autoscale(False)
        plot_util.scale_bar(ax,
                            self._frame_size,
                            dist=1,
                            text='1"',
                            color='w',
                            font_size=font_size)
        if 'no_arrow' not in kwargs or not kwargs['no_arrow']:
            plot_util.coordinate_arrows(ax,
                                        self._frame_size,
                                        self._coords,
                                        color='w',
                                        arrow_size=self._arrow_size,
                                        font_size=font_size)
            plot_util.text_description(ax,
                                       self._frame_size,
                                       text=text,
                                       color="w",
                                       backgroundcolor='k',
                                       flipped=False,
                                       font_size=font_size)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cb = plt.colorbar(im, cax=cax)
        cb.set_label(colorbar_label, fontsize=font_size)
        return ax
示例#2
0
    def critical_curve_caustics(self,
                                kwargs_lens,
                                compute_window=5,
                                grid_scale=0.01):
        """

        :param kwargs_lens: lens model kwargs
        :param compute_window: window size in arcsec where the critical curve is computed
        :param grid_scale: numerical grid spacing of the computation of the critical curves
        :return: lists of ra and dec arrays corresponding to different disconnected critical curves and their caustic counterparts

        """
        numPix = int(compute_window / grid_scale)
        x_grid_high_res, y_grid_high_res = util.make_grid(numPix,
                                                          deltapix=grid_scale,
                                                          subgrid_res=1)
        mag_high_res = util.array2image(
            self._lensModel.magnification(x_grid_high_res, y_grid_high_res,
                                          kwargs_lens))

        ra_crit_list = []
        dec_crit_list = []
        ra_caustic_list = []
        dec_caustic_list = []

        import matplotlib.pyplot as plt
        cs = plt.contour(util.array2image(x_grid_high_res),
                         util.array2image(y_grid_high_res),
                         mag_high_res, [0],
                         alpha=0.0)
        paths = cs.collections[0].get_paths()
        for i, p in enumerate(paths):
            v = p.vertices
            ra_points = v[:, 0]
            dec_points = v[:, 1]
            ra_crit_list.append(ra_points)
            dec_crit_list.append(dec_points)
            ra_caustics, dec_caustics = self._lensModel.ray_shooting(
                ra_points, dec_points, kwargs_lens)
            ra_caustic_list.append(ra_caustics)
            dec_caustic_list.append(dec_caustics)
        plt.cla()
        return ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list
    def _deflection_kernel(x_grid, y_grid, delta_pix):
        """
        numerical gridded integration kernel for convergence to deflection angle with given pixel size

        :param x_grid: x-axis coordinates
        :param y_grid: y-axis coordinates
        :param delta_pix: pixel size (per dimension)
        :return: kernel for x-direction and kernel of y-direction deflection angles
        """
        x_mean = np.mean(x_grid)
        y_mean = np.mean(y_grid)
        x_shift = x_grid - x_mean
        y_shift = y_grid - y_mean
        r2 = x_shift**2 + y_shift**2
        r2[r2 < (delta_pix / 2)**2] = (delta_pix / 2)**2

        kernel_x = util.array2image(x_shift / r2)
        kernel_y = util.array2image(y_shift / r2)
        return kernel_x, kernel_y
示例#4
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
示例#5
0
 def _array2image_subset(self, array):
     """
     maps a 1d array into a (nx, ny) 2d grid with array populating the idex_mask indices
     :param array: 1d array
     :return: 2d array
     """
     grid1d = np.zeros(self._nx * self._ny)
     grid1d[self._high_res_indexes1d] = array
     grid2d = util.array2image(grid1d, self._nx, self._ny)
     return grid2d
示例#6
0
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)
示例#7
0
    def test_sersic(self):
        from lenstronomy.LensModel.Profiles.sersic import Sersic
        from lenstronomy.LightModel.Profiles.sersic import Sersic as SersicLight
        sersic_lens = Sersic()
        sersic_light = SersicLight()
        kwargs_light = {
            'n_sersic': 2,
            'R_sersic': 0.5,
            'I0_sersic': 1,
            'center_x': 0,
            'center_y': 0
        }
        kwargs_lens = {
            'n_sersic': 2,
            'R_sersic': 0.5,
            'k_eff': 1,
            'center_x': 0,
            'center_y': 0
        }
        deltaPix = 0.01
        numPix = 1000
        x_grid, y_grid = util.make_grid(numPix=numPix, deltapix=deltaPix)
        x_grid2d = util.array2image(x_grid)
        y_grid2d = util.array2image(y_grid)

        f_xx, f_yy, _ = sersic_lens.hessian(x_grid, y_grid, **kwargs_lens)
        f_x, f_y = sersic_lens.derivatives(x_grid, y_grid, **kwargs_lens)
        f_x = util.array2image(f_x)
        kappa = util.array2image((f_xx + f_yy) / 2.)
        f_x_num, f_y_num = convergence_integrals.deflection_from_kappa_grid(
            kappa, deltaPix)
        x1, y1 = 500, 550
        x0, y0 = int(numPix / 2.), int(numPix / 2.)
        npt.assert_almost_equal(f_x[x1, y1], f_x_num[x1, y1], decimal=2)
        f_num = convergence_integrals.potential_from_kappa_grid(
            kappa, deltaPix)
        f_ = sersic_lens.function(x_grid2d[x1, y1], y_grid2d[x1, y1],
                                  **kwargs_lens)
        f_00 = sersic_lens.function(x_grid2d[x0, y0], y_grid2d[x0, y0],
                                    **kwargs_lens)
        npt.assert_almost_equal(f_ - f_00,
                                f_num[x1, y1] - f_num[x0, y0],
                                decimal=2)
示例#8
0
def test_make_grid_transform():
    numPix = 11
    theta = np.pi / 2
    deltaPix = 0.05
    Mpix2coord = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) * deltaPix
    ra_coord, dec_coord = util.make_grid_transformed(numPix, Mpix2coord)
    ra2d = util.array2image(ra_coord)
    assert ra2d[5, 5] == 0
    assert ra2d[4, 5] == deltaPix
    npt.assert_almost_equal(ra2d[5, 4], 0, decimal=10)
示例#9
0
    def test_light2mass_conversion(self):
        numPix = 100
        deltaPix = 0.05

        lightModel = LightModel(light_model_list=['SERSIC_ELLIPSE', 'SERSIC'])
        kwargs_lens_light = [{
            'R_sersic': 0.5,
            'n_sersic': 4,
            'amp': 2,
            'e1': 0,
            'e2': 0.05
        }, {
            'R_sersic': 1.5,
            'n_sersic': 1,
            'amp': 2
        }]

        kwargs_interpol = light2mass.light2mass_interpol(
            lens_light_model_list=['SERSIC_ELLIPSE', 'SERSIC'],
            kwargs_lens_light=kwargs_lens_light,
            numPix=numPix,
            deltaPix=deltaPix,
            subgrid_res=1)
        from lenstronomy.LensModel.lens_model import LensModel
        lensModel = LensModel(lens_model_list=['INTERPOL_SCALED'])
        kwargs_lens = [kwargs_interpol]
        import lenstronomy.Util.util as util
        x_grid, y_grid = util.make_grid(numPix, deltapix=deltaPix)
        kappa = lensModel.kappa(x_grid, y_grid, kwargs=kwargs_lens)
        kappa = util.array2image(kappa)
        kappa /= np.mean(kappa)
        flux = lightModel.surface_brightness(x_grid, y_grid, kwargs_lens_light)
        flux = util.array2image(flux)
        flux /= np.mean(flux)
        # import matplotlib.pyplot as plt
        # plt.matshow(flux-kappa)
        # plt.colorbar()
        # plt.show()
        delta_kappa = (kappa - flux) / flux
        max_delta = np.max(np.abs(delta_kappa))
        assert max_delta < 1
        # assert max_diff < 0.01
        npt.assert_almost_equal(flux[0, 0], kappa[0, 0], decimal=2)
示例#10
0
 def error_map_source_plot(self,
                           ax,
                           numPix,
                           deltaPix_source,
                           v_min=None,
                           v_max=None,
                           with_caustics=False):
     x_grid_source, y_grid_source = util.make_grid_transformed(
         numPix, self._Mpix2coord * deltaPix_source / self._deltaPix)
     x_center = self._kwargs_source[0]['center_x']
     y_center = self._kwargs_source[0]['center_y']
     x_grid_source += x_center
     y_grid_source += y_center
     coords_source = Coordinates(self._Mpix2coord * deltaPix_source /
                                 self._deltaPix,
                                 ra_at_xy_0=x_grid_source[0],
                                 dec_at_xy_0=y_grid_source[0])
     error_map_source = self._analysis.error_map_source(
         self._kwargs_source, x_grid_source, y_grid_source, self._cov_param)
     error_map_source = util.array2image(error_map_source)
     d_s = numPix * deltaPix_source
     im = ax.matshow(error_map_source,
                     origin='lower',
                     extent=[0, d_s, 0, d_s],
                     cmap=self._cmap,
                     vmin=v_min,
                     vmax=v_max)  # source
     ax.get_xaxis().set_visible(False)
     ax.get_yaxis().set_visible(False)
     ax.autoscale(False)
     divider = make_axes_locatable(ax)
     cax = divider.append_axes("right", size="5%", pad=0.05)
     cb = plt.colorbar(im, cax=cax)
     cb.set_label(r'error variance', fontsize=15)
     if with_caustics:
         ra_caustic_list, dec_caustic_list = self._caustics()
         plot_line_set(ax,
                       coords_source,
                       ra_caustic_list,
                       dec_caustic_list,
                       color='b')
     scale_bar(ax, d_s, dist=0.1, text='0.1"', color='w', flipped=False)
     coordinate_arrows(ax,
                       d_s,
                       coords_source,
                       arrow_size=self._arrow_size,
                       color='w')
     text_description(ax,
                      d_s,
                      text="Error map in source",
                      color="w",
                      backgroundcolor='k',
                      flipped=False)
     source_position_plot(ax, coords_source, self._kwargs_source)
     return ax
示例#11
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=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',
            'psf_symmetry': 2,
            'psf_iter_factor': 0.2,
            'block_center_neighbour': 0.1,
            'error_map_radius': 0.5,
            'new_procedure': True
        }

        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
示例#12
0
    def setup(self):
        self.supersampling_factor = 3
        lightModel = LightModel(light_model_list=['GAUSSIAN'])
        self.delta_pix = 1.
        x, y = util.make_grid(20, deltapix=self.delta_pix)
        x_sub, y_sub = util.make_grid(20*self.supersampling_factor, deltapix=self.delta_pix/self.supersampling_factor)
        kwargs = [{'amp': 1, 'sigma': 2, 'center_x': 0, 'center_y': 0}]
        flux = lightModel.surface_brightness(x, y, kwargs)
        self.model = util.array2image(flux)
        flux_sub = lightModel.surface_brightness(x_sub, y_sub, kwargs)
        self.model_sub = util.array2image(flux_sub)

        x, y = util.make_grid(5, deltapix=self.delta_pix)
        kwargs_kernel = [{'amp': 1, 'sigma': 1, 'center_x': 0, 'center_y': 0}]
        kernel = lightModel.surface_brightness(x, y, kwargs_kernel)
        self.kernel = util.array2image(kernel) / np.sum(kernel)

        x_sub, y_sub = util.make_grid(5*self.supersampling_factor, deltapix=self.delta_pix/self.supersampling_factor)
        kernel_sub = lightModel.surface_brightness(x_sub, y_sub, kwargs_kernel)
        self.kernel_sub = util.array2image(kernel_sub) / np.sum(kernel_sub)
示例#13
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
示例#14
0
    def test_potential_from_kappa(self):

        sis = SIS()
        deltaPix = 0.005
        x_grid, y_grid = util.make_grid(numPix=2000, deltapix=deltaPix)
        kwargs_sis = {'theta_E': 1., 'center_x': 0, 'center_y': 0}

        f_xx, f_yy, _ = sis.hessian(x_grid, y_grid, **kwargs_sis)
        f_ = sis.function(x_grid, y_grid, **kwargs_sis)
        f_ = util.array2image(f_)
        kappa = util.array2image((f_xx + f_yy) / 2.)
        potential_num = convergence_integrals.potential_from_kappa_grid(
            kappa, deltaPix)

        x1, y1 = 560, 500
        x2, y2 = 550, 500
        # test relative potential at two different point way inside the kappa map
        d_f_num = potential_num[x1, y1] - potential_num[x2, y2]
        d_f = f_[x1, y1] - f_[x2, y2]
        npt.assert_almost_equal(d_f_num, d_f, decimal=2)
示例#15
0
    def array_masked2image(self, array):
        """

        :param array: 1d array of values not masked out (part of linear fitting)
        :return: 2d array of full image
        """
        nx, ny = self.Data.num_pixel_axes
        grid1d = np.zeros(nx * ny)
        grid1d[self._mask1d] = array
        grid2d = util.array2image(grid1d, nx, ny)
        return grid2d
示例#16
0
    def magnification_plot(self, ax, v_min=-10, v_max=10):
        """

        :param ax:
        :return:
        """
        mag_result = util.array2image(
            self._lensModel.magnification(self._x_grid, self._y_grid,
                                          self._kwargs_lens))
        im = ax.matshow(mag_result,
                        origin='lower',
                        extent=[0, self._frame_size, 0, self._frame_size],
                        vmin=v_min,
                        vmax=v_max,
                        cmap=self._cmap,
                        alpha=0.5)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.autoscale(False)
        scale_bar(ax, self._frame_size, dist=1, text='1"', color='k')
        coordinate_arrows(ax,
                          self._frame_size,
                          self._coords,
                          color='k',
                          arrow_size=self._arrow_size)
        text_description(ax,
                         self._frame_size,
                         text="Magnification model",
                         color="k",
                         backgroundcolor='w')
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cb = plt.colorbar(im, cax=cax)
        cb.set_label(r'det(A$^{-1}$)', fontsize=15)

        plot_line_set(ax,
                      self._coords,
                      self._ra_caustic_list,
                      self._dec_caustic_list,
                      color='b')
        plot_line_set(ax,
                      self._coords,
                      self._ra_crit_list,
                      self._dec_crit_list,
                      color='r')
        ra_image, dec_image = self._imageModel.image_positions(
            self._kwargs_else, self._kwargs_lens)
        image_position_plot(ax,
                            self._coords,
                            ra_image[0],
                            dec_image[0],
                            color='k')
        source_position_plot(ax, self._coords, self._kwargs_source)
        return ax
示例#17
0
    def test_update_iterative(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_new = self.psf_fitting.update_iterative(
            kwargs_psf,
            self.kwargs_lens,
            self.kwargs_source,
            self.kwargs_lens_light,
            self.kwargs_ps,
            factor=0.2,
            num_iter=3,
            symmetry=1)
        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,
            factor=0.2,
            num_iter=3,
            symmetry=1,
            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
示例#18
0
    def potential_from_kappa(self, kappa, x_grid, y_grid, deltaPix):
        """

        :param kappa: 1d grid of convergence values
        :param x_grid: x-coordinate grid
        :param y_grid: y-coordinate grid
        :return: lensing potential in a 2d grid at positions x_grid, y_grid
        """
        kernel = self._potential_kernel(x_grid, y_grid)
        f_ = scp.fftconvolve(kernel, util.array2image(kappa),
                             mode='same') / np.pi * deltaPix**2
        return f_
示例#19
0
def test_averaging_even_kernel():

    subgrid_res = 4

    x_grid, y_gird = Util.make_grid(19, 1., 1)
    sigma = 1.5
    flux = gaussian.function(x_grid, y_gird, amp=1, sigma=sigma)
    kernel_super = Util.array2image(flux)

    kernel_pixel = kernel_util.averaging_even_kernel(kernel_super, subgrid_res)
    npt.assert_almost_equal(np.sum(kernel_pixel), 1, decimal=5)
    assert len(kernel_pixel) == 5

    x_grid, y_gird = Util.make_grid(17, 1., 1)
    sigma = 1.5
    flux = gaussian.function(x_grid, y_gird, amp=1, sigma=sigma)
    kernel_super = Util.array2image(flux)

    kernel_pixel = kernel_util.averaging_even_kernel(kernel_super, subgrid_res)
    npt.assert_almost_equal(np.sum(kernel_pixel), 1, decimal=5)
    assert len(kernel_pixel) == 5
示例#20
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))
示例#21
0
def test_degrade_kernel():

    x_grid, y_gird = Util.make_grid(19 * 5, 1., 1)
    sigma = 1.5
    amp = 2
    flux = gaussian.function(x_grid, y_gird, amp=2, sigma=sigma)
    kernel_super = Util.array2image(flux) / np.sum(flux) * amp

    for degrading_factor in range(7):
        kernel_degraded = kernel_util.degrade_kernel(
            kernel_super, degrading_factor=degrading_factor + 1)
        npt.assert_almost_equal(np.sum(kernel_degraded), amp, decimal=8)
 def test_coordinate_grid(self):
     deltaPix = 0.05
     Mpix2a = np.array([[1, 0], [0, 1]]) * deltaPix
     ra_0 = 1.
     dec_0 = 1.
     coords = Coordinates(transform_pix2angle=Mpix2a,
                          ra_at_xy_0=ra_0,
                          dec_at_xy_0=dec_0)
     ra_grid, dec_grid = coords.coordinate_grid(numPix=10)
     ra_grid_2d = util.array2image(ra_grid)
     dec_grid_2d = util.array2image(dec_grid)
     assert ra_grid[0] == ra_0
     assert dec_grid[0] == dec_0
     x_pos, y_pos = 1, 2
     ra, dec = coords.map_pix2coord(x_pos, y_pos)
     npt.assert_almost_equal(ra_grid_2d[int(y_pos), int(x_pos)],
                             ra,
                             decimal=8)
     npt.assert_almost_equal(dec_grid_2d[int(y_pos), int(x_pos)],
                             dec,
                             decimal=8)
示例#23
0
def center_kernel(kernel, iterations=20):
    """
    given a kernel that might not be perfectly centered, this routine computes its light weighted center and then
    moves the center in an iterative process such that it is centered

    :param kernel: 2d array (odd numbers)
    :param iterations: int, number of iterations
    :return: centered kernel
    """
    kernel = kernel_norm(kernel)
    nx, ny = np.shape(kernel)
    if nx %2 == 0:
        raise ValueError("kernel needs odd number of pixels")
    # make coordinate grid of kernel
    x_grid, y_grid = util.make_grid(nx, deltapix=1, left_lower=False)
    # compute 1st moments to get light weighted center
    x_w = np.sum(kernel * util.array2image(x_grid))
    y_w = np.sum(kernel * util.array2image(y_grid))
    # de-shift kernel
    kernel_centered = de_shift_kernel(kernel, shift_x=-x_w, shift_y=-y_w, iterations=iterations)
    return kernel_norm(kernel_centered)
示例#24
0
    def _array2image(self, array):
        """
        maps a 1d array into a (nx, ny) 2d grid with array populating the idex_mask indices

        :param array: 1d array
        :return:
        """
        nx, ny = self._nx * self._supersampling_factor, self._ny * self._supersampling_factor
        grid1d = np.zeros((nx * ny))
        grid1d[self._compute_indexes] = array
        grid2d = util.array2image(grid1d, nx, ny)
        return grid2d
示例#25
0
def lens_model_plot(ax, lensModel, kwargs_lens, numPix=500, deltaPix=0.01, sourcePos_x=0, sourcePos_y=0, point_source=False, with_caustics=False):
    """
    plots a lens model (convergence) and the critical curves and caustics

    :param ax:
    :param kwargs_lens:
    :param numPix:
    :param deltaPix:
    :return:
    """
    from lenstronomy.SimulationAPI.simulations import Simulation
    simAPI = Simulation()
    kwargs_data = simAPI.data_configure(numPix, deltaPix)
    data = Data(kwargs_data)
    _frame_size = numPix * deltaPix
    _coords = data._coords
    x_grid, y_grid = data.coordinates
    lensModelExt = LensModelExtensions(lensModel)

    #ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExt.critical_curve_caustics(
    #    kwargs_lens, compute_window=_frame_size, grid_scale=deltaPix/2.)
    x_grid1d = util.image2array(x_grid)
    y_grid1d = util.image2array(y_grid)
    kappa_result = lensModel.kappa(x_grid1d, y_grid1d, kwargs_lens)
    kappa_result = util.array2image(kappa_result)
    im = ax.matshow(np.log10(kappa_result), origin='lower',
                    extent=[0, _frame_size, 0, _frame_size], cmap='Greys', vmin=-1, vmax=1) #, cmap=self._cmap, vmin=v_min, vmax=v_max)
    if with_caustics is True:
        ra_crit_list, dec_crit_list = lensModelExt.critical_curve_tiling(kwargs_lens, compute_window=_frame_size,
                                                                         start_scale=deltaPix, max_order=10)
        ra_caustic_list, dec_caustic_list = lensModel.ray_shooting(ra_crit_list, dec_crit_list, kwargs_lens)
        plot_line_set(ax, _coords, ra_caustic_list, dec_caustic_list, color='g')
        plot_line_set(ax, _coords, ra_crit_list, dec_crit_list, color='r')
    if point_source:
        from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver
        solver = LensEquationSolver(lensModel)
        theta_x, theta_y = solver.image_position_from_source(sourcePos_x, sourcePos_y, kwargs_lens)
        mag_images = lensModel.magnification(theta_x, theta_y, kwargs_lens)
        x_image, y_image = _coords.map_coord2pix(theta_x, theta_y)
        abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']
        for i in range(len(x_image)):
            x_ = (x_image[i] + 0.5) * deltaPix
            y_ = (y_image[i] + 0.5) * deltaPix
            ax.plot(x_, y_, 'dk', markersize=4*(1 + np.log(np.abs(mag_images[i]))), alpha=0.5)
            ax.text(x_, y_, abc_list[i], fontsize=20, color='k')
        x_source, y_source = _coords.map_coord2pix(sourcePos_x, sourcePos_y)
        ax.plot((x_source + 0.5) * deltaPix, (y_source + 0.5) * deltaPix, '*k', markersize=10)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.autoscale(False)
    #image_position_plot(ax, _coords, self._kwargs_else)
    #source_position_plot(ax, self._coords, self._kwargs_source)
    return ax
示例#26
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)
示例#27
0
    def _subgrid_index(self, idex_mask, subgrid_res, nx, ny):
        """

        :param idex_mask: 1d array of mask of data
        :param subgrid_res: subgrid resolution
        :return: 1d array of equivalent mask in subgrid resolution
        """
        idex_sub = np.repeat(idex_mask, subgrid_res, axis=0)
        idex_sub = util.array2image(idex_sub, nx=nx, ny=ny * subgrid_res)
        idex_sub = np.repeat(idex_sub, subgrid_res, axis=0)
        idex_sub = util.image2array(idex_sub)
        return idex_sub
示例#28
0
    def deflection_plot(self, ax, v_min=None, v_max=None, axis=0,
                        with_caustics=False, image_name_list=None,
                        text="Deflection model", font_size=15,
                        colorbar_label=r'arcsec'):
        """

        :param kwargs_lens:
        :param kwargs_else:
        :return:
        """

        alpha1, alpha2 = self._lensModel.alpha(self._x_grid, self._y_grid, self._kwargs_lens_partial)
        alpha1 = util.array2image(alpha1)
        alpha2 = util.array2image(alpha2)
        if axis == 0:
            alpha = alpha1
        else:
            alpha = alpha2
        im = ax.matshow(alpha, origin='lower', extent=[0, self._frame_size, 0, self._frame_size],
                        vmin=v_min, vmax=v_max, cmap=self._cmap, alpha=0.5)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax.autoscale(False)
        plot_util.scale_bar(ax, self._frame_size, dist=1, text='1"', color='k', font_size=font_size)
        plot_util.coordinate_arrows(ax, self._frame_size, self._coords, color='k',
                          arrow_size=self._arrow_size, font_size=font_size)
        plot_util.text_description(ax, self._frame_size, text=text, color="k",
                         backgroundcolor='w', font_size=font_size)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cb = plt.colorbar(im, cax=cax)
        cb.set_label(colorbar_label, fontsize=font_size)
        if with_caustics is True:
            ra_crit_list, dec_crit_list = self._critical_curves()
            ra_caustic_list, dec_caustic_list = self._caustics()
            plot_util.plot_line_set(ax, self._coords, ra_caustic_list, dec_caustic_list, color='b')
            plot_util.plot_line_set(ax, self._coords, ra_crit_list, dec_crit_list, color='r')
        ra_image, dec_image = self.bandmodel.PointSource.image_position(self._kwargs_ps_partial, self._kwargs_lens_partial)
        plot_util.image_position_plot(ax, self._coords, ra_image, dec_image, image_name_list=image_name_list)
        return ax
示例#29
0
    def test_kwargs_interpolation(self):
        numPix = 101
        deltaPix = 0.1
        x_grid_interp, y_grid_interp = util.make_grid(numPix, deltaPix)
        sis = SIS()
        kwargs_SIS = {'theta_E': 1., 'center_x': 0.5, 'center_y': -0.5}
        f_sis = sis.function(x_grid_interp, y_grid_interp, **kwargs_SIS)
        f_x_sis, f_y_sis = sis.derivatives(x_grid_interp, y_grid_interp,
                                           **kwargs_SIS)
        f_xx_sis, f_yy_sis, f_xy_sis = sis.hessian(x_grid_interp,
                                                   y_grid_interp, **kwargs_SIS)
        x_axes, y_axes = util.get_axes(x_grid_interp, y_grid_interp)
        interp_func = Interpol_func()
        kwargs_interp = {
            'grid_interp_x': x_axes,
            'grid_interp_y': y_axes,
            'f_': util.array2image(f_sis),
            'f_x': util.array2image(f_x_sis),
            'f_y': util.array2image(f_y_sis),
            'f_xx': util.array2image(f_xx_sis),
            'f_yy': util.array2image(f_yy_sis),
            'f_xy': util.array2image(f_xy_sis)
        }
        x, y = 1., 1.
        alpha_x, alpha_y = interp_func.derivatives(x, y, **kwargs_interp)
        assert alpha_x == 0.31622776601683794

        f_ = interp_func.function(x, y, **kwargs_interp)
        npt.assert_almost_equal(f_, 1.5811388300841898)
示例#30
0
    def pixel_kernel(self, num_pix):
        """
        computes a pixelized kernel from the MGE parameters

        :param num_pix: int, size of kernel (odd number per axis)
        :return: pixel kernel centered
        """
        from lenstronomy.LightModel.Profiles.gaussian import MultiGaussian
        mg = MultiGaussian()
        x, y = util.make_grid(numPix=num_pix, deltapix=self._pixel_scale)
        kernel = mg.function(x, y, amp=self._fraction_list, sigma=self._sigmas_scaled)
        kernel = util.array2image(kernel)
        return kernel / np.sum(kernel)