Ejemplo n.º 1
0
 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))
Ejemplo n.º 2
0
    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
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
 def test_raise(self):
     with self.assertRaises(ValueError):
         num_pix = 10
         data = ImageData(np.zeros((num_pix, num_pix)))
         lens_model = LensModel(['SPEP'])
         image_grid_class = NumericsSubFrame(data, PSF('NONE')).grid_class
         source_grid_class = NumericsSubFrame(data, PSF('NONE')).grid_class
         lensing_op = LensingOperator(lens_model,
                                      image_grid_class,
                                      source_grid_class,
                                      num_pix,
                                      source_interpolation='sth')
Ejemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     super(TestRaise, self).__init__(*args, **kwargs)
     self.num_pix = 10
     _, _, ra_at_xy_0, dec_at_xy_0, _, _, Mpix2coord, _ \
         = l_util.make_grid_with_coordtransform(numPix=self.num_pix, deltapix=0.5, subgrid_res=1,
                                                inverse=False, left_lower=False)
     kwargs_data_nonsquare = {
         '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 + 10)),  # non-square image
     }
     kwargs_data = {
         '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)),  # non-square image
     }
     self.data_nonsquare = ImageData(**kwargs_data_nonsquare)
     self.data = ImageData(**kwargs_data)
     psf = PSF('NONE')
     self.numerics = NumericsSubFrame(self.data, psf)
     lens_model = LensModel(['SPEP'])
     self.source_model_class = LightModel(['SLIT_STARLETS'])
     self.lens_light_model_class = LightModel(['SLIT_STARLETS'])
     # get grid classes
     image_grid_class = self.numerics.grid_class
     source_numerics = NumericsSubFrame(self.data,
                                        psf,
                                        supersampling_factor=1)
     source_grid_class = source_numerics.grid_class
     self.lensing_op = LensingOperator(lens_model, image_grid_class,
                                       source_grid_class, self.num_pix)
     self.model_op = ModelOperators(self.data, self.lensing_op,
                                    self.numerics)
     self.model_op.add_lens_light(self.lens_light_model_class)
     self.model_op_nolens = ModelOperators(self.data, self.lensing_op,
                                           self.numerics)
Ejemplo n.º 7
0
    def setup(self):
        self.num_pix = 25  # cutout pixel size
        self.subgrid_res_source = 2
        delta_pix = 0.32
        _, _, 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 = {
            '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))
        }

        data_class = ImageData(**kwargs_data)
        numerics_image = NumericsSubFrame(data_class, PSF('NONE'))
        numerics_source = NumericsSubFrame(
            data_class,
            PSF('NONE'),
            supersampling_factor=self.subgrid_res_source)
        self.source_plane = SizeablePlaneGrid(numerics_source.grid_class,
                                              verbose=True)

        # create a mask mimicking the real case of lensing operation
        lens_model_class = LensModel(['SIE'])
        kwargs_lens = [{
            'theta_E': 1.5,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }]
        lensing_op = LensingOperator(lens_model_class,
                                     numerics_image.grid_class,
                                     numerics_source.grid_class, self.num_pix,
                                     self.subgrid_res_source)
        lensing_op.update_mapping(kwargs_lens)
        unit_image = np.ones((self.num_pix, self.num_pix))
        mask_image = np.zeros((self.num_pix, self.num_pix))
        mask_image[2:-2, 2:-2] = 1  # some binary image that mask out borders
        self.unit_image_mapped = lensing_op.image2source_2d(unit_image,
                                                            no_flux_norm=False)
        self.mask_mapped = lensing_op.image2source_2d(mask_image)
Ejemplo n.º 8
0
    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)
Ejemplo n.º 9
0
    def setup(self):
        self.num_pix = 49  # cutout pixel size
        self.subgrid_res_source = 2
        self.num_pix_source = self.num_pix * self.subgrid_res_source

        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)

        self.image_data = np.random.rand(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': self.image_data,
        }
        data = ImageData(**kwargs_data)

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

        # PSF
        kernel_pixel = np.zeros((self.num_pix, self.num_pix))
        kernel_pixel[int(self.num_pix / 2),
                     int(self.num_pix / 2)] = 1  # just a dirac here
        kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_pixel}
        psf = PSF(**kwargs_psf)

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

        # list of source light profiles
        source_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_source = [{'n_scales': self.n_scales_source}]

        # list of lens light profiles
        lens_light_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}]

        # define some mask
        likelihood_mask = np.ones((self.num_pix, self.num_pix))

        # get grid classes
        self.numerics = NumericsSubFrame(data, psf)
        image_grid_class = self.numerics.grid_class
        source_numerics = NumericsSubFrame(
            data, psf, supersampling_factor=self.subgrid_res_source)
        source_grid_class = source_numerics.grid_class

        # get a lensing operator
        self.lensing_op = LensingOperator(lens_model, image_grid_class,
                                          source_grid_class, self.num_pix)
        self.lensing_op.update_mapping(kwargs_lens)

        self.model_op = ModelOperators(data, self.lensing_op, self.numerics)
        self.model_op._set_likelihood_mask(likelihood_mask)
        self.model_op.add_source_light(source_model)
        self.model_op.add_lens_light(lens_light_model)
        self.model_op_nolens = ModelOperators(data, self.lensing_op,
                                              self.numerics)
        self.model_op_nolens._set_likelihood_mask(likelihood_mask)
        self.model_op_nolens.add_source_light(source_model)

        # define some test images in direct space
        self.X_s = np.random.rand(self.num_pix_source,
                                  self.num_pix_source)  # source light
        self.X_l = np.random.rand(self.num_pix, self.num_pix)  # lens light

        # define some test images in wavelets space
        self.alpha_s = np.random.rand(self.n_scales_source,
                                      self.num_pix_source,
                                      self.num_pix_source)  # source light
        self.alpha_l = np.random.rand(self.n_scales_lens, self.num_pix,
                                      self.num_pix)  # lens light
Ejemplo n.º 10
0
class TestModelOperators(object):
    """
    tests the Lensing Operator classes
    """
    def setup(self):
        self.num_pix = 49  # cutout pixel size
        self.subgrid_res_source = 2
        self.num_pix_source = self.num_pix * self.subgrid_res_source

        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)

        self.image_data = np.random.rand(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': self.image_data,
        }
        data = ImageData(**kwargs_data)

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

        # PSF
        kernel_pixel = np.zeros((self.num_pix, self.num_pix))
        kernel_pixel[int(self.num_pix / 2),
                     int(self.num_pix / 2)] = 1  # just a dirac here
        kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_pixel}
        psf = PSF(**kwargs_psf)

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

        # list of source light profiles
        source_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_source = [{'n_scales': self.n_scales_source}]

        # list of lens light profiles
        lens_light_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}]

        # define some mask
        likelihood_mask = np.ones((self.num_pix, self.num_pix))

        # get grid classes
        self.numerics = NumericsSubFrame(data, psf)
        image_grid_class = self.numerics.grid_class
        source_numerics = NumericsSubFrame(
            data, psf, supersampling_factor=self.subgrid_res_source)
        source_grid_class = source_numerics.grid_class

        # get a lensing operator
        self.lensing_op = LensingOperator(lens_model, image_grid_class,
                                          source_grid_class, self.num_pix)
        self.lensing_op.update_mapping(kwargs_lens)

        self.model_op = ModelOperators(data, self.lensing_op, self.numerics)
        self.model_op._set_likelihood_mask(likelihood_mask)
        self.model_op.add_source_light(source_model)
        self.model_op.add_lens_light(lens_light_model)
        self.model_op_nolens = ModelOperators(data, self.lensing_op,
                                              self.numerics)
        self.model_op_nolens._set_likelihood_mask(likelihood_mask)
        self.model_op_nolens.add_source_light(source_model)

        # define some test images in direct space
        self.X_s = np.random.rand(self.num_pix_source,
                                  self.num_pix_source)  # source light
        self.X_l = np.random.rand(self.num_pix, self.num_pix)  # lens light

        # define some test images in wavelets space
        self.alpha_s = np.random.rand(self.n_scales_source,
                                      self.num_pix_source,
                                      self.num_pix_source)  # source light
        self.alpha_l = np.random.rand(self.n_scales_lens, self.num_pix,
                                      self.num_pix)  # lens light

    def test_set_wavelet_scales(self):
        self.model_op.set_source_wavelet_scales(self.n_scales_source)
        Phi_T_s_X = self.model_op.Phi_T_s(self.X_s)
        self.model_op.set_lens_wavelet_scales(self.n_scales_lens)
        Phi_T_l_X = self.model_op.Phi_T_l(self.X_l)
        # test that transformed image has the right shape in terms of number of scales
        assert Phi_T_s_X.shape[0] == self.n_scales_source
        assert Phi_T_l_X.shape[0] == self.n_scales_lens

    def test_subtract_from_data_and_reset(self):
        image_to_subtract = np.eye(self.num_pix, self.num_pix)
        self.model_op.subtract_from_data(image_to_subtract)
        npt.assert_equal(self.model_op.Y, self.image_data)
        npt.assert_equal(self.model_op.Y_eff,
                         self.image_data - image_to_subtract)
        self.model_op.reset_data()
        npt.assert_equal(self.model_op.Y, self.image_data)
        npt.assert_equal(self.model_op.Y_eff, self.image_data)

    def test_spectral_norm_source(self):
        self.model_op.set_source_wavelet_scales(self.n_scales_source)
        npt.assert_almost_equal(self.model_op.spectral_norm_source,
                                0.97,
                                decimal=2)

    def test_spectral_norm_lens(self):
        self.model_op.set_lens_wavelet_scales(self.n_scales_lens)
        npt.assert_almost_equal(self.model_op.spectral_norm_lens,
                                0.99,
                                decimal=2)

    def test_data_terms(self):
        npt.assert_equal(self.model_op.Y, self.image_data)
        npt.assert_equal(self.model_op.Y_eff, self.image_data)

    def test_convolution(self):
        H_X_s = self.model_op.H(self.X_s)
        npt.assert_equal(
            H_X_s, self.numerics.convolution_class.convolution2d(self.X_s))
        H_T_X_s = self.model_op.H_T(self.X_s)
        conv_transpose = self.numerics.convolution_class.copy_transpose()
        npt.assert_equal(H_T_X_s, conv_transpose.convolution2d(self.X_s))

    def test_lensing(self):
        F_X_s = self.model_op.F(self.X_s)
        npt.assert_equal(F_X_s, self.lensing_op.source2image_2d(self.X_s))
        F_T_X_l = self.model_op.F_T(self.X_l)
        npt.assert_equal(F_T_X_l, self.lensing_op.image2source_2d(self.X_l))

    def test_wavelet_transform(self):
        # TODO : do more accurate tests here
        self.model_op.set_source_wavelet_scales(self.n_scales_source)
        self.model_op.set_lens_wavelet_scales(self.n_scales_lens)
        Phi_alpha_s = self.model_op.Phi_s(self.alpha_s)
        Phi_alpha_l = self.model_op.Phi_l(self.alpha_l)
        assert Phi_alpha_s.shape == (self.num_pix * self.subgrid_res_source,
                                     self.num_pix * self.subgrid_res_source)
        assert Phi_alpha_l.shape == (self.num_pix, self.num_pix)
        Phi_T_X_s = self.model_op.Phi_T_s(self.X_s)
        Phi_T_X_l = self.model_op.Phi_T_l(self.X_l)
        assert Phi_T_X_s.shape == (self.n_scales_source,
                                   self.num_pix * self.subgrid_res_source,
                                   self.num_pix * self.subgrid_res_source)
        assert Phi_T_X_l.shape == (self.n_scales_lens, self.num_pix,
                                   self.num_pix)
Ejemplo n.º 11
0
    def __init__(self,
                 data_class,
                 lens_model_class,
                 image_numerics_class,
                 source_numerics_class,
                 lens_light_mask=None,
                 source_interpolation='bilinear',
                 minimal_source_plane=False,
                 use_mask_for_minimal_source_plane=True,
                 min_num_pix_source=20,
                 min_threshold=3,
                 threshold_increment_high_freq=1,
                 threshold_decrease_type='exponential',
                 fixed_spectral_norm_source=0.98,
                 include_regridding_error=False,
                 sparsity_prior_norm=1,
                 force_positivity=True,
                 formulation='analysis',
                 external_likelihood_penalty=False,
                 random_seed=None,
                 verbose=False,
                 show_steps=False,
                 thread_count=1):
        """
        :param data_class: lenstronomy.imaging_data.ImageData instance describing the data.
        :param lens_model_class: lenstronomy.lens_model.LensModel instance describing the lens mass model.
        :param image_numerics_class: lenstronomy.ImSim.Numerics.numerics_subframe.NumericsSubFrame instance for image plane.
        :param source_numerics_class: lenstronomy.ImSim.Numerics.numerics_subframe.NumericsSubFrame instance for source plane.
        :param lens_light_mask: boolean mask with False/0 to exclude pixels that are assumed to contain only lens light flux.
        Defaults to None.
        :param source_interpolation: type of interpolation of source pixels on the source plane grid.
        It can be 'nearest' for nearest-neighbor or 'bilinear' for bilinear interpolation. Defaults to 'bilinear'.
        :param minimal_source_plane: if True, reduce the source plane grid size to the minimum set by min_num_pix_source.
         Defaults to False.
        :param use_mask_for_minimal_source_plane: if True, use the likelihood_mask to compute minimal source plane.
         Defaults to True.
        :param min_num_pix_source: minimal number of pixels on a side of the square source grid.
        Only used when minimal_source_plane is True. Defaults to 20.
        :param min_threshold: in unit of the noise (sigma), minimum threshold for wavelets denoising.
        Typically between 3 (more conservative thresholding) and 5 (more aggressive thresholding). Defaults to 3.
        :param threshold_increment_high_freq: additive number to the threshold level (in unit of the noise) for the highest frequencies on wavelets space.
        Defaults to 1.
        :param threshold_decrease_type: strategy for decreasing the threshold level at each iteration. Can be 'none' (no decrease, directly sets to min_threshold), 'linear' or 'exponential'.
        Defaults to None, which is 'exponential' for the source-only solver, 'linear' for the source-lens solver.
        :param fixed_spectral_norm_source: if None, update the spectral norm for the source operator, for optimal gradient descent step size.
        Defaults to 0.98, which is a conservative value typical of most lens models.
        :param sparsity_prior_norm: prior l-norm (0 or 1). If 1, l1-norm and soft-thresholding are applied.
        If 0, it is l0-norm and hard-thresholding. Defaults to 1.
        :param force_positivity: if True, apply positivity constraint to the source flux.
        Defaults to True.
        :param formulation: type of formalism for the minimization problem. 'analysis' solves the problem in direct space.
        'synthesis' solves the peoblem in wavelets space. Defaults to 'analysis'.
        :param external_likelihood_penalty: if True, the solve() method returns a non-zero penalty, 
        e.g. for penalize more a given lens model during lens model optimization. Defaults to False.
        :param random_seed: seed for random number generator, used to initialise the algorithm. None for no seed.
        Defaults to None.
        :param verbose: if True, prints statements during optimization.
        Defaults to False.
        :param show_steps: if True, displays plot of the reconstructed light profiles during optimization.
        Defaults to False.
        :param thread_count: number of threads (multithreading) to speedup wavelets computations (only works if pySAP is properly installed).
        Defaults to 1.
        """
        num_pix_x, num_pix_y = data_class.num_pixel_axes
        if num_pix_x != num_pix_y:
            raise ValueError("Only square images are supported")
        image_grid_class = image_numerics_class.grid_class
        source_grid_class = source_numerics_class.grid_class
        lensing_operator_class = LensingOperator(
            lens_model_class,
            image_grid_class,
            source_grid_class,
            num_pix_x,
            lens_light_mask=lens_light_mask,
            minimal_source_plane=minimal_source_plane,
            min_num_pix_source=min_num_pix_source,
            use_mask_for_minimal_source_plane=use_mask_for_minimal_source_plane,
            source_interpolation=source_interpolation,
            verbose=verbose)

        super(SparseSolverBase, self).__init__(
            data_class,
            lensing_operator_class,
            image_numerics_class,
            fixed_spectral_norm_source=fixed_spectral_norm_source,
            thread_count=thread_count,
            random_seed=random_seed)

        # engine that computes noise levels in image / source plane, in wavelets space
        self.noise = NoiseLevels(
            data_class,
            subgrid_res_source=source_grid_class.supersampling_factor,
            include_regridding_error=include_regridding_error)

        # threshold level k_min (in units of the noise)
        self._k_min = min_threshold
        if threshold_increment_high_freq < 0:
            raise ValueError(
                "threshold_increment_high_freq cannot be negative")
        else:
            self._increm_high_freq = threshold_increment_high_freq

        # strategy to decrease threshold up to the max threshold above
        if threshold_decrease_type not in [
                'none', 'lin', 'linear', 'exp', 'exponential'
        ]:
            raise ValueError(
                "threshold_decrease_type must be in ['none', 'lin', 'linear', 'exp', 'exponential']"
            )
        self._threshold_decrease_type = threshold_decrease_type

        if sparsity_prior_norm not in [0, 1]:
            raise ValueError(
                "Sparsity prior norm can only be 0 or 1 (l0-norm or l1-norm)")
        self._sparsity_prior_norm = sparsity_prior_norm
        self._formulation = formulation
        self._force_positivity = force_positivity

        self._external_likelihood_penalty = external_likelihood_penalty

        self._verbose = verbose
        self._show_steps = show_steps

        self._tracker = SolverTracker(self, verbose=verbose)
        self._plotter = SolverPlotter(self, show_now=True)
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
    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))
Ejemplo n.º 14
0
    def setup(self):
        self.num_pix = 49  # cutout pixel size
        self.subgrid_res_source = 2
        self.num_pix_source = self.num_pix * self.subgrid_res_source
        self.background_rms = 0.05
        self.noise_map = self.background_rms * np.ones(
            (self.num_pix, self.num_pix))

        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)

        self.image_data = np.random.rand(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': self.image_data,
            'background_rms': self.background_rms,
            'noise_map': self.noise_map,
        }
        data = ImageData(**kwargs_data)

        gaussian_func = Gaussian()
        x, y = l_util.make_grid(41, 1)
        gaussian = gaussian_func.function(x,
                                          y,
                                          amp=1,
                                          sigma=0.02,
                                          center_x=0,
                                          center_y=0)
        self.psf_kernel = gaussian / gaussian.sum()

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

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

        # list of source light profiles
        self.source_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_source = [{'n_scales': self.n_scales_source}]

        # list of lens light profiles
        self.lens_light_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}]

        # get grid classes
        image_grid_class = NumericsSubFrame(data, PSF('NONE')).grid_class
        source_grid_class = NumericsSubFrame(
            data, PSF('NONE'),
            supersampling_factor=self.subgrid_res_source).grid_class

        # get a lensing operator
        self.lensing_op = LensingOperator(lens_model, image_grid_class,
                                          source_grid_class, self.num_pix)

        self.noise_class = NoiseLevels(
            data,
            subgrid_res_source=self.subgrid_res_source,
            include_regridding_error=False)
        self.noise_class_regrid = NoiseLevels(
            data,
            subgrid_res_source=self.subgrid_res_source,
            include_regridding_error=True)
Ejemplo n.º 15
0
class TestNoiseLevels(object):
    """
    tests the Lensing Operator classes
    """
    def setup(self):
        self.num_pix = 49  # cutout pixel size
        self.subgrid_res_source = 2
        self.num_pix_source = self.num_pix * self.subgrid_res_source
        self.background_rms = 0.05
        self.noise_map = self.background_rms * np.ones(
            (self.num_pix, self.num_pix))

        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)

        self.image_data = np.random.rand(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': self.image_data,
            'background_rms': self.background_rms,
            'noise_map': self.noise_map,
        }
        data = ImageData(**kwargs_data)

        gaussian_func = Gaussian()
        x, y = l_util.make_grid(41, 1)
        gaussian = gaussian_func.function(x,
                                          y,
                                          amp=1,
                                          sigma=0.02,
                                          center_x=0,
                                          center_y=0)
        self.psf_kernel = gaussian / gaussian.sum()

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

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

        # list of source light profiles
        self.source_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_source = [{'n_scales': self.n_scales_source}]

        # list of lens light profiles
        self.lens_light_model = LightModel(['SLIT_STARLETS'])
        self.kwargs_lens_light = [{'n_scales': self.n_scales_lens}]

        # get grid classes
        image_grid_class = NumericsSubFrame(data, PSF('NONE')).grid_class
        source_grid_class = NumericsSubFrame(
            data, PSF('NONE'),
            supersampling_factor=self.subgrid_res_source).grid_class

        # get a lensing operator
        self.lensing_op = LensingOperator(lens_model, image_grid_class,
                                          source_grid_class, self.num_pix)

        self.noise_class = NoiseLevels(
            data,
            subgrid_res_source=self.subgrid_res_source,
            include_regridding_error=False)
        self.noise_class_regrid = NoiseLevels(
            data,
            subgrid_res_source=self.subgrid_res_source,
            include_regridding_error=True)

    def test_background_rms(self):
        assert self.background_rms == self.noise_class.background_rms

    def test_noise_map(self):
        npt.assert_equal(self.noise_map, self.noise_class.noise_map)
        npt.assert_equal(self.noise_map, self.noise_class_regrid.noise_map)
        npt.assert_equal(self.noise_map, self.noise_class.effective_noise_map)

    def test_update_source_levels(self):
        wavelet_transform_source = lambda x: self.source_model.func_list[
            0].decomposition_2d(x, self.kwargs_source[0]['n_scales'])
        image2source_transform = lambda x: self.lensing_op.image2source_2d(
            x, kwargs_lens=self.kwargs_lens)
        upscale_transform = lambda x: x
        self.noise_class.update_source_levels(
            self.num_pix,
            self.num_pix_source,
            wavelet_transform_source,
            image2source_transform,
            upscale_transform,
            psf_kernel=None)  # without psf_kernel specified
        assert self.noise_class.levels_source.shape == (self.n_scales_source,
                                                        self.num_pix_source,
                                                        self.num_pix_source)
        self.noise_class.update_source_levels(self.num_pix,
                                              self.num_pix_source,
                                              wavelet_transform_source,
                                              image2source_transform,
                                              upscale_transform,
                                              psf_kernel=self.psf_kernel)
        assert self.noise_class.levels_source.shape == (self.n_scales_source,
                                                        self.num_pix_source,
                                                        self.num_pix_source)

    def test_update_image_levels(self):
        wavelet_transform_image = lambda x: self.lens_light_model.func_list[
            0].decomposition_2d(x, self.kwargs_lens_light[0]['n_scales'])
        self.noise_class.update_image_levels(self.num_pix,
                                             wavelet_transform_image)
        assert self.noise_class.levels_image.shape == (self.n_scales_lens,
                                                       self.num_pix,
                                                       self.num_pix)

    def test_update_regridding_error(self):
        magnification_map = self.lensing_op.magnification_map(self.kwargs_lens)
        self.noise_class.update_regridding_error(
            magnification_map)  # should do nothing
        npt.assert_equal(self.noise_class.effective_noise_map, self.noise_map)
        self.noise_class_regrid.update_regridding_error(magnification_map)
        npt.assert_equal(
            self.noise_class_regrid.effective_noise_map,
            np.sqrt(self.noise_map**2 +
                    self.noise_class_regrid.regridding_error_map**2))