Esempio n. 1
0
    def test_derivatives(self):
        """

        :return:
        """
        doublechameleon = DoubleChameleon()
        chameleon = Chameleon()

        x = np.linspace(0.1, 10, 10)
        phi_G, q = 0.3, 0.8
        theta_E = 1.
        ratio = 2.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_light = {'theta_E': 1., 'ratio': 2, 'w_c1': .5, 'w_t1': 1., 'e11': e1, 'e21': e2, 'w_c2': .1, 'w_t2': .5, 'e12': e1, 'e22': e2}

        kwargs_1 = {'theta_E': theta_E / (1 + 1. / ratio), 'w_c': .5, 'w_t': 1., 'e1': e1, 'e2': e2}
        kwargs_2 = {'theta_E': theta_E / (1 + ratio), 'w_c': .1, 'w_t': .5, 'e1': e1, 'e2': e2}
        f_x, f_y = doublechameleon.derivatives(x=x, y=1., **kwargs_light)
        f_x1, f_y1 = chameleon.derivatives(x=x, y=1., **kwargs_1)
        f_x2, f_y2 = chameleon.derivatives(x=x, y=1., **kwargs_2)
        npt.assert_almost_equal(f_x, f_x1 + f_x2, decimal=8)
        npt.assert_almost_equal(f_y, f_y1 + f_y2, decimal=8)
 def test_critical_curves_tiling(self):
     lens_model_list = ['SPEP']
     phi, q = 1., 0.8
     e1, e2 = param_util.phi_q2_ellipticity(phi, q)
     kwargs_lens = [{
         'theta_E': 1.,
         'gamma': 2.,
         'e1': e1,
         'e2': e2,
         'center_x': 0,
         'center_y': 0
     }]
     lensModel = LensModelExtensions(LensModel(lens_model_list))
     ra_crit, dec_crit = lensModel.critical_curve_tiling(kwargs_lens,
                                                         compute_window=5,
                                                         start_scale=0.01,
                                                         max_order=10)
     # here we test whether the caustic points are in fact at high magnifications (close to infinite)
     # close here means above magnification of 1000. This is more precise than the critical_curve_caustics() method
     lens_model = LensModel(lens_model_list)
     mag = lens_model.magnification(ra_crit, dec_crit, kwargs_lens)
     assert np.all(np.abs(mag) > 1000)
Esempio n. 3
0
    def test_derivatives(self):
        """

        :return:
        """
        x = np.linspace(0.1, 10, 10)
        w_c, w_t = 0.5, 1.
        phi_G, q = 0.3, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_light = {'theta_E': 1., 'w_c': .5, 'w_t': 1., 'e1': e1, 'e2': e2}
        theta_E_convert = self.chameleon._theta_E_convert(theta_E=1, w_c=0.5, w_t=1.)
        s_scale_1 = np.sqrt(4 * w_c ** 2 / (1. + q) ** 2)
        s_scale_2 = np.sqrt(4 * w_t ** 2 / (1. + q) ** 2)
        kwargs_1 = {'theta_E': theta_E_convert, 's_scale': s_scale_1, 'e1': e1, 'e2': e2}
        kwargs_2 = {'theta_E': theta_E_convert, 's_scale': s_scale_2, 'e1': e1, 'e2': e2}
        f_x, f_y = self.chameleon.derivatives(x=x, y=1., **kwargs_light)
        f_x_1, f_y_1 = self.nie.derivatives(x=x, y=1., **kwargs_1)
        f_x_2, f_y_2 = self.nie.derivatives(x=x, y=1., **kwargs_2)
        npt.assert_almost_equal(f_x, (f_x_1 - f_x_2), decimal=5)
        npt.assert_almost_equal(f_y, (f_y_1 - f_y_2), decimal=5)
        f_x, f_y = self.chameleon.derivatives(x=1, y=0., **kwargs_light)
        npt.assert_almost_equal(f_x, 1, decimal=1)
Esempio n. 4
0
    def test_function(self):
        phi_E = 1.
        gamma = 1.9
        q = 0.9
        phi_G = 1.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        x = np.array([1.])
        y = np.array([2])
        a = np.zeros_like(x)
        values = self.PEMD.function(x, y, phi_E, gamma, e1, e2)
        if fastell4py_bool:
            npt.assert_almost_equal(values[0], 2.1571106351401803, decimal=5)
        else:
            assert values == 0
        a += values
        x = np.array(1.)
        y = np.array(2.)
        a = np.zeros_like(x)
        values = self.PEMD.function(x, y, phi_E, gamma, e1, e2)
        print(x, values)
        a += values
        if fastell4py_bool:
            npt.assert_almost_equal(values, 2.1571106351401803, decimal=5)
        else:
            assert values == 0
        assert type(x) == type(values)

        x = np.array([2, 3, 4])
        y = np.array([1, 1, 1])
        values = self.PEMD.function(x, y, phi_E, gamma, e1, e2)
        if fastell4py_bool:
            npt.assert_almost_equal(values[0], 2.180188584782964, decimal=7)
            npt.assert_almost_equal(values[1], 3.2097137160951874, decimal=7)
            npt.assert_almost_equal(values[2], 4.3109976673748, decimal=7)
        else:
            npt.assert_almost_equal(values[0], 0, decimal=7)
            npt.assert_almost_equal(values[1], 0, decimal=7)
            npt.assert_almost_equal(values[2], 0, decimal=7)
Esempio n. 5
0
    def _update_kwargs(self, x, kwargs_list):
        """

        :param x: list of parameters corresponding to the free parameter of the first lens model in the list
        :param kwargs_list: list of lens model kwargs
        :return: updated kwargs_list
        """
        lens_model = self._lens_mode_list[0]
        if self._solver_type == 'CENTER':
            [center_x, center_y] = x
            kwargs_list[0]['center_x'] = center_x
            kwargs_list[0]['center_y'] = center_y
        elif self._solver_type == 'ELLIPSE':
            [e1, e2] = x
            kwargs_list[0]['e1'] = e1
            kwargs_list[0]['e2'] = e2
        elif self._solver_type == 'SHAPELETS':
            [c10, c01] = x
            coeffs = list(kwargs_list[0]['coeffs'])
            coeffs[1: 3] = [c10, c01]
            kwargs_list[0]['coeffs'] = coeffs
        elif self._solver_type == 'THETA_E_PHI':
            [theta_E, phi_G] = x
            kwargs_list[0]['theta_E'] = theta_E
            phi_G_no_sense, gamma_ext = param_util.shear_cartesian2polar(kwargs_list[1]['gamma1'], kwargs_list[1]['gamma2'])
            gamma1, gamma2 = param_util.shear_polar2cartesian(phi_G, gamma_ext)
            kwargs_list[1]['gamma1'] = gamma1
            kwargs_list[1]['gamma2'] = gamma2
        elif self._solver_type == 'THETA_E_ELLIPSE':
            [theta_E, phi_G] = x
            kwargs_list[0]['theta_E'] = theta_E
            phi_G_no_sense, q = param_util.ellipticity2phi_q(kwargs_list[0]['e1'], kwargs_list[0]['e2'])
            e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
            kwargs_list[0]['e1'] = e1
            kwargs_list[0]['e2'] = e2
        else:
            raise ValueError("Solver type %s not supported for 2-point solver!" % self._solver_type)
        return kwargs_list
Esempio n. 6
0
 def setup(self):
     lensModel = LensModel(lens_model_list=['SPEP'])
     solver = LensEquationSolver(lensModel=lensModel)
     e1, e2 = param_util.phi_q2_ellipticity(0, 0.7)
     self.kwargs_lens = [{
         'theta_E': 1.,
         'center_x': 0,
         'center_y': 0,
         'e1': e1,
         'e2': e2,
         'gamma': 2
     }]
     self.sourcePos_x, self.sourcePos_y = 0.01, -0.01
     self.x_pos, self.y_pos = solver.image_position_from_source(
         sourcePos_x=self.sourcePos_x,
         sourcePos_y=self.sourcePos_y,
         kwargs_lens=self.kwargs_lens)
     self.PointSource = PointSource(
         point_source_type_list=[
             'LENSED_POSITION', 'UNLENSED', 'SOURCE_POSITION'
         ],
         lensModel=lensModel,
         fixed_magnification_list=[False] * 3,
         additional_images_list=[False] * 4,
         flux_from_point_source_list=[True, True, True])
     self.kwargs_ps = [{
         'ra_image': self.x_pos,
         'dec_image': self.y_pos,
         'point_amp': np.ones_like(self.x_pos)
     }, {
         'ra_image': [1.],
         'dec_image': [1.],
         'point_amp': [10]
     }, {
         'ra_source': self.sourcePos_x,
         'dec_source': self.sourcePos_y,
         'point_amp': np.ones_like(self.x_pos)
     }, {}]
Esempio n. 7
0
    def test_function(self):
        phi_E = 1.
        gamma = 1.9
        q = 0.9
        phi_G = 1.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        x = np.array([1.])
        y = np.array([2])
        a = np.zeros_like(x)
        values = self.PEMD.function(x, y, phi_E, gamma, e1, e2)
        if fastell4py_bool:
            assert values == 2.1567297115381039
        else:
            assert values == 0
        a += values
        x = np.array(1.)
        y = np.array(2.)
        a = np.zeros_like(x)
        values = self.PEMD.function(x, y, phi_E, gamma, e1, e2)
        print(x, values)
        a += values
        if fastell4py_bool:
            assert values == 2.1567297115381039
        else:
            assert values == 0
        assert type(x) == type(values)

        x = np.array([2, 3, 4])
        y = np.array([1, 1, 1])
        values = self.PEMD.function(x, y, phi_E, gamma, e1, e2)
        if fastell4py_bool:
            npt.assert_almost_equal(values[0], 2.1798076611034141, decimal=7)
            npt.assert_almost_equal(values[1], 3.209319798597186, decimal=7)
            npt.assert_almost_equal(values[2], 4.3105937398856398, decimal=7)
        else:
            npt.assert_almost_equal(values[0], 0, decimal=7)
            npt.assert_almost_equal(values[1], 0, decimal=7)
            npt.assert_almost_equal(values[2], 0, decimal=7)
    def test_function(self):
        """

        :return:
        """
        chameleon = Chameleon()
        nie = NIE()

        x = np.linspace(0.1, 10, 10)
        w_c, w_t = 0.5, 1.
        phi_G, q = 0.3, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_light = {'amp': 1., 'w_c': .5, 'w_t': 1., 'e1': e1, 'e2': e2}
        s_scale_1 = np.sqrt(4 * w_c**2 / (1. + q)**2)
        s_scale_2 = np.sqrt(4 * w_t**2 / (1. + q)**2)
        amp_new, w_c, w_t = chameleon._chameleonLens._theta_E_convert(
            1, w_c, w_t)
        kwargs_1 = {'amp': amp_new, 's_scale': s_scale_1, 'e1': e1, 'e2': e2}
        kwargs_2 = {'amp': amp_new, 's_scale': s_scale_2, 'e1': e1, 'e2': e2}
        flux = chameleon.function(x=x, y=1., **kwargs_light)
        flux1 = nie.function(x=x, y=1., **kwargs_1)
        flux2 = nie.function(x=x, y=1., **kwargs_2)
        npt.assert_almost_equal(flux, (flux1 - flux2) / (1. + q), decimal=5)
Esempio n. 9
0
    def test_regularization(self):

        phi_E = 1.
        gamma = 2.
        q = 1.
        phi_G = 1.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)

        x = 0.
        y = 0.
        f_x, f_y = self.EPL.derivatives(x, y, phi_E, gamma, e1, e2)
        npt.assert_almost_equal(f_x, 0.)
        npt.assert_almost_equal(f_y, 0.)

        x = 0.
        y = 0.
        f_xx, f_xy, f_yx, f_yy = self.EPL.hessian(x, y, phi_E, gamma, e1, e2)
        assert f_xx > 10 ** 5
        assert f_yy > 10 ** 5
        #npt.assert_almost_equal(f_xx, 10**10)
        #npt.assert_almost_equal(f_yy, 10**10)
        npt.assert_almost_equal(f_xy, 0)
        npt.assert_almost_equal(f_yx, 0)
Esempio n. 10
0
 def test_hessian(self):
     x = np.array([1.])
     y = np.array([2.])
     phi_E = 1.
     gamma = 2.
     q = 0.9
     phi_G = 1.
     s_scale = 0.001
     e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
     f_xx, f_xy, f_yx, f_yy = self.SPEMD.hessian(x, y, phi_E, gamma, e1, e2,
                                                 s_scale)
     if fastell4py_bool:
         f_xx_nie, f_xy_nie, f_yx_nie, f_yy_nie = self.NIE.hessian(
             x, y, phi_E, e1, e2, s_scale)
         npt.assert_almost_equal(f_xx, f_xx_nie, decimal=4)
         npt.assert_almost_equal(f_yy, f_yy_nie, decimal=4)
         npt.assert_almost_equal(f_xy, f_xy_nie, decimal=4)
         npt.assert_almost_equal(f_yx, f_yx_nie, decimal=4)
     else:
         npt.assert_almost_equal(f_xx, 0, decimal=7)
         npt.assert_almost_equal(f_yy, 0, decimal=7)
         npt.assert_almost_equal(f_xy, 0, decimal=7)
     npt.assert_almost_equal(f_xy, f_yx, decimal=8)
Esempio n. 11
0
    def test_constraint_lensmodel(self):
        lens_model_list = ['SPEP', 'SIS']
        lensModel = LensModel(lens_model_list)
        solver = Solver(solver_type='PROFILE', lensModel=lensModel, num_images=4)

        lensEquationSolver = LensEquationSolver(lensModel)
        sourcePos_x = 0.1
        sourcePos_y = -0.1
        deltapix = 0.05
        numPix = 150
        gamma = 1.9
        phi_G, q = 0.5, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_lens = [{'theta_E': 1., 'gamma': gamma, 'e1': e1, 'e2': e2, 'center_x': 0.1, 'center_y': -0.1},
                       {'theta_E': 0.1, 'center_x': 0.5, 'center_y': 0}]
        x_pos, y_pos = lensEquationSolver.findBrightImage(sourcePos_x, sourcePos_y, kwargs_lens, numImages=4, min_distance=deltapix, search_window=numPix*deltapix)
        kwargs_lens_init = [{'theta_E': 1.3, 'gamma': gamma, 'e1': 0, 'e2': 0, 'center_x': 0., 'center_y': 0}, {'theta_E': 0.1, 'center_x': 0.5, 'center_y': 0}]
        kwargs_lens_new, accuracy = solver.constraint_lensmodel(x_pos, y_pos, kwargs_lens_init)

        npt.assert_almost_equal(kwargs_lens_new[0]['theta_E'], kwargs_lens[0]['theta_E'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['e1'], kwargs_lens[0]['e1'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['e2'], kwargs_lens[0]['e2'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['center_x'], kwargs_lens[0]['center_x'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['center_y'], kwargs_lens[0]['center_y'], decimal=3)

        npt.assert_almost_equal(kwargs_lens_new[0]['theta_E'], 1., decimal=3)
        lensModel = LensModel(lens_model_list=lens_model_list)
        x_source_new, y_source_new = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens_new)
        dist = np.sqrt((x_source_new - x_source_new[0]) ** 2 + (y_source_new - y_source_new[0]) ** 2)
        assert np.max(dist) < 0.000001
        kwargs_ps4 = [{'ra_image': x_pos, 'dec_image': y_pos}]
        kwargs_lens_new = solver.update_solver(kwargs_lens_init, x_pos, y_pos)
        npt.assert_almost_equal(kwargs_lens_new[0]['theta_E'], kwargs_lens[0]['theta_E'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['e1'], kwargs_lens[0]['e1'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['e2'], kwargs_lens[0]['e2'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['center_x'], kwargs_lens[0]['center_x'], decimal=3)
        npt.assert_almost_equal(kwargs_lens_new[0]['center_y'], kwargs_lens[0]['center_y'], decimal=3)
Esempio n. 12
0
 def test_hessian(self):
     x = np.array([1])
     y = np.array([2])
     sigma0 = 1.
     Ra, Rs = 0.5, 0.8
     q, phi_G = 0.8, 0
     e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
     f_xx, f_xy, f_yx, f_yy = self.profile.hessian(x,
                                                   y,
                                                   sigma0,
                                                   Ra,
                                                   Rs,
                                                   e1,
                                                   e2,
                                                   center_x=0,
                                                   center_y=0)
     assert f_xx[0] == 0.064049581333103234
     assert f_yy[0] == -0.054062473386906618
     assert f_xy[0] == -0.060054723013958089
     npt.assert_almost_equal(f_xy, f_yx, decimal=6)
     x = np.array([1, 3, 4])
     y = np.array([2, 1, 1])
     values = self.profile.hessian(x,
                                   y,
                                   sigma0,
                                   Ra,
                                   Rs,
                                   e1,
                                   e2,
                                   center_x=0,
                                   center_y=0)
     assert values[0][0] == 0.064049581333103234
     assert values[3][0] == -0.054062473386906618
     assert values[1][0] == -0.060054723013958089
     assert values[0][1] == -0.028967667070611824
     assert values[3][1] == 0.06717994677218897
     assert values[1][1] == -0.04425260183293922
Esempio n. 13
0
 def test_static(self):
     doublechameleon = DoubleChameleon()
     x, y = 1., 1.
     phi_G, q = 0.3, 0.8
     e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
     kwargs_light = {
         'alpha_1': 1,
         'ratio': 0.5,
         'w_c1': .5,
         'w_t1': 1.,
         'e11': e1,
         'e21': e2,
         'w_c2': .1,
         'w_t2': .5,
         'e12': e1,
         'e22': e2
     }
     f_ = doublechameleon.function(x, y, **kwargs_light)
     doublechameleon.set_static(**kwargs_light)
     f_static = doublechameleon.function(x, y, **kwargs_light)
     npt.assert_almost_equal(f_, f_static, decimal=8)
     doublechameleon.set_dynamic()
     kwargs_light = {
         'alpha_1': 2,
         'ratio': 0.5,
         'w_c1': .5,
         'w_t1': 1.,
         'e11': e1,
         'e21': e2,
         'w_c2': .1,
         'w_t2': .5,
         'e12': e1,
         'e22': e2
     }
     f_dyn = doublechameleon.function(x, y, **kwargs_light)
     assert f_dyn != f_static
Esempio n. 14
0
    def test_sersic_elliptic(self):
        x = np.array([1])
        y = np.array([2])
        I0_sersic = 1
        R_sersic = 1
        n_sersic = 1
        phi_G = 1
        q = 0.9
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        center_x = 0
        center_y = 0
        values = self.sersic_elliptic.function(x, y, I0_sersic, R_sersic, n_sersic, e1, e2, center_x, center_y)
        npt.assert_almost_equal(values[0], 0.12595366113005077, decimal=6)
        x = np.array([0])
        y = np.array([0])
        values = self.sersic_elliptic.function(x, y, I0_sersic, R_sersic, n_sersic, e1, e2, center_x, center_y)
        npt.assert_almost_equal(values[0], 5.1482553482055664, decimal=2)

        x = np.array([2,3,4])
        y = np.array([1,1,1])
        values = self.sersic_elliptic.function(x, y, I0_sersic, R_sersic, n_sersic, e1, e2, center_x, center_y)
        npt.assert_almost_equal(values[0], 0.11308277793465012, decimal=6)
        npt.assert_almost_equal(values[1], 0.021188620675507107, decimal=6)
        npt.assert_almost_equal(values[2], 0.0037276744362724477, decimal=6)
Esempio n. 15
0
    def test_hessian(self):
        """

        :return:
        """
        x = np.linspace(0.1, 10, 10)
        w_c, w_t = 0.5, 1.
        phi_G, q = 0.3, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_light = {
            'alpha_1': 1.,
            'w_c': .5,
            'w_t': 1.,
            'e1': e1,
            'e2': e2
        }
        theta_E_convert, w_c, w_t, s_scale_1, s_scale_2 = self.chameleon.param_convert(
            alpha_1=1, w_c=0.5, w_t=1., e1=e1, e2=e2)
        kwargs_1 = {
            'theta_E': theta_E_convert,
            's_scale': s_scale_1,
            'e1': e1,
            'e2': e2
        }
        kwargs_2 = {
            'theta_E': theta_E_convert,
            's_scale': s_scale_2,
            'e1': e1,
            'e2': e2
        }
        f_xx, f_yy, f_xy = self.chameleon.hessian(x=x, y=1., **kwargs_light)
        f_xx_1, f_yy_1, f_xy_1 = self.nie.hessian(x=x, y=1., **kwargs_1)
        f_xx_2, f_yy_2, f_xy_2 = self.nie.hessian(x=x, y=1., **kwargs_2)
        npt.assert_almost_equal(f_xx, (f_xx_1 - f_xx_2), decimal=5)
        npt.assert_almost_equal(f_yy, (f_yy_1 - f_yy_2), decimal=5)
        npt.assert_almost_equal(f_xy, (f_xy_1 - f_xy_2), decimal=5)
Esempio n. 16
0
 def test_realistic_1(self):
     """
     realistic test example
     :return:
     """
     light_profile_list = ['HERNQUIST_ELLIPSE']
     phi, q = 0.74260706384506325, 0.46728323131925864
     e1, e2 = param_util.phi_q2_ellipticity(phi, q)
     kwargs_light = [{
         'Rs': 0.10535462602138289,
         'e1': e1,
         'e2': e2,
         'center_x': -0.02678473951679429,
         'center_y': 0.88691126347462712,
         'amp': 3.7114695634960109
     }]
     lightProfile = LightProfile(light_profile_list)
     R = 0.01
     light2d = lightProfile.light_2d(R=R, kwargs_list=kwargs_light)
     out = integrate.quad(
         lambda x: lightProfile.light_3d(np.sqrt(R**2 + x**2), kwargs_light
                                         ), 0, 100)
     print(out, 'out')
     npt.assert_almost_equal(light2d / (out[0] * 2), 1., decimal=3)
Esempio n. 17
0
    def test_profile_slope(self):
        lens_model = LensModelExtensions(LensModel(lens_model_list=['SPP']))
        gamma_in = 2.
        kwargs_lens = [{'theta_E': 1., 'gamma': gamma_in, 'center_x': 0, 'center_y': 0}]
        gamma_out = lens_model.profile_slope(kwargs_lens)
        npt.assert_array_almost_equal(gamma_out, gamma_in, decimal=3)
        gamma_in = 1.7
        kwargs_lens = [{'theta_E': 1., 'gamma': gamma_in, 'center_x': 0, 'center_y': 0}]
        gamma_out = lens_model.profile_slope(kwargs_lens)
        npt.assert_array_almost_equal(gamma_out, gamma_in, decimal=3)

        gamma_in = 2.5
        kwargs_lens = [{'theta_E': 1., 'gamma': gamma_in, 'center_x': 0, 'center_y': 0}]
        gamma_out = lens_model.profile_slope(kwargs_lens)
        npt.assert_array_almost_equal(gamma_out, gamma_in, decimal=3)

        lens_model = LensModelExtensions(LensModel(lens_model_list=['SPEP']))
        gamma_in = 2.
        phi, q = 0.34403343049704888, 0.89760957136967312
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_lens = [{'theta_E': 1.4516812130749424, 'e1': e1, 'e2': e2, 'center_x': -0.04507598845306314,
         'center_y': 0.054491803177414651, 'gamma': gamma_in}]
        gamma_out = lens_model.profile_slope(kwargs_lens)
        npt.assert_array_almost_equal(gamma_out, gamma_in, decimal=3)
    def test_critical_curves(self):
        lens_model_list = ['SPEP']
        phi, q = 1., 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_lens = [{
            'theta_E': 1.,
            'gamma': 2.,
            'e1': e1,
            'e2': e2,
            'center_x': 0,
            'center_y': 0
        }]
        lens_model = LensModel(lens_model_list)
        lensModelExtensions = LensModelExtensions(LensModel(lens_model_list))
        ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExtensions.critical_curve_caustics(
            kwargs_lens, compute_window=5, grid_scale=0.005)

        # here we test whether the caustic points are in fact at high magnifications (close to infinite)
        # close here means above magnification of 1000000 (with matplotlib method, this limit achieved was 170)
        for k in range(len(ra_crit_list)):
            ra_crit = ra_crit_list[k]
            dec_crit = dec_crit_list[k]
            mag = lens_model.magnification(ra_crit, dec_crit, kwargs_lens)
            assert np.all(np.abs(mag) > 100000)
Esempio n. 19
0
    def test_function(self):
        """

        :return:
        """
        doublechameleon = DoubleChameleonPointMass()

        phi_G, q = 0.3, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_light = {
            'theta_E': 1.,
            'ratio_pointmass': 3,
            'ratio_chameleon': 2,
            'w_c1': .5,
            'w_t1': 1.,
            'e11': e1,
            'e21': e2,
            'w_c2': .1,
            'w_t2': .5,
            'e12': e1,
            'e22': e2
        }
        flux = doublechameleon.function(x=1, y=1., **kwargs_light)
        npt.assert_almost_equal(flux, 1.2324939073557235, decimal=4)
Esempio n. 20
0
    def test_hessian(self):
        """

        :return:
        """
        doublechameleon = DoubleChameleon()
        chameleon = Chameleon()

        x = np.linspace(0.1, 10, 10)
        phi_G, q = 0.3, 0.8
        theta_E = 1.
        ratio = 2.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_lens = {
            'theta_E': theta_E,
            'ratio': ratio,
            'w_c1': .5,
            'w_t1': 1.,
            'e11': e1,
            'e21': e2,
            'w_c2': .1,
            'w_t2': .5,
            'e12': e1,
            'e22': e2
        }
        kwargs_light = {
            'amp': theta_E,
            'ratio': ratio,
            'w_c1': .5,
            'w_t1': 1.,
            'e11': e1,
            'e21': e2,
            'w_c2': .1,
            'w_t2': .5,
            'e12': e1,
            'e22': e2
        }

        kwargs_1 = {
            'theta_E': theta_E / (1 + 1. / ratio),
            'w_c': .5,
            'w_t': 1.,
            'e1': e1,
            'e2': e2
        }
        kwargs_2 = {
            'theta_E': theta_E / (1 + ratio),
            'w_c': .1,
            'w_t': .5,
            'e1': e1,
            'e2': e2
        }
        f_xx, f_yy, f_xy = doublechameleon.hessian(x=x, y=1., **kwargs_lens)
        f_xx1, f_yy1, f_xy1 = chameleon.hessian(x=x, y=1., **kwargs_1)
        f_xx2, f_yy2, f_xy2 = chameleon.hessian(x=x, y=1., **kwargs_2)
        npt.assert_almost_equal(f_xx, f_xx1 + f_xx2, decimal=8)
        npt.assert_almost_equal(f_yy, f_yy1 + f_yy2, decimal=8)
        npt.assert_almost_equal(f_xy, f_xy1 + f_xy2, decimal=8)
        light = DoubleChameleonLight()
        f_xx, f_yy, f_xy = doublechameleon.hessian(x=np.linspace(0, 1, 10),
                                                   y=np.zeros(10),
                                                   **kwargs_lens)
        kappa = 1. / 2 * (f_xx + f_yy)
        kappa_norm = kappa / np.mean(kappa)
        flux = light.function(x=np.linspace(0, 1, 10),
                              y=np.zeros(10),
                              **kwargs_light)
        flux_norm = flux / np.mean(flux)
        npt.assert_almost_equal(kappa_norm, flux_norm, decimal=5)
Esempio n. 21
0
    def setup(self):

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

        # PSF specification

        kwargs_data = sim_util.data_configure_simple(numPix, deltaPix,
                                                     exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncation': 5}
        psf_class = PSF(**kwargs_psf)
        # 'EXERNAL_SHEAR': external shear
        kwargs_shear = {
            'gamma1': 0.01,
            'gamma2': 0.01
        }  # gamma_ext: shear strength, psi_ext: shear angel (in radian)
        phi, q = 0.2, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': e1,
            'e2': e2
        }

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

        lens_light_model_list = ['SERSIC']
        self.kwargs_lens_light = [kwargs_sersic]
        lens_light_model_class = LightModel(
            light_model_list=lens_light_model_list)
        source_model_list = ['SERSIC_ELLIPSE']
        self.kwargs_source = [kwargs_sersic_ellipse]
        source_model_class = LightModel(light_model_list=source_model_list)
        self.kwargs_ps = [
            {
                'ra_source': 0.0001,
                'dec_source': 0.0,
                'source_amp': 1.
            }
        ]  # quasar point source position in the source plane and intrinsic brightness
        point_source_class = PointSource(
            point_source_type_list=['SOURCE_POSITION'],
            fixed_magnification_list=[True])
        kwargs_numerics = {
            'supersampling_factor': 2,
            'supersampling_convolution': True
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class,
                                kwargs_numerics=kwargs_numerics)
        image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens,
                                             self.kwargs_source,
                                             self.kwargs_lens_light,
                                             self.kwargs_ps)
        data_class.update_data(image_sim)
        kwargs_data['image_data'] = image_sim
        self.solver = LensEquationSolver(lensModel=lens_model_class)
        multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics],
                           [kwargs_data, kwargs_psf, kwargs_numerics]]
        kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'point_source_model_list': ['SOURCE_POSITION'],
            'fixed_magnification_list': [True],
            'lens_light_model_list': lens_light_model_list
        }
        self.imageModel = JointLinear(multi_band_list, kwargs_model)
def generate_lens(sigma_bkg=sigma_bkg,
                  exp_time=exp_time,
                  numPix=numPix,
                  deltaPix=deltaPix,
                  fwhm=fwhm,
                  psf_type=psf_type,
                  kernel_size=kernel_size,
                  z_source=z_source,
                  z_lens=z_lens,
                  phi_ext=phi_ext,
                  gamma_ext=gamma_ext,
                  theta_E=theta_E,
                  gamma_lens=gamma_lens,
                  e1_lens=e1_lens,
                  e2_lens=e2_lens,
                  center_x_lens_light=center_x_lens_light,
                  center_y_lens_light=center_y_lens_light,
                  source_x=source_y,
                  source_y=source_y,
                  q_source=q_source,
                  phi_source=phi_source,
                  center_x=center_x,
                  center_y=center_y,
                  amp_source=amp_source,
                  R_sersic_source=R_sersic_source,
                  n_sersic_source=n_sersic_source,
                  phi_lens_light=phi_lens_light,
                  q_lens_light=q_lens_light,
                  amp_lens=amp_lens,
                  R_sersic_lens=R_sersic_lens,
                  n_sersic_lens=n_sersic_lens,
                  amp_ps=amp_ps,
                  supersampling_factor=supersampling_factor,
                  v_min=v_min,
                  v_max=v_max,
                  cosmo=cosmo,
                  cosmo2=cosmo2,
                  lens_pos_eq_lens_light_pos=True,
                  same_cosmology=True):
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time,
                                                 sigma_bkg)
    data_class = ImageData(**kwargs_data)

    kwargs_psf = {'psf_type': psf_type, 'pixel_size': deltaPix, 'fwhm': fwhm}

    psf_class = PSF(**kwargs_psf)
    cosmo = FlatLambdaCDM(H0=75, Om0=0.3, Ob0=0.)
    cosmo = FlatLambdaCDM(H0=65, Om0=0.3, Ob0=0.)

    gamma1, gamma2 = param_util.shear_polar2cartesian(phi=phi_ext,
                                                      gamma=gamma_ext)
    kwargs_shear = {'gamma1': gamma1, 'gamma2': gamma2}

    if lens_pos_eq_lens_light_pos:
        center_x = center_x_lens_light
        center_y = center_y_lens_light

    if same_cosmology:
        cosmo2 = cosmo

    kwargs_spemd = {
        'theta_E': theta_E,
        'gamma': gamma_lens,
        'center_x': center_x,
        'center_y': center_y,
        'e1': e1_lens,
        'e2': e2_lens
    }
    lens_model_list = ['SPEP', 'SHEAR']
    kwargs_lens = [kwargs_spemd, kwargs_shear]
    lens_model_class = LensModel(lens_model_list=lens_model_list,
                                 z_lens=z_lens,
                                 z_source=z_source,
                                 cosmo=cosmo)
    lens_model_class2 = LensModel(lens_model_list=lens_model_list,
                                  z_lens=z_lens,
                                  z_source=z_source,
                                  cosmo=cosmo2)

    e1_source, e2_source = param_util.phi_q2_ellipticity(phi_source, q_source)

    kwargs_sersic_source = {
        'amp': amp_source,
        'R_sersic': R_sersic_source,
        'n_sersic': n_sersic_source,
        'e1': e1_source,
        'e2': e2_source,
        'center_x': source_x,
        'center_y': source_y
    }

    source_model_list = ['SERSIC_ELLIPSE']
    kwargs_source = [kwargs_sersic_source]
    source_model_class = LightModel(light_model_list=source_model_list)
    ##
    e1_lens_light, e2_lens_light = param_util.phi_q2_ellipticity(
        phi_lens_light, q_lens_light)
    kwargs_sersic_lens = {
        'amp': amp_lens,
        'R_sersic': R_sersic_lens,
        'n_sersic': n_sersic_lens,
        'e1': e1_lens_light,
        'e2': e2_lens_light,
        'center_x': center_x_lens_light,
        'center_y': center_y_lens_light
    }
    lens_light_model_list = ['SERSIC_ELLIPSE']
    kwargs_lens_light = [kwargs_sersic_lens]
    lens_light_model_class = LightModel(light_model_list=lens_light_model_list)
    ##
    lensEquationSolver = LensEquationSolver(lens_model_class)

    x_image, y_image = lensEquationSolver.findBrightImage(
        source_x,
        source_y,  #position of ps
        kwargs_lens,  #lens proporties
        numImages=4,  #expected number of images
        min_distance=deltaPix,  #'resolution'
        search_window=numPix * deltaPix)  #search window limits
    mag = lens_model_class.magnification(
        x_image,
        y_image,  #for found above ps positions
        kwargs=kwargs_lens)  # and same lens properties

    kwargs_ps = [{
        'ra_image': x_image,
        'dec_image': y_image,
        'point_amp': np.abs(mag) * amp_ps
    }]
    point_source_list = ['LENSED_POSITION']
    point_source_class = PointSource(point_source_type_list=point_source_list,
                                     fixed_magnification_list=[False])
    kwargs_numerics = {'supersampling_factor': supersampling_factor}
    imageModel = ImageModel(
        data_class,  # take generated above data specs
        psf_class,  # same for psf
        lens_model_class,  # lens model (gal+ext)
        source_model_class,  # sourse light model
        lens_light_model_class,  # lens light model
        point_source_class,  # add generated ps images
        kwargs_numerics=kwargs_numerics)
    image_sim = imageModel.image(kwargs_lens, kwargs_source, kwargs_lens_light,
                                 kwargs_ps)

    poisson = image_util.add_poisson(image_sim, exp_time=exp_time)
    bkg = image_util.add_background(image_sim, sigma_bkd=sigma_bkg)

    image_sim = image_sim + bkg + poisson

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

    cmap_string = 'gray'
    cmap = plt.get_cmap(cmap_string)
    cmap.set_bad(color='b', alpha=1.)
    cmap.set_under('k')
    f, axes = plt.subplots(1, 1, figsize=(6, 6), sharex=False, sharey=False)
    ax = axes
    im = ax.matshow(np.log10(image_sim),
                    origin='lower',
                    vmin=v_min,
                    vmax=v_max,
                    cmap=cmap,
                    extent=[0, 1, 0, 1])
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.autoscale(False)
    plt.show()
    kwargs_model = {
        'lens_model_list': lens_model_list,
        'lens_light_model_list': lens_light_model_list,
        'source_light_model_list': source_model_list,
        'point_source_model_list': point_source_list
    }

    from lenstronomy.Analysis.td_cosmography import TDCosmography
    td_cosmo = TDCosmography(z_lens,
                             z_source,
                             kwargs_model,
                             cosmo_fiducial=cosmo)

    # time delays, the unit [days] is matched when the lensing angles are in arcsec
    t_days = td_cosmo.time_delays(kwargs_lens, kwargs_ps, kappa_ext=0)
    dt_days = t_days[1:] - t_days[0]
    dt_sigma = [3, 5, 10]  # Gaussian errors
    dt_measured = np.random.normal(dt_days, dt_sigma)
    print("the measured relative delays are: ", dt_measured)
    return f, source_model_list, kwargs_data, kwargs_psf, kwargs_numerics, dt_measured, dt_sigma, kwargs_ps, lens_model_list, lens_light_model_list, source_model_list, point_source_list, lens_model_class2
Esempio n. 23
0
class Lens0712(Quad):

    x = np.array([-0.785, -0.729, 0.027, 0.389])
    y = np.array([-0.142, -0.298, -0.805, 0.317])
    m = np.array([1., 0.843, 0.418, 0.082])

    sigma_x = np.array([0.005]*4)
    sigma_y = np.array([0.005]*4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.5, 1.5

    data = Data(x, y, m, None, None,
                         sigma_x = sigma_x, sigma_y = sigma_y,
                         sigma_m=sigma_m)

    identifier = 'lens0712'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.001
    srcmax = 0.02

    satellite_mass_model = ['SERSIC_ELLIPSE_GAUSS_DEC']
    # from mass center
    satellite_pos_mass = np.array([0, 0])

    disk_q, disk_angle = 0.23, 90 - 59.7

    disk_angle *= np.pi / 180

    disk_angle *= np.pi / 180
    e1_disk, e2_disk = phi_q2_ellipticity(disk_angle, disk_q)
    satellite_kwargs = [{'k_eff': 0.294, 'R_sersic': 0.389, 'n_sersic': 1, 'e1': e1_disk,
                         'e2': e2_disk, 'center_x':satellite_pos_mass[0], 'center_y':satellite_pos_mass[1]}]

    def optimize_fit(self, kwargs_fit={}, macro_init = None, print_output = False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = {}
        satellites['lens_model_name'] = self.satellite_mass_model
        satellites['z_satellite'] = [self.zlens]
        satellites['kwargs_satellite'] = self.satellite_kwargs

        kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self, kwargs_fit={}, macro_init = None, print_output = False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:', macromodel.ellip_PA_polar()[0], macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image '+str(self.fluximg)+':')
        print('observed: ', self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ', optdata.compute_flux_ratios(index=self.flux_ratio_index))
Esempio n. 24
0
    print(seed)
    para=gene_para(seed=seed,fixh0=102)
    #==============================================================================
    # #######lens light 
    #==============================================================================
    from lenstronomy.LightModel.light_model import LightModel
    lens_light_para=para.lens_light()
    np.random.seed(seed)
    
    import magVSamp as mva
    
    lens_light_para['q'] = 0.9 + np.random.normal(0,0.01)
    
    lens_light_tran_Reff=lens_light_para['R_sersic']/np.sqrt(lens_light_para['q'])  #!!!
    #lens_light_tran_Reff = 1.1
    lens_light_para['e1'], lens_light_para['e2'] = param_util.phi_q2_ellipticity(phi=lens_light_para['phi_G'], q=lens_light_para['q'])
    
    lens_amp=mva.getAmp_lenstronomy(SERSIC_in_mag=lens_light_para,zp=zp)
    lens_light_para['amp_sersic']=lens_amp
    lens_light_model_list = ['SERSIC_ELLIPSE']
    kwargs_lens_light = {'amp':lens_light_para['amp_sersic'], 'R_sersic': lens_light_tran_Reff, 'n_sersic': lens_light_para['n_sersic'],
    					  'center_x': 0.0, 'center_y': 0.0, 'e1':lens_light_para['e1'], 'e2':lens_light_para['e2']}
    kwargs_lens_light_copy = copy.deepcopy(kwargs_lens_light)
    kwargs_lens_light_copy['phi_G'] =  lens_light_para['phi_G']
    kwargs_lens_light_copy['q'] =  lens_light_para['q']
    
    lens_light_para['amp_sersic'] = 1
    light = LightModel(['SERSIC_ELLIPSE'])
    total_flux_testamp1 = light.total_flux([kwargs_lens_light])  #The total flux for each sersic components as list
    flux_should = 10.**(-0.4*(lens_light_para['mag_sersic']-zp))
Esempio n. 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)
Esempio n. 26
0
    def test_all_spep(self):
        lensModel = LensModel(['SPEP'])
        solver_spep_center = Solver2Point(lensModel, solver_type='CENTER')
        solver_spep_ellipse = Solver2Point(lensModel, solver_type='ELLIPSE')
        image_position_spep = LensEquationSolver(lensModel)
        sourcePos_x = 0.1
        sourcePos_y = 0.03
        gamma = 1.9
        phi_G, q = 0.5, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_lens = [{
            'theta_E': 1,
            'gamma': gamma,
            'e1': e1,
            'e2': e2,
            'center_x': 0.1,
            'center_y': -0.1
        }]
        x_pos, y_pos = image_position_spep.findBrightImage(
            sourcePos_x,
            sourcePos_y,
            kwargs_lens,
            numImages=2,
            min_distance=0.01,
            search_window=5,
            precision_limit=10**(-10),
            num_iter_max=10)
        print(x_pos, y_pos, 'test')
        x_pos = x_pos[:2]
        y_pos = y_pos[:2]
        kwargs_init = [{
            'theta_E': 1,
            'gamma': gamma,
            'e1': e1,
            'e2': e2,
            'center_x': 0,
            'center_y': 0
        }]
        kwargs_out_center, precision = solver_spep_center.constraint_lensmodel(
            x_pos, y_pos, kwargs_init)

        kwargs_init = [{
            'theta_E': 1,
            'gamma': gamma,
            'e1': 0,
            'e2': 0,
            'center_x': 0.1,
            'center_y': -0.1
        }]
        kwargs_out_ellipse, precision = solver_spep_ellipse.constraint_lensmodel(
            x_pos, y_pos, kwargs_init)

        npt.assert_almost_equal(kwargs_out_center[0]['center_x'],
                                kwargs_lens[0]['center_x'],
                                decimal=3)
        npt.assert_almost_equal(kwargs_out_center[0]['center_y'],
                                kwargs_lens[0]['center_y'],
                                decimal=3)
        npt.assert_almost_equal(kwargs_out_center[0]['center_y'],
                                -0.1,
                                decimal=3)

        npt.assert_almost_equal(kwargs_out_ellipse[0]['e1'],
                                kwargs_lens[0]['e1'],
                                decimal=3)
        npt.assert_almost_equal(kwargs_out_ellipse[0]['e2'],
                                kwargs_lens[0]['e2'],
                                decimal=3)
        npt.assert_almost_equal(kwargs_out_ellipse[0]['e1'], e1, decimal=3)
Esempio n. 27
0
     orientdiff = orientdiff+180
 print (pahst, pasdss, orientdiff)
 phi0new = (phi0-orientdiff)
 if phi0new > 360:
     phi0new = phi0new-360
 phi1new = (phi1-orientdiff)
 if phi1new > 360:
     phi1new = phi1new-360
 phi2new = (phi2-orientdiff)
 if phi2new > 360:
     phi1new = phi2new-360
 phi0final = np.radians(-1*(phi0new-90))
 phi1final = np.radians(-1*(phi1new-90))
 phi2final = np.radians(-1*(phi2new-90))
 print (phi1, phi1new, phi1final, orientdiff)
 e1bulge, e2bulge = param_util.phi_q2_ellipticity(phi0final, q0)
 e1disk, e2disk = param_util.phi_q2_ellipticity(phi1final, q1)
 e1bar, e2bar = param_util.phi_q2_ellipticity(phi2final, q2)
 
 obj = '{0}'.format(ID)
 ID = 'L{0}'.format(ID)             # Object ID
 deep_seed = False                  # False = trial run
 no_MCMC = True                     # True = without MCMC 
 mpi_para = False
 pltshow = 0  #Change to 1 to show the plot while fitting.
 pix_sz = 0.396  # The pixel scale of the SDSS images
 exp_time = 53.91 #Exposure time in seconds of the SDSS images
 lowerpos = -3*pix_sz #lower limit offset in x
 upperpos = 3*pix_sz #lower limit offset in y
 spreadx = 2*pix_sz #spread in x
 spready = 2*pix_sz #spread in y
Esempio n. 28
0
    def test_all_nfw(self):
        lensModel = LensModel(['SPEP'])
        solver_nfw_ellipse = Solver2Point(lensModel, solver_type='ELLIPSE')
        solver_nfw_center = Solver2Point(lensModel, solver_type='CENTER')
        spep = LensModel(['SPEP'])

        image_position_nfw = LensEquationSolver(LensModel(['SPEP', 'NFW']))
        sourcePos_x = 0.1
        sourcePos_y = 0.03
        deltapix = 0.05
        numPix = 100
        gamma = 1.9
        Rs = 0.1
        nfw = NFW()
        alpha_Rs = nfw._rho02alpha(1., Rs)
        phi_G, q = 0.5, 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        kwargs_lens = [{
            'theta_E': 1.,
            'gamma': gamma,
            'e1': e1,
            'e2': e2,
            'center_x': 0.1,
            'center_y': -0.1
        }, {
            'Rs': Rs,
            'alpha_Rs': alpha_Rs,
            'center_x': -0.5,
            'center_y': 0.5
        }]
        x_pos, y_pos = image_position_nfw.findBrightImage(
            sourcePos_x,
            sourcePos_y,
            kwargs_lens,
            numImages=2,
            min_distance=deltapix,
            search_window=numPix * deltapix)
        print(len(x_pos), 'number of images')
        x_pos = x_pos[:2]
        y_pos = y_pos[:2]

        kwargs_init = [{
            'theta_E': 1,
            'gamma': gamma,
            'e1': e1,
            'e2': e2,
            'center_x': 0.,
            'center_y': 0
        }, {
            'Rs': Rs,
            'alpha_Rs': alpha_Rs,
            'center_x': -0.5,
            'center_y': 0.5
        }]
        kwargs_out_center, precision = solver_nfw_center.constraint_lensmodel(
            x_pos, y_pos, kwargs_init)
        source_x, source_y = spep.ray_shooting(x_pos[0], y_pos[0],
                                               kwargs_out_center)
        x_pos_new, y_pos_new = image_position_nfw.findBrightImage(
            source_x,
            source_y,
            kwargs_out_center,
            numImages=2,
            min_distance=deltapix,
            search_window=numPix * deltapix)
        print(kwargs_out_center, 'kwargs_out_center')
        npt.assert_almost_equal(x_pos_new[0], x_pos[0], decimal=2)
        npt.assert_almost_equal(y_pos_new[0], y_pos[0], decimal=2)

        npt.assert_almost_equal(kwargs_out_center[0]['center_x'],
                                kwargs_lens[0]['center_x'],
                                decimal=2)
        npt.assert_almost_equal(kwargs_out_center[0]['center_y'],
                                kwargs_lens[0]['center_y'],
                                decimal=2)
        npt.assert_almost_equal(kwargs_out_center[0]['center_y'],
                                -0.1,
                                decimal=2)

        kwargs_init = [{
            'theta_E': 1.,
            'gamma': gamma,
            'e1': 0,
            'e2': 0,
            'center_x': 0.1,
            'center_y': -0.1
        }, {
            'Rs': Rs,
            'alpha_Rs': alpha_Rs,
            'center_x': -0.5,
            'center_y': 0.5
        }]
        kwargs_out_ellipse, precision = solver_nfw_ellipse.constraint_lensmodel(
            x_pos, y_pos, kwargs_init)

        npt.assert_almost_equal(kwargs_out_ellipse[0]['e1'],
                                kwargs_lens[0]['e1'],
                                decimal=2)
        npt.assert_almost_equal(kwargs_out_ellipse[0]['e2'],
                                kwargs_lens[0]['e2'],
                                decimal=2)
        npt.assert_almost_equal(kwargs_out_ellipse[0]['e1'], e1, decimal=2)
Esempio n. 29
0
    def test_hessian(self):
        x = np.array([1])
        y = np.array([2])
        phi_E = 1.
        gamma = 1.9
        q = 0.9
        phi_G = 1.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        f_xx, f_xy, f_yx, f_yy = self.PEMD.hessian(x, y, phi_E, gamma, e1, e2)
        if fastell4py_bool:
            npt.assert_almost_equal(f_xx, 0.4179041, decimal=7)
            npt.assert_almost_equal(f_yy, 0.1404714, decimal=7)
            npt.assert_almost_equal(f_xy, -0.1856134, decimal=7)
        else:
            npt.assert_almost_equal(f_xx, 0, decimal=7)
            npt.assert_almost_equal(f_yy, 0, decimal=7)
            npt.assert_almost_equal(f_xy, 0, decimal=7)
        npt.assert_almost_equal(f_xy, f_yx, decimal=8)

        x = 1.
        y = 2.
        phi_E = 1.
        gamma = 1.9
        q = 0.9
        phi_G = 1.
        e1, e2 = param_util.phi_q2_ellipticity(phi_G, q)
        a = np.zeros_like(x)
        f_xx, f_xy, f_yx, f_yy = self.PEMD.hessian(x, y, phi_E, gamma, e1, e2)
        if fastell4py_bool:
            npt.assert_almost_equal(f_xx, 0.41790408341142493, decimal=7)
            npt.assert_almost_equal(f_yy, 0.14047143086334482, decimal=7)
            npt.assert_almost_equal(f_xy, -0.1856133848300859, decimal=7)
        else:
            npt.assert_almost_equal(f_xx, 0, decimal=7)
            npt.assert_almost_equal(f_yy, 0, decimal=7)
            npt.assert_almost_equal(f_xy, 0, decimal=7)
        a += f_xx
        x = np.array([1, 3, 4])
        y = np.array([2, 1, 1])
        values = self.PEMD.hessian(x, y, phi_E, gamma, e1, e2)
        print(values, 'values')
        if fastell4py_bool:
            npt.assert_almost_equal(values[0][0],
                                    0.41789957732890953,
                                    decimal=5)
            npt.assert_almost_equal(values[3][0],
                                    0.14047593655054141,
                                    decimal=5)
            npt.assert_almost_equal(values[1][0],
                                    -0.18560737698052343,
                                    decimal=5)
            npt.assert_almost_equal(values[0][1],
                                    0.068359818958208918,
                                    decimal=5)
            npt.assert_almost_equal(values[3][1],
                                    0.32494089371516482,
                                    decimal=5)
            npt.assert_almost_equal(values[1][1],
                                    -0.097845438684594374,
                                    decimal=5)
        else:
            npt.assert_almost_equal(values[0][0], 0, decimal=7)
Esempio n. 30
0
    def sample(self):
        """Gets kwargs of sampled parameters to be passed to lenstronomy

        Returns
        -------
        dict
            dictionary of config-specified components (e.g. lens mass), itself
            a dictionary of sampled parameters corresponding to the config-specified
            profile of that component

        """
        kwargs = Dict()
        # Sample redshifts
        z_lens, z_src = self.sample_redshifts(redshifts_cfg=self.redshift)
        # Sample velocity dispersion
        vel_disp_iso = self.sample_vel_disp(vel_disp_cfg=self.kinematics.vel_disp)
        # Sample lens_mass and lens_light parameters
        abmag_lens = self.get_lens_absolute_magnitude(vel_disp_iso)
        apmag_lens = self.get_lens_apparent_magnitude(abmag_lens, z_lens)
        theta_E = self.theta_E_model(vel_disp_iso, z_lens, z_src, self.cosmo)
        R_eff_lens, r_eff_lens = self.get_lens_size(vel_disp_iso, z_lens, apmag_lens)
        gamma = self.gamma_model(R_eff_lens)
        lens_light_q = self.lens_axis_ratio_model(vel_disp_iso) 
        kwargs['lens_mass'] = dict(
                                   theta_E=theta_E,
                                   gamma=gamma,
                                   )
        kwargs['lens_light'] = dict(
                                    magnitude=apmag_lens,
                                    R_sersic=r_eff_lens,
                                    q=lens_light_q,
                                    )
        kwargs['external_shear'] = {}

        # Sample src_light parameters
        abmag_src = self.get_src_absolute_magnitude(z_src)
        apmag_src = self.get_src_apparent_magnitude(abmag_src, z_src)
        R_eff_src, r_eff_src = self.get_src_size(z_src, abmag_src)
        kwargs['src_light'] = dict(
                                   magnitude=apmag_src,
                                   R_sersic=r_eff_src,
                                   )

        # Sample AGN_light parameters
        if 'agn_light' in self.components:
            abmag_agn = self.get_agn_absolute_magnitude(z_src)
            apmag_agn = self.get_src_apparent_magnitude(abmag_agn, z_src) 
            kwargs['agn_light'] = dict(
                                       magnitude=apmag_agn,
                                       )

        # Miscellaneous other parameters to export
        kwargs['misc'] = dict(
                              z_lens=z_lens,
                              z_src=z_src,
                              vel_disp_iso=vel_disp_iso,
                              lens_light_R_eff=R_eff_lens,
                              src_light_R_eff=R_eff_src,
                              lens_light_abmag=abmag_lens,
                              src_light_abmag=abmag_src,
                              )

        # Sample remaining parameters, not constrained by the above empirical relations,
        # independently from their (marginally) diagonal BNN prior
        for comp, param_name in self.params_to_realize:
            hyperparams = getattr(self, comp)[param_name].copy()
            kwargs[comp][param_name] = self.sample_param(hyperparams)

        # Convert any q, phi into e1, e2 as required by lenstronomy
        for comp in self.comps_qphi_to_e1e2: # e.g. 'lens_mass'
            q = kwargs[comp].pop('q')
            phi = kwargs[comp].pop('phi')
            e1, e2 = param_util.phi_q2_ellipticity(phi, q)
            kwargs[comp]['e1'] = e1
            kwargs[comp]['e2'] = e2

        # Source pos is defined wrt the lens pos
        kwargs['src_light']['center_x'] += kwargs['lens_mass']['center_x']
        kwargs['src_light']['center_y'] += kwargs['lens_mass']['center_y']

        # Ext shear is defined wrt the lens center
        kwargs['external_shear']['ra_0'] = kwargs['lens_mass']['center_x']
        kwargs['external_shear']['dec_0'] = kwargs['lens_mass']['center_y']

        if 'lens_light' in self.components:
            # Lens light shares center with lens mass
            kwargs['lens_light']['center_x'] = kwargs['lens_mass']['center_x']
            kwargs['lens_light']['center_y'] = kwargs['lens_mass']['center_y']

        return kwargs