def make_fermi_data(): filename = '$GAMMAPY_EXTRA/datasets/fermi_survey/all.fits.gz' image = SkyImage.read(filename, hdu='COUNTS') background = SkyImage.read(filename, hdu='BACKGROUND') return dict(image=image, background=background)
def make_poisson_data(): from gammapy.datasets import load_poisson_stats_image filename = load_poisson_stats_image(return_filenames=True) image = SkyImage.read(filename=filename) background = SkyImage.read(filename=filename) background.data = np.ones_like(image.data, dtype=float) return dict(image=image, background=background)
def make_fermi_data(): import os filename = os.environ['GAMMAPY_EXTRA'] + '/datasets/fermi_survey/all.fits.gz' image = SkyImage.read(filename=filename, extname='COUNTS') background = SkyImage.read(filename=filename, extname='BACKGROUND') return dict(image=image, background=background)
def make_fermi_data(): import os filename = os.environ[ 'GAMMAPY_EXTRA'] + '/datasets/fermi_survey/all.fits.gz' image = SkyImage.read(filename=filename, extname='COUNTS') background = SkyImage.read(filename=filename, extname='BACKGROUND') return dict(image=image, background=background)
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)
def mask_rxj1713(): filename = 'RXJ1713_above2TeV_2016.fits.gz' print('Reading {}'.format(filename)) image = SkyImage.read(filename) # The position from SIMBAD for "RX J1713.7-3946" and "SNR G347.3-00.5" # are offset by ~ 0.2 deg from the TeV shell center position # http://simbad.u-strasbg.fr/simbad/sim-id?Ident=SNR+G347.3-00.5 # SkyCoord.from_name('SNR G347.3-00.5') # Here we put the center position from TeVCat, which was taken from a HESS paper # http://tevcat.uchicago.edu/?mode=1&showsrc=84 region = CircleSkyRegion( center=SkyCoord(ra='17h13m33.6s', dec='-39d45m36s'), radius=Angle(0.7, 'deg'), ) # filename = 'RXJ1713_mask.reg' # print('Writing {}'.format(filename)) # write_ds9([region], filename=filename) # # fig, ax, cbar = image.plot() # filename = 'RXJ1713.png' # print('Writing {}'.format(filename)) # fig.savefig(filename) mask = image.region_mask(region) image.data *= mask.data filename = 'RXJ1713_above2TeV_2016_masked.fits.gz' print('Writing {}'.format(filename)) image.write(filename, overwrite=True)
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)
def make_counts_image(dataset, max_runs): log.info(f'Making all-sky image for dataset: {dataset}') data_store = DataStore.from_dir(f'1dc/1dc/index/{dataset}') image = SkyImage.empty( nxpix=3600, nypix=1800, binsz=0.1, xref=0, yref=0, proj='AIT', coordsys='GAL', ) # Define energy band # energy_band = Energy([1, 10], 'TeV') obs_ids = list(data_store.obs_table['OBS_ID']) obs_ids = obs_ids[:max_runs] if max_runs > 0 else obs_ids # Show a progress bar from tqdm import tqdm obs_ids = tqdm(obs_ids) for obs_id in obs_ids: events = data_store.obs(obs_id).events image.fill_events(events) image.data = image.data.astype('float32') filename = f'checks/images/allsky_counts_{dataset}.fits.gz' log.info(f'Writing {filename}') image.write(filename, overwrite=True)
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 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
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')
def make_images_grouped(): images = SkyImageList([ SkyImage.read('counts.fits.gz'), SkyImage.read('background.fits.gz'), SkyImage.read('exposure.fits.gz'), SkyImage.read('exclusion.fits.gz'), SkyImage.read('model.fits.gz'), ]) images[0].name = 'counts' images[1].name = 'background' images[2].name = 'exposure' images[3].name = 'exclusion' images[4].name = 'model' filename = 'input_all.fits.gz' print('Writing {}'.format(filename)) images.write(filename, clobber=True)
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
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 get_image(): filename = '/Users/deil/code/gammapy-extra/datasets/fermi_2fhl/gll_psch_v08.fit.gz' print('Reading {}'.format(filename)) image = SkyImage.read(filename) image.data = image.data.astype(float) sigma_pix = 3 sigma_deg = sigma_pix * image.wcs_pixel_scale()[0] print('Smoothing by sigma = {} pix = {:.3f}'.format(sigma_pix, sigma_deg)) image = image.smooth('gauss', sigma_pix) return image
def estimate_reflected(self, EXCLUSION_FILE, size): #just extracts the reflected background on_size=0.11 * u.deg #0.11 for point source cuts... allsky_mask = SkyImage.read(EXCLUSION_FILE) exclusion_mask = allsky_mask.cutout(position=self.obspos,size=size) on_region=CircleSkyRegion(self.obspos,on_size) background_estimator = ReflectedRegionsBackgroundEstimator(obs_list=self.obslist, on_region=on_region, exclusion_mask = exclusion_mask) background_estimator.run() return background_estimator.result[0]
def make_CS_model(outdir, data_image, ampl_init,ampl_frozen, threshold_zero_value): CS_map = SkyImage.read("CStot.fits") if 'COMMENT' in CS_map.meta: del CS_map.meta['COMMENT'] cs_reproj = CS_map.reproject(data_image) cs_reproj.data[np.where(np.isnan(cs_reproj.data))] = 0 cs_reproj.data[np.where(cs_reproj.data < threshold_zero_value)] = 0 cs_reproj.data = cs_reproj.data / cs_reproj.data.sum() cs_reproj.write(outdir + "/cs_map_reproj.fits", clobber=True) load_table_model("CS", outdir + "/cs_map_reproj.fits") set_par(CS.ampl, val=ampl_init, min=0, max=None, frozen=ampl_frozen) return CS
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 = SkyImage.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)
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
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
def run_benchmark(): # Set up data store and select N_OBS times the observation OBS_ID data_store = DataStore.from_dir('$GAMMAPY_EXTRA/test_datasets/cta_1dc/') obs_ids = OBS_ID * np.ones(N_OBS) obs_list = data_store.obs_list(obs_id=obs_ids) target_position = SkyCoord(0, 0, unit='deg', frame='galactic') on_radius = 0.2 * u.deg on_region = CircleSkyRegion(center=target_position, radius=on_radius) bkg_estimator = RingBackgroundEstimator( r_in=0.5 * u.deg, width=0.2 * u.deg, ) # Define reference image centered on the target xref = target_position.galactic.l.value yref = target_position.galactic.b.value ref_image = SkyImage.empty( nxpix=800, nypix=600, binsz=0.02, xref=xref, yref=yref, proj='TAN', coordsys='GAL', ) exclusion_mask = ref_image.region_mask(on_region) exclusion_mask.data = 1 - exclusion_mask.data image_estimator = IACTBasicImageEstimator( reference=ref_image, emin=100 * u.GeV, emax=100 * u.TeV, offset_max=3 * u.deg, background_estimator=bkg_estimator, exclusion_mask=exclusion_mask, ) result = image_estimator.run(obs_list)
def make_EG_model(outdir, data_image): """ Parameters ---------- outdir: str directory chere are stored the data data_image: SkyImage on map to reproject the psf Returns ------- """ EmGal_map = SkyImage.read("HGPS_large_scale_emission_model.fits", ext=1) emgal_reproj = EmGal_map.reproject(data_image) emgal_reproj.data[np.where(np.isnan(emgal_reproj.data))] = 0 emgal_reproj.write(outdir + "/emgal_reproj.fits", clobber=True) load_table_model("EmGal", outdir + "/emgal_reproj.fits") set_par(EmGal.ampl, val=1e-8, min=0, max=None, frozen=None) return EmGal
ENERGY_SPEC = { 'mode': 'edges', 'enumbins': 5, 'emin': 0.5, 'emax': 40, 'eunit': 'TeV' } REF_CUBE = SkyCube.empty(emin=0.5, emax=40.0, enumbins=5, **WCS_SPEC) # setting up the data store data_store = DataStore.from_dir("$GAMMAPY_EXTRA/test_datasets/cube/data") # temporary fix for load psftable for one of the run that is not implemented yet... data_store.hdu_table.remove_row(14) # read in TeVCat exclusion mask exclusion_mask = SkyImage.read( '$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits') # reproject exclusion mask to reference cube exclusion_mask = exclusion_mask.reproject(reference=REF_CUBE.sky_image_ref, order='nearest-neighbor') exclusion_mask.show() #Select the offset band on which you want to select the events in the FOV of each observation offset_band = Angle([0, 2.49], 'deg') # instanciate StackedObsCubeMaker cube_maker = StackedObsCubeMaker( empty_cube_images=REF_CUBE, empty_exposure_cube=REF_CUBE, offset_band=offset_band, data_store=data_store,
#get the observations name="PKS 2155-304" #name="Mkn 421" #name="1ES 0347-121" datastore = DataStore.from_dir("$HESS_DATA") src=SkyCoord.from_name(name) sep=SkyCoord.separation(src,datastore.obs_table.pointing_radec) srcruns=(datastore.obs_table[sep<1.5*u.deg]) 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) 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
"""Example how to compute and plot reflected regions.""" import matplotlib.pyplot as plt import numpy as np from astropy.coordinates import SkyCoord, Angle from regions import CircleSkyRegion from gammapy.image import SkyImage, lon_lat_rectangle_mask from gammapy.background import ReflectedRegionsFinder exclusion_mask = SkyImage.empty( nxpix=801, nypix=701, binsz=0.01, coordsys='CEL', xref=83.633, yref=23.014, fill=1 ) # Exclude Rectangular region mask = lon_lat_rectangle_mask( exclusion_mask.coordinates().ra, exclusion_mask.coordinates().dec, lat_max=Angle('24 deg'), lat_min=Angle('23 deg') ) exclusion_mask.data *= np.invert(mask) pos = SkyCoord(83.633, 22.014, unit='deg') radius = Angle(0.3, 'deg') on_region = CircleSkyRegion(pos, radius) center = SkyCoord(83.633, 24, unit='deg') finder = ReflectedRegionsFinder( region=on_region, center=center, exclusion_mask=exclusion_mask,
from gammapy.image import SkyImage, IACTBasicImageEstimator, SkyImageList from gammapy.background import FoVBackgroundEstimator from importlib import reload datastore = DataStore.from_dir("/Users/asinha/HESS_newbkg") name = "LMC" src = SkyCoord.from_name(name) myid = np.loadtxt("LMC_id.txt") mylist = datastore.obs_list(myid) ref_image = SkyImage.empty( nxpix=400, nypix=400, binsz=0.05, xref=src.galactic.l.value, yref=src.galactic.b.value, coordsys='GAL', proj='TAN', ) src_names = ["LMC N132D", "30 Dor C", "LHA 120-N 157B", "LMC P3"] l = [280.31, 279.60, 279.55, 277.73] * u.deg b = [-32.78, -31.91, -31.75, -32.09] * u.deg radius = [0.2, 0.2, 0.5, 0.2] * u.deg srctab = Table([src_names, l, b, radius], names=("src_names", "longitude", "latitude", "radius"), meta={'name': 'known source'}) off_regions = []
#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 + "_" +
"""Plot significance image with HESS and MILAGRO colormap. """ import numpy as np import matplotlib.pyplot as plt from gammapy.image import colormap_hess, colormap_milagro from astropy.visualization.mpl_normalize import ImageNormalize from astropy.visualization import LinearStretch from gammapy.image import SkyImage filename = '$GAMMAPY_EXTRA/test_datasets/unbundled/poisson_stats_image/expected_ts_0.000.fits.gz' image = SkyImage.read(filename, extname='sqrt_ts') # Plot with the HESS and Milagro colormap vmin, vmax, vtransition = -5, 15, 5 plt.figure(figsize=(12, 6)) normalize = ImageNormalize(vmin=vmin, vmax=vmax, stretch=LinearStretch()) transition = normalize(vtransition) plt.subplot(121) cmap = colormap_hess(transition=transition) plt.imshow(image, cmap=cmap, norm=normalize) plt.axis('off') plt.colorbar(shrink=0.7) plt.title('HESS-style colormap') plt.subplot(122) cmap = colormap_milagro(transition=transition) plt.imshow(image, cmap=cmap, norm=normalize) plt.axis('off') plt.colorbar(shrink=0.7)
"""Produces an image from 1FHL catalog point sources. """ import numpy as np import matplotlib.pyplot as plt from aplpy import FITSFigure from gammapy.datasets import FermiGalacticCenter from gammapy.image import catalog_image, SkyImage from gammapy.irf import EnergyDependentTablePSF # Create image of defined size reference = SkyImage.empty(nxpix=300, nypix=100, binsz=1).to_image_hdu() psf_file = FermiGalacticCenter.filenames()['psf'] psf = EnergyDependentTablePSF.read(psf_file) # Create image image = catalog_image(reference, psf, catalog='1FHL', source_type='point', total_flux='True') # Plot fig = FITSFigure(image.to_fits()[0], figsize=(15, 5)) fig.show_colorscale(interpolation='bicubic', cmap='afmhot', stretch='log', vmin=1E-12, vmax=1E-8) fig.tick_labels.set_xformat('ddd') fig.tick_labels.set_yformat('dd') ticks = np.logspace(-12, -8, 5) fig.add_colorbar(ticks=ticks, axis_label_text='Flux (ph s^-1 cm^-2 TeV^-1)') fig.colorbar._colorbar_axes.set_yticklabels(['{:.0e}'.format(_) for _ in ticks]) plt.tight_layout() plt.show()
"""Plot significance image with HESS and MILAGRO colormap. """ import numpy as np import matplotlib.pyplot as plt from gammapy.image import colormap_hess, colormap_milagro from astropy.visualization.mpl_normalize import ImageNormalize from astropy.visualization import LinearStretch from gammapy.image import SkyImage filename = '$GAMMAPY_EXTRA/test_datasets/unbundled/poisson_stats_image/expected_ts_0.000.fits.gz' image = SkyImage.read(filename, hdu='SQRT_TS') # Plot with the HESS and Milagro colormap vmin, vmax, vtransition = -5, 15, 5 plt.figure(figsize=(12, 6)) normalize = ImageNormalize(vmin=vmin, vmax=vmax, stretch=LinearStretch()) transition = normalize(vtransition) plt.subplot(121) cmap = colormap_hess(transition=transition) plt.imshow(image, cmap=cmap, norm=normalize) plt.axis('off') plt.colorbar(shrink=0.7) plt.title('HESS-style colormap') plt.subplot(122) cmap = colormap_milagro(transition=transition) plt.imshow(image, cmap=cmap, norm=normalize) plt.axis('off') plt.colorbar(shrink=0.7)
"""Plot Fermi PSF.""" import matplotlib.pyplot as plt from astropy import units as u from gammapy.datasets import FermiGalacticCenter from gammapy.irf import EnergyDependentTablePSF from gammapy.image import SkyImage filename = FermiGalacticCenter.filenames()['psf'] fermi_psf = EnergyDependentTablePSF.read(filename) fig = plt.figure(figsize=(6, 5)) # Create an empty sky image to show the PSF image_psf = SkyImage.empty() energies = [1] * u.GeV for energy in energies: psf = fermi_psf.table_psf_at_energy(energy=energy) image_psf.data = psf.kernel(image_psf) norm = image_psf.plot_norm('log') image_psf.plot(fig=fig, add_cbar=True, norm=norm) plt.show()
#name="Mkn 421" #name="1ES 0347-121" datastore = DataStore.from_dir("$HESS_DATA") src = SkyCoord.from_name(name) sep = SkyCoord.separation(src, datastore.obs_table.pointing_radec) srcruns = (datastore.obs_table[sep < 1.5 * u.deg]) 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) 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)
"""Produces an image from 1FHL catalog point sources. """ import numpy as np import matplotlib.pyplot as plt from aplpy import FITSFigure from gammapy.datasets import FermiGalacticCenter from gammapy.image import catalog_image, SkyImage from gammapy.irf import EnergyDependentTablePSF # Create image of defined size reference = SkyImage.empty(nxpix=300, nypix=100, binsz=1).to_image_hdu() psf_file = FermiGalacticCenter.filenames()['psf'] psf = EnergyDependentTablePSF.read(psf_file) # Create image image = catalog_image(reference, psf, catalog='1FHL', source_type='point', total_flux='True') # Plot fig = FITSFigure(image.to_fits(format='fermi-background')[0], figsize=(15, 5)) fig.show_colorscale(interpolation='bicubic', cmap='afmhot', stretch='log', vmin=1E-12, vmax=1E-8) fig.tick_labels.set_xformat('ddd') fig.tick_labels.set_yformat('dd') ticks = np.logspace(-12, -8, 5)
from astropy import units as u from astropy.coordinates import SkyCoord from astropy.convolution import Tophat2DKernel from gammapy.datasets import FermiGalacticCenter from gammapy.image import SkyImageList, SkyImage from gammapy.detect import KernelBackgroundEstimator # Parameters CORRELATION_RADIUS = 10 # Pixels SIGNIFICANCE_THRESHOLD = 5 # Sigma MASK_DILATION_RADIUS = 0.5 * u.deg # Load example images. filename = ('$GAMMAPY_EXTRA/datasets/source_diffuse_separation/' 'galactic_simulations/fermi_counts.fits') counts = SkyImage.read(filename) center = SkyCoord(0, 0, frame='galactic', unit='deg') images = SkyImageList() images['counts'] = counts.cutout(center, (10 * u.deg, 80 * u.deg)) kernel_src = Tophat2DKernel(CORRELATION_RADIUS).array kernel_bkg = np.ones((10, 150)) kbe = KernelBackgroundEstimator( kernel_src=kernel_src, kernel_bkg=kernel_bkg, significance_threshold=SIGNIFICANCE_THRESHOLD, mask_dilation_radius=MASK_DILATION_RADIUS, )
"""Plot Fermi PSF.""" import matplotlib.pyplot as plt from astropy import units as u from gammapy.datasets import FermiGalacticCenter from gammapy.irf import EnergyDependentTablePSF from gammapy.image import SkyImage filename = FermiGalacticCenter.filenames()['psf'] fermi_psf = EnergyDependentTablePSF.read(filename) fig = plt.figure(figsize=(6, 5)) # Compute a PSF kernel image # TODO: change this example after introducing PSF kernel class # (using SkyImage this way for kernels is weird) psf_image = SkyImage.empty() energy = 1 * u.GeV psf = fermi_psf.table_psf_at_energy(energy=energy) psf_image.data = psf.kernel(psf_image, rad_max=1 * u.deg).value psf_image.plot(fig=fig, add_cbar=True) plt.show()
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()))
#crab_pos = SkyCoord.from_name('crab') on_region = CircleSkyRegion(crab_pos, 0.15 * u.deg) model = models.LogParabola( alpha=2.3, beta=0, amplitude=1e-11 * u.Unit('cm-2 s-1 TeV-1'), reference=1 * u.TeV, ) flux_point_binning = EnergyBounds.equal_log_spacing(0.7, 30, 5, u.TeV) # 0.7, 30, 5, u.TeV exclusion_mask = SkyImage.read( '/Users/lucatosti/gammapy-extra/datasets/exclusion_masks/tevcat_exclusion.fits' ) config = dict(outdir=None, background=dict( on_region=on_region, exclusion_mask=exclusion_mask, min_distance=0.1 * u.rad, ), extraction=dict(containment_correction=False), fit=dict(model=model, stat='wstat', forward_folded=True, fit_range=flux_point_binning[[0, -1]]), fp_binning=flux_point_binning)