Exemple #1
0
def plot_containment_radii(fraction):
    """Plotting script for 68% and 95% containment radii."""

    psf_gc = FermiGalacticCenter.psf()
    gtpsf_table_gc = get_psf_table(psf_gc,  10000, 300000, 15)

    psf_vela = FermiVelaRegion.psf()
    gtpsf_table_vela = get_psf_table(psf_vela, 10000, 300000, 15)
    
    if fraction == 68:
        true_table_rep = load_lat_psf_performance('P7REP_SOURCE_V15_68')
        true_table = load_lat_psf_performance('P7SOURCEV6_68')
        rad = 'CONT_68'
    elif fraction == 95:
        true_table_rep = load_lat_psf_performance('P7REP_SOURCE_V15_95')
        true_table = load_lat_psf_performance('P7SOURCEV6_95')
        rad = 'CONT_95'
    
    plt.plot(gtpsf_table_gc['ENERGY'], gtpsf_table_gc[rad],
             color='red',label='Fermi Tools PSF @ Galactic Center')
    plt.plot(gtpsf_table_vela['ENERGY'], gtpsf_table_vela[rad],
             color='blue', label='Fermi Tools PSF @ Vela Region')
    plt.plot(true_table_rep['energy'], true_table_rep['containment_angle'],
             color='green', linestyle='--', label='P7REP_SOURCE_V15')
    plt.plot(true_table['energy'], true_table['containment_angle'],
             color='black', linestyle='--', label='P7SOURCEV6')

    plt.xlim([10000, 300000])

    plt.legend()
    plt.semilogx()
    plt.xlabel('Energy/MeV')
    plt.ylabel('PSF Containment Radius/deg')

    return plt
def correlate_fermi_psf(image,
                        max_offset,
                        resolution=0.1,
                        energy='None',
                        energy_band=[10, 500]):
    from astropy.coordinates import Angle
    from astropy.units import Quantity
    from gammapy.datasets import FermiGalacticCenter
    from gammapy.irf import EnergyDependentTablePSF

    # Parameters
    filename = FermiGalacticCenter.filenames()['psf']
    pixel_size = Angle(resolution, 'deg')
    offset_max = Angle(max_offset, 'deg')
    if energy == 'None':
        energy_band = Quantity(energy_band, 'GeV')
        fermi_psf = EnergyDependentTablePSF.read(filename)
        psf = fermi_psf.table_psf_in_energy_band(energy_band=energy_band,
                                                 spectral_index=2.5)
    else:
        energy = Quantity(energy, 'GeV')
        fermi_psf = EnergyDependentTablePSF.read(filename)
        psf = fermi_psf.table_psf_at_energy(energy=energy)
    psf.normalize()
    kernel = psf.kernel(pixel_size=pixel_size, offset_max=offset_max)
    kernel_image = kernel.value / kernel.value.sum()

    # TODO: Write unit test (this will be useful):

    #kernel_image_integral = kernel_image.sum() * pixel_size.to('radian').value ** 2
    #print('Kernel image integral: {0}'.format(kernel_image_integral))
    #print('shape: {0}'.format(kernel_image.shape))
    return convolve(image, kernel_image, mode='constant')
def correlate_fermi_psf(image, max_offset, resolution=0.1, energy = 'None', energy_band=[10, 500]):
    from astropy.coordinates import Angle
    from astropy.units import Quantity
    from gammapy.datasets import FermiGalacticCenter
    from gammapy.irf import EnergyDependentTablePSF

    # Parameters
    filename = FermiGalacticCenter.filenames()['psf']
    pixel_size = Angle(resolution, 'deg')
    offset_max = Angle(max_offset, 'deg')
    if energy == 'None':
        energy_band = Quantity(energy_band, 'GeV')
        fermi_psf = EnergyDependentTablePSF.read(filename)
        psf = fermi_psf.table_psf_in_energy_band(energy_band=energy_band, spectral_index=2.5)
    else:
        energy = Quantity(energy, 'GeV')
        fermi_psf = EnergyDependentTablePSF.read(filename)
        psf = fermi_psf.table_psf_at_energy(energy=energy)
    psf.normalize()
    kernel = psf.kernel(pixel_size=pixel_size, offset_max=offset_max)
    kernel_image = kernel.value/kernel.value.sum()
    
    # TODO: Write unit test (this will be useful):
    
    #kernel_image_integral = kernel_image.sum() * pixel_size.to('radian').value ** 2
    #print('Kernel image integral: {0}'.format(kernel_image_integral))
    #print('shape: {0}'.format(kernel_image.shape))
    return convolve(image, kernel_image, mode='constant')
Exemple #4
0
 def main(self, figure, subplot):
     filename = FermiGalacticCenter.filenames()['counts']
     self.fits_figure = FITSFigure(filename,
                                   hdu=1,
                                   figure=figure,
                                   subplot=subplot)
     self.fits_figure.show_colorscale(vmin=1, vmax=10, cmap='afmhot')
     self.fits_figure.ticks.set_xspacing(2)
from gammapy.irf import EnergyDependentTablePSF
from gammapy.image import make_empty_image, catalog_image, binary_disk
from gammapy.image.utils import cube_to_image, solid_angle
from gammapy.data import SpectralCube
from gammapy.image.utils import WCS
from gammapy.spectrum.flux_point import _energy_lafferty_power_law

# *** PREPARATION ***

# Parameters

CORRELATION_RADIUS = 3  # pix
SIGNIFICANCE_THRESHOLD = 5
MASK_DILATION_RADIUS = 0.3

psf_file = FermiGalacticCenter.filenames()['psf']
psf = EnergyDependentTablePSF.read(psf_file)

# *** LOADING INPUT ***

# Counts must be provided as a counts ImageHDU
flux_file = raw_input('Flux Map: ')
exposure_file = raw_input('Exposure Map: ')
spec_ind = input('Spectral Index (for reprojection): ')
flux_hdu = fits.open(flux_file)[1]
flux_wcs = WCS(flux_hdu.header)
energy_flux = Quantity([_energy_lafferty_power_law(10000, 500000, spec_ind)],
                       'MeV')
flux_data = np.zeros((1, 1800, 3600))
flux_data[0] = Quantity(flux_hdu.data, '')
flux_spec_cube = SpectralCube(data=flux_data, wcs=flux_wcs, energy=energy_flux)
from gammapy.irf import EnergyDependentTablePSF
from gammapy.image import make_empty_image, catalog_image, binary_disk
from gammapy.image.utils import cube_to_image, solid_angle
from gammapy.data import SpectralCube
from gammapy.image.utils import WCS
from gammapy.spectrum.flux_point import _energy_lafferty_power_law

# *** PREPARATION ***

# Parameters

CORRELATION_RADIUS = 3  # pix
SIGNIFICANCE_THRESHOLD = 5
MASK_DILATION_RADIUS = 0.3

psf_file = FermiGalacticCenter.filenames()["psf"]
psf = EnergyDependentTablePSF.read(psf_file)

# *** LOADING INPUT ***

# Counts must be provided as a counts ImageHDU
flux_file = raw_input("Flux Map: ")
exposure_file = raw_input("Exposure Map: ")
spec_ind = input("Spectral Index (for reprojection): ")
flux_hdu = fits.open(flux_file)[1]
flux_wcs = WCS(flux_hdu.header)
energy_flux = Quantity([_energy_lafferty_power_law(10000, 500000, spec_ind)], "MeV")
flux_data = np.zeros((1, 1800, 3600))
flux_data[0] = Quantity(flux_hdu.data, "")
flux_spec_cube = SpectralCube(data=flux_data, wcs=flux_wcs, energy=energy_flux)
from gammapy.irf import EnergyDependentTablePSF
from gammapy.image import make_empty_image, catalog_image, binary_disk
from gammapy.image.utils import cube_to_image, solid_angle
from gammapy.data import SpectralCube
from gammapy.image.utils import WCS
from gammapy.spectrum.flux_point import _energy_lafferty_power_law

# *** PREPARATION ***

# Parameters

CORRELATION_RADIUS = 3 # pix
SIGNIFICANCE_THRESHOLD = 5
MASK_DILATION_RADIUS = 0.3

psf_file = FermiGalacticCenter.filenames()['psf']
psf = EnergyDependentTablePSF.read(psf_file)

# *** LOADING INPUT ***

# Counts must be provided as a counts ImageHDU
flux_file = raw_input('Flux Map: ')
exposure_file = raw_input('Exposure Map: ')
spec_ind = input('Spectral Index (for reprojection): ')
flux_hdu = fits.open(flux_file)[1]
flux_wcs = WCS(flux_hdu.header)
energy_flux = Quantity([_energy_lafferty_power_law(10000, 500000, spec_ind)], 'MeV')
flux_data = np.zeros((1, 101, 2001))
flux_data[0] = Quantity(flux_hdu.data, '')
flux_spec_cube = SpectralCube(data=flux_data, wcs=flux_wcs, energy=energy_flux)
"""Compute integral flux in an energy band for the Fermi diffuse model.
"""
from astropy.units import Quantity
from gammapy.datasets import FermiGalacticCenter

cube = FermiGalacticCenter.diffuse_model()
print(cube)

energy_band = Quantity([10, 50], 'GeV')
image = cube.integral_flux_image(energy_band, energy_bins=100)
image.writeto('fermi_diffuse_integral_flux_image.fits', clobber=True)

# Some checks
surface_brightness = Quantity(image.data.mean(), 'cm^-2 s^-1 sr^-1')
print('Mean surface brightness in image: {0}'.format(surface_brightness))
"""Produces an image from 1FHL catalog point sources.
"""
from gammapy.datasets import FermiGalacticCenter
from gammapy.image import make_empty_image, catalog_image

# Create image of defined size
reference = make_empty_image(nxpix=3600, nypix=1800, binsz=0.1)
psf_file = FermiGalacticCenter.psf()

# Create image
image = catalog_image(reference,
                      psf,
                      catalog='1FHL',
                      source_type='point',
                      total_flux='True')
hdu = image.to_fits()[0]
hdu.writeto('Image_1FHL.fits', clobber=True)
Exemple #10
0
"""Test npred model image computation.
"""
from astropy.coordinates import Angle
from gammapy.datasets import FermiGalacticCenter
from gammapy.utils.energy import EnergyBounds
from gammapy.irf import EnergyDependentTablePSF
from gammapy.cube import SkyCube, compute_npred_cube, convolve_cube

filenames = FermiGalacticCenter.filenames()
flux_cube = SkyCube.read(filenames['diffuse_model'])
exposure_cube = SkyCube.read(filenames['exposure_cube'])
psf = EnergyDependentTablePSF.read(filenames['psf'])

flux_cube = flux_cube.reproject_to(exposure_cube)

energy_bounds = EnergyBounds([10, 30, 100, 500], 'GeV')
npred_cube = compute_npred_cube(flux_cube, exposure_cube, energy_bounds)

offset_max = Angle(1, 'deg')
npred_cube_convolved = convolve_cube(npred_cube, psf, offset_max)
"""Produces an image from 1FHL catalog point sources.
"""
from gammapy.datasets import FermiGalacticCenter
from gammapy.image import make_empty_image, catalog_image

# Create image of defined size
reference = make_empty_image(nxpix=3600, nypix=1800, binsz=0.1)
psf_file = FermiGalacticCenter.psf()

# Create image
image = catalog_image(reference, psf, catalog='1FHL', source_type='point',
                  total_flux='True')
hdu = image.to_fits()[0]
hdu.writeto('Image_1FHL.fits', clobber=True)

Here's a high-level description ... see the code for details:
* The background is estimated from a ring around each pixel.
* The significance is computed using the Li & Ma formula
  for the counts within a circle around each pixel.
* An iterative scheme is used to define an exclusion mask of
  pixels that shouldn't be used for background estimation.
"""
# TODO: Fix this script and include images in the docs!
__doctest_skip__ = ['*']
import numpy as np
from astropy.io import fits
from gammapy.datasets import FermiGalacticCenter
from gammapy.image import threshold, binary_dilation_circle
from gammapy.background import Maps, ring_correlate_off_maps

counts = FermiGalacticCenter.counts()
binsz = counts.header['CDELT2']
maps = Maps([counts], theta=0.3)

for iteration in range(3):
    print('Iteration: {0}'.format(iteration))
    ring_correlate_off_maps(maps, r_in=0.5, r_out=0.8)
    significance = maps.significance.data
    # exclusion = threshold(significance, threshold=5)
    exclusion = np.where(significance > 4, 0, 1).astype(int)
    exclusion = binary_dilation_circle(exclusion, radius=0.4 * binsz)
    maps['exclusion'].data = exclusion.astype(np.uint8)

maps.make_derived_maps()
output_file = 'fermi_all_gc.fits'
print('Writing file: {0}'.format(output_file))
Exemple #13
0
 def main(self, figure, subplot):
     filename = FermiGalacticCenter.filenames()['counts']
     self.fits_figure = FITSFigure(filename, hdu=1, figure=figure, subplot=subplot)
     self.fits_figure.show_colorscale(vmin=1, vmax=10, cmap='afmhot')
     self.fits_figure.ticks.set_xspacing(2)
Exemple #14
0
 def main(self, figure, box):
     filename = FermiGalacticCenter.filenames()['counts']
     self.fits_figure = FITSFigure(filename, figure=figure, subplot=box)
     self.fits_figure.show_colorscale(vmin=1, vmax=10)
Exemple #15
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Compute integral flux in an energy band for the Fermi diffuse model.
"""
from astropy.units import Quantity
from gammapy.datasets import FermiGalacticCenter

cube = FermiGalacticCenter.diffuse_model()
print(cube)

energy_band = Quantity([10, 50], 'GeV')
image = cube.integral_flux_image(energy_band, energy_bins=100)
image.writeto('fermi_diffuse_integral_flux_image.fits', clobber=True)

# Some checks
surface_brightness = Quantity(image.data.mean(), 'cm^-2 s^-1 sr^-1')
print('Mean surface brightness in image: {0}'.format(surface_brightness))