Beispiel #1
0
def coordinate_images(infile,
                      outfile,
                      make_coordinate_maps,
                      make_distance_map,
                      overwrite):
    """Make maps that can be used to create profiles.

    The following images can be created:
    * LON -- Longitude coordinate
    * LAT -- Latitude coordinate
    * DIST -- Distance to mask
    * SOLID_ANGLE -- Solid angle
    """
    import logging
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)s - %(message)s')
    from astropy.io import fits
    from gammapy.utils.fits import get_hdu

    logging.info('Reading {0}'.format(infile))
    hdu = get_hdu(infile)

    out_hdus = fits.HDUList()

    if make_coordinate_maps:
        from gammapy.image import coordinates
        logging.info('Computing LON and LAT maps')
        lon, lat = coordinates(hdu)
        out_hdus.append(fits.ImageHDU(lon, hdu.header, 'LON'))
        out_hdus.append(fits.ImageHDU(lat, hdu.header, 'LAT'))

    if make_distance_map:
        from gammapy.image import exclusion_distance
        logging.info('Computing DIST map')
        dist = exclusion_distance(hdu.data)
        out_hdus.append(fits.ImageHDU(dist, hdu.header, 'DIST'))

    logging.info('Writing {0}'.format(outfile))
    out_hdus.writeto(outfile, clobber=overwrite)
def make_model_image(psf='Fermi', resolution=0.1, center=[0, 0], lat_range=[0, 180], lon_range=[0, 360], catalog='1FHL', total_flux='False', filename='1fhl_fermi_psf.fits'):  
    from gammapy.image import coordinates
    from astropy.convolution import convolve
    from astropy.modeling.models import Gaussian2D, Disk2D
    from gammapy.image import images_to_cube
    from gammapy.image import paste_cutout_into_image
    from gammapy.image.utils import solid_angle
    
    reference = make_reference_survey_image(resolution, lat_range, lon_range, center, units='ph/cm2/s/sr') #Check these units!
    
    lons, lats = coordinates(reference) 
    source_table = fits.open('simulated_galaxy_1.fits')[1].data
    sources = np.arange(len(source_table['flux'])).astype(int)
    
    if psf == 'None':
        # If there is no PSF defined, sources will be modelled as Gaussians
        source_kernel = Gaussian2D(0, 0, 0, 0.1, 0.1)
        new_image = im_1 = im_2 = im_3 = source_kernel(lats, lons)
    else:
        # Otherwise, all of the flux will be placed into the reference pixel to be later PSF convolved with the defined PSF
        # Hence original reference empty image is called
        new_image = im_1 = im_2 = im_3 = reference.data

    from gammapy.image import wcs_histogram2d
    
    header = reference.header
    lon = source_table['GLON']
    lat = source_table['GLAT']
    flux = source_table['flux']
    total_point_image = wcs_histogram2d(header, lon, lat, weights=flux)
    new_image = total_point_image.data
    #import IPython; IPython.embed(); 1 /0

    """
    print len(sources)
    total_point_image = fits.ImageHDU(header=reference.header, data=new_image)
    from astropy.wcs import WCS
    wcs = WCS(total_point_image.header)
    new_image = np.zeros_like(total_point_image.data, dtype=np.float64)
    for source in sources:
        source_type = 'PointSource'#source_table['Source_Type'][source]
        print source
        if source_type == 'ExtendedSource':
            raise NotImplementedError
            # This needs more work...
            #image = source_table['Image'][source]
            #image.data = (image.data * solid_angle(image).value.mean()) / 1000000000000  # TODO: fix this hack... units???
            #resample_factor1 = np.round(reference.header['CDELT1'] / image.header['CDELT1'])
            #resample_factor2 = np.round(reference.header['CDELT2'] / image.header['CDELT2'])
            #block_factors = np.array([resample_factor1, resample_factor2])  # TODO: fix this approximation... kapteyn image utils reprojectto?
            #resampled_image = block_reduce_hdu(image, block_factors, np.sum)
            #paste_cutout_into_image(total_point_image, resampled_image)
            
        elif source_type == 'PointSource':
            lon = source_table['GLON'][source]
            lat = source_table['GLAT'][source]
            flux = source_table['flux'][source]
            precise = False
            if precise:
                raise NotImplementedError
            else:
                #print(lon, lat)
                #import IPython; IPython.embed()
                print lon, lat
                x, y = wcs.wcs_world2pix(lon, lat, 0)
                print x, y
                
                # TODO: check if this is 0.5 or 1 pix off
                xi, yi = x.astype(int), y.astype(int)
                
                new_image[yi, xi] += flux
            
            
    total_point_image = fits.ImageHDU(header=reference.header, data=new_image)
    """
    # Ensure flux or counts remain the same
    if total_flux == 'True':
        factor = source_table['Flux'].sum()
    else:
        factor = total_flux
        
    if psf == 'None':
        new_image = (new_image/new_image.sum()) * factor
    elif psf == 'Gaussian':
        new_image = correlate_gauss((new_image/new_image.sum()), 2)
    elif psf == 'Disk':
        new_image = disk_correlate((new_image/new_image.sum()), 2)
    elif psf == 'Fermi':
        print "Original Flux"
        print new_image.sum()
        new_image = correlate_fermi_psf(new_image, 5)
        print "PSF Convolved Flux"
        print new_image.sum()
    header = reference.header
    image = fits.ImageHDU(data=new_image, header=header)
    image.writeto(filename, clobber=True)
energy_exp = Quantity([10000, 500000], 'MeV')
exposure_data = Quantity(exposure_hdu.data, '')
exposure_spec_cube = SpectralCube(data=exposure_data, wcs=exposure_wcs, energy=energy_exp)
exposure_spec_cube = exposure_spec_cube.reproject_to(flux_spec_cube)

counts_data = flux_spec_cube.data * exposure_spec_cube.data
counts = fits.ImageHDU(data=counts_data[0], header=flux_hdu.header)



binsz=input('Bin size: ')
label1='Total Flux'
filename1 = flux_file
smooth = 0.1
hdu = fits.open(filename1)[1]
lons, lats = coordinates(hdu)
lat_profile = image_profile(profile_axis='lat', image=hdu, lats=[-10, 10], lons=[-100, 100], binsz=binsz, errors=True, standard_error=0.1, counts=counts)
plt.figure(figsize=(5,4))
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
flux = np.float64(lat_profile['BIN_VALUE'])
lats = lat_profile['GLAT_MIN']
profile1 = np.histogram(lats, bins=np.sort(lats), weights=np.float64(flux))
xstep=binsz
y_smooth_1 = gaussian_filter(profile1[0], smooth / xstep)
lats_x = lat_profile['GLAT_MIN'][1:] - 0.5 * binsz
plt.plot(lats_x, y_smooth_1, label='{0}'.format(label1))
plt.hlines(0, -5, 5)
plt.xlabel(r'Galactic Latitude/$deg$', fontsize=10)
plt.ylabel(r'Flux/ph cm$^{-2}$ s$^{-1}$', fontsize=10)
plt.xlim([-5, 5])
Beispiel #4
0
energy_exp = Quantity([10000, 500000], 'MeV')
exposure_data = Quantity(exposure_hdu.data, '')
exposure_spec_cube = SpectralCube(data=exposure_data,
                                  wcs=exposure_wcs,
                                  energy=energy_exp)
exposure_spec_cube = exposure_spec_cube.reproject_to(flux_spec_cube)

counts_data = flux_spec_cube.data * exposure_spec_cube.data
counts = fits.ImageHDU(data=counts_data[0], header=flux_hdu.header)

binsz = input('Bin size: ')
label1 = 'Total Flux'
filename1 = flux_file
smooth = 0.1
hdu = fits.open(filename1)[1]
lons, lats = coordinates(hdu)
lat_profile = image_profile(profile_axis='lat',
                            image=hdu,
                            lats=[-10, 10],
                            lons=[-100, 100],
                            binsz=binsz,
                            errors=True,
                            standard_error=0.1,
                            counts=counts)
plt.figure(figsize=(5, 4))
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
flux = np.float64(lat_profile['BIN_VALUE'])
lats = lat_profile['GLAT_MIN']
profile1 = np.histogram(lats, bins=np.sort(lats), weights=np.float64(flux))
xstep = binsz
exposure_wcs = WCS(exposure_hdu.header)
energy_exp = Quantity([10000, 500000], 'MeV')
exposure_data = Quantity(exposure_hdu.data, '')
exposure_spec_cube = SpectralCube(data=exposure_data, wcs=exposure_wcs, energy=energy_exp)
exposure_spec_cube = exposure_spec_cube.reproject_to(counts_spec_cube)

flux_data = counts_spec_cube.data / exposure_spec_cube.data
flux = fits.ImageHDU(data=flux_data[0], header=counts_hdu.header)



binsz=input('Bin size: ')

label1='Total Flux'
smooth = 0.2
lons, lats = coordinates(flux)
lat_profile_total = image_profile(profile_axis='lat', image=flux, lats=[-10, 10], lons=[-100, 100], binsz=binsz, errors=True, counts=counts_hdu)

label2='Separated Background'
background = fits.open(background_file)[1]
lat_profile_background = image_profile(profile_axis='lat', image=background, lats=[-10, 10], lons=[-100, 100], binsz=binsz, errors=True, counts=counts_hdu)

label3='Fermi Diffuse Model'
diffuse = fits.open('diffuse_correct.fits')[1]
lat_profile_diffuse = image_profile(profile_axis='lat', image=diffuse, lats=[-10, 10], lons=[-100, 100], binsz=binsz, errors=False)
plt.clf()
plt.figure(figsize=(7, 6))
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
flux = np.float64(lat_profile_total['BIN_VALUE'])
background = np.float64(lat_profile_background['BIN_VALUE'])
Beispiel #6
0
exposure_wcs = WCS(exposure_hdu.header)
energy_exp = Quantity([10000, 500000], 'MeV')
exposure_data = Quantity(exposure_hdu.data, '')
exposure_spec_cube = SpectralCube(data=exposure_data,
                                  wcs=exposure_wcs,
                                  energy=energy_exp)
exposure_spec_cube = exposure_spec_cube.reproject_to(counts_spec_cube)

flux_data = counts_spec_cube.data / exposure_spec_cube.data
flux = fits.ImageHDU(data=flux_data[0], header=counts_hdu.header)

binsz = input('Bin size: ')

label1 = 'Total Flux'
smooth = 0.2
lons, lats = coordinates(flux)
lon_profile_total = image_profile(profile_axis='lon',
                                  image=flux,
                                  lats=[-5, 5],
                                  lons=[-101, 101],
                                  binsz=binsz,
                                  errors=True,
                                  counts=counts_hdu)

label2 = 'Separated Background'
background = fits.open(background_file)[1]
lon_profile_background = image_profile(profile_axis='lon',
                                       image=background,
                                       lats=[-5, 5],
                                       lons=[-101, 101],
                                       binsz=binsz,
def make_model_image(psf='Fermi',
                     resolution=0.1,
                     center=[0, 0],
                     lat_range=[0, 180],
                     lon_range=[0, 360],
                     catalog='1FHL',
                     total_flux='False',
                     filename='1fhl_fermi_psf.fits'):
    from gammapy.image import coordinates
    from astropy.convolution import convolve
    from astropy.modeling.models import Gaussian2D, Disk2D
    from gammapy.image import images_to_cube
    from gammapy.image import paste_cutout_into_image
    from gammapy.image.utils import solid_angle

    reference = make_reference_survey_image(
        resolution, lat_range, lon_range, center,
        units='ph/cm2/s/sr')  #Check these units!

    lons, lats = coordinates(reference)
    source_table = fits.open('simulated_galaxy_1.fits')[1].data
    sources = np.arange(len(source_table['flux'])).astype(int)

    if psf == 'None':
        # If there is no PSF defined, sources will be modelled as Gaussians
        source_kernel = Gaussian2D(0, 0, 0, 0.1, 0.1)
        new_image = im_1 = im_2 = im_3 = source_kernel(lats, lons)
    else:
        # Otherwise, all of the flux will be placed into the reference pixel to be later PSF convolved with the defined PSF
        # Hence original reference empty image is called
        new_image = im_1 = im_2 = im_3 = reference.data

    from gammapy.image import wcs_histogram2d

    header = reference.header
    lon = source_table['GLON']
    lat = source_table['GLAT']
    flux = source_table['flux']
    total_point_image = wcs_histogram2d(header, lon, lat, weights=flux)
    new_image = total_point_image.data
    #import IPython; IPython.embed(); 1 /0
    """
    print len(sources)
    total_point_image = fits.ImageHDU(header=reference.header, data=new_image)
    from astropy.wcs import WCS
    wcs = WCS(total_point_image.header)
    new_image = np.zeros_like(total_point_image.data, dtype=np.float64)
    for source in sources:
        source_type = 'PointSource'#source_table['Source_Type'][source]
        print source
        if source_type == 'ExtendedSource':
            raise NotImplementedError
            # This needs more work...
            #image = source_table['Image'][source]
            #image.data = (image.data * solid_angle(image).value.mean()) / 1000000000000  # TODO: fix this hack... units???
            #resample_factor1 = np.round(reference.header['CDELT1'] / image.header['CDELT1'])
            #resample_factor2 = np.round(reference.header['CDELT2'] / image.header['CDELT2'])
            #block_factors = np.array([resample_factor1, resample_factor2])  # TODO: fix this approximation... kapteyn image utils reprojectto?
            #resampled_image = block_reduce_hdu(image, block_factors, np.sum)
            #paste_cutout_into_image(total_point_image, resampled_image)
            
        elif source_type == 'PointSource':
            lon = source_table['GLON'][source]
            lat = source_table['GLAT'][source]
            flux = source_table['flux'][source]
            precise = False
            if precise:
                raise NotImplementedError
            else:
                #print(lon, lat)
                #import IPython; IPython.embed()
                print lon, lat
                x, y = wcs.wcs_world2pix(lon, lat, 0)
                print x, y
                
                # TODO: check if this is 0.5 or 1 pix off
                xi, yi = x.astype(int), y.astype(int)
                
                new_image[yi, xi] += flux
            
            
    total_point_image = fits.ImageHDU(header=reference.header, data=new_image)
    """
    # Ensure flux or counts remain the same
    if total_flux == 'True':
        factor = source_table['Flux'].sum()
    else:
        factor = total_flux

    if psf == 'None':
        new_image = (new_image / new_image.sum()) * factor
    elif psf == 'Gaussian':
        new_image = correlate_gauss((new_image / new_image.sum()), 2)
    elif psf == 'Disk':
        new_image = disk_correlate((new_image / new_image.sum()), 2)
    elif psf == 'Fermi':
        print "Original Flux"
        print new_image.sum()
        new_image = correlate_fermi_psf(new_image, 5)
        print "PSF Convolved Flux"
        print new_image.sum()
    header = reference.header
    image = fits.ImageHDU(data=new_image, header=header)
    image.writeto(filename, clobber=True)