Exemple #1
0
    def bkg_image(self, bkg_norm=True):
        """
        Make the background image for one observation from a bkg model.

        Parameters
        ----------
        bkg_norm : bool
            If true, apply the scaling factor from the number of counts
            outside the exclusion region to the bkg image
        """
        bkg_image = SkyImage.empty_like(self.empty_image)
        table = self.bkg.acceptance_curve_in_energy_band(
            energy_band=self.energy_band)
        center = self.obs_center.galactic
        bkg_hdu = fill_acceptance_image(self.header, center, table["offset"],
                                        table["Acceptance"],
                                        self.offset_band[1])
        bkg_image.data = Quantity(
            bkg_hdu.data,
            table["Acceptance"].unit) * bkg_image.solid_angle() * self.livetime
        bkg_image.data = bkg_image.data.decompose()
        bkg_image.data = bkg_image.data.value
        if bkg_norm:
            scale, counts = self.background_norm_factor(
                self.images["counts"], bkg_image)
            bkg_image.data = scale * bkg_image.data
            if self.save_bkg_scale:
                self.table_bkg_scale.add_row([self.obs_id, scale, counts])

        self.images["bkg"] = bkg_image
Exemple #2
0
def image_coordinates(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
    """
    from astropy.io import fits
    from gammapy.utils.fits import get_hdu
    from gammapy.image import SkyImage, SkyMask

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

    out_hdus = fits.HDUList()

    if make_coordinate_maps:
        image = SkyImage.empty_like(hdu)
        log.info('Computing LON and LAT maps')
        lon, lat = image.coordinates()
        out_hdus.append(fits.ImageHDU(lon, hdu.header, 'LON'))
        out_hdus.append(fits.ImageHDU(lat, hdu.header, 'LAT'))

    if make_distance_map:
        excl = SkyMask.from_image_hdu(hdu)
        log.info('Computing DIST map')
        dist = excl.exclusion_distance
        out_hdus.append(fits.ImageHDU(dist, hdu.header, 'DIST'))

    log.info('Writing {0}'.format(outfile))
    out_hdus.writeto(outfile, clobber=overwrite)
Exemple #3
0
    def counts_image(self):
        """Fill the counts image for the events of one observation."""
        self.images['counts'] = SkyImage.empty_like(self.empty_image,
                                                    name='counts')

        if len(self.events.table) > self.ncounts_min:
            self.images['counts'].fill_events(self.events)
 def _get_empty_skyimage(self):
     """
     Get empty sky image like reference image.
     """
     p = self.parameters
     image = SkyImage.empty_like(self.reference)
     image.meta['emin'] = str(p['emin'])
     image.meta['emax'] = str(p['emax'])
     return image
Exemple #5
0
    def significance_image(self, radius):
        """Make the significance image from the counts and bkg images.

        Parameters
        ----------
        radius : float
            Disk radius in pixels.
        """
        image = SkyImage.empty_like(self.empty_image)
        disk = Tophat2DKernel(radius)
        disk.normalize('peak')
        counts = self.images["counts"].convolve(disk.array)
        bkg = self.images["bkg"].convolve(disk.array)
        image.data = significance(counts.data, bkg.data)
        self.images["significance"] = image
Exemple #6
0
def summed():

    comp_image = image_estimator.run(mylist)
    comp_image.names

    print("Total number of counts",images[0].data.sum())
    print("Total number of excess events",images[3].data.sum())

    fermi=SkyImage.read("FDA16.fits")
    fermi_rep=fermi.reproject(ref_image)

    #Make sure that the exclusion mask properly excludes all sources

    masked_excess = SkyImage.empty_like(images['excess'])
    masked_excess.data = comp_image['excess'].data * exclusion_mask.data
    masked_excess.plot(cmap='viridis',stretch='sqrt',add_cbar=True)

    plt.hist(masked_excess.data.flatten(),bins=100,log=True)

    #smooth

    excess_smooth=comp_image.smooth(radius=0.5*u.deg)
    excess_smooth.show()

    counts_smooth=comp_image.smooth(radius=0.5*u.deg)
    counts_smooth.show()

    #cutout

    excess_cut=excess_smooth.cutout(
        position=SkyCoord(src.galactic.l.value, src.galactic.b.value, unit='deg', frame='galactic'),
        size=(9*u.deg, 9*u.deg))

    excess_cut.plot(cmap='viridis',add_cbar=True,stretch='sqrt')

    counts_cut=counts_smooth.cutout(
        position=SkyCoord(src.galactic.l.value, src.galactic.b.value, unit='deg', frame='galactic'),
        size=(9*u.deg, 9*u.deg))

    counts_cut.plot(cmap='viridis',add_cbar=True,stretch='sqrt')

    fermi_cutout=fermi_rep.cutout(
        position=SkyCoord(src.galactic.l.value, src.galactic.b.value, unit='deg', frame='galactic'),
        size=(9*u.deg, 9*u.deg))

    fig, ax, _ = excess_cut.plot(cmap='viridis',add_cbar=True,stretch='sqrt')
    ax.contour(fermi_cutout.data, cmap='Blues')
Exemple #7
0
    def exposure_image(self, spectral_index=2.3, for_integral_flux=False):
        r"""Compute the exposure image for one observation.

        Excess/exposure will give the differential flux at the energy Eref at the middle of the ``self.energy_band``

        If ``for_integral_flux`` is true, it will give the integrated flux over the ``self.energy_band``

        Exposure is define as follow:

        .. math ::

            EXPOSURE = \int_{E_1}^{E_2} A(E) \phi(E) * T \, dE

        with ``T`` the observation livetime, ``A(E)`` the effective area,
        the energy integration range :math:`[E_1,E_2]` given by ``self.energy_range``
        and assuming a power law for the flux :math:`\phi(E) = \phi_{Eref} \times \frac{E}{E_{ref}}^{\gamma}`
        with :math:`\gamma` the spectral index of the assumed power law.

        If ``for_integral_flux`` is true,
        :math:`EXPOSURE = \int_{E_1}^{E_2} A(E) \phi_{E} * T \, dE / \int \phi_{E} \, dE`

        Parameters
        ----------
        spectral_index : float
            Assumed power-law spectral index
        for_integral_flux : bool
            True if you want that the total excess / exposure gives the integrated flux
        """
        from scipy.interpolate import interp1d
        # TODO: should be re-implemented using the make_exposure_cube function
        table = self.make_1d_expected_counts(spectral_index, for_integral_flux)
        exposure = SkyImage.empty_like(self.empty_image,
                                       unit=table["npred"].unit)

        # calculate pixel offset from center (in world coordinates)
        coord = exposure.coordinates()
        offset = coord.separation(self.obs_center)

        # Interpolate for the offset of each pixel
        f = interp1d(table["theta"],
                     table["npred"],
                     bounds_error=False,
                     fill_value=0)
        exposure.data = f(offset)
        exposure.data[offset >= self.offset_band[1]] = 0
        self.images["exposure"] = exposure
        self.images["exposure"] = 0.0
Exemple #8
0
    if param_fit["Em_gal"]:
        #EmGal=make_EG_model(outdir_data, on,1e-8, None)
        #EmGal=make_EG_model(outdir_data, on,1, None)
        #EmGal=make_EG_model(outdir_data, on,2e-4, True)
        #EmGal=make_EG_model(outdir_data, on,2e-10, True)
        #EmGal=make_EG_model(outdir_data, on,1.83937 , True)
        EmGal = UniformGaussianPlane()
        model = bkg + 1e-8 * psf_SgrA(exposure * EmGal)
        #model = psf_SgrA(exposure*EmGal)
    else:
        model = bkg
    set_full_model(model)
    fit()
    result = get_fit_results()
    #import IPython; IPython.embed()
    shape = np.shape(on.data)
    mask = get_data().mask.reshape(shape)
    map_data = SkyImage.empty_like(on)
    model_map = SkyImage.empty_like(on)
    resid = SkyImage.empty_like(on)
    map_data.data = get_data().y.reshape(shape) * mask
    model_map.data = get_model()(get_data().x0,
                                 get_data().x1).reshape(shape) * mask
    resid.data = map_data.data - model_map.data
    pt.figure(1)
    resid.plot(add_cbar=True)
    pt.savefig("resid_Em_gal.png")
    print("Counts data: " + str(map_data.data.sum()))
    print("Counts model: " + str(model_map.data.sum()))
Exemple #9
0
backnorm = []
Ncounts = []
list_zen = filter(lambda o1: o1.pointing_zen.value < 34.3, mylist)
N = len(list_zen)
#print N

N = 1

for i in range(N):
    #    if i%10 ==0:
    #        print "----running observation -- ",i

    obs = list_zen[i]

    events = datastore.obs(obs.obs_id).events
    counts_image = SkyImage.empty_like(ref_image)
    counts_image.fill_events(events)

    exclusion_region = regions.CircleSkyRegion(src, 0.3 * u.deg)
    mask = counts_image.region_mask(exclusion_region)

    mask1 = copy.copy(mask)
    mask1.data = np.invert(mask.data)

    image_maker = SingleObsImageMaker(
        obs=obs,
        empty_image=ref_image,
        energy_band=energy_band,
        offset_band=offset_band,
        exclusion_mask=mask1,
    )
    #covar_res=get_conf_results()
    try:
        table_covar = join(table_covar,
                           covar_table(covar_res, energy_centers[i_E]),
                           join_type='outer')
    except NameError:
        table_covar = covar_table(covar_res, energy_centers[i_E])

    save_resid(outdir_result + "/residual_" + name + "_" + str("%.2f" % E1) +
               "_" + str("%.2f" % E2) + "_TeV.fits",
               clobber=True)

    #plot en significativite et ts des maps
    shape = np.shape(on.data)
    mask = get_data().mask.reshape(shape)
    map_data = SkyImage.empty_like(on)
    model_map = SkyImage.empty_like(on)
    exp_map = SkyImage.empty_like(on)
    map_data.data = get_data().y.reshape(shape) * mask
    model_map.data = get_model()(get_data().x0,
                                 get_data().x1).reshape(shape) * mask
    exp_map.data = np.ones(map_data.data.shape) * mask
    kernel = Gaussian2DKernel(5)
    TS = compute_ts_image(map_data, model_map, exp_map, kernel)
    TS.write(outdir_result + "/TS_map_" + name + "_" + str("%.2f" % E1) + "_" +
             str("%.2f" % E2) + "_TeV.fits",
             clobber=True)
    sig = SkyImage.empty(TS["ts"])
    sig.data = np.sqrt(TS["ts"].data)
    sig.name = "sig"
    sig.write(outdir_result + "/significance_map_" + name + "_" +
show_image(images['excess'], vmax=2)

# In[18]:

# Significance image
# Just for fun, let's compute it by hand ...
from astropy.convolution import Tophat2DKernel
kernel = Tophat2DKernel(4)
kernel.normalize('peak')

counts_conv = images['counts'].convolve(kernel.array)
background_conv = images['background'].convolve(kernel.array)

from gammapy.stats import significance
significance_image = SkyImage.empty_like(ref_image)
significance_image.data = significance(counts_conv.data, background_conv.data)
show_image(significance_image, vmax=8)

# ## Source Detection
#
# Use the class [TSImageEstimator](http://docs.gammapy.org/dev/api/gammapy.detect.compute_ts_image.html#gammapy.detect.TSImageEstimator.html) and [photutils.find_peaks](http://photutils.readthedocs.io/en/stable/api/photutils.find_peaks.html) to detect point-like sources on the images:

# In[19]:

# cut out smaller piece of the PSF image to save computing time
# for covenience we're "misusing" the SkyImage class represent the PSF on the sky.
kernel = images['psf'].cutout(target_position, size=1.1 * u.deg)
kernel.show()

# In[20]:
Exemple #12
0
 def excess_image(self):
     """Compute excess between counts and bkg image."""
     total_excess = SkyImage.empty_like(self.empty_image)
     total_excess.data = self.images["counts"].data - self.images["bkg"].data
     self.images["excess"] = total_excess
Exemple #13
0
                                          exclusion_mask=exclusion_mask)

comp_image = image_estimator.run(mylist)
comp_image.names

images = comp_image

print("Total number of counts", images[0].data.sum())
print("Total number of excess events", images[3].data.sum())

fermi = SkyImage.read("FDA16.fits")
fermi_rep = fermi.reproject(ref_image)

#Make sure that the exclusion mask properly excludes all sources

masked_excess = SkyImage.empty_like(images['excess'])
masked_excess.data = comp_image['excess'].data * exclusion_mask.data
masked_excess_cutout = masked_excess.cutout(position=SkyCoord(
    src.galactic.l.value, src.galactic.b.value, unit='deg', frame='galactic'),
                                            size=(9 * u.deg, 9 * u.deg))
masked_excess_cutout.show(add_cbar=True)

#masked_excess.plot(cmap='viridis',stretch='sqrt',add_cbar=True)
#plt.hist(masked_excess.data.flatten(),bins=100,log=True)

#smooth

excess_smooth = comp_image[3].smooth(radius=0.5 * u.deg)
excess_smooth.show(add_cbar=True)
counts_smooth = comp_image[3].smooth(radius=0.5 * u.deg)
#counts_smooth.show()