Ejemplo n.º 1
0
    def _optimize_4imgs_lenstronomy(self,
                                    lens_systems,
                                    data2fit=None,
                                    tol_source=None,
                                    tol_mag=None,
                                    tol_centroid=None,
                                    centroid_0=None,
                                    n_particles=50,
                                    n_iterations=400,
                                    res=None,
                                    source_shape='GAUSSIAN',
                                    source_size_kpc=None,
                                    polar_grid=None,
                                    optimizer_routine=str,
                                    verbose=bool,
                                    re_optimize=False,
                                    particle_swarm=True,
                                    restart=1,
                                    constrain_params=None,
                                    return_ray_path=False,
                                    pso_convergence_mean=None,
                                    pso_compute_magnification=None,
                                    tol_simplex_params=None,
                                    tol_simplex_func=None,
                                    simplex_n_iter=None,
                                    optimizer_kwargs={},
                                    finite_source_magnification=True,
                                    chi2_mode='source',
                                    tol_image=None,
                                    adaptive_grid=None,
                                    grid_rmax_scale=1):

        data, opt_sys = [], []

        lenstronomyWrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                          z_source=self.zsrc)
        assert len(lens_systems) == 1
        for i, system in enumerate(lens_systems):

            compute_fluxes = True
            kwargs_lens, [xsrc, ysrc], [
                x_opt, y_opt
            ], optimizer = lenstronomyWrap.run_optimize(
                system,
                self.zsrc,
                data2fit.x,
                data2fit.y,
                tol_source,
                data2fit.m,
                tol_mag,
                tol_centroid,
                centroid_0,
                optimizer_routine,
                self.zmain,
                n_particles,
                n_iterations,
                verbose,
                restart,
                re_optimize,
                particle_swarm,
                constrain_params,
                pso_convergence_mean=pso_convergence_mean,
                pso_compute_magnification=pso_compute_magnification,
                tol_simplex_params=tol_simplex_params,
                tol_simplex_func=tol_simplex_func,
                simplex_n_iter=simplex_n_iter,
                optimizer_kwargs=optimizer_kwargs,
                chi2_mode=chi2_mode,
                tol_image=tol_image)

            if len(x_opt) != len(data2fit.x) or len(y_opt) != len(data2fit.y):
                print('Warning: optimization found the wrong number of images')

                x_opt, y_opt = lenstronomyWrap.solve_leq(xsrc,
                                                         ysrc,
                                                         optimizer.lensModel,
                                                         kwargs_lens,
                                                         brightimg=True,
                                                         precision_lim=10**-12,
                                                         nitermax=20)

                if len(x_opt) != len(data2fit.x) or len(y_opt) != len(
                        data2fit.y):
                    x_opt = data2fit.x
                    y_opt = data2fit.y
                    compute_fluxes = False

            lensModel = optimizer.lensModel

            if system.multiplane:
                optimizer_kwargs = {}

                if hasattr(optimizer._optimizer, '_mags'):
                    optimizer_kwargs.update(
                        {'magnification_pointsrc': optimizer._optimizer._mags})
                else:
                    mags = lensModel.magnification(x_opt, y_opt, kwargs_lens)
                    optimizer_kwargs.update({'magnification_pointsrc': mags})

                optimizer_kwargs.update({
                    'precomputed_rays':
                    optimizer.lensModel._foreground._rays
                })

                if return_ray_path:

                    xpath, ypath = [], []
                    for xi, yi in zip(x_opt, y_opt):
                        _x, _y, redshifts, Tzlist = lensModel._full_lensmodel.\
                        lens_model.ray_shooting_partial_steps(0, 0, xi,
                                       yi, 0, self.zsrc, kwargs_lens)

                        xpath.append(_x)
                        ypath.append(_y)
                    nplanes = len(xpath[0])
                    x_path, y_path = [], []
                    for ni in range(0, nplanes):

                        arrx = np.array([
                            xpath[0][ni], xpath[1][ni], xpath[2][ni],
                            xpath[3][ni]
                        ])
                        arry = np.array([
                            ypath[0][ni], ypath[1][ni], ypath[2][ni],
                            ypath[3][ni]
                        ])
                        x_path.append(arrx)
                        y_path.append(arry)

                    optimizer_kwargs.update({'path_x': np.array(x_path)})
                    optimizer_kwargs.update({'path_y': np.array(y_path)})
                    optimizer_kwargs.update({'path_Tzlist': Tzlist})
                    optimizer_kwargs.update({'path_redshifts': redshifts})
                else:
                    optimizer_kwargs = None

            if finite_source_magnification and compute_fluxes:
                fluxes = self._ray_trace_finite(
                    x_opt,
                    y_opt,
                    xsrc,
                    ysrc,
                    system.multiplane,
                    lensModel,
                    kwargs_lens,
                    res,
                    source_shape,
                    source_size_kpc,
                    polar_grid,
                    adaptive_grid=adaptive_grid,
                    grid_rmax_scale=grid_rmax_scale)
            elif compute_fluxes:
                try:
                    fluxes = optimizer_kwargs['magnification_pointsrc']
                except:
                    fluxes = np.absolute(
                        lensModel.magnification(x_opt, y_opt, kwargs_lens))
            else:
                fluxes = np.array([np.nan] * 4)

            optimized_sys = self.update_system(lens_system=system,
                                               newkwargs=kwargs_lens,
                                               method='lenstronomy')

            new_data = Data(x_opt, y_opt, fluxes, None, [xsrc, ysrc])
            new_data.sort_by_pos(data2fit.x, data2fit.y)
            data.append(new_data)
            opt_sys.append(optimized_sys)

        return data, opt_sys, optimizer_kwargs, {
            'kwargs_lens': kwargs_lens,
            'lensModel': lensModel,
            'source_x': xsrc,
            'source_y': ysrc
        }
Ejemplo n.º 2
0
    def _solve_4imgs_lenstronomy(self,
                                 lens_systems,
                                 data2fit=None,
                                 method=str,
                                 sigmas=None,
                                 ray_trace=True,
                                 res=None,
                                 source_shape='GAUSSIAN',
                                 source_size_kpc=None,
                                 print_mag=False,
                                 raytrace_with=None,
                                 polar_grid=True,
                                 solver_type=None,
                                 N_iter_max=None,
                                 brightimg=None,
                                 adaptive_grid=False,
                                 grid_rmax_scale=1):

        data, opt_sys = [], []

        lenstronomyWrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                          z_source=self.zsrc)

        for i, system in enumerate(lens_systems):

            lensModel, kwargs_lens = lenstronomyWrap.get_lensmodel(system)

            kwargs_lens, precision = lenstronomyWrap.fit_lensmodel(
                data2fit.x, data2fit.y, lensModel, solver_type, kwargs_lens)

            xsrc, ysrc = lensModel.ray_shooting(data2fit.x, data2fit.y,
                                                kwargs_lens)
            xsrc, ysrc = np.mean(xsrc), np.mean(ysrc)

            x_img, y_img = lenstronomyWrap.solve_leq(xsrc, ysrc, lensModel,
                                                     solver_type, kwargs_lens,
                                                     brightimg)

            if print_mag:
                print('computing mag # ' + str(i + 1) + ' of ' +
                      str(len(lens_systems)))

            source_scale = self.cosmo.kpc_per_asec(self.zsrc)
            source_size = source_size_kpc * source_scale**-1
            img_sep_small = min_img_sep(x_img, y_img)

            raytracing = raytrace.RayTrace(xsrc=xsrc,
                                           ysrc=ysrc,
                                           multiplane=system.multiplane,
                                           source_size=source_size,
                                           res=res,
                                           source_shape=source_shape,
                                           polar_grid=polar_grid,
                                           minimum_image_sep=img_sep_small,
                                           adaptive_grid=adaptive_grid,
                                           grid_rmax_scale=grid_rmax_scale)

            fluxes = raytracing.magnification(x_img, y_img, lensModel,
                                              kwargs_lens)

            optimized_sys = self.update_system(lens_system=system,
                                               newkwargs=kwargs_lens,
                                               method='lenstronomy')

            new_data = Data(x_img, y_img, fluxes, None, [xsrc, ysrc])
            new_data.sort_by_pos(data2fit.x, data2fit.y)
            data.append(new_data)
            opt_sys.append(optimized_sys)

        return data, opt_sys