Example #1
0
    def _new_shear(self, start_e1, start_e2, delta_phi, delta_gamma):

        phi_start, gamma_start = shear_cartesian2polar(start_e1, start_e2)

        phi_min, phi_max = phi_start + delta_phi, phi_start - delta_phi

        gamma_min, gamma_max = max(0.0001, gamma_start -
                                   delta_gamma), gamma_start + delta_gamma

        e1_min, e2_min = shear_polar2cartesian(phi_min, gamma_min)
        e1_max, e2_max = shear_polar2cartesian(phi_max, gamma_max)

        return e1_min, e2_min, e1_max, e2_max
Example #2
0
    def test_solver_simplified(self):
        lens_model_list = ['SPEP', 'SHEAR_GAMMA_PSI']
        lensModel = LensModel(lens_model_list)

        lensEquationSolver = LensEquationSolver(lensModel)
        sourcePos_x = 0.1
        sourcePos_y = -0.1
        deltapix = 0.05
        numPix = 150
        gamma = 1.9
        gamma_ext = 0.05
        psi_ext = 0.4
        #e1, e2 = param_util.phi_gamma_ellipticity(phi=psi_ext, gamma=gamma_ext)
        kwargs_lens = [{'theta_E': 1., 'gamma': gamma, 'e1': 0.1, 'e2': -0.1, 'center_x': 0.1, 'center_y': -0.1},
                       {'gamma_ext': gamma_ext, 'psi_ext': psi_ext}]
        x_pos, y_pos = lensEquationSolver.findBrightImage(sourcePos_x, sourcePos_y, kwargs_lens, numImages=4,
                                                          min_distance=deltapix, search_window=numPix * deltapix)
        e1_new, e2_new = param_util.shear_polar2cartesian(phi=0., gamma=gamma_ext + 0.1)
        kwargs_lens_init = [{'theta_E': 1.3, 'gamma': gamma, 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0},
                            {'gamma_ext': gamma_ext + 0.1, 'psi_ext': 0}]
        solver = Solver4Point(lensModel, solver_type='PROFILE_SHEAR')
        kwargs_lens_new, accuracy = solver.constraint_lensmodel(x_pos, y_pos, kwargs_lens_init)
        assert accuracy < 10**(-10)
        x_source, y_source = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens_new)
        x_source, y_source = np.mean(x_source), np.mean(y_source)
        x_pos_new, y_pos_new = lensEquationSolver.findBrightImage(x_source, y_source, kwargs_lens_new, numImages=4,
                                                          min_distance=deltapix, search_window=numPix * deltapix)
        print(x_pos, x_pos_new)
        x_pos = np.sort(x_pos)
        x_pos_new = np.sort(x_pos_new)
        y_pos = np.sort(y_pos)
        y_pos_new = np.sort(y_pos_new)
        for i in range(len(x_pos)):
            npt.assert_almost_equal(x_pos[i], x_pos_new[i], decimal=6)
            npt.assert_almost_equal(y_pos[i], y_pos_new[i], decimal=6)
Example #3
0
    def args_to_kwargs(self, args):

        (thetaE, center_x, center_y, e1, e2, g1, g2) = args
        gamma = self.kwargs_lens[0]['gamma']

        kwargs_epl = {
            'theta_E': thetaE,
            'center_x': center_x,
            'center_y': center_y,
            'e1': e1,
            'e2': e2,
            'gamma': gamma
        }

        phi, _ = shear_cartesian2polar(g1, g2)
        gamma1, gamma2 = shear_polar2cartesian(phi, self._shear_strength)
        kwargs_shear = {'gamma1': gamma1, 'gamma2': gamma2}

        self.kwargs_lens[0] = kwargs_epl
        self.kwargs_lens[1] = kwargs_shear

        self.kwargs_lens[2]['center_x'] = center_x
        self.kwargs_lens[2]['center_y'] = center_y
        phi, _ = ellipticity2phi_q(e1, e2)
        self.kwargs_lens[2]['phi_m'] = phi

        return self.kwargs_lens
Example #4
0
    def argstovary_todictionary(self,values):

        args_list = []
        count = 0

        for n in range(0, int(self._Ntovary)):

            args = {}

            if hasattr(self.routine, '_fixshear') and n == 1:
                # here values is [theta_E, x, y, e1, e2, shear_theta]
                # so convert into shear e1 e2
                gamma1, gamma2 = shear_polar2cartesian(values[count],
                                               self.routine.fixed_values[n]['shear_magnitude'])
                args.update({'gamma1': gamma1, 'gamma2': gamma2})

            else:
                for key in self.routine.param_names[n]:

                    if key in self.routine.fixed_names[n]:
                        args.update({key:self.routine.fixed_values[n][key]})
                    else:
                        args.update({key:values[count]})
                        count += 1

            args_list.append(args)

        return args_list
Example #5
0
def test_phi_gamma_ellipticity_2():
    e1, e2 = -0.04, -0.01
    phi, gamma = param_util.shear_cartesian2polar(e1, e2)

    e1_out, e2_out = param_util.shear_polar2cartesian(phi, gamma)
    npt.assert_almost_equal(e1, e1_out, decimal=10)
    npt.assert_almost_equal(e2, e2_out, decimal=10)
Example #6
0
    def args_to_kwargs(self, args):
        """

        :param args: array of lens model parameters
        :return: dictionary of lens model parameters with fixed shear = shear_strength
        """

        (thetaE, center_x, center_y, e1, e2, g1, g2) = args
        gamma = self.kwargs_lens[0]['gamma']

        kwargs_epl = {
            'theta_E': thetaE,
            'center_x': center_x,
            'center_y': center_y,
            'e1': e1,
            'e2': e2,
            'gamma': gamma
        }

        phi, _ = shear_cartesian2polar(g1, g2)
        gamma1, gamma2 = shear_polar2cartesian(phi, self._shear_strength)
        kwargs_shear = {'gamma1': gamma1, 'gamma2': gamma2}

        self.kwargs_lens[0] = kwargs_epl
        self.kwargs_lens[1] = kwargs_shear

        return self.kwargs_lens
Example #7
0
def test_phi_gamma_ellipticity():
    phi = -1.
    gamma = 0.1
    e1, e2 = param_util.shear_polar2cartesian(phi, gamma)
    print(e1, e2, 'e1, e2')
    phi_out, gamma_out = param_util.shear_cartesian2polar(e1, e2)
    assert phi == phi_out
    assert gamma == gamma_out
Example #8
0
def test_phi_gamma_ellipticity():
    phi = -1.
    gamma = 0.1
    e1, e2 = param_util.shear_polar2cartesian(phi, gamma)
    print(e1, e2, 'e1, e2')
    phi_out, gamma_out = param_util.shear_cartesian2polar(e1, e2)
    npt.assert_almost_equal(phi_out, phi, decimal=8)
    npt.assert_almost_equal(gamma_out, gamma_out, decimal=8)
Example #9
0
 def test_derivatives(self):
     x = np.array([1, 3, 4])
     y = np.array([2, 1, 1])
     gamma, psi = 0.1, 0.5
     gamma1, gamma2 = param_util.shear_polar2cartesian(phi=psi, gamma=gamma)
     values = self.shear.derivatives(x, y, gamma, psi)
     values_e1e2 = self.shear_e1e2.derivatives(x, y, gamma1, gamma2)
     npt.assert_almost_equal(values, values_e1e2, decimal=5)
Example #10
0
    def test_solver_profile_shear_2(self):
        lens_model_list = ['SPEP', 'SHEAR']
        lensModel = LensModel(lens_model_list)

        lensEquationSolver = LensEquationSolver(lensModel)
        sourcePos_x = 0.
        sourcePos_y = 0.1
        deltapix = 0.05
        numPix = 150
        gamma = 1.98
        gamma1, gamma2 = -0.04, -0.01

        kwargs_shear = {'gamma1': gamma1, 'gamma2': gamma2}  # shear values to the source plane
        kwargs_spemd = {'theta_E': 1.66, 'gamma': gamma, 'center_x': 0.0, 'center_y': 0.0, 'e1': 0.1,
                        'e2': 0.05}  # parameters of the deflector lens model

        kwargs_lens = [kwargs_spemd, kwargs_shear]
        x_pos, y_pos = lensEquationSolver.findBrightImage(sourcePos_x, sourcePos_y, kwargs_lens, numImages=4,
                                                          min_distance=deltapix, search_window=numPix * deltapix)
        print(x_pos, y_pos, 'test positions')

        gamma_ext = np.sqrt(gamma1 ** 2 + gamma2 ** 2)
        gamma1_init, gamma2_init = param_util.shear_polar2cartesian(gamma=gamma_ext, phi=-1.3)

        kwargs_lens_init = [{'theta_E': 1.3, 'gamma': gamma, 'e1': 0, 'e2': 0, 'center_x': 0., 'center_y': 0},
                            {'gamma1': gamma1_init, 'gamma2': gamma2_init}]
        solver = Solver4Point(lensModel, solver_type='PROFILE_SHEAR')
        kwargs_lens_new, accuracy = solver.constraint_lensmodel(x_pos, y_pos, kwargs_lens_init)
        assert accuracy < 10**(-10)
        x_source, y_source = lensModel.ray_shooting(x_pos, y_pos, kwargs_lens_new)
        x_source, y_source = np.mean(x_source), np.mean(y_source)
        x_pos_new, y_pos_new = lensEquationSolver.findBrightImage(x_source, y_source, kwargs_lens_new, numImages=4,
                                                          min_distance=deltapix, search_window=numPix * deltapix)
        print(x_pos, x_pos_new)
        x_pos = np.sort(x_pos)
        x_pos_new = np.sort(x_pos_new)
        y_pos = np.sort(y_pos)
        y_pos_new = np.sort(y_pos_new)
        for i in range(len(x_pos)):
            npt.assert_almost_equal(x_pos[i], x_pos_new[i], decimal=6)
            npt.assert_almost_equal(y_pos[i], y_pos_new[i], decimal=6)
        npt.assert_almost_equal(kwargs_lens_new[1]['gamma1'], kwargs_lens[1]['gamma1'], decimal=8)
        npt.assert_almost_equal(kwargs_lens_new[1]['gamma2'], kwargs_lens[1]['gamma2'], decimal=8)
        npt.assert_almost_equal(kwargs_lens_new[0]['e1'], kwargs_lens[0]['e1'], decimal=8)
        npt.assert_almost_equal(kwargs_lens_new[0]['e2'], kwargs_lens[0]['e2'], decimal=8)
Example #11
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
Example #12
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
        """
        if self._solver_type == 'PROFILE_SHEAR_GAMMA_PSI':
            phi_G = x[5]  # % (2 * np.pi)
            kwargs_list[1]['psi_ext'] = phi_G
        if self._solver_type == 'PROFILE_SHEAR':
            phi_G = x[5] % np.pi
            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
        lens_model = self._lens_mode_list[0]
        if lens_model in ['SPEP', 'SPEMD', 'SIE', 'NIE', 'PEMD', 'EPL']:
            [theta_E, e1, e2, center_x, center_y, _] = x
            kwargs_list[0]['theta_E'] = theta_E
            kwargs_list[0]['e1'] = e1
            kwargs_list[0]['e2'] = e2
            kwargs_list[0]['center_x'] = center_x
            kwargs_list[0]['center_y'] = center_y
        elif lens_model in ['NFW_ELLIPSE', 'CNFW_ELLIPSE']:
            [alpha_Rs, e1, e2, center_x, center_y, _] = x
            kwargs_list[0]['alpha_Rs'] = alpha_Rs
            kwargs_list[0]['e1'] = e1
            kwargs_list[0]['e2'] = e2
            kwargs_list[0]['center_x'] = center_x
            kwargs_list[0]['center_y'] = center_y
        elif lens_model in ['SHAPELETS_CART']:
            [c10, c01, c20, c11, c02, _] = x
            coeffs = list(kwargs_list[0]['coeffs'])
            coeffs[1:6] = [c10, c01, c20, c11, c02]
            kwargs_list[0]['coeffs'] = coeffs
        else:
            raise ValueError(
                "Lens model %s not supported for 4-point solver!" % lens_model)
        return kwargs_list
Example #13
0
def add_g1g2_columns(metadata):
    """Add alternate shear definitions (gamma1, gamma2) for external shear defined in terms of shear modulus and angle (gamma_ext, psi_ext)

    Parameters
    ----------
    metadata : pd.DataFrame
        the metadatadata generated by Baobab

    Returns
    -------
    pd.DataFrame
        metadata augmented with gamma1, gamma2 for the external shear component

    """
    gamma_ext = metadata['external_shear_gamma_ext'].values
    psi_ext = metadata['external_shear_psi_ext'].values
    gamma1, gamma2 = param_util.shear_polar2cartesian(phi=psi_ext,
                                                      gamma=gamma_ext)
    metadata['external_shear_gamma1'] = gamma1
    metadata['external_shear_gamma2'] = gamma2
    return metadata
def generate_lens(sigma_bkg=sigma_bkg,
                  exp_time=exp_time,
                  numPix=numPix,
                  deltaPix=deltaPix,
                  fwhm=fwhm,
                  psf_type=psf_type,
                  kernel_size=kernel_size,
                  z_source=z_source,
                  z_lens=z_lens,
                  phi_ext=phi_ext,
                  gamma_ext=gamma_ext,
                  theta_E=theta_E,
                  gamma_lens=gamma_lens,
                  e1_lens=e1_lens,
                  e2_lens=e2_lens,
                  center_x_lens_light=center_x_lens_light,
                  center_y_lens_light=center_y_lens_light,
                  source_x=source_y,
                  source_y=source_y,
                  q_source=q_source,
                  phi_source=phi_source,
                  center_x=center_x,
                  center_y=center_y,
                  amp_source=amp_source,
                  R_sersic_source=R_sersic_source,
                  n_sersic_source=n_sersic_source,
                  phi_lens_light=phi_lens_light,
                  q_lens_light=q_lens_light,
                  amp_lens=amp_lens,
                  R_sersic_lens=R_sersic_lens,
                  n_sersic_lens=n_sersic_lens,
                  amp_ps=amp_ps,
                  supersampling_factor=supersampling_factor,
                  v_min=v_min,
                  v_max=v_max,
                  cosmo=cosmo,
                  cosmo2=cosmo2,
                  lens_pos_eq_lens_light_pos=True,
                  same_cosmology=True):
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time,
                                                 sigma_bkg)
    data_class = ImageData(**kwargs_data)

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

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

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

    if lens_pos_eq_lens_light_pos:
        center_x = center_x_lens_light
        center_y = center_y_lens_light

    if same_cosmology:
        cosmo2 = cosmo

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

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

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

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

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

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

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

    image_sim = image_sim + bkg + poisson

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

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

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

    # time delays, the unit [days] is matched when the lensing angles are in arcsec
    t_days = td_cosmo.time_delays(kwargs_lens, kwargs_ps, kappa_ext=0)
    dt_days = t_days[1:] - t_days[0]
    dt_sigma = [3, 5, 10]  # Gaussian errors
    dt_measured = np.random.normal(dt_days, dt_sigma)
    print("the measured relative delays are: ", dt_measured)
    return f, source_model_list, kwargs_data, kwargs_psf, kwargs_numerics, dt_measured, dt_sigma, kwargs_ps, lens_model_list, lens_light_model_list, source_model_list, point_source_list, lens_model_class2
Example #15
0
 def derivatives(self, x, y, gamma_ext, psi_ext, ra_0=0, dec_0=0):
     # rotation angle
     gamma1, gamma2 = param_util.shear_polar2cartesian(psi_ext, gamma_ext)
     return self._shear_e1e2.derivatives(x, y, gamma1, gamma2, ra_0, dec_0)
Example #16
0
 def hessian(self, x, y, gamma_ext, psi_ext, ra_0=0, dec_0=0):
     gamma1, gamma2 = param_util.shear_polar2cartesian(psi_ext, gamma_ext)
     return self._shear_e1e2.hessian(x, y, gamma1, gamma2, ra_0, dec_0)
Example #17
0
def caustics_epl_shear(kwargs_lens,
                       num_th=500,
                       maginf=0,
                       sourceplane=True,
                       return_which=None):
    """
    Analytically calculates the caustics of an EPL+shear lens model.
    Since for gamma>2, the outer critical curve does not exist, the option to find the curves for a set, finite magnification exists, by supplying maginf, so that the routine finds the curve of this magnification, rather than the true caustic.

    :param kwargs_lens: List of kwargs in lenstronomy style, following ['EPL', 'SHEAR'] format
    :param num_th: resolution.
    :param maginf: the outer critical curve for t>1 will be replaced with the curve where the inverse magnification is maginf
    :param sourceplane: if True (default), ray-shoot the calculated critical curves to the source plane
    :param return_which: options 'quad' (boundary of area within which there are 4 images), 'double' (boundary of area within which there are 2 images),
     'caustic' (the diamond caustic) and 'cut' (the cut, if it exists, that is if t<2, else, if t>2, returns the caustic) and None (in that case: return quad, caustic, cut)
    :return: (2,N) array if return_which set, else a tuple of (caustic, cut, quad)
    """
    e1, e2 = kwargs_lens[0]['e1'], kwargs_lens[0]['e2']
    if len(kwargs_lens) > 1:
        gamma1unr, gamma2unr = kwargs_lens[1]['gamma1'], kwargs_lens[1][
            'gamma2']
    else:
        gamma1unr, gamma2unr = 0, 0
    _check_center(kwargs_lens)
    t = kwargs_lens[0]['gamma'] - 1 if 'gamma' in kwargs_lens[0] else 1
    theta_ell, q = ellipticity2phi_q(e1, e2)
    theta_gamma, gamma_mag = shear_cartesian2polar(gamma1unr, gamma2unr)
    b = np.sqrt(q) * kwargs_lens[0]['theta_E']
    cen = np.expand_dims(
        np.array([kwargs_lens[0]['center_x'], kwargs_lens[0]['center_y']]), 1)
    theta_gamma -= theta_ell
    gamma1, gamma2 = shear_polar2cartesian(theta_gamma, gamma_mag)
    M = rotmat(-theta_ell)
    phiell, q = ellipticity2phi_q(e1, e2)
    theta = np.linspace(0, 2 * np.pi, num_th, endpoint=False)
    r = 1
    R, phi = pol_to_ell(1, theta, q)
    Omega = omega(phi, t, q)
    aa = 1
    bb = -(2 - t)
    frac_roverR = r / R
    cc = (1 - t) * (2 - t) * (cdot(np.exp(1j * theta),
                                   Omega)) / frac_roverR * 2 / (1 + q)
    cc -= (1 - t)**2 * (2 / (1 + q))**2 * np.abs(Omega)**2 / frac_roverR**2
    # Shear stuff:
    gammaint_fac = (-np.exp(2j * theta) * (2 - t) / 2 +
                    (1 - t) * np.exp(1j * theta) * 2 /
                    (1 + q) * Omega / frac_roverR)
    gamma = gamma1 + 1j * gamma2
    aa -= np.abs(gamma)**2
    bb -= 2 * cdot(gamma, gammaint_fac)
    usol = np.array(solvequadeq(cc, bb, aa)).T
    xcr_4, ycr_4 = pol_to_cart(b * usol[:, 1]**(-1 / t) * frac_roverR, theta)
    if t > 1:  # If t>1, get the approximate outer caustic instead (where inverse magnification = maginf).
        usol = np.array(solvequadeq(cc, bb, aa - maginf)).T
        xcr_cut, ycr_cut = pol_to_cart(b * usol[:, 1]**(-1 / t) * frac_roverR,
                                       theta)
    else:
        usol = np.array(solvequadeq(cc, bb, aa + maginf)).T
        xcr_cut, ycr_cut = pol_to_cart(b * usol[:, 0]**(-1 / t) * frac_roverR,
                                       theta)
    al_cut = _alpha_epl_shear(xcr_cut,
                              ycr_cut,
                              b,
                              q,
                              t,
                              gamma1,
                              gamma2,
                              Omega=Omega)
    al_4 = _alpha_epl_shear(xcr_4, ycr_4, b, q, t, gamma1, gamma2, Omega=Omega)
    if sourceplane:
        xca_cut, yca_cut = xcr_cut - al_cut.real, ycr_cut - al_cut.imag
        xca_4, yca_4 = xcr_4 - al_4.real, ycr_4 - al_4.imag
    else:
        xca_cut, yca_cut = xcr_cut, ycr_cut
        xca_4, yca_4 = xcr_4, ycr_4
    if return_which == 'caustic':
        return M @ (xca_4, yca_4) + cen
    if return_which == 'cut':
        return M @ (xca_cut, yca_cut) + cen

    rcut, thcut = cart_to_pol(xca_cut, yca_cut)
    r, th = cart_to_pol(xca_4, yca_4)
    r2 = np.interp(th, thcut, rcut, period=2 * np.pi)

    if return_which == 'double':
        r = np.fmax(r, r2)
    else:  # Quad
        r = np.fmin(r, r2)

    pos_tosample = np.empty((2, num_th))
    pos_tosample[0], pos_tosample[1] = pol_to_cart(r, th)
    if return_which in ('double', 'quad'):
        return M @ pos_tosample + cen

    return M @ (xca_4, yca_4) + cen, M @ (
        xca_cut, yca_cut
    ) + cen, M @ pos_tosample + cen  # Mostly for some backward compatibility
Example #18
0
def run(Ntotal_cusp, Ntotal_fold, Ntotal_cross, start_idx):

    continue_loop = True
    n_computed = 0
    done_cusp, done_fold, done_cross = False, False, False
    n_cusp, n_fold, n_cross = 0, 0, 0

    if Ntotal_cusp == 0:
        done_cusp = True
    if Ntotal_fold == 0:
        done_fold = True
    if Ntotal_cross == 0:
        done_cross = True

    lens_idx = int(start_idx) + n_computed
    dpath = dpath_base + str(lens_idx)

    if os.path.exists(dpath + '/lensdata.txt'):
        return

    while continue_loop:

        if done_cusp and done_cross and done_fold:
            break

        while True:
            rein, vdis, zlens, zsrc = sample_from_strides(1)
            if rein <= rein_max and rein >= rein_min:
                if zlens <= z_lens_max:
                    if zsrc <= z_src_max:
                        break

        pyhalo = pyHalo(zlens, zsrc)

        print('rein, zlens, zsrc: ',
              str(rein) + ' ' + str(zlens) + ' ' + str(zsrc))

        ellip = draw_ellip()
        ellip_theta = draw_ellip_PA()
        shear = draw_shear()

        shear_theta = draw_shear_PA_correlated(ellip_theta, sigma=40)

        halo_args = {
            'mdef_main': mass_def,
            'mdef_los': mass_def,
            'sigma_sub': sigma_sub,
            'log_mlow': log_ml,
            'log_mhigh': log_mh,
            'power_law_index': -1.9,
            'parent_m200': M_halo,
            'r_tidal': r_tidal,
            'cone_opening_angle': 5 * rein,
            'opening_angle_factor': 5,
            'subtract_subhalo_mass_sheet': True,
            'subhalo_mass_sheet_scale': 1.,
            'R_ein_main': rein,
            'LOS_normalization': LOSnorm
        }

        realization = pyhalo.render(model_type, halo_args)[0]

        e1, e2 = phi_q2_ellipticity(shear_theta * np.pi / 180, 1 - ellip)
        gamma1, gamma2 = shear_polar2cartesian(shear_theta * np.pi / 180,
                                               shear)
        kwargs_lens = [{
            'theta_E': rein,
            'center_x': 0,
            'center_y': 0,
            'e1': e1,
            'e2': e2,
            'gamma': gamma
        }, {
            'gamma1': gamma1,
            'gamma2': gamma2
        }]
        macromodel = MacroLensModel([PowerLawShear(zlens, kwargs_lens)])
        source_args = {
            'center_x': None,
            'center_y': None,
            'source_fwhm_pc': source_size_fwhm_pc
        }
        quasar = Quasar(source_args)
        system = QuadLensSystem(macromodel, zsrc, quasar, realization,
                                pyhalo._cosmology)

        print('zlens: ', zlens)
        print('zsrc: ', zsrc)
        print('src_size_pc: ', source_size_fwhm_pc)
        print('R_ein:', rein)
        print('shear, ellip: ', shear, ellip)
        print('nhalos: ', len(realization.halos))

        continue_findimg_loop = True

        while continue_findimg_loop:

            src_r = np.random.uniform(0.01, 0.1)

            src_phi = np.random.uniform(-np.pi, np.pi)
            srcx, srcy = src_r * np.cos(src_phi), src_r * np.sin(src_phi)
            print(srcx, srcy, np.sqrt(srcx**2 + srcy**2))
            system.update_source_centroid(srcx, srcy)

            lens_model_smooth, kwargs_lens_smooth = system.get_lensmodel(False)
            lensModel, kwargs_lens = system.get_lensmodel()

            x_guess, y_guess = system.solve_lens_equation(
                lens_model_smooth, kwargs_lens_smooth)
            if len(x_guess) != 4:
                continue

            min_sep = min_img_sep(x_guess, y_guess)
            lens_config = identify(x_guess, y_guess, rein)

            if min_sep < 0.2:
                continue
            if lens_config == 0:
                config = 'cross'
                if done_cross:
                    continue
            elif lens_config == 1:
                config = 'fold'
                if done_fold:
                    continue
            else:
                config = 'cusp'
                if done_cusp:
                    continue
            print('solving lens equation with halos... ')
            t0 = time()
            #x_image, y_image = iterative_rayshooting(srcx, srcy,
            #                                         x_guess, y_guess, lensModel, kwargs_lens)

            x_image, y_image = system.solve_lens_equation(
                lensModel, kwargs_lens, 10**-6)
            tend = time()
            dt = np.round(tend - t0, 2) / 60
            print('solved lens equation with ' + str(len(realization.halos)) +
                  ' halos in ' + str(dt) + ' min.')
            lens_config = identify(x_image, y_image, rein)
            min_sep = min_img_sep(x_image, y_image)

            if min_sep < 0.2:
                continue

            if lens_config == 0:
                config = 'cross'
                if done_cross:
                    continue
            elif lens_config == 1:
                config = 'fold'
                if done_fold:
                    continue
            else:
                config = 'cusp'
                if done_cusp:
                    continue

            images = system.background_quasar.get_images(
                x_image, y_image, lensModel, kwargs_lens)

            break_loop = False
            for img in images:
                if flux_at_edge(img):
                    break_loop = True

            if break_loop:
                print('flux at edge... ')
                continue
            print(config)
            other_lens_args = {}
            other_lens_args['zlens'] = zlens
            other_lens_args['zsrc'] = zsrc
            other_lens_args['gamma'] = gamma
            other_lens_args['config'] = config
            other_lens_args['source_fwhm_pc'] = source_size_fwhm_pc
            other_lens_args['rmax2d_asec'] = 3 * rein
            continue_findimg_loop = False

        if lens_config == 0:
            n_cross += 1
            if n_cross == Ntotal_cross:
                done_cross = True
        elif lens_config == 1:
            n_fold += 1
            if n_fold == Ntotal_fold:
                done_fold = True
        else:
            n_cusp += 1
            if n_cusp == Ntotal_cusp:
                done_cusp = True

        n_computed += 1

        create_directory(dpath)

        x_image += np.random.normal(0, 0.005, 4)
        y_image += np.random.normal(0, 0.005, 4)
        magnifications = system.quasar_magnification(x_image, y_image,
                                                     lensModel, kwargs_lens)
        data_with_halos = LensedQuasar(x_image, y_image, magnifications)
        data_with_halos.nimg = 4
        data_with_halos.srcx = 0.
        data_with_halos.srcy = 0.
        data_with_halos.t = [0., 0., 0., 0.]
        write_data(dpath + '/lensdata.txt', [data_with_halos], mode='write')

        to_write = get_info_string(halo_args, other_lens_args)
        write_info(str(to_write), dpath + '/info.txt')