示例#1
0
def fit_galaxy(galaxy_im, psf_ave, psf_std=None, source_params=None, background_rms=0.04, pix_sz = 0.08,
            exp_time = 300., fix_n=None, image_plot = True, corner_plot=True,
            deep_seed = False, galaxy_msk=None, galaxy_std=None, flux_corner_plot = False,
            tag = None, no_MCMC= False, pltshow = 1, return_Chisq = False, dump_result = False, pso_diag=False):
    '''
    A quick fit for the QSO image with (so far) single sersice + one PSF. The input psf noise is optional.
    
    Parameter
    --------
        galaxy_im: An array of the QSO image.
        psf_ave: The psf image.
        psf_std: The psf noise, optional.
        source_params: The prior for the source. Default is given.
        background_rms: default as 0.04
        exp_time: default at 2400.
        deep_seed: if Ture, more mcmc steps will be performed.
        tag: The name tag for save the plot
            
    Return
    --------
        Will output the fitted image (Set image_plot = True), the corner_plot and the flux_ratio_plot.
        source_result, ps_result, image_ps, image_host
    
    To do
    --------
        
    '''
    # data specifics need to set up based on the data situation
    background_rms = background_rms  #  background noise per pixel (Gaussian)
    exp_time = exp_time  #  exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
    numPix = len(galaxy_im)  #  cutout pixel size
    deltaPix = pix_sz
    if psf_ave is not None:
        psf_type = 'PIXEL'  # 'gaussian', 'pixel', 'NONE'
        kernel = psf_ave
    
#    if psf_std is not None:
#        kwargs_numerics = {'subgrid_res': 1, 'psf_error_map': True}     #Turn on the PSF error map
#    else: 
    kwargs_numerics = {'supersampling_factor': 1, 'supersampling_convolution': False}
        
    if source_params is None:
        # here are the options for the host galaxy fitting
        fixed_source = []
        kwargs_source_init = []
        kwargs_source_sigma = []
        kwargs_lower_source = []
        kwargs_upper_source = []
        # Disk component, as modelled by an elliptical Sersic profile
        if fix_n == None:
            fixed_source.append({})  # we fix the Sersic index to n=1 (exponential)
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': 2., 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.5, 'R_sersic': 0.1, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.01, 'n_sersic': 0.3, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3., 'n_sersic': 7., 'center_x': 10, 'center_y': 10})
        elif fix_n is not None:
            fixed_source.append({'n_sersic': fix_n})
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': fix_n, 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.001, 'R_sersic': 0.1, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.01, 'n_sersic': fix_n, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3, 'n_sersic': fix_n, 'center_x': 10, 'center_y': 10})
        source_params = [kwargs_source_init, kwargs_source_sigma, fixed_source, kwargs_lower_source, kwargs_upper_source]
    else:
        source_params = source_params
    kwargs_params = {'source_model': source_params}
    
    #==============================================================================
    #Doing the QSO fitting 
    #==============================================================================
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, background_rms, inverse=True)
    data_class = ImageData(**kwargs_data)
    if psf_ave is not None:
        kwargs_psf = {'psf_type': psf_type, 'kernel_point_source': kernel}
    else:
        kwargs_psf =  {'psf_type': 'NONE'}
    
    psf_class = PSF(**kwargs_psf)
    data_class.update_data(galaxy_im)
    
    light_model_list = ['SERSIC_ELLIPSE'] * len(source_params[0])
    lightModel = LightModel(light_model_list=light_model_list)
    
    kwargs_model = { 'source_light_model_list': light_model_list}
    # numerical options and fitting sequences
    kwargs_constraints = {}
    
    kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                         'source_marg': False,  #In likelihood_module.LikelihoodModule -- whether to fully invert the covariance matrix for marginalization
                          'check_positive_flux': True,       
                          'image_likelihood_mask_list': [galaxy_msk]
                         }
    kwargs_data['image_data'] = galaxy_im
    if galaxy_std is not None:
        kwargs_data['noise_map'] = galaxy_std
    if psf_std is not None:
        kwargs_psf['psf_error_map'] = psf_std
                  
    image_band = [kwargs_data, kwargs_psf, kwargs_numerics]
    multi_band_list = [image_band]
    
    kwargs_data_joint = {'multi_band_list': multi_band_list, 'multi_band_type': 'multi-linear'}  # 'single-band', 'multi-linear', 'joint-linear'
    fitting_seq = FittingSequence(kwargs_data_joint, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params)
    
    if deep_seed == False:
        fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 50, 'n_iterations': 50}],
            ['MCMC', {'n_burn': 10, 'n_run': 10, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]            
    elif deep_seed == True:
         fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 100, 'n_iterations': 80}],
            ['MCMC', {'n_burn': 10, 'n_run': 15, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]
    elif deep_seed == 'very_deep':
         fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 150, 'n_iterations': 150}],
            ['MCMC', {'n_burn': 10, 'n_run': 20, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]
    if no_MCMC == True:
        fitting_kwargs_list = [fitting_kwargs_list[0],
                               ]        
    
    start_time = time.time()
    chain_list = fitting_seq.fit_sequence(fitting_kwargs_list)
    kwargs_result = fitting_seq.best_fit()
    ps_result = kwargs_result['kwargs_ps']
    source_result = kwargs_result['kwargs_source']
    
    if no_MCMC == False:
        sampler_type, samples_mcmc, param_mcmc, dist_mcmc  = chain_list[1]      
    
#    chain_list, param_list, samples_mcmc, param_mcmc, dist_mcmc = fitting_seq.fit_sequence(fitting_kwargs_list)
#    lens_result, source_result, lens_light_result, ps_result, cosmo_temp = fitting_seq.best_fit()
    end_time = time.time()
    print(end_time - start_time, 'total time needed for computation')
    print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
    # this is the linear inversion. The kwargs will be updated afterwards
    imageModel = ImageModel(data_class, psf_class, source_model_class=lightModel,kwargs_numerics=kwargs_numerics)
    imageLinearFit = ImageLinearFit(data_class=data_class, psf_class=psf_class,
                                       source_model_class=lightModel,
                                       kwargs_numerics=kwargs_numerics)    
    image_reconstructed, error_map, _, _ = imageLinearFit.image_linear_solve(kwargs_source=source_result, kwargs_ps=ps_result)
#    image_host = []   #!!! The linear_solver before and after could have different result for very faint sources.
#    for i in range(len(source_result)):
#        image_host_i = imageModel.source_surface_brightness(source_result,de_lensed=True,unconvolved=False, k=i)
#        print("image_host_i", source_result[i])
#        print("total flux", image_host_i.sum())
#        image_host.append(image_host_i)  
        
    # let's plot the output of the PSO minimizer
    modelPlot = ModelPlot(multi_band_list, kwargs_model, kwargs_result,
                          arrow_size=0.02, cmap_string="gist_heat", likelihood_mask_list=[galaxy_msk])  
    
    if pso_diag == True:
        f, axes = chain_plot.plot_chain_list(chain_list,0)
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
                
    reduced_Chisq =  imageLinearFit.reduced_chi2(image_reconstructed, error_map)
    if image_plot:
        f, axes = plt.subplots(1, 3, figsize=(16, 16), sharex=False, sharey=False)
        modelPlot.data_plot(ax=axes[0])
        modelPlot.model_plot(ax=axes[1])
        modelPlot.normalized_residual_plot(ax=axes[2], v_min=-6, v_max=6)
        f.tight_layout()
        #f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05)
        if tag is not None:
            f.savefig('{0}_fitted_image.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
    image_host = []    
    for i in range(len(source_result)):
        image_host_i = imageModel.source_surface_brightness(source_result,de_lensed=True,unconvolved=False, k=i)
#        print("image_host_i", source_result[i])
#        print("total flux", image_host_i.sum())
        image_host.append(image_host_i)  
        
    if corner_plot==True and no_MCMC==False:
        # here the (non-converged) MCMC chain of the non-linear parameters
        if not samples_mcmc == []:
           n, num_param = np.shape(samples_mcmc)
           plot = corner.corner(samples_mcmc, labels=param_mcmc, show_titles=True)
           if tag is not None:
               plot.savefig('{0}_para_corner.pdf'.format(tag))
           if pltshow == 0:
               plt.close()
           else:
               plt.show()
    if flux_corner_plot ==True and no_MCMC==False:
        param = Param(kwargs_model, kwargs_fixed_source=source_params[2], **kwargs_constraints)
        mcmc_new_list = []
        labels_new = ["host{0} flux".format(i) for i in range(len(source_params[0]))]
        for i in range(len(samples_mcmc)):
            kwargs_out = param.args2kwargs(samples_mcmc[i])
            kwargs_light_source_out = kwargs_out['kwargs_source']
            kwargs_ps_out =  kwargs_out['kwargs_ps']
            image_reconstructed, _, _, _ = imageLinearFit.image_linear_solve(kwargs_source=kwargs_light_source_out, kwargs_ps=kwargs_ps_out)
            fluxs = []
            for j in range(len(source_params[0])):
                image_j = imageModel.source_surface_brightness(kwargs_light_source_out,unconvolved= False, k=j)
                fluxs.append(np.sum(image_j))
            mcmc_new_list.append( fluxs )
            if int(i/1000) > int((i-1)/1000) :
                print(len(samples_mcmc), "MCMC samplers in total, finished translate:", i    )
        plot = corner.corner(mcmc_new_list, labels=labels_new, show_titles=True)
        if tag is not None:
            plot.savefig('{0}_HOSTvsQSO_corner.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show() 

    if galaxy_std is None:
        noise_map = np.sqrt(data_class.C_D+np.abs(error_map))
    else:
        noise_map = np.sqrt(galaxy_std**2+np.abs(error_map))   
        
    if dump_result == True:
        if flux_corner_plot==True and no_MCMC==False:
            trans_paras = [source_params[2], mcmc_new_list, labels_new, 'source_params[2], mcmc_new_list, labels_new']
        else:
            trans_paras = []
        picklename= tag + '.pkl'
        best_fit = [source_result, image_host, 'source_result, image_host']
#        pso_fit = [chain_list, param_list, 'chain_list, param_list']
#        mcmc_fit = [samples_mcmc, param_mcmc, dist_mcmc, 'samples_mcmc, param_mcmc, dist_mcmc']
        chain_list_result = [chain_list, 'chain_list']
        pickle.dump([best_fit, chain_list_result, trans_paras], open(picklename, 'wb'))
        
    if return_Chisq == False:
        return source_result, image_host, noise_map
    elif return_Chisq == True:
        return source_result, image_host, noise_map, reduced_Chisq
示例#2
0
    def test_point_source_rendering(self):
        # initialize data

        numPix = 100
        deltaPix = 0.05
        kwargs_data = sim_util.data_configure_simple(numPix,
                                                     deltaPix,
                                                     exposure_time=1,
                                                     background_rms=1)
        data_class = ImageData(**kwargs_data)
        kernel = np.zeros((5, 5))
        kernel[2, 2] = 1
        kwargs_psf = {
            'kernel_point_source': kernel,
            'psf_type': 'PIXEL',
            'psf_error_map': np.ones_like(kernel) * 0.001
        }
        psf_class = PSF(**kwargs_psf)
        lens_model_class = LensModel(['SPEP'])
        source_model_class = LightModel([])
        lens_light_model_class = LightModel([])
        kwargs_numerics = {
            'supersampling_factor': 2,
            'supersampling_convolution': True,
            'point_source_supersampling_factor': 1
        }
        point_source_class = PointSource(
            point_source_type_list=['LENSED_POSITION'],
            fixed_magnification_list=[False])
        makeImage = ImageModel(data_class,
                               psf_class,
                               lens_model_class,
                               source_model_class,
                               lens_light_model_class,
                               point_source_class,
                               kwargs_numerics=kwargs_numerics)
        # chose point source positions
        x_pix = np.array([10, 5, 10, 90])
        y_pix = np.array([40, 50, 60, 50])
        ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix)
        e1, e2 = param_util.phi_q2_ellipticity(0, 0.8)
        kwargs_lens_init = [{
            'theta_E': 1,
            'gamma': 2,
            'e1': e1,
            'e2': e2,
            'center_x': 0,
            'center_y': 0
        }]
        kwargs_else = [{
            'ra_image': ra_pos,
            'dec_image': dec_pos,
            'point_amp': np.ones_like(ra_pos)
        }]
        image = makeImage.image(kwargs_lens_init,
                                kwargs_source={},
                                kwargs_lens_light={},
                                kwargs_ps=kwargs_else)
        #print(np.shape(model), 'test')
        #image = makeImage.ImageNumerics.array2image(model)
        for i in range(len(x_pix)):
            npt.assert_almost_equal(image[y_pix[i], x_pix[i]], 1, decimal=2)

        x_pix = np.array([10.5, 5.5, 10.5, 90.5])
        y_pix = np.array([40, 50, 60, 50])
        ra_pos, dec_pos = makeImage.Data.map_pix2coord(x_pix, y_pix)
        phi, q = 0., 0.8
        e1, e2 = param_util.phi_q2_ellipticity(phi, q)
        kwargs_lens_init = [{
            'theta_E': 1,
            'gamma': 2,
            'e1': e1,
            'e2': e2,
            'center_x': 0,
            'center_y': 0
        }]
        kwargs_else = [{
            'ra_image': ra_pos,
            'dec_image': dec_pos,
            'point_amp': np.ones_like(ra_pos)
        }]
        image = makeImage.image(kwargs_lens_init,
                                kwargs_source={},
                                kwargs_lens_light={},
                                kwargs_ps=kwargs_else)
        #image = makeImage.ImageNumerics.array2image(model)
        for i in range(len(x_pix)):
            print(int(y_pix[i]), int(x_pix[i] + 0.5))
            npt.assert_almost_equal(image[int(y_pix[i]),
                                          int(x_pix[i])],
                                    0.5,
                                    decimal=1)
            npt.assert_almost_equal(image[int(y_pix[i]),
                                          int(x_pix[i] + 0.5)],
                                    0.5,
                                    decimal=1)
示例#3
0
class TestData(object):

    def setup(self):
        self.deltaPix = 0.05
        fwhm = 0.2
        kwargs_gaussian = {'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncate': 5, 'pixel_size': self.deltaPix}
        self.psf_gaussian = PSF(kwargs_psf=kwargs_gaussian)
        kernel_point_source = kernel_util.kernel_gaussian(kernel_numPix=21, deltaPix=self.deltaPix, fwhm=fwhm)
        kwargs_pixel = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source}
        self.psf_pixel = PSF(kwargs_psf=kwargs_pixel)

    def test_kernel_point_source(self):
        kernel_gaussian = self.psf_gaussian.kernel_point_source
        kernel_pixel = self.psf_pixel.kernel_point_source
        assert len(kernel_gaussian) == 21
        assert len(kernel_pixel) == 21

    def test_psf_convolution(self):

        deltaPix = 0.05
        fwhm = 0.2
        fwhm_object = 0.1
        kwargs_gaussian = {'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncate': 5, 'pixel_size': deltaPix}
        psf_gaussian = PSF(kwargs_psf=kwargs_gaussian)
        kernel_point_source = kernel_util.kernel_gaussian(kernel_numPix=21, deltaPix=deltaPix, fwhm=fwhm)
        kwargs_pixel = {'psf_type': 'PIXEL', 'kernel_point_source': kernel_point_source}
        psf_pixel = PSF(kwargs_psf=kwargs_pixel)

        subgrid_res_input = 15

        grid = kernel_util.kernel_gaussian(kernel_numPix=11*subgrid_res_input, deltaPix=deltaPix / float(subgrid_res_input), fwhm=fwhm_object)
        grid_true = image_util.re_size(grid, subgrid_res_input)
        grid_conv = psf_gaussian.psf_convolution(grid, deltaPix / float(subgrid_res_input))
        grid_conv_true = image_util.re_size(grid_conv, subgrid_res_input)

        # subgrid resoluton Gaussian convolution
        for i in range(1, subgrid_res_input+1):

            subgrid_res = i

            grid = kernel_util.kernel_gaussian(kernel_numPix=11*subgrid_res, deltaPix=deltaPix / float(subgrid_res), fwhm=fwhm_object)
            grid_conv = psf_gaussian.psf_convolution(grid, deltaPix / float(subgrid_res))
            grid_conv_finite = image_util.re_size(grid_conv, subgrid_res)
            min_diff = np.min(grid_conv_true-grid_conv_finite)
            max_diff = np.max(grid_conv_true-grid_conv_finite)
            print(min_diff, max_diff)
        npt.assert_almost_equal(min_diff, 0, decimal=7)
        npt.assert_almost_equal(max_diff, 0, decimal=7)
        # subgrid resoluton Pixel convolution
        for i in range(1,subgrid_res_input+1):

            subgrid_res = i

            grid = kernel_util.kernel_gaussian(kernel_numPix=11*subgrid_res, deltaPix=deltaPix / float(subgrid_res), fwhm=fwhm_object)
            grid_conv = psf_pixel.psf_convolution(grid, deltaPix / float(subgrid_res), subgrid_res=subgrid_res, psf_subgrid=True)
            grid_conv_finite = image_util.re_size(grid_conv, subgrid_res)
            min_diff = np.min(grid_conv_true-grid_conv_finite)
            max_diff = np.max(grid_conv_true-grid_conv_finite)
            print(min_diff, max_diff)
        npt.assert_almost_equal(min_diff, 0, decimal=3)
        npt.assert_almost_equal(max_diff, 0, decimal=3)
        # subgrid ray-tracing but pixel convolution on normal grid
        for i in range(1,subgrid_res_input+1):

            subgrid_res = i

            grid = kernel_util.kernel_gaussian(kernel_numPix=11*subgrid_res, deltaPix=deltaPix / float(subgrid_res), fwhm=0.2)
            grid_finite = image_util.re_size(grid, subgrid_res)
            grid_conv_finite = psf_pixel.psf_convolution(grid_finite, deltaPix, subgrid_res=1)
            min_diff = np.min(grid_conv_true-grid_conv_finite)
            max_diff = np.max(grid_conv_true-grid_conv_finite)
            print(min_diff, max_diff)
        npt.assert_almost_equal(min_diff, 0, decimal=3)
        npt.assert_almost_equal(max_diff, 0, decimal=3)

    def test_kernel_subsampled(self):
        deltaPix = 0.05  # pixel size of image
        numPix = 40  # number of pixels per axis
        subsampling_res = 3  # subsampling scale factor (in each dimension)
        fwhm = 0.3  # FWHM of the PSF kernel
        fwhm_object = 0.2  # FWHM of the Gaussian source to be convolved

        # create Gaussian/Pixelized kernels
        # first we create the sub-sampled kernel
        kernel_point_source_subsampled = kernel_util.kernel_gaussian(kernel_numPix=11*subsampling_res, deltaPix=deltaPix/subsampling_res, fwhm=fwhm)
        # to have the same consistent kernel, we re-size (average over the sub-sampled pixels) the sub-sampled kernel
        kernel_point_source = image_util.re_size(kernel_point_source_subsampled, subsampling_res)
        # here we create the two PSF() classes
        kwargs_pixel_subsampled = {'psf_type': 'PIXEL', 'kernel_point_source_subsampled': kernel_point_source_subsampled, 'point_source_subsampling_factor': subsampling_res}
        psf_pixel_subsampled = PSF(kwargs_psf=kwargs_pixel_subsampled)
        kwargs_pixel = {'psf_type': 'PIXEL',
                        'kernel_point_source': kernel_point_source}
        psf_pixel = PSF(kwargs_psf=kwargs_pixel)

        # here we create the image of the Gaussian source and convolve it with the regular kernel
        image_unconvolved = kernel_util.kernel_gaussian(kernel_numPix=numPix, deltaPix=deltaPix, fwhm=fwhm_object)
        image_convolved_regular = psf_pixel.psf_convolution_new(image_unconvolved, subgrid_res=1, subsampling_size=None)

        # here we create the image by computing the sub-sampled Gaussian source and convolve it with the sub-sampled PSF kernel
        image_unconvolved_highres = kernel_util.kernel_gaussian(kernel_numPix=numPix*subsampling_res, deltaPix=deltaPix/subsampling_res, fwhm=fwhm_object) * subsampling_res**2
        image_convolved_subsampled = psf_pixel_subsampled.psf_convolution_new(image_unconvolved_highres, subgrid_res=subsampling_res, subsampling_size=5)

        # We demand the two procedures to be the same up to the numerics affecting the finite resolution
        npt.assert_almost_equal(np.sum(image_convolved_regular), np.sum(image_convolved_subsampled), decimal=8)
        npt.assert_almost_equal((image_convolved_subsampled - image_convolved_regular) / (np.max(image_convolved_subsampled)), 0, decimal=2)

    def test_fwhm(self):
        deltaPix = 0.05
        fwhm = 0.1
        kwargs = {'psf_type': 'GAUSSIAN', 'fwhm': fwhm, 'truncate': 5, 'pixel_size': deltaPix}
        fwhm_compute = self.psf_gaussian.psf_fwhm(kwargs=kwargs, deltaPix=deltaPix)
        assert fwhm_compute == fwhm

        kernel = kernel_util.kernel_gaussian(kernel_numPix=11, deltaPix=deltaPix, fwhm=fwhm)
        kwargs = {'psf_type': 'PIXEL',  'truncate': 5, 'pixel_size': deltaPix, 'kernel_point_source': kernel}
        fwhm_compute = self.psf_gaussian.psf_fwhm(kwargs=kwargs, deltaPix=deltaPix)
        npt.assert_almost_equal(fwhm_compute, fwhm, decimal=6)

        kwargs = {'psf_type': 'PIXEL', 'truncate': 5, 'pixel_size': deltaPix, 'kernel_point_source_subsampled': kernel}
        fwhm_compute = self.psf_gaussian.psf_fwhm(kwargs=kwargs, deltaPix=deltaPix)
        npt.assert_almost_equal(fwhm_compute, fwhm, decimal=6)
    def setup(self):
        self.SimAPI = Simulation()

        # data specifics
        sigma_bkg = 1.  # background noise per pixel
        exp_time = 10  # 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 = self.SimAPI.data_configure(numPix, deltaPix, exp_time,
                                                 sigma_bkg)
        data_class = Data(kwargs_data)

        kwargs_psf = self.SimAPI.psf_configure(psf_type='GAUSSIAN',
                                               fwhm=fwhm,
                                               kernelsize=31,
                                               deltaPix=deltaPix,
                                               truncate=5)
        psf_class = PSF(kwargs_psf)

        # 'EXERNAL_SHEAR': external shear
        kwargs_shear = {
            'e1': 0.01,
            'e2': 0.01
        }  # gamma_ext: shear strength, psi_ext: shear angel (in radian)
        e1, e2 = param_util.phi_q2_ellipticity(0.2, 0.8)
        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
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 7,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.2,
            'e2': 0.3
        }

        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': 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 = {'subgrid_res': 2, 'psf_subgrid': True}
        self.imageModel = ImageModel(data_class,
                                     psf_class,
                                     lens_model_class,
                                     source_model_class,
                                     lens_light_model_class,
                                     point_source_class,
                                     kwargs_numerics=kwargs_numerics)
示例#5
0
    def setup(self):

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # 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

        self.kwargs_data = sim_util.data_configure_simple(
            numPix, deltaPix, exp_time, sigma_bkg)
        data_class = ImageData(**self.kwargs_data)
        kwargs_psf_gaussian = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_gaussian = PSF(**kwargs_psf_gaussian)
        self.kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf_gaussian.kernel_point_source,
            'psf_error_map': np.zeros_like(psf_gaussian.kernel_point_source)
        }
        psf_class = PSF(**self.kwargs_psf)
        # 'EXTERNAL_SHEAR': external shear
        kwargs_shear = {
            'e1': 0.01,
            'e2': 0.01
        }  # gamma_ext: shear strength, psi_ext: shear angel (in radian)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_model_list = ['SPEP', 'SHEAR']
        self.kwargs_lens = [kwargs_spemd, kwargs_shear]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {
            'amp': 1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        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': 1.
            }
        ]  # quasar point source position in the source plane and intrinsic brightness
        point_source_list = ['SOURCE_POSITION']
        point_source_class = PointSource(
            point_source_type_list=point_source_list,
            fixed_magnification_list=[True])
        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False,
            'compute_mode': 'regular',
            'point_source_supersampling_factor': 1
        }
        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.data_class = data_class
        self.psf_class = psf_class
        self.kwargs_data['image_data'] = image_sim
        self.kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'lens_light_model_list': lens_light_model_list,
            'point_source_model_list': point_source_list,
            'fixed_magnification_list': [False],
            'index_lens_model_list': [[0, 1]],
        }
        self.kwargs_numerics = kwargs_numerics

        num_source_model = len(source_model_list)

        self.kwargs_constraints = {
            'num_point_source_list': [4],
            'image_plane_source_list': [False] * num_source_model,
            'solver_type':
            'NONE',  # 'PROFILE', 'PROFILE_SHEAR', 'ELLIPSE', 'CENTER'
        }

        self.kwargs_likelihood = {
            'force_no_add_image': True,
            'source_marg': True,
            'linear_prior': [1],
            'position_uncertainty': 0.004,
            'check_solver': False,
            'solver_tolerance': 0.001,
            'check_positive_flux': True,
        }
示例#6
0
def sim_non_lens_gal(data,
                     numPix=101,
                     sigma_bkg=8.0,
                     exp_time=100.0,
                     deltaPix=0.263,
                     psf_type='GAUSSIAN',
                     kernel_size=91):

    full_band_images = np.zeros((numPix, numPix, 4))
    center_x_1 = np.random.uniform(-0.03, 0.03)
    center_y_1 = np.random.uniform(-0.03, 0.03)
    flux_1 = mag_to_flux(data['source_mag'], 27.5)
    flux_2 = mag_to_flux(data['lens_mag'], 27.5)

    light_model_list = ['SERSIC_ELLIPSE', 'SERSIC']
    lightModel = LightModel(light_model_list=light_model_list)

    kwargs_disk = {
        'amp': flux_1,
        'R_sersic': data['source_R_sersic'],
        'n_sersic': data['source_n_sersic'],
        'e1': data['source_e1'],
        'e2': data['source_e2'],
        'center_x': center_x_1,
        'center_y': center_y_1
    }
    kwargs_bulge = {
        'amp': flux_2,
        'R_sersic': data['lens_R_sersic'],
        'n_sersic': data['lens_n_sersic'],
        'center_x': center_x_1,
        'center_y': center_y_1
    }

    kwargs_host = [kwargs_disk, kwargs_bulge]

    color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3}

    for band in ['g', 'r', 'i', 'z']:

        kwargs_data = sim_util.data_configure_simple(numPix, deltaPix,
                                                     exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': psf_type,
            'fwhm': data['psf_%s' % band],
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_class = PSF(**kwargs_psf)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_light_model_class=lightModel,
                                kwargs_numerics=kwargs_numerics)

        image_sim = imageModel.image(kwargs_lens_light=kwargs_host)
        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

        full_band_images[:, :, color_idx[band]] += image_sim

    return full_band_images
示例#7
0
    def update_iterative(self,
                         kwargs_psf,
                         kwargs_params,
                         num_iter=10,
                         no_break=True,
                         stacking_method='median',
                         block_center_neighbour=0,
                         keep_psf_error_map=True,
                         psf_symmetry=1,
                         psf_iter_factor=0.2,
                         verbose=True):
        """

        :param kwargs_psf:
        :param kwargs_params:
        :param num_iter:
        :param no_break:
        :param stacking_method:
        :param block_center_neighbour:
        :param keep_psf_error_map:
        :param psf_symmetry:
        :param psf_iter_factor:
        :param verbose:
        :return:
        """
        self._image_model_class.PointSource.set_save_cache(True)
        if not 'kernel_point_source_init' in kwargs_psf:
            kernel_point_source_init = copy.deepcopy(
                kwargs_psf['kernel_point_source'])
        else:
            kernel_point_source_init = kwargs_psf['kernel_point_source_init']
        kwargs_psf_new = copy.deepcopy(kwargs_psf)
        kwargs_psf_final = copy.deepcopy(kwargs_psf)
        if 'psf_error_map' in kwargs_psf:
            error_map_final = kwargs_psf['psf_error_map']
        else:
            error_map_final = np.zeros_like(kernel_point_source_init)
        error_map_init = copy.deepcopy(error_map_final)
        psf_class = PSF(**kwargs_psf)
        self._image_model_class.update_psf(psf_class)
        logL_before = self._image_model_class.likelihood_data_given_model(
            **kwargs_params)
        logL_best = copy.deepcopy(logL_before)
        i_best = 0
        for i in range(num_iter):
            kwargs_psf_new, logL_after, error_map = self.update_psf(
                kwargs_psf_new,
                kwargs_params,
                stacking_method=stacking_method,
                psf_symmetry=psf_symmetry,
                psf_iter_factor=psf_iter_factor,
                block_center_neighbour=block_center_neighbour)
            if logL_after > logL_best:
                kwargs_psf_final = copy.deepcopy(kwargs_psf_new)
                error_map_final = copy.deepcopy(error_map)
                logL_best = logL_after
                i_best = i + 1
            else:
                if not no_break:
                    if verbose:
                        print(
                            "iterative PSF reconstruction makes reconstruction worse in step %s - aborted"
                            % i)
                    break
        if verbose is True:
            print("iteration of step %s gave best reconstruction." % i_best)
            print("log likelihood before: %s and log likelihood after: %s" %
                  (logL_before, logL_best))
        if keep_psf_error_map is True:
            kwargs_psf_final['psf_error_map'] = error_map_init
        else:
            kwargs_psf_final['psf_error_map'] = error_map_final
        kwargs_psf_final['kernel_point_source_init'] = kernel_point_source_init
        return kwargs_psf_final
    def __init__(self,
                 multi_band_list,
                 kwargs_model,
                 likelihood_mask_list=None,
                 band_index=0,
                 kwargs_pixelbased=None,
                 linear_solver=True):
        """

        :param multi_band_list: list of imaging band configurations [[kwargs_data, kwargs_psf, kwargs_numerics],[...], ...]
        :param kwargs_model: model option keyword arguments
        :param likelihood_mask_list: list of likelihood masks (booleans with size of the individual images
        :param band_index: integer, index of the imaging band to model
        :param kwargs_pixelbased: keyword arguments with various settings related to the pixel-based solver
         (see SLITronomy documentation)
        :param linear_solver: bool, if True (default) fixes the linear amplitude parameters 'amp' (avoid sampling) such
         that they get overwritten by the linear solver solution.
        """
        self.type = 'single-band-multi-model'
        if likelihood_mask_list is None:
            likelihood_mask_list = [None for i in range(len(multi_band_list))]
        lens_model_class, source_model_class, lens_light_model_class, point_source_class, extinction_class = class_creator.create_class_instances(
            band_index=band_index, **kwargs_model)
        kwargs_data = multi_band_list[band_index][0]
        kwargs_psf = multi_band_list[band_index][1]
        kwargs_numerics = multi_band_list[band_index][2]
        data_i = ImageData(**kwargs_data)
        psf_i = PSF(**kwargs_psf)

        index_lens_model_list = kwargs_model.get(
            'index_lens_model_list',
            [None for i in range(len(multi_band_list))])
        self._index_lens_model = index_lens_model_list[band_index]
        index_source_list = kwargs_model.get(
            'index_source_light_model_list',
            [None for i in range(len(multi_band_list))])
        self._index_source = index_source_list[band_index]
        index_lens_light_list = kwargs_model.get(
            'index_lens_light_model_list',
            [None for i in range(len(multi_band_list))])
        self._index_lens_light = index_lens_light_list[band_index]
        index_point_source_list = kwargs_model.get(
            'index_point_source_model_list',
            [None for i in range(len(multi_band_list))])
        self._index_point_source = index_point_source_list[band_index]
        index_optical_depth = kwargs_model.get(
            'index_optical_depth_model_list',
            [None for i in range(len(multi_band_list))])
        self._index_optical_depth = index_optical_depth[band_index]
        self._linear_solver = linear_solver

        super(SingleBandMultiModel,
              self).__init__(data_i,
                             psf_i,
                             lens_model_class,
                             source_model_class,
                             lens_light_model_class,
                             point_source_class,
                             extinction_class,
                             kwargs_numerics=kwargs_numerics,
                             likelihood_mask=likelihood_mask_list[band_index],
                             kwargs_pixelbased=kwargs_pixelbased)
    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 = Data(kwargs_data)
        kwargs_psf = sim_util.psf_configure_simple(psf_type='GAUSSIAN',
                                                   fwhm=fwhm,
                                                   kernelsize=31,
                                                   deltaPix=deltaPix,
                                                   truncate=5)
        psf_class = PSF(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.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 = {'subgrid_res': 2, '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)
        kwargs_data['image_data'] = image_sim
        self.solver = LensEquationSolver(lensModel=lens_model_class)
        idex_lens_1 = [0, 1]
        idex_lens_2 = [2, 3]
        multi_band_list = [[
            kwargs_data, kwargs_psf, kwargs_numerics, {
                'index_lens_model_list': idex_lens_1
            }
        ],
                           [
                               kwargs_data, kwargs_psf, kwargs_numerics, {
                                   'index_lens_model_list': idex_lens_2
                               }
                           ]]
        lens_model_list_joint = lens_model_list + lens_model_list
        self.kwargs_lens_joint = self.kwargs_lens + self.kwargs_lens
        self.imageModel = MultiFrame(multi_band_list, lens_model_list_joint,
                                     source_model_class,
                                     lens_light_model_class,
                                     point_source_class)
示例#10
0
kwargs_data = sim_util.data_configure_simple(81,
                                             0.04,
                                             1000,
                                             0.001,
                                             inverse=True)
data_class = Data(kwargs_data)
data_class.update_data(agn_image)
kernel_size = len(psf)
kernel = psf
kwargs_psf = sim_util.psf_configure_simple(psf_type='PIXEL',
                                           fwhm=0.2,
                                           kernelsize=kernel_size,
                                           deltaPix=0.04,
                                           kernel=kernel)
from lenstronomy.Data.psf import PSF
psf_class = PSF(kwargs_psf)

from lenstronomy.LightModel.light_model import LightModel
light_model_list = ['SERSIC_ELLIPSE'] * len(source_params_2)
lightModel = LightModel(light_model_list=light_model_list)

from lenstronomy.PointSource.point_source import PointSource
pointSource = PointSource(point_source_type_list=point_source_list)
kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}
#kwargs_numerics['mask'] = QSO_msk
imageModel = ImageModel(data_class,
                        psf_class,
                        source_model_class=lightModel,
                        point_source_class=pointSource,
                        kwargs_numerics=kwargs_numerics)
    def setup(self):
        self.SimAPI = Simulation()

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

        # PSF specification

        self.kwargs_data = self.SimAPI.data_configure(numPix, deltaPix, exp_time, sigma_bkg)
        data_class = Data(self.kwargs_data)
        kwargs_psf = self.SimAPI.psf_configure(psf_type='GAUSSIAN', fwhm=fwhm, kernelsize=11, deltaPix=deltaPix,
                                               truncate=3,
                                               kernel=None)
        self.kwargs_psf = self.SimAPI.psf_configure(psf_type='PIXEL', fwhm=fwhm, kernelsize=11, deltaPix=deltaPix,
                                                    truncate=6,
                                                    kernel=kwargs_psf['kernel_point_source'])
        psf_class = 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)
        kwargs_spemd = {'theta_E': 1., 'gamma': 1.8, 'center_x': 0, 'center_y': 0, 'e1': 0.1, 'e2': 0.1}

        lens_model_list = ['SPEP', 'SHEAR']
        self.kwargs_lens = [kwargs_spemd, kwargs_shear]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {'amp': 1., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0}
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {'amp': 1., 'R_sersic': .6, 'n_sersic': 3, 'center_x': 0, 'center_y': 0,
                                 'e1': 0.1, 'e2': 0.1}

        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': 1.}]  # quasar point source position in the source plane and intrinsic brightness
        point_source_list = ['SOURCE_POSITION']
        point_source_class = PointSource(point_source_type_list=point_source_list, fixed_magnification_list=[True])
        kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}
        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 = self.SimAPI.simulate(imageModel, self.kwargs_lens, self.kwargs_source,
                                         self.kwargs_lens_light, self.kwargs_ps)

        data_class.update_data(image_sim)
        self.data_class = data_class
        self.psf_class = psf_class
        self.kwargs_data['image_data'] = image_sim
        self.kwargs_model = {'lens_model_list': lens_model_list,
                               'source_light_model_list': source_model_list,
                               'lens_light_model_list': lens_light_model_list,
                               'point_source_model_list': point_source_list,
                               'fixed_magnification_list': [False],
                             }
        self.kwargs_numerics = {
                               'subgrid_res': 1,
                               'psf_subgrid': False}

        num_source_model = len(source_model_list)

        self.kwargs_constraints = {'joint_center_lens_light': False,
                              'joint_center_source_light': False,
                              'num_point_source_list': [4],
                              'additional_images_list': [False],
                              'fix_to_point_source_list': [False] * num_source_model,
                              'image_plane_source_list': [False] * num_source_model,
                              'solver': False,
                              'solver_type': 'PROFILE_SHEAR',  # 'PROFILE', 'PROFILE_SHEAR', 'ELLIPSE', 'CENTER'
                              }

        self.kwargs_likelihood = {'force_no_add_image': True,
                             'source_marg': True,
                             'point_source_likelihood': False,
                             'position_uncertainty': 0.004,
                             'check_solver': False,
                             'solver_tolerance': 0.001,
                             'check_positive_flux': True,
                             }
示例#12
0
    def setup(self):
        self.num_pix = 49  # cutout pixel size
        self.subgrid_res_source = 2
        self.num_pix_source = self.num_pix * self.subgrid_res_source
        self.background_rms = 0.05
        self.noise_map = self.background_rms * np.ones(
            (self.num_pix, self.num_pix))

        delta_pix = 0.24
        _, _, ra_at_xy_0, dec_at_xy_0, _, _, Mpix2coord, _ \
            = l_util.make_grid_with_coordtransform(numPix=self.num_pix, deltapix=delta_pix, subgrid_res=1,
                                                         inverse=False, left_lower=False)

        self.image_data = np.random.rand(self.num_pix, self.num_pix)
        kwargs_data = {
            'ra_at_xy_0': ra_at_xy_0,
            'dec_at_xy_0': dec_at_xy_0,
            'transform_pix2angle': Mpix2coord,
            'image_data': self.image_data,
            'background_rms': self.background_rms,
            'noise_map': self.noise_map,
        }
        data = ImageData(**kwargs_data)

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

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

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

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

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

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

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

        self.noise_class = NoiseLevels(
            data,
            subgrid_res_source=self.subgrid_res_source,
            include_regridding_error=False)
        self.noise_class_regrid = NoiseLevels(
            data,
            subgrid_res_source=self.subgrid_res_source,
            include_regridding_error=True)
示例#13
0
def fit_qso_multiband(QSO_im_list, psf_ave_list, psf_std_list=None, source_params=None,ps_param=None,
                      background_rms_list=[0.04]*5, pix_sz = 0.168,
                      exp_time = 300., fix_n=None, image_plot = True, corner_plot=True,
                      flux_ratio_plot=True, deep_seed = False, fixcenter = False, QSO_msk_list=None,
                      QSO_std_list=None, tag = None, no_MCMC= False, pltshow = 1, new_band_seq=None):
    '''
    A quick fit for the QSO image with (so far) single sersice + one PSF. The input psf noise is optional.
    
    Parameter
    --------
        QSO_im: An array of the QSO image.
        psf_ave: The psf image.
        psf_std: The psf noise, optional.
        source_params: The prior for the source. Default is given.
        background_rms: default as 0.04
        exp_time: default at 2400.
        deep_seed: if Ture, more mcmc steps will be performed.
        tag: The name tag for save the plot
            
    Return
    --------
        Will output the fitted image (Set image_plot = True), the corner_plot and the flux_ratio_plot.
        source_result, ps_result, image_ps, image_host
    
    To do
    --------
        
    '''
    # data specifics need to set up based on the data situation
    background_rms_list = background_rms_list  #  background noise per pixel (Gaussian)
    exp_time = exp_time  #  exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
    numPix = len(QSO_im_list[0])  #  cutout pixel size
    deltaPix = pix_sz
    psf_type = 'PIXEL'  # 'gaussian', 'pixel', 'NONE'
    kernel_list = psf_ave_list
    if new_band_seq == None:
        new_band_seq= range(len(QSO_im_list))
    
#    if psf_std_list is not None:
#        kwargs_numerics_list = [{'subgrid_res': 1, 'psf_subgrid': False, 'psf_error_map': True}] * len(QSO_im_list)     #Turn on the PSF error map
#    else: 
    kwargs_numerics_list = [{'supersampling_factor': 1, 'supersampling_convolution': False}] * len(QSO_im_list)
    
    if source_params is None:
        # here are the options for the host galaxy fitting
        fixed_source = []
        kwargs_source_init = []
        kwargs_source_sigma = []
        kwargs_lower_source = []
        kwargs_upper_source = []
        
        # Disk component, as modelled by an elliptical Sersic profile
        if fix_n == None:
            fixed_source.append({})  # we fix the Sersic index to n=1 (exponential)
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': 2., 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.5, 'R_sersic': 0.5, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.1, 'n_sersic': 0.3, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3., 'n_sersic': 7., 'center_x': 10, 'center_y': 10})
        elif fix_n is not None:
            fixed_source.append({'n_sersic': fix_n})
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': fix_n, 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.001, 'R_sersic': 0.5, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.1, 'n_sersic': fix_n, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3, 'n_sersic': fix_n, 'center_x': 10, 'center_y': 10})
        source_params = [kwargs_source_init, kwargs_source_sigma, fixed_source, kwargs_lower_source, kwargs_upper_source]
    else:
        source_params = source_params
    
    if ps_param is None:
        center_x = 0.0
        center_y = 0.0
        point_amp = QSO_im_list[0].sum()/2.
        fixed_ps = [{}]
        kwargs_ps = [{'ra_image': [center_x], 'dec_image': [center_y], 'point_amp': [point_amp]}]
        kwargs_ps_init = kwargs_ps
        kwargs_ps_sigma = [{'ra_image': [0.01], 'dec_image': [0.01]}]
        kwargs_lower_ps = [{'ra_image': [-10], 'dec_image': [-10]}]
        kwargs_upper_ps = [{'ra_image': [10], 'dec_image': [10]}]
        ps_param = [kwargs_ps_init, kwargs_ps_sigma, fixed_ps, kwargs_lower_ps, kwargs_upper_ps]
    else:
        ps_param = ps_param
    
    kwargs_params = {'source_model': source_params,
                     'point_source_model': ps_param}
    
    #==============================================================================
    #Doing the QSO fitting 
    #==============================================================================
    kwargs_data_list, data_class_list = [], []
    for i in range(len(QSO_im_list)):
        kwargs_data_i = sim_util.data_configure_simple(numPix, deltaPix, exp_time, background_rms_list[i], inverse=True)
        kwargs_data_list.append(kwargs_data_i)
        data_class_list.append(ImageData(**kwargs_data_i))
    kwargs_psf_list = []
    psf_class_list = []
    for i in range(len(QSO_im_list)):
        kwargs_psf_i = {'psf_type': psf_type, 'kernel_point_source': kernel_list[i]}
        kwargs_psf_list.append(kwargs_psf_i)
        psf_class_list.append(PSF(**kwargs_psf_i))
        data_class_list[i].update_data(QSO_im_list[i])
    
    light_model_list = ['SERSIC_ELLIPSE'] * len(source_params[0])
    lightModel = LightModel(light_model_list=light_model_list)
    point_source_list = ['UNLENSED']
    pointSource = PointSource(point_source_type_list=point_source_list)
    
    imageModel_list = []
    for i in range(len(QSO_im_list)):
        kwargs_data_list[i]['image_data'] = QSO_im_list[i]
#        if QSO_msk_list is not None:
#            kwargs_numerics_list[i]['mask'] = QSO_msk_list[i]
        if QSO_std_list is not None:
            kwargs_data_list[i]['noise_map'] = QSO_std_list[i]
#        if psf_std_list is not None:
#            kwargs_psf_list[i]['psf_error_map'] = psf_std_list[i]
    
    image_band_list = []
    for i in range(len(QSO_im_list)):
        imageModel_list.append(ImageModel(data_class_list[i], psf_class_list[i], source_model_class=lightModel,
                                        point_source_class=pointSource, kwargs_numerics=kwargs_numerics_list[i]))
                  
        
        image_band_list.append([kwargs_data_list[i], kwargs_psf_list[i], kwargs_numerics_list[i]])
    multi_band_list = [image_band_list[i] for i in range(len(QSO_im_list))]
    
    # numerical options and fitting sequences
    
    kwargs_model = { 'source_light_model_list': light_model_list,
                    'point_source_model_list': point_source_list
                    }
    
    if fixcenter == False:
        kwargs_constraints = {'num_point_source_list': [1]
                              }
    elif fixcenter == True:
        kwargs_constraints = {'joint_source_with_point_source': [[0, 0]],
                              'num_point_source_list': [1]
                              }
    
    kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                         'source_marg': False,  #In likelihood_module.LikelihoodModule -- whether to fully invert the covariance matrix for marginalization
                          'check_positive_flux': True,       
                          'image_likelihood_mask_list': [QSO_msk_list]
                         }
    
#    mpi = False  # MPI possible, but not supported through that notebook.
    # The Params for the fitting. kwargs_init: initial input. kwargs_sigma: The parameter uncertainty. kwargs_fixed: fixed parameters;
    #kwargs_lower,kwargs_upper: Lower and upper limits.
    kwargs_data_joint = {'multi_band_list': multi_band_list, 'multi_band_type': 'multi-linear'}  # 'single-band', 'multi-linear', 'joint-linear'
    fitting_seq = FittingSequence(kwargs_data_joint, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params)
    
    if deep_seed == False:
        fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 80, 'n_iterations': 60, 'compute_bands': [True]+[False]*(len(QSO_im_list)-1)}],
            ['align_images', {'n_particles': 10, 'n_iterations': 10, 'compute_bands': [False]+[True]*(len(QSO_im_list)-1)}],
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 100, 'n_iterations': 200, 'compute_bands': [True]*len(QSO_im_list)}],
            ['MCMC', {'n_burn': 10, 'n_run': 20, 'walkerRatio': 50, 'sigma_scale': .1}]              
            ]
    elif deep_seed == True:
         fitting_kwargs_list = [
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 150, 'n_iterations': 60, 'compute_bands': [True]+[False]*(len(QSO_im_list)-1)}],
            ['align_images', {'n_particles': 20, 'n_iterations': 20, 'compute_bands': [False]+[True]*(len(QSO_im_list)-1)}],
            ['PSO', {'sigma_scale': 0.8, 'n_particles': 150, 'n_iterations': 200, 'compute_bands': [True]*len(QSO_im_list)}],
            ['MCMC', {'n_burn': 20, 'n_run': 40, 'walkerRatio': 50, 'sigma_scale': .1}]                 
            ]
    if no_MCMC == True:
        del fitting_kwargs_list[-1]
    
    start_time = time.time()
#    lens_result, source_result, lens_light_result, ps_result, cosmo_temp, chain_list, param_list, samples_mcmc, param_mcmc, dist_mcmc = fitting_seq.fit_sequence(fitting_kwargs_list)
    chain_list, param_list, samples_mcmc, param_mcmc, dist_mcmc = fitting_seq.fit_sequence(fitting_kwargs_list)
    lens_result, source_result, lens_light_result, ps_result, cosmo_temp = fitting_seq.best_fit()    
    end_time = time.time()
    print(end_time - start_time, 'total time needed for computation')
    print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
    source_result_list, ps_result_list = [], []
    image_reconstructed_list, error_map_list, image_ps_list, image_host_list, shift_RADEC_list=[], [], [], [],[]
    imageLinearFit_list = []
    for k in range(len(QSO_im_list)):
    # this is the linear inversion. The kwargs will be updated afterwards
        imageLinearFit_k = ImageLinearFit(data_class_list[k], psf_class_list[k], source_model_class=lightModel,
                                        point_source_class=pointSource, kwargs_numerics=kwargs_numerics_list[k])  
        image_reconstructed_k, error_map_k, _, _ = imageLinearFit_k.image_linear_solve(kwargs_source=source_result, kwargs_ps=ps_result)
        imageLinearFit_list.append(imageLinearFit_k) 
        
        [kwargs_data_k, kwargs_psf_k, kwargs_numerics_k] = fitting_seq.multi_band_list[k]
#        data_class_k = data_class_list[k] #ImageData(**kwargs_data_k)
#        psf_class_k = psf_class_list[k] #PSF(**kwargs_psf_k)
#        imageModel_k = ImageModel(data_class_k, psf_class_k, source_model_class=lightModel,
#                                point_source_class=pointSource, kwargs_numerics=kwargs_numerics_list[k])
        imageModel_k = imageModel_list[k]
        modelPlot = ModelPlot(multi_band_list[k], kwargs_model, lens_result, source_result,
                                 lens_light_result, ps_result, arrow_size=0.02, cmap_string="gist_heat", likelihood_mask=QSO_im_list[k])
        print("source_result", 'for', "k", source_result)
        image_host_k = []
        for i in range(len(source_result)):
            image_host_k.append(imageModel_list[k].source_surface_brightness(source_result,de_lensed=True,unconvolved=False, k=i))
        image_ps_k = imageModel_k.point_source(ps_result)
        # let's plot the output of the PSO minimizer
        
        image_reconstructed_list.append(image_reconstructed_k)
        source_result_list.append(source_result)
        ps_result_list.append(ps_result)
        error_map_list.append(error_map_k)
        image_ps_list.append(image_ps_k)
        image_host_list.append(image_host_k)
        if 'ra_shift' in fitting_seq.multi_band_list[k][0].keys():
            shift_RADEC_list.append([fitting_seq.multi_band_list[k][0]['ra_shift'], fitting_seq.multi_band_list[k][0]['dec_shift']])
        else:
            shift_RADEC_list.append([0,0])
        if image_plot:
            f, axes = plt.subplots(3, 3, figsize=(16, 16), sharex=False, sharey=False)
            modelPlot.data_plot(ax=axes[0,0], text="Data")
            modelPlot.model_plot(ax=axes[0,1])
            modelPlot.normalized_residual_plot(ax=axes[0,2], v_min=-6, v_max=6)
            
            modelPlot.decomposition_plot(ax=axes[1,0], text='Host galaxy', source_add=True, unconvolved=True)
            modelPlot.decomposition_plot(ax=axes[1,1], text='Host galaxy convolved', source_add=True)
            modelPlot.decomposition_plot(ax=axes[1,2], text='All components convolved', source_add=True, lens_light_add=True, point_source_add=True)
            
            modelPlot.subtract_from_data_plot(ax=axes[2,0], text='Data - Point Source', point_source_add=True)
            modelPlot.subtract_from_data_plot(ax=axes[2,1], text='Data - host galaxy', source_add=True)
            modelPlot.subtract_from_data_plot(ax=axes[2,2], text='Data - host galaxy - Point Source', source_add=True, point_source_add=True)
            f.tight_layout()
            if tag is not None:
                f.savefig('{0}_fitted_image_band{1}.pdf'.format(tag,new_band_seq[k]))
            if pltshow == 0:
                plt.close()
            else:
                plt.show()
            
            if corner_plot==True and no_MCMC==False and k ==0:
                # here the (non-converged) MCMC chain of the non-linear parameters
                if not samples_mcmc == []:
                   n, num_param = np.shape(samples_mcmc)
                   plot = corner.corner(samples_mcmc, labels=param_mcmc, show_titles=True)
                   if tag is not None:
                       plot.savefig('{0}_para_corner.pdf'.format(tag))
                   if pltshow == 0:
                       plt.close()
                   else:
                       plt.show()
            if flux_ratio_plot==True and no_MCMC==False:
                param = Param(kwargs_model, kwargs_fixed_source=source_params[2], kwargs_fixed_ps=fixed_ps, **kwargs_constraints)
                mcmc_new_list = []
                labels_new = [r"Quasar flux", r"host_flux", r"source_x", r"source_y"]
                # transform the parameter position of the MCMC chain in a lenstronomy convention with keyword arguments #
                for i in range(len(samples_mcmc)/10):
                    kwargs_lens_out, kwargs_light_source_out, kwargs_light_lens_out, kwargs_ps_out, kwargs_cosmo = param.getParams(samples_mcmc[i+ len(samples_mcmc)/10*9])
                    image_reconstructed, _, _, _ = imageLinearFit_list[k].image_linear_solve(kwargs_source=kwargs_light_source_out, kwargs_ps=kwargs_ps_out)
                    
                    image_ps = imageModel_list[k].point_source(kwargs_ps_out)
                    flux_quasar = np.sum(image_ps)
                    image_disk = imageModel_list[k].source_surface_brightness(kwargs_light_source_out,de_lensed=True,unconvolved=False, k=0)
                    flux_disk = np.sum(image_disk)
                    source_x = kwargs_ps_out[0]['ra_image']
                    source_y = kwargs_ps_out[0]['dec_image']
                    if flux_disk>0:
                        mcmc_new_list.append([flux_quasar, flux_disk, source_x, source_y])
                plot = corner.corner(mcmc_new_list, labels=labels_new, show_titles=True)
                if tag is not None:
                    plot.savefig('{0}_HOSTvsQSO_corner_band{1}.pdf'.format(tag,new_band_seq[k]))
                if pltshow == 0:
                    plt.close()
                else:
                    plt.show()
    errp_list = []
    for k in range(len(QSO_im_list)):
        if QSO_std_list is None:
            errp_list.append(np.sqrt(data_class_list[k].C_D+np.abs(error_map_list[k])))
        else:
            errp_list.append(np.sqrt(QSO_std_list[k]**2+np.abs(error_map_list[k])))
    return source_result_list, ps_result_list, image_ps_list, image_host_list, errp_list, shift_RADEC_list, fitting_seq     #fitting_seq.multi_band_list
示例#14
0
def fit_qso(QSO_im, psf_ave, psf_std=None, source_params=None,ps_param=None, background_rms=0.04, pix_sz = 0.168,
            exp_time = 300., fix_n=None, image_plot = True, corner_plot=True, supersampling_factor = 2, 
            flux_ratio_plot=False, deep_seed = False, fixcenter = False, QSO_msk=None, QSO_std=None,
            tag = None, no_MCMC= False, pltshow = 1, return_Chisq = False, dump_result = False, pso_diag=False):
    '''
    A quick fit for the QSO image with (so far) single sersice + one PSF. The input psf noise is optional.
    
    Parameter
    --------
        QSO_im: An array of the QSO image.
        psf_ave: The psf image.
        psf_std: The psf noise, optional.
        source_params: The prior for the source. Default is given. If [], means no Sersic light.
        background_rms: default as 0.04
        exp_time: default at 2400.
        deep_seed: if Ture, more mcmc steps will be performed.
        tag: The name tag for save the plot
            
    Return
    --------
        Will output the fitted image (Set image_plot = True), the corner_plot and the flux_ratio_plot.
        source_result, ps_result, image_ps, image_host
    
    To do
    --------
        
    '''
    # data specifics need to set up based on the data situation
    background_rms = background_rms  #  background noise per pixel (Gaussian)
    exp_time = exp_time  #  exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
    numPix = len(QSO_im)  #  cutout pixel size
    deltaPix = pix_sz
    psf_type = 'PIXEL'  # 'gaussian', 'pixel', 'NONE'
    kernel = psf_ave

    kwargs_numerics = {'supersampling_factor': supersampling_factor, 'supersampling_convolution': False} 
    
    if source_params is None:
        # here are the options for the host galaxy fitting
        fixed_source = []
        kwargs_source_init = []
        kwargs_source_sigma = []
        kwargs_lower_source = []
        kwargs_upper_source = []
        
        if fix_n == None:
            fixed_source.append({})  # we fix the Sersic index to n=1 (exponential)
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': 2., 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.5, 'R_sersic': 0.5, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.1, 'n_sersic': 0.3, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3., 'n_sersic': 7., 'center_x': 10, 'center_y': 10})
        elif fix_n is not None:
            fixed_source.append({'n_sersic': fix_n})
            kwargs_source_init.append({'R_sersic': 0.3, 'n_sersic': fix_n, 'e1': 0., 'e2': 0., 'center_x': 0., 'center_y': 0.})
            kwargs_source_sigma.append({'n_sersic': 0.001, 'R_sersic': 0.5, 'e1': 0.1, 'e2': 0.1, 'center_x': 0.1, 'center_y': 0.1})
            kwargs_lower_source.append({'e1': -0.5, 'e2': -0.5, 'R_sersic': 0.1, 'n_sersic': fix_n, 'center_x': -10, 'center_y': -10})
            kwargs_upper_source.append({'e1': 0.5, 'e2': 0.5, 'R_sersic': 3, 'n_sersic': fix_n, 'center_x': 10, 'center_y': 10})
        source_params = [kwargs_source_init, kwargs_source_sigma, fixed_source, kwargs_lower_source, kwargs_upper_source]
    else:
        source_params = source_params
    
    if ps_param is None:
        center_x = 0.0
        center_y = 0.0
        point_amp = QSO_im.sum()/2.
        fixed_ps = [{}]
        kwargs_ps = [{'ra_image': [center_x], 'dec_image': [center_y], 'point_amp': [point_amp]}]
        kwargs_ps_init = kwargs_ps
        kwargs_ps_sigma = [{'ra_image': [0.05], 'dec_image': [0.05]}]
        kwargs_lower_ps = [{'ra_image': [-0.6], 'dec_image': [-0.6]}]
        kwargs_upper_ps = [{'ra_image': [0.6], 'dec_image': [0.6]}]
        ps_param = [kwargs_ps_init, kwargs_ps_sigma, fixed_ps, kwargs_lower_ps, kwargs_upper_ps]
    else:
        ps_param = ps_param
    
    #==============================================================================
    #Doing the QSO fitting 
    #==============================================================================
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time, background_rms, inverse=True)
    data_class = ImageData(**kwargs_data)
    kwargs_psf = {'psf_type': psf_type, 'kernel_point_source': kernel}
    psf_class = PSF(**kwargs_psf)
    data_class.update_data(QSO_im)
    
    point_source_list = ['UNLENSED'] * len(ps_param[0])
    pointSource = PointSource(point_source_type_list=point_source_list)
    
    if fixcenter == False:
        kwargs_constraints = {'num_point_source_list': [1] * len(ps_param[0])
                              }
    elif fixcenter == True:
        kwargs_constraints = {'joint_source_with_point_source': [[i, i] for i in range(len(ps_param[0]))],
                              'num_point_source_list': [1] * len(ps_param[0])
                              }
    
    
    if source_params == []:   #fitting image as Point source only.
        kwargs_params = {'point_source_model': ps_param}
        lightModel = None
        kwargs_model = {'point_source_model_list': point_source_list }
        imageModel = ImageModel(data_class, psf_class, point_source_class=pointSource, kwargs_numerics=kwargs_numerics)
        kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                             'image_likelihood_mask_list': [QSO_msk]
                     }
    elif source_params != []:
        kwargs_params = {'source_model': source_params,
                 'point_source_model': ps_param}

        light_model_list = ['SERSIC_ELLIPSE'] * len(source_params[0])
        lightModel = LightModel(light_model_list=light_model_list)
        kwargs_model = { 'source_light_model_list': light_model_list,
                        'point_source_model_list': point_source_list
                        }
        imageModel = ImageModel(data_class, psf_class, source_model_class=lightModel,
                                point_source_class=pointSource, kwargs_numerics=kwargs_numerics)
        # numerical options and fitting sequences
        kwargs_likelihood = {'check_bounds': True,  #Set the bonds, if exceed, reutrn "penalty"
                             'source_marg': False,  #In likelihood_module.LikelihoodModule -- whether to fully invert the covariance matrix for marginalization
                              'check_positive_flux': True, 
                              'image_likelihood_mask_list': [QSO_msk]
                             }
    
    kwargs_data['image_data'] = QSO_im
    if QSO_std is not None:
        kwargs_data['noise_map'] = QSO_std
    
    if psf_std is not None:
        kwargs_psf['psf_error_map'] = psf_std
    image_band = [kwargs_data, kwargs_psf, kwargs_numerics]
    multi_band_list = [image_band]

    kwargs_data_joint = {'multi_band_list': multi_band_list, 'multi_band_type': 'multi-linear'}  # 'single-band', 'multi-linear', 'joint-linear'
    fitting_seq = FittingSequence(kwargs_data_joint, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params)
    
    if deep_seed == False:
        fitting_kwargs_list = [
             ['PSO', {'sigma_scale': 0.8, 'n_particles': 100, 'n_iterations': 60}],
             ['MCMC', {'n_burn': 10, 'n_run': 10, 'walkerRatio': 50, 'sigma_scale': .1}]
            ]
    elif deep_seed == True:
         fitting_kwargs_list = [
             ['PSO', {'sigma_scale': 0.8, 'n_particles': 250, 'n_iterations': 250}],
             ['MCMC', {'n_burn': 100, 'n_run': 200, 'walkerRatio': 10, 'sigma_scale': .1}]
            ]
    if no_MCMC == True:
        fitting_kwargs_list = [fitting_kwargs_list[0],
                               ]        

    start_time = time.time()
    chain_list = fitting_seq.fit_sequence(fitting_kwargs_list)
    kwargs_result = fitting_seq.best_fit()
    ps_result = kwargs_result['kwargs_ps']
    source_result = kwargs_result['kwargs_source']
    if no_MCMC == False:
        sampler_type, samples_mcmc, param_mcmc, dist_mcmc  = chain_list[1]    
    
    end_time = time.time()
    print(end_time - start_time, 'total time needed for computation')
    print('============ CONGRATULATION, YOUR JOB WAS SUCCESSFUL ================ ')
    imageLinearFit = ImageLinearFit(data_class=data_class, psf_class=psf_class,
                                    source_model_class=lightModel,
                                    point_source_class=pointSource, 
                                    kwargs_numerics=kwargs_numerics)    
    image_reconstructed, error_map, _, _ = imageLinearFit.image_linear_solve(kwargs_source=source_result, kwargs_ps=ps_result)
    # this is the linear inversion. The kwargs will be updated afterwards
    modelPlot = ModelPlot(multi_band_list, kwargs_model, kwargs_result,
                          arrow_size=0.02, cmap_string="gist_heat", likelihood_mask_list=[QSO_msk])
    image_host = []  #!!! The linear_solver before and after LensModelPlot could have different result for very faint sources.
    for i in range(len(source_result)):
        image_host.append(imageModel.source_surface_brightness(source_result, de_lensed=True,unconvolved=False,k=i))
    
    image_ps = []
    for i in range(len(ps_result)):
        image_ps.append(imageModel.point_source(ps_result, k = i))
    
    if pso_diag == True:
        f, axes = chain_plot.plot_chain_list(chain_list,0)
        if pltshow == 0:
            plt.close()
        else:
            plt.show()

    # let's plot the output of the PSO minimizer
    reduced_Chisq =  imageLinearFit.reduced_chi2(image_reconstructed, error_map)
    if image_plot:
        f, axes = plt.subplots(3, 3, figsize=(16, 16), sharex=False, sharey=False)
        modelPlot.data_plot(ax=axes[0,0], text="Data")
        modelPlot.model_plot(ax=axes[0,1])
        modelPlot.normalized_residual_plot(ax=axes[0,2], v_min=-6, v_max=6)
        
        modelPlot.decomposition_plot(ax=axes[1,0], text='Host galaxy', source_add=True, unconvolved=True)
        modelPlot.decomposition_plot(ax=axes[1,1], text='Host galaxy convolved', source_add=True)
        modelPlot.decomposition_plot(ax=axes[1,2], text='All components convolved', source_add=True, lens_light_add=True, point_source_add=True)
        
        modelPlot.subtract_from_data_plot(ax=axes[2,0], text='Data - Point Source', point_source_add=True)
        modelPlot.subtract_from_data_plot(ax=axes[2,1], text='Data - host galaxy', source_add=True)
        modelPlot.subtract_from_data_plot(ax=axes[2,2], text='Data - host galaxy - Point Source', source_add=True, point_source_add=True)
        
        f.tight_layout()
        #f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05)
        if tag is not None:
            f.savefig('{0}_fitted_image.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
        
    if corner_plot==True and no_MCMC==False:
        # here the (non-converged) MCMC chain of the non-linear parameters
        if not samples_mcmc == []:
           n, num_param = np.shape(samples_mcmc)
           plot = corner.corner(samples_mcmc, labels=param_mcmc, show_titles=True)
           if tag is not None:
               plot.savefig('{0}_para_corner.pdf'.format(tag))
           plt.close()               
           # if pltshow == 0:
           #     plt.close()
           # else:
           #     plt.show()
        
    if flux_ratio_plot==True and no_MCMC==False:
        param = Param(kwargs_model, kwargs_fixed_source=source_params[2], kwargs_fixed_ps=ps_param[2], **kwargs_constraints)
        mcmc_new_list = []
        if len(ps_param[2]) == 1:
            labels_new = ["Quasar flux"] +  ["host{0} flux".format(i) for i in range(len(source_params[0]))]
        else:
            labels_new = ["Quasar{0} flux".format(i) for i in range(len(ps_param[2]))] +  ["host{0} flux".format(i) for i in range(len(source_params[0]))]
        if len(samples_mcmc) > 10000:
            trans_steps = [len(samples_mcmc)-10000, len(samples_mcmc)]
        else:
            trans_steps = [0, len(samples_mcmc)]
        for i in range(trans_steps[0], trans_steps[1]):
            kwargs_out = param.args2kwargs(samples_mcmc[i])
            kwargs_light_source_out = kwargs_out['kwargs_source']
            kwargs_ps_out =  kwargs_out['kwargs_ps']
            image_reconstructed, _, _, _ = imageLinearFit.image_linear_solve(kwargs_source=kwargs_light_source_out, kwargs_ps=kwargs_ps_out)
            flux_quasar = []
            if len(ps_param[0]) == 1:
                image_ps_j = imageModel.point_source(kwargs_ps_out)
                flux_quasar.append(np.sum(image_ps_j))  
            else:    
                for j in range(len(ps_param[0])):
                    image_ps_j = imageModel.point_source(kwargs_ps_out, k=j)
                    flux_quasar.append(np.sum(image_ps_j))
            fluxs = []
            for j in range(len(source_params[0])):
                image_j = imageModel.source_surface_brightness(kwargs_light_source_out,unconvolved= False, k=j)
                fluxs.append(np.sum(image_j))
            mcmc_new_list.append(flux_quasar + fluxs )
            if int(i/1000) > int((i-1)/1000) :
                print(len(samples_mcmc), "MCMC samplers in total, finished translate:", i )
        plot = corner.corner(mcmc_new_list, labels=labels_new, show_titles=True)
        if tag is not None:
            plot.savefig('{0}_HOSTvsQSO_corner.pdf'.format(tag))
        if pltshow == 0:
            plt.close()
        else:
            plt.show()
    if QSO_std is None:
        noise_map = np.sqrt(data_class.C_D+np.abs(error_map))
    else:
        noise_map = np.sqrt(QSO_std**2+np.abs(error_map))
    if dump_result == True:
        if flux_ratio_plot==True and no_MCMC==False:
            trans_paras = [mcmc_new_list, labels_new, 'mcmc_new_list, labels_new']
        else:
            trans_paras = []
        picklename= tag + '.pkl'
        best_fit = [source_result, image_host, ps_result, image_ps,'source_result, image_host, ps_result, image_ps']
        chain_list_result = [chain_list, 'chain_list']
        kwargs_fixed_source=source_params[2]
        kwargs_fixed_ps=ps_param[2]
        classes = data_class, psf_class, lightModel, pointSource
        material = multi_band_list, kwargs_model, kwargs_result, QSO_msk, kwargs_fixed_source, kwargs_fixed_ps, kwargs_constraints, kwargs_numerics, classes
        pickle.dump([best_fit, chain_list_result, trans_paras, material], open(picklename, 'wb'))
    if return_Chisq == False:
        return source_result, ps_result, image_ps, image_host, noise_map
    elif return_Chisq == True:
        return source_result, ps_result, image_ps, image_host, noise_map, reduced_Chisq
示例#15
0
    def update_iterative(self,
                         kwargs_psf,
                         kwargs_params,
                         num_iter=10,
                         no_break=True,
                         stacking_method='median',
                         block_center_neighbour=0,
                         keep_psf_error_map=True,
                         psf_symmetry=1,
                         psf_iter_factor=0.2,
                         error_map_radius=None,
                         verbose=True,
                         block_center_neighbour_error_map=0):
        """

        :param kwargs_psf: keyword arguments to construct the PSF() class
        :param kwargs_params: keyword arguments of the parameters of the model components (e.g. 'kwargs_lens' etc)
        :param stacking_method: 'median', 'mean'; the different estimates of the PSF are stacked and combined together.
         The choices are:
         'mean': mean of pixel values as the estimator (not robust to outliers)
         'median': median of pixel values as the estimator (outlier rejection robust but needs >2 point sources in the data
        :param num_iter: number of iterations in the PSF fitting and image fitting process
        :param no_break: boolean, if True, runs until the end regardless of the next step getting worse, and then
         reads out the overall best fit
        :param block_center_neighbour: angle, radius of neighbouring point sources around their centers the estimates
         is ignored. Default is zero, meaning a not optimal subtraction of the neighbouring point sources might
         contaminate the estimate.
        :param keep_psf_error_map: boolean, if True keeps previous psf_error_map
        :param psf_symmetry: number of rotational invariant symmetries in the estimated PSF.
         =1 mean no additional symmetries. =4 means 90 deg symmetry. This is enforced by a rotatioanl stack according to
         the symmetry specified. These additional imposed symmetries can help stabelize the PSF estimate when there are
         limited constraints/number of point sources in the image.
        :param psf_iter_factor: factor in (0, 1] of ratio of old vs new PSF in the update in the iteration.
        :param error_map_radius: float, radius (in arc seconds) of the outermost error in the PSF estimate
         (e.g. to avoid double counting of overlapping PSF errors)
        :param verbose:
        :return: keyword argument of PSF constructor for PSF() class
        """
        self._image_model_class.PointSource.set_save_cache(True)
        if not 'kernel_point_source_init' in kwargs_psf:
            kernel_point_source_init = copy.deepcopy(
                kwargs_psf['kernel_point_source'])
        else:
            kernel_point_source_init = kwargs_psf['kernel_point_source_init']
        kwargs_psf_new = copy.deepcopy(kwargs_psf)
        kwargs_psf_final = copy.deepcopy(kwargs_psf)
        if 'psf_error_map' in kwargs_psf:
            error_map_final = kwargs_psf['psf_error_map']
        else:
            error_map_final = np.zeros_like(kernel_point_source_init)
        error_map_init = copy.deepcopy(error_map_final)
        psf_class = PSF(**kwargs_psf)
        self._image_model_class.update_psf(psf_class)
        logL_before = self._image_model_class.likelihood_data_given_model(
            **kwargs_params)
        logL_best = copy.deepcopy(logL_before)
        i_best = 0
        for i in range(num_iter):
            kwargs_psf_new, logL_after, error_map = self.update_psf(
                kwargs_psf_new,
                kwargs_params,
                stacking_method=stacking_method,
                psf_symmetry=psf_symmetry,
                psf_iter_factor=psf_iter_factor,
                block_center_neighbour=block_center_neighbour,
                error_map_radius=error_map_radius,
                block_center_neighbour_error_map=
                block_center_neighbour_error_map)
            if logL_after > logL_best:
                kwargs_psf_final = copy.deepcopy(kwargs_psf_new)
                error_map_final = copy.deepcopy(error_map)
                logL_best = logL_after
                i_best = i + 1
            else:
                if not no_break:
                    if verbose:
                        print(
                            "iterative PSF reconstruction makes reconstruction worse in step %s - aborted"
                            % i)
                    break
        if verbose is True:
            print("iteration of step %s gave best reconstruction." % i_best)
            print("log likelihood before: %s and log likelihood after: %s" %
                  (logL_before, logL_best))
        if keep_psf_error_map is True:
            kwargs_psf_final['psf_error_map'] = error_map_init
        else:
            kwargs_psf_final['psf_error_map'] = error_map_final
        kwargs_psf_final['kernel_point_source_init'] = kernel_point_source_init
        return kwargs_psf_final
示例#16
0
def test_supersampling_simple():
    """

    :return:
    """
    from lenstronomy.Data.psf import PSF
    from lenstronomy.SimulationAPI.data_api import DataAPI

    detector_pixel_scale = 0.04
    numpix = 64
    supersampling_factor = 2
    # generate a Gaussian image

    x, y = util.make_grid(numPix=numpix * supersampling_factor,
                          deltapix=detector_pixel_scale / supersampling_factor)
    from lenstronomy.LightModel.Profiles.gaussian import Gaussian
    gaussian = Gaussian()
    image_1d = gaussian.function(x, y, amp=1, sigma=0.1)
    image = util.array2image(image_1d)

    # generate psf kernal supersampled
    kernel_super = kernel_util.kernel_gaussian(
        kernel_numPix=21 * supersampling_factor + 1,
        deltaPix=detector_pixel_scale / supersampling_factor,
        fwhm=0.2)

    psf_parameters = {
        'psf_type': 'PIXEL',
        'kernel_point_source': kernel_super,
        'point_source_supersampling_factor': supersampling_factor
    }
    kwargs_detector = {
        'pixel_scale': detector_pixel_scale,
        'ccd_gain': 2.5,
        'read_noise': 4.0,
        'magnitude_zero_point': 25.0,
        'exposure_time': 5400.0,
        'sky_brightness': 22,
        'num_exposures': 1,
        'background_noise': None
    }
    kwargs_numerics = {
        'supersampling_factor': 2,
        'supersampling_convolution': True,
        'point_source_supersampling_factor': 2,
        'supersampling_kernel_size': 21
    }
    psf_model = PSF(**psf_parameters)
    data_class = DataAPI(numpix=numpix, **kwargs_detector).data_class

    from lenstronomy.ImSim.Numerics.numerics_subframe import NumericsSubFrame
    image_numerics = NumericsSubFrame(pixel_grid=data_class,
                                      psf=psf_model,
                                      **kwargs_numerics)

    conv_class = image_numerics.convolution_class
    conv_flat = conv_class.convolution2d(image)
    print(np.shape(conv_flat), 'shape of output')

    # psf_helper = lenstronomy_utils.PSFHelper(data_class, psf_model, kwargs_numerics)

    # Convolve with lenstronomy and with scipy
    # helper_image = psf_helper.psf_model(image)
    from scipy import signal

    scipy_image = signal.fftconvolve(image, kernel_super, mode='same')
    from lenstronomy.Util import image_util
    image_scipy_resized = image_util.re_size(scipy_image, supersampling_factor)
    image_unconvolved = image_util.re_size(image, supersampling_factor)

    # Compare the outputs

    # low res convolution as comparison
    kwargs_numerics_low_res = {
        'supersampling_factor': 2,
        'supersampling_convolution': False,
        'point_source_supersampling_factor': 2,
    }
    image_numerics_low_res = NumericsSubFrame(pixel_grid=data_class,
                                              psf=psf_model,
                                              **kwargs_numerics_low_res)
    conv_class_low_res = image_numerics_low_res.convolution_class
    conv_flat_low_res = conv_class_low_res.convolution2d(image_unconvolved)

    #import matplotlib.pyplot as plt
    #plt.matshow(image_scipy_resized - image_unconvolved)
    #plt.colorbar()
    #plt.show()

    #plt.matshow(image_scipy_resized - conv_flat)
    #plt.colorbar()
    #plt.show()

    #plt.matshow(image_scipy_resized - conv_flat_low_res)
    #plt.colorbar()
    #plt.show()

    np.testing.assert_almost_equal(conv_flat, image_scipy_resized)
示例#17
0
def sim_non_lens_agn(data,
                     center_x_1,
                     center_y_1,
                     center_x_2,
                     center_y_2,
                     numPix=101,
                     sigma_bkg=8.0,
                     exp_time=100.0,
                     deltaPix=0.263,
                     psf_type='GAUSSIAN',
                     kernel_size=91):

    full_band_images = np.zeros((numPix, numPix, 4))

    flux_1 = mag_to_flux(data['source_mag'], 27.5)
    flux_g_1 = mag_to_flux(data['mag_g'], 27.5)
    flux_r_1 = mag_to_flux(data['mag_r'], 27.5)
    flux_i_1 = mag_to_flux(data['mag_i'], 27.5)
    flux_z_1 = mag_to_flux(data['mag_z'], 27.5)

    flux_2 = mag_to_flux(data['lens_mag'], 27.5)
    flux_g_2 = flux_g_1 * flux_2 / flux_1
    flux_r_2 = flux_r_1 * flux_2 / flux_1
    flux_i_2 = flux_i_1 * flux_2 / flux_1
    flux_z_2 = flux_z_1 * flux_2 / flux_1

    center_x_list = [center_x_1, center_x_2]
    center_y_list = [center_y_1, center_y_2]

    kwargs_gal1 = {
        'amp': flux_1,
        'R_sersic': data['source_R_sersic'],
        'n_sersic': data['source_n_sersic'],
        'e1': data['source_e1'],
        'e2': data['source_e2'],
        'center_x': center_x_1,
        'center_y': center_y_1
    }
    kwargs_gal2 = {
        'amp': flux_2,
        'R_sersic': data['lens_R_sersic'],
        'n_sersic': data['lens_n_sersic'],
        'center_x': center_x_2,
        'center_y': center_y_2
    }
    kwargs_gals = [kwargs_gal1, kwargs_gal2]

    color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3}

    cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.)

    light_model_list = ['SERSIC_ELLIPSE', 'SERSIC']
    lightModel = LightModel(light_model_list=light_model_list)

    ###iterate through bands to simulate images
    for band in ['g', 'r', 'i', 'z']:

        #psf info
        kwargs_data = sim_util.data_configure_simple(numPix, deltaPix,
                                                     exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': psf_type,
            'fwhm': data['psf_%s' % band],
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_class = PSF(**kwargs_psf)

        point_source_list = ['UNLENSED']
        pointSource = PointSource(point_source_type_list=point_source_list)

        point_amp_list = [eval('flux_%s_1' % band), eval('flux_%s_2' % band)]
        kwargs_ps = [{
            'ra_image': center_x_list,
            'dec_image': center_y_list,
            'point_amp': point_amp_list
        }]
        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_light_model_class=lightModel,
                                point_source_class=pointSource,
                                kwargs_numerics=kwargs_numerics)

        # generate image
        image_sim = imageModel.image(kwargs_lens_light=kwargs_gals,
                                     kwargs_ps=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

        full_band_images[:, :, color_idx[band]] += image_sim

    return full_band_images
示例#18
0
    def setup(self):
        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # cutout pixel size
        deltaPix = 0.1  # pixel size in arcsec (area per pixel = deltaPix**2)
        fwhm = 0.5  # full width half max of PSF

        # PSF specification

        kwargs_data = simulation_util.data_configure_simple(
            numPix, deltaPix, exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix
        }
        psf_class = PSF(**kwargs_psf)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_model_list = ['SPEP']
        kwargs_lens = [kwargs_spemd]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {
            'amp': 1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_light_model_list = ['SERSIC']
        kwargs_lens_light = [kwargs_sersic]
        lens_light_model_class = LightModel(
            light_model_list=lens_light_model_list)
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_source = [kwargs_sersic_ellipse]
        source_model_class = LightModel(light_model_list=source_model_list)

        # Point Source
        point_source_model_list = ['UNLENSED']
        kwargs_ps = [{
            'ra_image': [0.4],
            'dec_image': [-0.2],
            'point_amp': [2]
        }]
        point_source_class = PointSource(
            point_source_type_list=point_source_model_list)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False,
            'compute_mode': 'regular'
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class=point_source_class,
                                kwargs_numerics=kwargs_numerics)
        image_sim = simulation_util.simulate_simple(imageModel, kwargs_lens,
                                                    kwargs_source,
                                                    kwargs_lens_light,
                                                    kwargs_ps)

        data_class.update_data(image_sim)
        kwargs_data['image_data'] = image_sim
        self.multi_band_list = [[kwargs_data, kwargs_psf, kwargs_numerics]]

        self.kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'lens_light_model_list': lens_light_model_list,
            'point_source_model_list': point_source_model_list,
            'fixed_magnification_list': [False],
            'index_lens_model_list': [[0]],
            'index_lens_light_model_list': [[0]],
            'index_source_light_model_list': [[0]],
            'index_point_source_model_list': [[0]],
        }

        self.kwargs_params = {
            'kwargs_lens': kwargs_lens,
            'kwargs_source': kwargs_source,
            'kwargs_lens_light': kwargs_lens_light,
            'kwargs_ps': kwargs_ps
        }

        self.single_band = SingleBandMultiModel(
            multi_band_list=self.multi_band_list,
            kwargs_model=self.kwargs_model,
            linear_solver=True)
        self.single_band_no_linear = SingleBandMultiModel(
            multi_band_list=self.multi_band_list,
            kwargs_model=self.kwargs_model,
            linear_solver=False)
示例#19
0
def sim_lens(data,
             numPix=101,
             sigma_bkg=8.0,
             exp_time=100.0,
             deltaPix=0.263,
             psf_type='GAUSSIAN',
             kernel_size=91):

    flux_g = mag_to_flux(data['mag_g'], 27.5)
    flux_r = mag_to_flux(data['mag_r'], 27.5)
    flux_i = mag_to_flux(data['mag_i'], 27.5)
    flux_z = mag_to_flux(data['mag_z'], 27.5)
    flux_source = mag_to_flux(data['source_mag'], 27.5)
    flux_lens = mag_to_flux(data['lens_mag'], 27.5)

    color_idx = {'g': 0, 'r': 1, 'i': 2, 'z': 3}

    cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.)

    full_band_images = np.zeros((numPix, numPix, 4))

    ### Set kwargs based on input data file
    #shear
    kwargs_shear = {
        'gamma_ext': data['lens_shear_gamma_ext'],
        'psi_ext': data['lens_shear_psi_ext']
    }
    #lens potential
    kwargs_spemd = {
        'theta_E': data['lens_theta_E'],
        'gamma': data['lens_gamma'],
        'center_x': data['lens_center_x'],
        'center_y': data['lens_center_y'],
        'e1': data['lens_e1'],
        'e2': data['lens_e2']
    }
    #lens light
    kwargs_sersic_lens = {
        'amp': flux_lens,
        'R_sersic': data['lens_R_sersic'],
        'n_sersic': data['lens_n_sersic'],
        'e1': data['lens_e1'],
        'e2': data['lens_e2'],
        'center_x': data['lens_center_x'],
        'center_y': data['lens_center_y']
    }
    #source
    kwargs_sersic_source = {
        'amp': flux_source,
        'R_sersic': data['source_R_sersic'],
        'n_sersic': data['source_n_sersic'],
        'e1': data['source_e1'],
        'e2': data['source_e2'],
        'center_x': data['source_center_x'],
        'center_y': data['source_center_y']
    }

    ###set model parameters based on kwargs
    #lens potential
    lens_model_list = ['SPEP', 'SHEAR_GAMMA_PSI']
    kwargs_lens = [kwargs_spemd, kwargs_shear]
    lens_model_class = LensModel(lens_model_list=lens_model_list)
    #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)
    #source
    source_model_list = ['SERSIC_ELLIPSE']
    kwargs_source = [kwargs_sersic_source]
    source_model_class = LightModel(light_model_list=source_model_list)

    ###configure image based on data properties
    kwargs_data = sim_util.data_configure_simple(numPix, deltaPix, exp_time,
                                                 sigma_bkg)
    data_class = ImageData(**kwargs_data)

    ###solve lens equation
    lensEquationSolver = LensEquationSolver(lens_model_class)
    x_image, y_image = lensEquationSolver.findBrightImage(
        kwargs_sersic_source['center_x'],
        kwargs_sersic_source['center_y'],
        kwargs_lens,
        numImages=4,
        min_distance=deltaPix,
        search_window=numPix * deltaPix)
    magnification = lens_model_class.magnification(x_image,
                                                   y_image,
                                                   kwargs=kwargs_lens)

    ###iterate through bands to simulate images
    for band in ['g', 'r', 'i', 'z']:

        #psf info
        kwargs_psf = {
            'psf_type': psf_type,
            'fwhm': data['psf_%s' % band],
            'pixel_size': deltaPix,
            'truncation': 3
        }
        psf_class = PSF(**kwargs_psf)

        #quasar info
        kwargs_ps = [{
            'ra_image':
            x_image,
            'dec_image':
            y_image,
            'point_amp':
            np.abs(magnification) * eval('flux_%s' % band)
        }]
        point_source_list = ['LENSED_POSITION']
        point_source_class = PointSource(
            point_source_type_list=point_source_list,
            fixed_magnification_list=[False])

        #build image model
        kwargs_numerics = {'supersampling_factor': 1}
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class,
                                kwargs_numerics=kwargs_numerics)

        #generate image
        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

        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
        }
        #build up an array with one slice for each band
        full_band_images[:, :, color_idx[band]] += image_sim

    return full_band_images
示例#20
0
    def setup(self):
        self.SimAPI = Simulation()

        # 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 = self.SimAPI.data_configure(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 = self.SimAPI.simulate(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)
        kwargs_psf_iter = {'stacking_option': 'median'}
        self.psf_fitting = PsfFitting(self.imageModel,
                                      kwargs_psf_iter=kwargs_psf_iter)
示例#21
0
    def update_psf(self,
                   kwargs_psf,
                   kwargs_params,
                   stacking_method='median',
                   psf_symmetry=1,
                   psf_iter_factor=1.,
                   block_center_neighbour=0):
        """

        :param kwargs_psf: keyword arguments to construct the PSF() class
        :param kwargs_params: keyword arguments of the parameters of the model components (e.g. 'kwargs_lens' etc)
        :param stacking_method: 'median', 'mean'; the different estimates of the PSF are stacked and combined together.
         The choices are:
         'mean': mean of pixel values as the estimator (not robust to outliers)
         'median': median of pixel values as the estimator (outlier rejection robust but needs >2 point sources in the data
        :param psf_symmetry: number of rotational invariant symmetries in the estimated PSF.
         =1 mean no additional symmetries. =4 means 90 deg symmetry. This is enforced by a rotatioanl stack according to
         the symmetry specified. These additional imposed symmetries can help stabelize the PSF estimate when there are
         limited constraints/number of point sources in the image.
        :param psf_iter_factor: factor in (0, 1] of ratio of old vs new PSF in the update in the iteration.
        :param block_center_neighbour: angle, radius of neighbouring point sources around their centers the estimates
         is ignored. Default is zero, meaning a not optimal subtraction of the neighbouring point sources might
         contaminate the estimate.
        :return: kwargs_psf_new, logL_after, error_map
        """

        psf_class = PSF(**kwargs_psf)
        self._image_model_class.update_psf(psf_class)

        kernel_old = psf_class.kernel_point_source
        kernel_size = len(kernel_old)
        kwargs_psf_copy = copy.deepcopy(kwargs_psf)
        kwargs_psf_new = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kwargs_psf_copy['kernel_point_source']
        }
        if 'psf_error_map' in kwargs_psf_copy:
            kwargs_psf_new[
                'psf_error_map'] = kwargs_psf_copy['psf_error_map'] / 10
        self._image_model_class.update_psf(PSF(**kwargs_psf_new))
        image_single_point_source_list = self.image_single_point_source(
            self._image_model_class, kwargs_params)
        kwargs_ps = kwargs_params.get('kwargs_ps', None)
        kwargs_lens = kwargs_params.get('kwargs_lens', None)
        ra_image, dec_image, amp = self._image_model_class.PointSource.point_source_list(
            kwargs_ps, kwargs_lens)
        x_, y_ = self._image_model_class.Data.map_coord2pix(
            ra_image, dec_image)

        point_source_list = self.cutout_psf(
            ra_image,
            dec_image,
            x_,
            y_,
            image_single_point_source_list,
            kernel_size,
            kernel_old,
            block_center_neighbour=block_center_neighbour)

        kernel_new, error_map = self.combine_psf(
            point_source_list,
            kernel_old,
            sigma_bkg=self._image_model_class.Data.background_rms,
            factor=psf_iter_factor,
            stacking_option=stacking_method,
            symmetry=psf_symmetry)
        kernel_new = kernel_util.cut_psf(kernel_new, psf_size=kernel_size)

        kwargs_psf_new['kernel_point_source'] = kernel_new
        kwargs_psf_new['point_source_supersampling_factor'] = 1
        if 'psf_error_map' in kwargs_psf_new:
            kwargs_psf_new['psf_error_map'] *= 10
        self._image_model_class.update_psf(PSF(**kwargs_psf_new))
        logL_after = self._image_model_class.likelihood_data_given_model(
            **kwargs_params)
        return kwargs_psf_new, logL_after, error_map
    def setup(self):
        self.num_pix = 25  # cutout pixel size
        delta_pix = 0.24
        _, _, ra_at_xy_0, dec_at_xy_0, _, _, Mpix2coord, _ \
            = l_util.make_grid_with_coordtransform(numPix=self.num_pix, deltapix=delta_pix, subgrid_res=1,
                                                   inverse=False, left_lower=False)
        kwargs_data = {
            #'background_rms': background_rms,
            #'exposure_time': np.ones((self.num_pix, self.num_pix)) * exp_time,  # individual exposure time/weight per pixel
            'ra_at_xy_0': ra_at_xy_0,
            'dec_at_xy_0': dec_at_xy_0,
            'transform_pix2angle': Mpix2coord,
            'image_data': np.zeros((self.num_pix, self.num_pix))
        }
        self.data = ImageData(**kwargs_data)

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

        # PSF specification
        kwargs_psf = {'psf_type': 'NONE'}
        self.psf = PSF(**kwargs_psf)

        # list of source light profiles
        source_model_list = ['SERSIC_ELLIPSE']
        kwargs_sersic_ellipse_source = {
            'amp': 2000,
            'R_sersic': 0.6,
            'n_sersic': 1,
            'e1': 0.1,
            'e2': 0.1,
            'center_x': 0.3,
            'center_y': 0.3
        }
        kwargs_source = [kwargs_sersic_ellipse_source]
        source_model = LightModel(light_model_list=source_model_list)

        # list of lens light profiles
        lens_light_model_list = []
        kwargs_lens_light = [{}]
        lens_light_model = LightModel(light_model_list=lens_light_model_list)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False
        }
        self.image_model = ImageModel(self.data,
                                      self.psf,
                                      self.lens_model,
                                      source_model,
                                      lens_light_model,
                                      point_source_class=None,
                                      kwargs_numerics=kwargs_numerics)
        self.image_grid_class = self.image_model.ImageNumerics.grid_class
        self.source_grid_class_default = NumericsSubFrame(self.data,
                                                          self.psf).grid_class

        # create simulated image
        image_sim_no_noise = self.image_model.image(self.kwargs_lens,
                                                    kwargs_source,
                                                    kwargs_lens_light)
        self.source_light_lensed = image_sim_no_noise
        self.data.update_data(image_sim_no_noise)

        # source only, in source plane, on same grid as data
        self.source_light_delensed = self.image_model.source_surface_brightness(
            kwargs_source, unconvolved=False, de_lensed=True)

        # define some auto mask for tests
        self.likelihood_mask = np.zeros_like(self.source_light_lensed)
        self.likelihood_mask[self.source_light_lensed > 0.1 *
                             self.source_light_lensed.max()] = 1
示例#23
0
    def setup(self):

        # we define a model consisting of a singe Sersric profile
        from lenstronomy.LightModel.light_model import LightModel
        light_model_list = ['SERSIC_ELLIPSE']
        self.lightModel = LightModel(light_model_list=light_model_list)
        self.kwargs_light = [{
            'amp': 100,
            'R_sersic': 0.5,
            'n_sersic': 3,
            'e1': 0,
            'e2': 0,
            'center_x': 0.02,
            'center_y': 0
        }]

        # we define a pixel grid and a higher resolution super sampling factor
        self._supersampling_factor = 5
        numPix = 61  # cutout pixel size
        deltaPix = 0.05  # pixel size in arcsec (area per pixel = deltaPix**2)
        x, y, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix = util.make_grid_with_coordtransform(
            numPix=numPix,
            deltapix=deltaPix,
            subgrid_res=1,
            left_lower=False,
            inverse=False)
        flux = self.lightModel.surface_brightness(
            x, y, kwargs_list=self.kwargs_light)
        flux = util.array2image(flux)
        flux_max = np.max(flux)
        conv_pixels_partial = np.zeros((numPix, numPix), dtype=bool)
        conv_pixels_partial[flux >= flux_max / 20] = True
        self._conv_pixels_partial = conv_pixels_partial

        # high resolution ray-tracing and high resolution convolution, the full calculation
        self.kwargs_numerics_true = {
            'supersampling_factor': self._supersampling_factor,
            # super sampling factor of (partial) high resolution ray-tracing
            'compute_mode': 'regular',  # 'regular' or 'adaptive'
            'supersampling_convolution': True,
            # bool, if True, performs the supersampled convolution (either on regular or adaptive grid)
            'supersampling_kernel_size': None,
            # size of the higher resolution kernel region (can be smaller than the original kernel). None leads to use the full size
            'flux_evaluate_indexes':
            None,  # bool mask, if None, it will evaluate all (sub) pixels
            'supersampled_indexes': None,
            # bool mask of pixels to be computed in supersampled grid (only for adaptive mode)
            'compute_indexes': None,
            # bool mask of pixels to be computed the PSF response (flux being added to). Only used for adaptive mode and can be set =likelihood mask.
            'point_source_supersampling_factor': 1,
            # int, supersampling factor when rendering a point source (not used in this script)
        }

        # high resolution convolution on a smaller PSF with low resolution convolution on the edges of the PSF and high resolution ray tracing
        self.kwargs_numerics_high_res_narrow = {
            'supersampling_factor': self._supersampling_factor,
            'compute_mode': 'regular',
            'supersampling_convolution': True,
            'supersampling_kernel_size': 5,
        }

        # low resolution convolution based on high resolution ray-tracing grid
        self.kwargs_numerics_low_conv_high_grid = {
            'supersampling_factor': self._supersampling_factor,
            'compute_mode': 'regular',
            'supersampling_convolution': False,
            # does not matter for supersampling_factor=1
            'supersampling_kernel_size': None,
            # does not matter for supersampling_factor=1
        }

        # low resolution convolution with a subset of pixels with high resolution ray-tracing
        self.kwargs_numerics_low_conv_high_adaptive = {
            'supersampling_factor': self._supersampling_factor,
            'compute_mode': 'adaptive',
            'supersampling_convolution': False,
            # does not matter for supersampling_factor=1
            'supersampling_kernel_size': None,
            # does not matter for supersampling_factor=1
            'supersampled_indexes': self._conv_pixels_partial,
            'convolution_kernel_size': 9,
        }

        # low resolution convolution with a subset of pixels with high resolution ray-tracing and high resoluton convolution on smaller kernel size
        self.kwargs_numerics_high_adaptive = {
            'supersampling_factor': self._supersampling_factor,
            'compute_mode': 'adaptive',
            'supersampling_convolution': True,
            # does not matter for supersampling_factor=1
            'supersampling_kernel_size':
            5,  # does not matter for supersampling_factor=1
            'supersampled_indexes': self._conv_pixels_partial,
            'convolution_kernel_size': 9,
        }

        # low resolution convolution and low resolution ray tracing, the simplest calculation
        self.kwargs_numerics_low_res = {
            'supersampling_factor': 1,
            'compute_mode': 'regular',
            'supersampling_convolution':
            False,  # does not matter for supersampling_factor=1
            'supersampling_kernel_size':
            None,  # does not matter for supersampling_factor=1
            'convolution_kernel_size': 9,
        }

        flux_evaluate_indexes = np.zeros((numPix, numPix), dtype=bool)
        flux_evaluate_indexes[flux >= flux_max / 1000] = True
        # low resolution convolution on subframe
        self.kwargs_numerics_partial = {
            'supersampling_factor': 1,
            'compute_mode': 'regular',
            'supersampling_convolution': False,
            # does not matter for supersampling_factor=1
            'supersampling_kernel_size':
            None,  # does not matter for supersampling_factor=1
            'flux_evaluate_indexes': flux_evaluate_indexes,
            'convolution_kernel_size': 9
        }

        # import PSF file
        kernel_super = kernel_util.kernel_gaussian(
            kernel_numPix=11 * self._supersampling_factor,
            deltaPix=deltaPix / self._supersampling_factor,
            fwhm=0.1)

        kernel_size = 9
        kernel_super = kernel_util.cut_psf(psf_data=kernel_super,
                                           psf_size=kernel_size *
                                           self._supersampling_factor)

        # make instance of the PixelGrid class
        from lenstronomy.Data.pixel_grid import PixelGrid
        kwargs_grid = {
            'nx': numPix,
            'ny': numPix,
            'transform_pix2angle': Mpix2coord,
            'ra_at_xy_0': ra_at_xy_0,
            'dec_at_xy_0': dec_at_xy_0
        }
        self.pixel_grid = PixelGrid(**kwargs_grid)

        # make instance of the PSF class
        from lenstronomy.Data.psf import PSF
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel_super,
            'point_source_supersampling_factor': self._supersampling_factor
        }
        self.psf_class = PSF(**kwargs_psf)

        # without convolution
        image_model_true = ImageModel(
            self.pixel_grid,
            self.psf_class,
            lens_light_model_class=self.lightModel,
            kwargs_numerics=self.kwargs_numerics_true)
        self.image_true = image_model_true.image(
            kwargs_lens_light=self.kwargs_light)
示例#24
0
    def setup(self):

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # cutout pixel size
        deltaPix = 0.1  # 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 = Data(kwargs_data)
        kwargs_psf = sim_util.psf_configure_simple(psf_type='GAUSSIAN', fwhm=fwhm, kernelsize=11, deltaPix=deltaPix,
                                              truncate=3,
                                              kernel=None)
        kwargs_psf = sim_util.psf_configure_simple(psf_type='PIXEL', fwhm=fwhm, kernelsize=11, deltaPix=deltaPix,
                                              truncate=6,
                                              kernel=kwargs_psf['kernel_point_source'])
        psf_class = PSF(kwargs_psf)
        kwargs_spemd = {'theta_E': 1., 'gamma': 1.8, 'center_x': 0, 'center_y': 0, 'e1': 0.1, 'e2': 0.1}

        lens_model_list = ['SPEP']
        self.kwargs_lens = [kwargs_spemd]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {'amp': 1., 'R_sersic': 0.1, 'n_sersic': 2, 'center_x': 0, 'center_y': 0}
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {'amp': 1., 'R_sersic': .6, 'n_sersic': 3, 'center_x': 0, 'center_y': 0,
                                 'e1': 0.1, 'e2': 0.1}

        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)

        kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}
        imageModel = ImageModel(data_class, psf_class, lens_model_class, source_model_class,
                                lens_light_model_class, kwargs_numerics=kwargs_numerics)
        image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens, self.kwargs_source,
                                         self.kwargs_lens_light)

        data_class.update_data(image_sim)
        self.data_class = data_class
        self.psf_class = psf_class

        kwargs_model = {'lens_model_list': lens_model_list,
                             'source_light_model_list': source_model_list,
                             'lens_light_model_list': lens_light_model_list,
                             'fixed_magnification_list': [False],
                             }
        self.kwargs_numerics = {
            'subgrid_res': 1,
            'psf_subgrid': False}

        num_source_model = len(source_model_list)

        kwargs_constraints = {
                                   'image_plane_source_list': [False] * num_source_model,
                                   }

        kwargs_likelihood = {
                                  'source_marg': True,
                                  'point_source_likelihood': False,
                                  'position_uncertainty': 0.004,
                                  'check_solver': False,
                                  'solver_tolerance': 0.001,
                                  }
        self.param_class = Param(kwargs_model, **kwargs_constraints)
        self.Likelihood = LikelihoodModule(imSim_class=imageModel, param_class=self.param_class, **kwargs_likelihood)
        self.sampler = Sampler(likelihoodModule=self.Likelihood)
示例#25
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,
                                                     inverse=True)
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'truncation': 5,
            'pixel_size': deltaPix
        }
        psf_class = PSF(**kwargs_psf)
        kernel = psf_class.kernel_point_source
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': kernel,
            'psf_error_map': np.ones_like(kernel) * 0.001
        }
        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.01,
                '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': False,
            'compute_mode': 'gaussian'
        }
        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 = ImageLinearFit(data_class,
                                         psf_class,
                                         lens_model_class,
                                         source_model_class,
                                         lens_light_model_class,
                                         point_source_class,
                                         kwargs_numerics=kwargs_numerics)
        self.solver = LensEquationSolver(lensModel=self.imageModel.LensModel)
示例#26
0
    def setup(self):

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 10  # cutout pixel size
        deltaPix = 0.1  # 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_gaussian = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix
        }
        psf = PSF(**kwargs_psf_gaussian)
        kwargs_psf = {
            'psf_type': 'PIXEL',
            'kernel_point_source': psf.kernel_point_source
        }
        psf_class = PSF(**kwargs_psf)
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.8,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_model_list = ['SPEP']
        self.kwargs_lens = [kwargs_spemd]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {
            'amp': 1.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        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)

        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False,
            'compute_mode': 'regular'
        }
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                kwargs_numerics=kwargs_numerics)
        image_sim = sim_util.simulate_simple(imageModel, self.kwargs_lens,
                                             self.kwargs_source,
                                             self.kwargs_lens_light)

        data_class.update_data(image_sim)
        kwargs_data['image_data'] = image_sim
        kwargs_data_joint = {
            'multi_band_list': [[kwargs_data, kwargs_psf, kwargs_numerics]],
            'multi_band_type': 'single-band'
        }
        self.data_class = data_class
        self.psf_class = psf_class

        kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'lens_light_model_list': lens_light_model_list,
            'fixed_magnification_list': [False],
        }
        self.kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}

        kwargs_constraints = {
            'image_plane_source_list': [False] * len(source_model_list)
        }

        kwargs_likelihood = {
            'source_marg': True,
            'position_uncertainty': 0.004,
            'check_solver': False,
            'solver_tolerance': 0.001,
        }
        self.param_class = Param(kwargs_model, **kwargs_constraints)
        self.Likelihood = LikelihoodModule(kwargs_data_joint=kwargs_data_joint,
                                           kwargs_model=kwargs_model,
                                           param_class=self.param_class,
                                           **kwargs_likelihood)
        self.sampler = Sampler(likelihoodModule=self.Likelihood)
示例#27
0
        if cut > 0:
            psf_data = psf_data[cut:-cut, :]
        elif cut < 0:
            psf_data = psf_data[:, -cut:cut]
        psf_data /= psf_data.sum()
    #%%
    numPix = 89
    light_model_list = ['SERSIC_ELLIPSE']
    kwargs_psf_high_res = {
        'psf_type': 'PIXEL',
        'kernel_point_source': psf_data,
        'pixel_size': deltaPix
    }
    kwargs_data_high_res = sim_util.data_configure_simple(numPix, deltaPix)
    data_class = ImageData(**kwargs_data_high_res)
    psf_class = PSF(**kwargs_psf_high_res)
    center_x, center_y = np.random.uniform(
        -0.2, 0.2) * deltaPix, np.random.uniform(-0.2, 0.2) * deltaPix
    point_amp = AGN_flux

    point_source_list = ['UNLENSED']
    pointSource = PointSource(point_source_type_list=point_source_list)
    kwargs_ps = [{
        'ra_image': [center_x],
        'dec_image': [center_y],
        'point_amp': [point_amp]
    }]
    light_model_list = ['SERSIC_ELLIPSE']
    lightModel = LightModel(light_model_list=light_model_list)

    q0 = np.random.uniform(0.5, 0.9)
示例#28
0
        plt.show()         
        
        psf = pyfits.getdata(folder+'Drz_PSF.fits')
        psf_fsize = 77
        psf_half_r = int(psf_fsize/2)
        psf_peak = np.where(psf==psf.max())
        psf_peak = [psf_peak[0][0], psf_peak[1][0]]
        psf = psf[psf_peak[0]-psf_half_r:psf_peak[0]+psf_half_r+1,psf_peak[1]-psf_half_r:psf_peak[1]+psf_half_r+1]

        kwargs_data = sim_util.data_configure_simple(numPix = framesize, deltaPix = deltaPix) #,inverse=True)
        kwargs_data['image_data'] = lens_data
        kwargs_data['noise_map'] = len_std
        
        data_class = ImageData(**kwargs_data)
        kwargs_psf = {'psf_type': 'PIXEL', 'kernel_point_source': psf, 'pixel_size': deltaPix} #, 'psf_error_map': np.ones_like(psf)*0.01}
        psf_class = PSF(**kwargs_psf)
        
        #%%
        # lens model choicers
        fixed_lens = []
        kwargs_lens_init = []
        kwargs_lens_sigma = []
        kwargs_lower_lens = []
        kwargs_upper_lens = []
        fixed_lens.append({}) 
        fixed_lens.append({'ra_0': 0, 'dec_0': 0})
        kwargs_lens_init = kwargs_lens_list
        kwargs_lens_sigma.append({'theta_E': .2, 'e1': 0.1, 'e2': 0.1, 'gamma': 0.1, 'center_x': 0.01, 'center_y': 0.01})
        kwargs_lower_lens.append({'theta_E': 0.01, 'e1': -0.5, 'e2': -0.5, 'gamma': kwargs_lens_init[0]['gamma']-0.5, 'center_x': -10, 'center_y': -10})
        kwargs_upper_lens.append({'theta_E': 10, 'e1': 0.5, 'e2': 0.5, 'gamma': kwargs_lens_init[0]['gamma']+0.5, 'center_x': 10, 'center_y': 10})
        kwargs_lens_sigma.append({'gamma1': 0.1, 'gamma2': 0.1})
示例#29
0
    def setup(self):
        np.random.seed(42)

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

        kwargs_model = {
            'lens_model_list': ['SPEP'],
            'lens_light_model_list': ['SERSIC'],
            'source_light_model_list': ['SERSIC_ELLIPSE'],
            'point_source_model_list': ['SOURCE_POSITION'],
            'fixed_magnification_list': [True]
        }

        # PSF specification
        kwargs_band = sim_util.data_configure_simple(numPix, deltaPix,
                                                     exp_time, sigma_bkg)
        data_class = ImageData(**kwargs_band)
        kwargs_psf = {
            'psf_type': 'GAUSSIAN',
            'fwhm': fwhm,
            'pixel_size': deltaPix
        }
        psf_class = PSF(**kwargs_psf)
        print(np.shape(psf_class.kernel_point_source), 'test kernel shape -')
        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.95,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        self.kwargs_lens = [kwargs_spemd]
        kwargs_sersic = {
            'amp': 1 / 0.05**2.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        self.kwargs_lens_light = [kwargs_sersic]
        self.kwargs_source = [kwargs_sersic_ellipse]
        self.kwargs_ps = [
            {
                'ra_source': 0.55,
                'dec_source': 0.02,
                'source_amp': 1.
            }
        ]  # quasar point source position in the source plane and intrinsic brightness
        self.kwargs_cosmo = {'D_dt': 1000}
        kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False,
            'compute_mode': 'gaussian'
        }
        lens_model_class, source_model_class, lens_light_model_class, point_source_class, extinction_class = class_creator.create_class_instances(
            **kwargs_model)
        imageModel = ImageModel(data_class,
                                psf_class,
                                lens_model_class,
                                source_model_class,
                                lens_light_model_class,
                                point_source_class,
                                extinction_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)
        ra_pos, dec_pos = imageModel.PointSource.image_position(
            kwargs_ps=self.kwargs_ps, kwargs_lens=self.kwargs_lens)

        data_class.update_data(image_sim)
        kwargs_band['image_data'] = image_sim
        self.data_class = data_class
        self.psf_class = psf_class

        self.kwargs_model = kwargs_model
        self.kwargs_numerics = {
            'supersampling_factor': 1,
            'supersampling_convolution': False
        }

        kwargs_constraints = {
            'num_point_source_list': [4],
            'solver_type':
            'NONE',  # 'PROFILE', 'PROFILE_SHEAR', 'ELLIPSE', 'CENTER'
            'Ddt_sampling': True
        }

        def condition_definition(kwargs_lens,
                                 kwargs_source,
                                 kwargs_lens_light,
                                 kwargs_ps=None,
                                 kwargs_special=None,
                                 kwargs_extinction=None):
            logL = 0
            if kwargs_lens_light[0]['R_sersic'] > kwargs_source[0]['R_sersic']:
                logL -= 10**15
            return logL

        kwargs_likelihood = {
            'force_no_add_image': True,
            'source_marg': True,
            'astrometric_likelihood': True,
            'image_position_uncertainty': 0.004,
            'check_matched_source_position': False,
            'source_position_tolerance': 0.001,
            'source_position_sigma': 0.001,
            'check_positive_flux': True,
            'flux_ratio_likelihood': True,
            'prior_lens': [[0, 'theta_E', 1, 0.1]],
            'custom_logL_addition': condition_definition,
            'image_position_likelihood': True
        }
        self.kwargs_data = {
            'multi_band_list': [[kwargs_band, kwargs_psf, kwargs_numerics]],
            'multi_band_type': 'single-band',
            'time_delays_measured': np.ones(4),
            'time_delays_uncertainties': np.ones(4),
            'flux_ratios': np.ones(4),
            'flux_ratio_errors': np.ones(4),
            'ra_image_list': ra_pos,
            'dec_image_list': dec_pos
        }
        self.param_class = Param(self.kwargs_model, **kwargs_constraints)
        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.Likelihood = LikelihoodModule(kwargs_data_joint=self.kwargs_data,
                                           kwargs_model=kwargs_model,
                                           param_class=self.param_class,
                                           **kwargs_likelihood)
    def setup(self):
        np.random.seed(42)

        # data specifics
        sigma_bkg = 0.05  # background noise per pixel
        exp_time = 100  # exposure time (arbitrary units, flux per pixel is in units #photons/exp_time unit)
        numPix = 50  # cutout pixel size
        deltaPix = 0.1  # 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 = Data(kwargs_data)
        kwargs_psf = sim_util.psf_configure_simple(psf_type='GAUSSIAN',
                                                   fwhm=fwhm,
                                                   kernelsize=11,
                                                   deltaPix=deltaPix,
                                                   truncate=3,
                                                   kernel=None)
        psf_class = PSF(kwargs_psf)

        kwargs_spemd = {
            'theta_E': 1.,
            'gamma': 1.95,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        lens_model_list = ['SPEP']
        self.kwargs_lens = [kwargs_spemd]
        lens_model_class = LensModel(lens_model_list=lens_model_list)
        kwargs_sersic = {
            'amp': 1 / 0.05**2.,
            'R_sersic': 0.1,
            'n_sersic': 2,
            'center_x': 0,
            'center_y': 0
        }
        # 'SERSIC_ELLIPSE': elliptical Sersic profile
        kwargs_sersic_ellipse = {
            'amp': 1.,
            'R_sersic': .6,
            'n_sersic': 3,
            'center_x': 0,
            'center_y': 0,
            'e1': 0.1,
            'e2': 0.1
        }

        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.55,
                'dec_source': 0.02,
                'source_amp': 1.
            }
        ]  # quasar point source position in the source plane and intrinsic brightness
        self.kwargs_cosmo = {'D_dt': 1000}
        point_source_list = ['SOURCE_POSITION']
        point_source_class = PointSource(
            point_source_type_list=point_source_list,
            fixed_magnification_list=[True])
        kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}
        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.data_class = data_class
        self.psf_class = psf_class

        self.kwargs_model = {
            'lens_model_list': lens_model_list,
            'source_light_model_list': source_model_list,
            'lens_light_model_list': lens_light_model_list,
            'point_source_model_list': point_source_list,
        }

        self.kwargs_numerics = {'subgrid_res': 1, 'psf_subgrid': False}

        kwargs_constraints = {
            'num_point_source_list': [4],
            'solver_type':
            'NONE',  # 'PROFILE', 'PROFILE_SHEAR', 'ELLIPSE', 'CENTER'
            'cosmo_type': 'D_dt'
        }

        kwargs_likelihood = {
            'force_no_add_image': True,
            'source_marg': True,
            'point_source_likelihood': True,
            'position_uncertainty': 0.004,
            'check_solver': True,
            'solver_tolerance': 0.001,
            'check_positive_flux': True,
        }
        self.param_class = Param(self.kwargs_model, **kwargs_constraints)
        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.Likelihood = LikelihoodModule(imSim_class=self.imageModel,
                                           param_class=self.param_class,
                                           **kwargs_likelihood)