def make_image_from_2d_bg():
    center = SkyCoord(83.63, 22.01, unit='deg').galactic
    energy_band = Energy([1, 10], 'TeV')
    offset_band = Angle([0, 2.49], 'deg')
    data_store = DataStore.from_dir(
        '/Users/jouvin/Desktop/these/temp/bg_model_image/')

    # TODO: fix `binarize` implementation
    # exclusion_mask = exclusion_mask.binarize()
    image = SkyImage.empty(nxpix=250,
                           nypix=250,
                           binsz=0.02,
                           xref=center.l.deg,
                           yref=center.b.deg,
                           proj='TAN',
                           coordsys='GAL')

    refheader = image.to_image_hdu().header
    exclusion_mask = SkyMask.read(
        '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')
    exclusion_mask = exclusion_mask.reproject(reference=refheader)
    mosaic_images = StackedObsImageMaker(image,
                                         energy_band=energy_band,
                                         offset_band=offset_band,
                                         data_store=data_store,
                                         obs_table=data_store.obs_table,
                                         exclusion_mask=exclusion_mask)
    mosaic_images.make_images(make_background_image=True,
                              for_integral_flux=True,
                              radius=10.,
                              make_psf=True,
                              region_center=center)
    filename = 'fov_bg_images.fits'
    log.info('Writing {}'.format(filename))
    mosaic_images.images.write(filename, clobber=True)
Exemple #2
0
def plot_result(results):
    import matplotlib.pyplot as plt

    # Plot model
    energy = Energy.equal_log_spacing(1e-3, 1e2, nbins=100, unit='TeV')
    flux = results['model'](energy.to('TeV').value)
    flux = Quantity(flux, 'erg cm-2 s-1')
    plt.plot(energy, flux, label='model')

    # Plot data points
    data = FermiData()
    plt.errorbar(x=data.x,
                 y=data.y,
                 yerr=data.staterror,
                 fmt='ro',
                 label='data')

    data = IACTData()
    plt.errorbar(x=data.x,
                 y=data.y,
                 yerr=data.staterror,
                 fmt='ro',
                 label='data')

    # Make it pretty
    plt.loglog()
    plt.xlabel('Energy (TeV)')
    plt.ylabel('E^2 * dN / dE (TeV cm^-2 s^-1)')
    plt.legend()
    filename = 'example_sherpa_mwl.png'
    print('Writing {}'.format(filename))
    plt.savefig(filename)
Exemple #3
0
    def from_arrays(cls,
                    energy,
                    diff_flux,
                    energy_err_hi=None,
                    energy_err_lo=None,
                    diff_flux_err_hi=None,
                    diff_flux_err_lo=None):
        """Create `~gammapy.spectrum.DifferentialFluxPoints` from numpy arrays"""
        t = Table()
        energy = Energy(energy)
        diff_flux = Quantity(diff_flux)
        if not diff_flux.unit.is_equivalent('TeV-1 cm-2 s-1'):
            raise ValueError('Flux (unit {}) not a differential flux'.format(
                diff_flux.unit))

        # Set errors to zero by default
        def_f = np.zeros(len(energy)) * diff_flux.unit
        def_e = np.zeros(len(energy)) * energy.unit
        energy_err_hi = def_e if energy_err_hi is None else energy_err_hi
        energy_err_lo = def_e if energy_err_lo is None else energy_err_lo
        diff_flux_err_hi = def_f if diff_flux_err_hi is None else diff_flux_err_hi
        diff_flux_err_lo = def_f if diff_flux_err_lo is None else diff_flux_err_lo

        t['ENERGY'] = energy
        t['ENERGY_ERR_HI'] = energy_err_hi
        t['ENERGY_ERR_LO'] = energy_err_lo
        t['DIFF_FLUX'] = diff_flux
        t['DIFF_FLUX_ERR_HI'] = diff_flux_err_hi
        t['DIFF_FLUX_ERR_LO'] = diff_flux_err_lo
        return cls(t)
def make_psf_several_energyband(energy_bins,
                                source_name,
                                center,
                                ObsList,
                                outdir,
                                spectral_index=2.3):
    """
    Compute the mean psf for a set of observation for different energy bands
    Parameters
    ----------
    energy_band: energy band on which you want to compute the map
    source_name: name of the source you want to compute the image
    center: SkyCoord of the source
    ObsList: ObservationList to use to compute the psf (could be different that the data_store for G0p9 for the GC for example)
    outdir: directory where the fits image will go
    spectral_index: assumed spectral index to compute the psf

    Returns
    -------

    """
    for i, E in enumerate(energy_bins[0:-1]):
        energy_band = Energy([energy_bins[i].value, energy_bins[i + 1].value],
                             energy_bins.unit)
        print energy_band
        make_psf(energy_band, source_name, center, ObsList, outdir,
                 spectral_index)
Exemple #5
0
def test_image_pipe(tmpdir):
    tmpdir = str(tmpdir)
    from subprocess import call
    outdir = tmpdir
    outdir2 = outdir + '/background'

    cmd = 'mkdir -p {}'.format(outdir2)
    print('Executing: {}'.format(cmd))
    call(cmd, shell=True)

    ds = DataStore.from_dir("$GAMMAPY_EXTRA/datasets/hess-crab4-hd-hap-prod2")
    ds.copy_obs(ds.obs_table, tmpdir)
    data_store = DataStore.from_dir(tmpdir)

    bgmaker = OffDataBackgroundMaker(data_store, outdir=outdir2)

    bgmaker.select_observations(selection='all')
    bgmaker.group_observations()
    bgmaker.make_model("2D")
    bgmaker.save_models("2D")

    fn = outdir2 + '/group-def.fits'

    hdu_index_table = bgmaker.make_total_index_table(
        data_store=data_store,
        modeltype='2D',
        out_dir_background_model=outdir2,
        filename_obs_group_table=fn
    )

    fn = outdir + '/hdu-index.fits.gz'
    hdu_index_table.write(fn, overwrite=True)

    tmpdir = str(tmpdir)
    center = SkyCoord(83.63, 22.01, unit='deg').galactic
    energy_band = Energy([1, 10], 'TeV')
    offset_band = Angle([0, 2.49], 'deg')
    data_store = DataStore.from_dir(tmpdir)

    # TODO: fix `binarize` implementation
    # exclusion_mask = exclusion_mask.binarize()
    image = SkyImage.empty(nxpix=250, nypix=250, binsz=0.02, xref=center.l.deg,
                           yref=center.b.deg, proj='TAN', coordsys='GAL')

    refheader = image.to_image_hdu().header
    exclusion_mask = SkyMask.read('$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')
    exclusion_mask = exclusion_mask.reproject(reference=refheader)
    # Pb with the load psftable for one of the run that is not implemented yet...
    data_store.hdu_table.remove_row(14)
    mosaic = MosaicImage(image, energy_band=energy_band, offset_band=offset_band, data_store=data_store,
                         obs_table=data_store.obs_table, exclusion_mask=exclusion_mask)
    mosaic.make_images(make_background_image=True, for_integral_flux=True, radius=10.)
    assert_allclose(mosaic.maps['counts'].data.sum(), 2334.0, atol=3)
    assert_allclose(mosaic.maps['bkg'].data.sum(), 1987.1513636663785, atol=3)
    assert_allclose(mosaic.maps['exposure'].data.sum(), 54190569251987.68, atol=3)
    assert_allclose(mosaic.maps['significance'].lookup(center), 33.707901541600634, atol=3)
    assert_allclose(mosaic.maps['excess'].data.sum(), 346.8486363336217, atol=3)
    def plot_spectral_models(self):

        for component in self.get_components(tags=['pwn', 'composite']):
            fig, ax = plt.subplots()
            table = component['table']
            tag = component['tag']
            vals = []
            idx = 0

            energies = Energy.equal_log_spacing(emin=0.02,
                                                emax=100,
                                                unit='TeV',
                                                nbins=40)
            for row in table:
                idx += 1
                if (idx < 100):
                    spec = LogParabola(
                        amplitude=row['spec_norm'] * u.Unit('MeV-1 s-1 cm-2'),
                        alpha=row['spec_alpha'],
                        reference=1 * u.TeV,
                        beta=row['spec_beta'],
                    )
                    fluxes = []
                    e2dnde = []
                    for energy in energies:
                        dnde = spec.evaluate(
                            energy=energy,
                            amplitude=row['spec_norm'] *
                            u.Unit('MeV-1 s-1 cm-2'),
                            alpha=row['spec_alpha'],
                            reference=1 * u.TeV,
                            beta=row['spec_beta'],
                        )
                        fluxes.append(dnde.value)
                        e2dnde.append(
                            ((energy**2 * dnde).to('erg cm-2 s-1')).value)
                    ax.plot(energies.value,
                            e2dnde,
                            color='black',
                            alpha=0.2,
                            lw=2)
                else:
                    break

            ax.set_title('{} spectra'.format(component['tag']))
            ax.loglog()
            ax.set_xlabel('Energy (TeV)')
            ax.set_ylabel('e2dnde (erg cm-2 s-1)')
            ax.set_ylim(2e-18, 5e-10)

            fig.tight_layout()
            filename = 'ctadc_skymodel_gps_sources_spectra_{}.png'.format(
                component['tag'])
            log.info('Writing {}'.format(filename))
            fig.savefig(filename)
            plt.close(fig)
    def _get_ref_cube(self, enumbins=11):
        p = self.parameters

        wcs = self.reference.wcs.deepcopy()
        shape = (enumbins, ) + self.reference.data.shape
        data = np.zeros(shape)

        energy = Energy.equal_log_spacing(p['emin'], p['emax'], enumbins,
                                          'TeV')
        energy_axis = LogEnergyAxis(energy, mode='center')
        return SkyCube(data=data, wcs=wcs, energy_axis=energy_axis)
def make_psf_cube(image_size,
                  energy_cube,
                  source_name,
                  center_maps,
                  center,
                  ObsList,
                  outdir,
                  spectral_index=2.3):
    """
    Compute the mean psf for a set of observation for different energy bands
    Parameters
    ----------
    image_size:int, Total number of pixel of the 2D map
    energy: Tuple for the energy axis: (Emin,Emax,nbins)
    source_name: name of the source you want to compute the image
    center_maps: SkyCoord
            center of the images
    center: SkyCoord 
            position where we want to compute the psf
    ObsList: ObservationList to use to compute the psf (could be different that the data_store for G0p9 for the GC for example)
    outdir: directory where the fits image will go
    spectral_index: assumed spectral index to compute the psf

    Returns
    -------

    """
    ref_cube = make_empty_cube(image_size, energy_cube, center_maps)
    header = ref_cube.sky_image_ref.to_image_hdu().header
    energy_bins = ref_cube.energies(mode="edges")
    for i_E, E in enumerate(energy_bins[0:-1]):
        energy_band = Energy(
            [energy_bins[i_E].value, energy_bins[i_E + 1].value],
            energy_bins.unit)
        energy = EnergyBounds.equal_log_spacing(energy_band[0].value,
                                                energy_band[1].value, 100,
                                                energy_band.unit)
        # Here all the observations have a center at less than 2 degrees from the Crab so it will be ok to estimate the mean psf on the Crab source postion (the area is define for offset equal to 2 degrees...)
        psf_energydependent = ObsList.make_mean_psf(center, energy, theta=None)
        try:
            psf_table = psf_energydependent.table_psf_in_energy_band(
                energy_band, spectral_index=spectral_index)
        except:
            psf_table = TablePSF(
                psf_energydependent.offset,
                Quantity(np.zeros(len(psf_energydependent.offset)), u.sr**-1))
        ref_cube.data[i_E, :, :] = fill_acceptance_image(
            header, center_maps, psf_table._offset.to("deg"),
            psf_table._dp_domega,
            psf_table._offset.to("deg")[-1]).data
    ref_cube.write(outdir + "/mean_psf_cube_" + source_name + ".fits",
                   format="fermi-counts")
Exemple #9
0
def plot_spectral_model(model, ax, plot_kwargs):
    energies = Energy.equal_log_spacing(emin=0.02,
                                        emax=100,
                                        unit='TeV',
                                        nbins=40)
    fluxes = []
    for energy in energies:
        energy_gammalib = gammalib.GEnergy(energy.value, 'TeV')
        fluxes.append(model.eval(energy_gammalib))

    dnde = u.Quantity(fluxes, 'cm-2 s-1 MeV-1')
    e2dnde = (energies**2 * dnde).to('erg cm-2 s-1')

    ax.plot(energies.value, e2dnde.value, **plot_kwargs)
Exemple #10
0
def make_mean_psf_cube(image_size,
                       energy_cube,
                       center_maps,
                       center,
                       ObsList,
                       spectral_index=2.3):
    """
    Compute the mean psf for a set of observation for different energy bands
    Parameters
    ----------
    image_size:int, Total number of pixel of the 2D map
    energy: Tuple for the energy axis: (Emin,Emax,nbins)
    center_maps: SkyCoord
            center of the images
    center: SkyCoord 
            position where we want to compute the psf
    ObsList: ObservationList to use to compute the psf (could be different that the data_store for G0p9 for the GC for example)
    spectral_index: assumed spectral index to compute the psf

    Returns
    -------
    ref_cube : `~gammapy.cube.SkyCube`
             PSF mean cube

    """
    ref_cube = make_empty_cube(image_size, energy_cube, center_maps)
    header = ref_cube.sky_image_ref.to_image_hdu().header
    energy_bins = ref_cube.energies()
    for i_E, E in enumerate(energy_bins[0:-1]):
        energy_band = Energy(
            [energy_bins[i_E].value, energy_bins[i_E + 1].value],
            energy_bins.unit)
        energy = EnergyBounds.equal_log_spacing(energy_band[0].value,
                                                energy_band[1].value, 100,
                                                energy_band.unit)
        psf_energydependent = ObsList.make_psf(center, energy, theta=None)
        try:
            psf_table = psf_energydependent.table_psf_in_energy_band(
                energy_band, spectral_index=spectral_index)
        except:
            psf_table = TablePSF(
                psf_energydependent.offset,
                Quantity(np.zeros(len(psf_energydependent.offset)), u.sr**-1))
        ref_cube.data[i_E, :, :] = fill_acceptance_image(
            header, center_maps, psf_table._offset.to("deg"),
            psf_table._dp_domega,
            psf_table._offset.to("deg")[-1]).data
    return ref_cube
Exemple #11
0
def make_model():
    dir = str(gammapy_extra.dir) + '/datasets/hess-crab4-hd-hap-prod2'
    data_store = DataStore.from_dir(dir)
    obs_table = data_store.obs_table
    ebounds = EnergyBounds.equal_log_spacing(0.1, 100, 100, 'TeV')
    offset = sqrt_space(start=0, stop=2.5, num=100) * u.deg

    excluded_sources = make_excluded_sources()

    multi_array = EnergyOffsetBackgroundModel(ebounds, offset)
    multi_array.fill_obs(obs_table, data_store, excluded_sources)
    # multi_array.fill_obs(obs_table, data_store)
    multi_array.compute_rate()
    bgarray = multi_array.bg_rate
    energy_range = Energy([1, 10], 'TeV')
    table = bgarray.acceptance_curve_in_energy_band(energy_range,
                                                    energy_bins=10)

    multi_array.write('energy_offset_array.fits', overwrite=True)
    table.write('acceptance_curve.fits', overwrite=True)
Exemple #12
0
def make_image_from_2d_bg():
    center = SkyCoord(83.63, 22.01, unit='deg').galactic
    energy_band = Energy([1, 10], 'TeV')
    offset_band = Angle([0, 2.49], 'deg')
    data_store = DataStore.from_dir(
        '/Users/jouvin/Desktop/these/temp/bg_model_image/')

    # TODO: fix `binarize` implementation
    # exclusion_mask = exclusion_mask.binarize()
    image = SkyMap.empty(nxpix=250,
                         nypix=250,
                         binsz=0.02,
                         xref=center.l.deg,
                         yref=center.b.deg,
                         proj='TAN',
                         coordsys='GAL')

    refheader = image.to_image_hdu().header
    exclusion_mask = ExclusionMask.read(
        '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')
    exclusion_mask = exclusion_mask.reproject(reference=refheader)
    images = ImageAnalysis(image,
                           energy_band=energy_band,
                           offset_band=offset_band,
                           data_store=data_store,
                           obs_table=data_store.obs_table,
                           exclusion_mask=exclusion_mask)

    images.make_maps(radius=10.,
                     bkg_norm=True,
                     spectral_index=2.3,
                     for_integral_flux=True)
    # images.make_total_exposure()
    filename = 'fov_bg_maps.fits'
    log.info('Writing {}'.format(filename))

    images.maps.write(filename, clobber=True)
def plot_result(results):
    import matplotlib.pyplot as plt

    # Plot model
    energy = Energy.equal_log_spacing(1e-3, 1e2, nbins=100, unit='TeV')
    flux = results['model'](energy.to('TeV').value)
    flux = Quantity(flux, 'erg cm-2 s-1')
    plt.plot(energy, flux, label='model')

    # Plot data points
    data = FermiData()
    plt.errorbar(x=data.x, y=data.y, yerr=data.staterror, fmt='ro', label='data')

    data = IACTData()
    plt.errorbar(x=data.x, y=data.y, yerr=data.staterror, fmt='ro', label='data')

    # Make it pretty
    plt.loglog()
    plt.xlabel('Energy (TeV)')
    plt.ylabel('E^2 * dN / dE (TeV cm^-2 s^-1)')
    plt.legend()
    filename = 'example_sherpa_mwl.png'
    print('Writing {}'.format(filename))
    plt.savefig(filename)
Exemple #14
0
name += "_LS_fwhm_min_"+str(param_fit["Large scale"]["fwhm_min"])+"_init_"+str(param_fit["Large scale"]["fwhm_init"])
#if param_fit["Gauss_to_CS"]["fwhm_min"]:
name += "_CS_fwhm_min_"+str(param_fit["Gauss_to_CS"]["fwhm_min"])+"_init_"+str(param_fit["Gauss_to_CS"]["fwhm_init"])

  
name += "_GC_source_fwhm_"+str(param_fit["gauss_SgrA"]["fwhm_init"])     
if param_fit["Large scale"]["ellip_frozen"]:
    name += "_eLS_"+str(param_fit["Large scale"]["ellip_init"])
if param_fit["Large scale"]["fwhm_frozen"]:
    name += "_fwhmLS_"+str(param_fit["Large scale"]["fwhm_init"])
if param_fit["Gauss_to_CS"]["fwhm_frozen"]:
    name += "_fwhmCS_"+str(param_fit["Gauss_to_CS"]["fwhm_init"])
if param_fit["central_gauss"]["fwhm_frozen"]:
    name += "_fwhmCC_"+str(param_fit["central_gauss"]["fwhm_init"])              
config_name = input_param["general"]["config_name"]
energy_reco=[Energy(input_param["energy binning"]["Emin"],"TeV"),Energy(input_param["energy binning"]["Emax"],"TeV"), input_param["energy binning"]["nbin"]]


outdir_data = make_outdir_data(source_name, name_method_fond,config_name,image_size,for_integral_flux=False,ereco=energy_reco)
directory = make_outdir_filesresult(source_name, name_method_fond,config_name,image_size,for_integral_flux=False,ereco=energy_reco)

#directory="/Users/jouvin/Desktop/these/test_Gammapy/script/ash_stereo_thsq64/Image_GC_bkg_coszenbinning_zen_0_34_49_61_72_26binE/binE_1_min_0.5_max_100.0_size_image_250_pix_exposure_flux_diff/files_result"
#outdir_data="/Users/jouvin/Desktop/these/test_Gammapy/script/ash_stereo_thsq64/Image_GC_bkg_coszenbinning_zen_0_34_49_61_72_26binE/binE_1_min_0.5_max_100.0_size_image_250_pix_exposure_flux_diff"
energy_bins=EnergyBounds.equal_log_spacing(0.5,100,1,"TeV")
pix_to_deg=0.02
for i, E in enumerate(energy_bins[:-1]):
    E1=energy_bins[i].value
    E2=energy_bins[i+1].value
    print("Energy band:"+str("%.2f" % E1)+"-"+str("%.2f" % E2)+" TeV")
    filename=directory+"/morphology_fit_result_"+name+"_"+str("%.2f" % E1)+"_"+str("%.2f" % E2)+"_TeV.txt"
    filename_err=directory+"/morphology_fit_covar_"+name+"_"+str("%.2f" % E1)+"_"+str("%.2f" % E2)+"_TeV.txt"
obsid=srcruns['OBS_ID'].data
good_obs=np.loadtxt("PKS2155_PA_201801.list.txt",usecols=(0))
obsid1=np.intersect1d(good_obs,obsid)
mylist=datastore.obs_list(obsid1)
#N=len(mylist)

ref_image = SkyImage.empty(
    nxpix=400, nypix=400, binsz=0.02,
    xref=src.ra.deg, yref=src.dec.deg,
    coordsys='CEL', proj='TAN',
)

exclusion_mask_tevcat = SkyImage.read('$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')
exclusion_mask_tevcat = exclusion_mask_tevcat.reproject(reference=ref_image)

energy_band = Energy([0.52480746, 1.58489319], 'TeV')
energy_band = Energy([0.5, 1.5], 'TeV')
of1=Angle([0.0, 0.50251891], 'deg')
of2=Angle([0.50251891, 1.20499801], 'deg')
of3=Angle([1.20499801, 2.01007563], 'deg')
of4=Angle([2.01007563, 2.48734169], 'deg')
#of1=Angle([0.0, 1.2], 'deg')
#of2=Angle([0.50251891, 1.2], 'deg')
offset_band = [of1,of2,of3,of4]
backnorm=[]
Ncounts=[]



list_zen=filter(lambda o1: o1.pointing_zen.value<34.3, mylist)
Exemple #16
0

from gammapy.utils.nddata import NDDataArray, DataAxis, BinnedDataAxis
from gammapy.utils.energy import Energy, EnergyBounds
import numpy as np
import astropy.units as u


# ## 1D example
# 
# Let's start with a simple example. A one dimensional array storing an exposure in ``cm-2 s-1`` as a function of energy. The energy axis is log spaced and thus also the interpolation shall take place in log.

# In[ ]:


energies = Energy.equal_log_spacing(10, 100, 10, unit=u.TeV)
x_axis = DataAxis(energies, name="energy", interpolation_mode="log")
data = np.arange(20, 0, -2) / u.cm ** 2 / u.s
nddata = NDDataArray(axes=[x_axis], data=data)
print(nddata)
print(nddata.axis("energy"))


# In[ ]:


eval_energies = np.linspace(2, 6, 20) * 1e4 * u.GeV
eval_exposure = nddata.evaluate(energy=eval_energies, method="linear")

plt.plot(
    nddata.axis("energy").nodes.value,
Exemple #17
0
    coord_center_pix = sky_mask_cube.sky_image_ref.coordinates(
        mode="center").icrs
    lon = np.tile(coord_center_pix.data.lon.degree, (len(energies) - 1, 1, 1))
    lat = np.tile(coord_center_pix.data.lat.degree, (len(energies) - 1, 1, 1))
    coord_3d_center_pix = SkyCoord(lon, lat, unit="deg")
    index_excluded_region = np.where(
        (exclusion_region.center
         ).separation(coord_3d_center_pix) < exclusion_region.radius)
    sky_mask_cube.data[:] = 1
    sky_mask_cube.data[index_excluded_region] = 0

    sky_mask_cube.write("mask.fits", format="fermi-counts", clobber=True)


if __name__ == '__main__':
    energy_true = [Energy(0.1, "TeV"), Energy(100, "TeV"), 20]
    energy_reco = [Energy(0.5, "TeV"), Energy(40, "TeV"), 5]
    center = SkyCoord(83.63, 22.01, unit='deg').galactic
    make_cubes(ereco=energy_reco,
               etrue=energy_true,
               use_etrue=True,
               center=center)
    make_cubes(ereco=energy_reco,
               etrue=energy_reco,
               use_etrue=False,
               center=center)

    # This is just a test case for the test for the 3d Analysis if we want to exclude a region in the fit
    exclude_region = CircleSkyRegion(SkyCoord(83.60, 21.88, unit='deg'),
                                     Angle(0.1, "deg"))
    make_skymaskcube(ereco=energy_reco,
Exemple #18
0
if param_fit["central_gauss"]["fit"]:
    name += "_central_gauss"
if param_fit["arc source"]["fit"]:
    name += "_arcsource"
if param_fit["SgrB2"]["fit"]:
    name += "_SgrB2"

residus_l = list()
residus_err_l = list()
residus_b = list()
residus_err_b = list()
for i_E, E in enumerate(energy_bins[0:-1]):
    #for i_E, E in enumerate(energy_bins[0:-1]):
    E1 = energy_bins[i_E].value
    E2 = energy_bins[i_E + 1].value
    energy_band = Energy([E1, E2], energy_bins.unit)
    print "energy band: ", E1, " TeV- ", E2, "TeV"
    # load Data
    on = SkyImageList.read(outdir_data + "/fov_bg_maps" + str(E1) + "_" +
                           str(E2) + "_TeV.fits")["counts"]
    on.write(outdir_data + "/on_maps" + str(E1) + "_" + str(E2) + "_TeV.fits",
             clobber=True)
    data = fits.open(outdir_data + "/on_maps" + str(E1) + "_" + str(E2) +
                     "_TeV.fits")
    load_image(1, data)
    # load exposure model
    exposure = make_exposure_model(outdir_data, E1, E2)
    # load bkg model
    bkg = make_bkg_model(outdir_data, E1, E2, freeze_bkg)
    # load psf model
    psf_SgrA = make_psf_model(outdir_data, E1, E2, on, "GC")
Exemple #19
0
def test_image_pipe(tmpdir):
    tmpdir = str(tmpdir)
    from subprocess import call
    outdir = tmpdir
    outdir2 = outdir + '/background'

    cmd = 'mkdir -p {}'.format(outdir2)
    print('Executing: {}'.format(cmd))
    call(cmd, shell=True)

    ds = DataStore.from_dir("$GAMMAPY_EXTRA/datasets/hess-crab4-hd-hap-prod2")
    ds.copy_obs(ds.obs_table, tmpdir)
    data_store = DataStore.from_dir(tmpdir)

    bgmaker = OffDataBackgroundMaker(data_store, outdir=outdir2)

    bgmaker.select_observations(selection='all')
    bgmaker.group_observations()
    bgmaker.make_model("2D")
    bgmaker.save_models("2D")

    fn = outdir2 + '/group-def.fits'

    hdu_index_table = bgmaker.make_total_index_table(
        data_store=data_store,
        modeltype='2D',
        out_dir_background_model=outdir2,
        filename_obs_group_table=fn)

    fn = outdir + '/hdu-index.fits.gz'
    hdu_index_table.write(fn, overwrite=True)

    tmpdir = str(tmpdir)
    center = SkyCoord(83.63, 22.01, unit='deg').galactic
    energy_band = Energy([1, 10], 'TeV')
    offset_band = Angle([0, 2.49], 'deg')
    data_store = DataStore.from_dir(tmpdir)

    # TODO: fix `binarize` implementation
    # exclusion_mask = exclusion_mask.binarize()
    image = SkyMap.empty(nxpix=250,
                         nypix=250,
                         binsz=0.02,
                         xref=center.l.deg,
                         yref=center.b.deg,
                         proj='TAN',
                         coordsys='GAL')

    refheader = image.to_image_hdu().header
    exclusion_mask = ExclusionMask.read(
        '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')
    exclusion_mask = exclusion_mask.reproject(reference=refheader)
    images = ImageAnalysis(image,
                           energy_band=energy_band,
                           offset_band=offset_band,
                           data_store=data_store,
                           obs_table=data_store.obs_table,
                           exclusion_mask=exclusion_mask)

    images.make_maps(radius=10.,
                     bkg_norm=True,
                     spectral_index=2.3,
                     for_integral_flux=True)
Exemple #20
0
ref_image = SkyImage.empty(
    nxpix=400,
    nypix=400,
    binsz=0.02,
    xref=src.ra.deg,
    yref=src.dec.deg,
    coordsys='CEL',
    proj='TAN',
)

exclusion_mask_tevcat = SkyImage.read(
    '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')
exclusion_mask_tevcat = exclusion_mask_tevcat.reproject(reference=ref_image)

energy_band = Energy([0.5, 1.0], 'TeV')
#energy_band = Energy([0.5, 50.0], 'TeV')
offset_band = Angle([0.0, 1.5], 'deg')
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]
Exemple #21
0
name += "_GC_source_fwhm_" + str(param_fit["gauss_SgrA"]["fwhm_init"])
if param_fit["Large scale"]["ellip_frozen"]:
    name += "_eLS_" + str(param_fit["Large scale"]["ellip_init"])
if param_fit["Large scale"]["fwhm_frozen"]:
    name += "_fwhmLS_" + str(param_fit["Large scale"]["fwhm_init"])
if param_fit["Gauss_to_CS"]["fwhm_frozen"]:
    name += "_fwhmCS_" + str(param_fit["Gauss_to_CS"]["fwhm_init"])

#Energy binning
energy_bins = EnergyBounds.equal_log_spacing(
    input_param["energy binning"]["Emin"],
    input_param["energy binning"]["Emax"],
    input_param["energy binning"]["nbin"], 'TeV')
E_center = energy_bins.log_centers
energy_reco = [
    Energy(input_param["energy binning"]["Emin"], "TeV"),
    Energy(input_param["energy binning"]["Emax"], "TeV"),
    input_param["energy binning"]["nbin"]
]

#outdir result and plot
config_name = input_param["general"]["config_name"]
outdir_result = make_outdir_filesresult(source_name,
                                        name_method_fond,
                                        config_name,
                                        image_size,
                                        for_integral_flux=False,
                                        ereco=energy_reco)
outdir_plot = make_outdir_plot(source_name,
                               name_method_fond,
                               config_name,
Exemple #22
0
# In[4]:


# Define sky image
ref_image = SkyImage.empty(
    nxpix=300, nypix=300, binsz=0.02,
    xref=83.63, yref=22.01,
    proj='TAN', coordsys='CEL',
)


# In[5]:


# Define energy band
energy_band = Energy([1, 10], 'TeV')


# In[6]:


# Define maximum field of view offset cut
offset_band = Angle([0, 2.49], 'deg')


# You define an exclusion mask that will be use to create the backgroud 2D map. The background map are normalized on the counts map outside the exclusion region

# In[7]:


# Define exclusion mask (known gamma-ray sources)
Exemple #23
0
freeze_bkg = input_param["param_fit_morpho"]["freeze_bkg"]
source_name = input_param["general"]["source_name"]
name_method_fond = input_param["general"]["name_method_fond"]
if freeze_bkg:
    name = "_bkg_fix"
else:
    name = "_bkg_free"
for_integral_flux = input_param["exposure"]["for_integral_flux"]
# Energy binning
energy_bins = EnergyBounds.equal_log_spacing(
    input_param["energy binning"]["Emin"],
    input_param["energy binning"]["Emax"],
    input_param["energy binning"]["nbin"], 'TeV')
energy_centers = energy_bins.log_centers
energy_reco = [
    Energy(input_param["energy binning"]["Emin"], "TeV"),
    Energy(input_param["energy binning"]["Emax"], "TeV"),
    input_param["energy binning"]["nbin"]
]

# outdir data and result
config_name = input_param["general"]["config_name"]
outdir_data = make_outdir_data(source_name,
                               name_method_fond,
                               config_name,
                               image_size,
                               for_integral_flux=False,
                               ereco=energy_reco)
outdir_result = make_outdir_filesresult(source_name,
                                        name_method_fond,
                                        config_name,
def make_images_several_energyband(image_size,
                                   energy_bins,
                                   offset_band,
                                   source_name,
                                   center,
                                   data_store,
                                   obs_table_subset,
                                   exclusion_mask,
                                   outdir,
                                   make_background_image=True,
                                   spectral_index=2.3,
                                   for_integral_flux=False,
                                   radius=10.,
                                   save_bkg_norm=True):
    """
    MAke the counts, bkg, mask, exposure, significance and ecxees images for different energy bands

    Parameters
    ----------
    energy_bins: array of energy bands on which you want to compute the map
    offset_band: offset band on which you want to compute the map
    center: SkyCoord of the source
    data_store: DataStore object containing the data used to coompute the image
    obs_table_subset: obs_table of the data_store containing the observations you want to use to compute the image. Could
    be smaller than the one of the datastore
    exclusion_mask: SkyMask used for the escluded regions
    outdir: directory where the fits image will go
    make_background_image: if you want to compute the bkg for the images. Most of the case yes otherwise there is only the counts image
    spectral_index: assumed spectral index to compute the exposure
    for_integral_flux: True if you want to get the inegrak flux with the exposure
    radius: Disk radius in pixels for the significance

    Returns
    -------
    """
    list_mosaicimages = list()
    for i, E in enumerate(energy_bins[0:-1]):
        energy_band = Energy([energy_bins[i].value, energy_bins[i + 1].value],
                             energy_bins.unit)
        print energy_band
        mosaicimages = make_images(image_size, energy_band, offset_band,
                                   center, data_store, obs_table_subset,
                                   exclusion_mask, outdir,
                                   make_background_image, spectral_index,
                                   for_integral_flux, radius, save_bkg_norm)
        list_mosaicimages.append(mosaicimages)
    if save_bkg_norm:
        table = Table()
        for i, mosaic_images in enumerate(list_mosaicimages):
            table_bkg = mosaic_images.table_bkg_scale
            if i == 0:
                array_bkg_scale = np.zeros(
                    (len(obs_table_subset), len(energy_bins[0:-1])))
                array_counts = np.zeros(
                    (len(obs_table_subset), len(energy_bins[0:-1])))
            itot = 0
            for irun, run in enumerate(table_bkg["OBS_ID"]):
                while run != obs_table_subset["OBS_ID"][itot]:
                    itot += 1
                array_bkg_scale[itot, i] = table_bkg["bkg_scale"][irun]
                array_counts[itot, i] = table_bkg["N_counts"][irun]
                itot += 1
        c0 = fits.Column(name="OBS_ID",
                         format='E',
                         array=table_bkg["OBS_ID"].data)
        c1 = fits.Column(name="bkg_norm", format='PE()', array=array_bkg_scale)
        c2 = fits.Column(name="counts", format='PE()', array=array_counts)
        hdu = fits.BinTableHDU.from_columns([c0, c1, c2])
        ebounds = energy_axis_to_ebounds(energy_bins)
        #ebounds = energy_axis_to_ebounds(BinnedDataAxis(energy_bins[0:-1],energy_bins[1:]))
        prim_hdu = fits.PrimaryHDU()
        hdu_list = fits.HDUList([prim_hdu, hdu, ebounds])
        hdu_list.writeto(outdir + "/table_bkg_norm_.fits")