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 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 = 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_images.make_images(make_background_image=True, for_integral_flux=True, radius=10., make_psf = True, region_center=center) filename = 'fov_bg_maps.fits' log.info('Writing {}'.format(filename)) mosaic_images.maps.write(filename, clobber=True)
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)
"""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 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 a rectangular region coords = exclusion_mask.coordinates() mask = (Angle('23d') < coords.dec) & (coords.dec < Angle('24d')) 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, min_distance_input='0.2 rad',
"""Produces an image from 1FHL catalog point sources. """ import numpy as np import matplotlib.pyplot as plt from astropy import units as u from astropy.visualization import simple_norm from gammapy.image import CatalogImageEstimator, SkyImage from gammapy.irf import EnergyDependentTablePSF from gammapy.catalog import SourceCatalog3FHL # Create reference image reference = SkyImage.empty(nxpix=300, nypix=100, binsz=0.1) emin, emax = [10, 500] * u.GeV fermi_3fhl = SourceCatalog3FHL() estimator = CatalogImageEstimator(reference=reference, emin=emin, emax=emax) result = estimator.run(fermi_3fhl) flux = result['flux'].smooth(radius=0.2 * u.deg) norm = simple_norm(flux.data, stretch='log') flux.show(norm=norm)
show_image(images['background'], vmax=4) show_image(images['excess'], vmax=2) """ #110380, 111140, 111159 #source_pos = SkyCoord.from_name('geminga',frame='galactic')#(83.633083, 22.0145, unit='deg') # If you have internet access, you could also use this to define the `source_pos`: #source_pos = SkyCoord.from_name('crab') source_pos = SkyCoord(0, 0, unit='deg',frame='galactic') #source_pos = SkyCoord.from_name('crab') print(source_pos) ref_image = SkyImage.empty( nxpix=800, nypix=800, binsz=0.02, #xref=source_pos.ra.deg, yref=source_pos.dec.deg, xref=source_pos.l.deg , yref=source_pos.b.deg, coordsys='GAL', proj='TAN', #coordsys='CEL' ) print("1") #events = data_store.obs(obs_id=23523).events###110380 events = data_store.obs(obs_id=110380).events counts_image = SkyImage.empty_like(ref_image) counts_image.fill_events(events) norm = simple_norm(counts_image.data, stretch='sqrt', min_cut=0, max_cut=0.3)#0.3 q1=counts_image.smooth(radius=0.1 * u.deg).plot(norm=norm, add_cbar=True) q=counts_image.cutout(position=SkyCoord(-5, 0, unit='deg', frame='galactic'),size=(20*u.deg, 20*u.deg)).smooth(radius=0.1 * u.deg).plot(norm=norm, add_cbar=True) #plt.show(counts_image) if(show_it==False): plt.show(q)
def make_images(image_size, energy_band, offset_band, 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 Parameters ---------- energy_band: energy band 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 ------- """ # TODO: fix `binarize` implementation image = SkyImage.empty(nxpix=image_size, nypix=image_size, binsz=0.02, xref=center.galactic.l.deg, yref=center.galactic.b.deg, proj='TAN', coordsys='GAL') refheader = image.to_image_hdu().header exclusion_mask = exclusion_mask.reproject(reference=refheader) mosaicimages = StackedObsImageMaker(image, energy_band=energy_band, offset_band=offset_band, data_store=data_store, obs_table=obs_table_subset, exclusion_mask=exclusion_mask, save_bkg_scale=save_bkg_norm) mosaicimages.make_images(make_background_image=make_background_image, spectral_index=spectral_index, for_integral_flux=for_integral_flux, radius=radius) filename = outdir + '/fov_bg_maps' + str(energy_band[0].value) + '_' + str( energy_band[1].value) + '_TeV.fits' if 'COMMENT' in mosaicimages.images["exclusion"].meta: del mosaicimages.images["exclusion"].meta['COMMENT'] write_mosaic_images(mosaicimages, filename) return mosaicimages
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 + "_" + str("%.2f" % E1) + "_" + str("%.2f" % E2) + "_TeV.fits", clobber=True) filename_table_result = outdir_result + "/morphology_fit_result" + name + ".txt" table_models.write(filename_table_result, format="ascii") filename_covar_result = outdir_result + "/morphology_fit_covar_result" + name + ".txt" table_covar.write(filename_covar_result, format="ascii")
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 = []
# Define reference image centered on the target # In[13]: from gammapy.image import SkyImage xref = pos_target.galactic.l.value yref = pos_target.galactic.b.value size = 10 * u.deg binsz = 0.02 # degree per pixel npix = int((size / binsz).value) print(npix) ref_image = SkyImage.empty( nxpix=500, nypix=500, binsz=binsz, xref=xref, yref=yref, proj='CAR', coordsys='GAL', ) print(ref_image) # We use the ring background estimation method, and an exclusion mask that excludes the bright source at the Galactic center. # In[14]: exclusion_mask = ref_image.region_mask(on_region) exclusion_mask.data = 1 - exclusion_mask.data exclusion_mask.plot() # In[15]:
"""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).value psf_image.plot(fig=fig, add_cbar=True) plt.show()
"""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,
"""Simulates a galaxy of point sources and produces an image. """ import numpy as np import matplotlib.pyplot as plt import astropy.units as u from aplpy import FITSFigure from gammapy.astro import population from gammapy.datasets import FermiGalacticCenter from gammapy.image import SkyImage, catalog_image from gammapy.irf import EnergyDependentTablePSF from gammapy.utils.random import sample_powerlaw # Create image of defined size reference = SkyImage.empty(nxpix=1000, nypix=200, binsz=0.2).to_image_hdu() psf_file = FermiGalacticCenter.filenames()['psf'] psf = EnergyDependentTablePSF.read(psf_file) # Simulation Parameters n_sources = int(5e2) table = population.make_base_catalog_galactic( n_sources=n_sources, rad_dis='L06', vel_dis='F06B', max_age=1e5 * u.yr, spiralarms=True, random_state=0, ) # Minimum source luminosity (s^-1)
target_position = SkyCoord.from_name('crab', frame='galactic') on_region_radius = Angle('0.11 deg') on_region = CircleSkyRegion(center=target_position, radius=on_region_radius) exclusion_region = CircleSkyRegion( center=SkyCoord.from_name('crab', frame='galactic'), radius=0.1 * u.deg, ) image_center = target_position.galactic exclusion_mask = SkyImage.empty( nxpix=150, nypix=150, binsz=0.05, xref=image_center.l.deg, yref=image_center.b.deg, proj='TAN', coordsys='GAL', ) exclusion_mask = exclusion_mask.region_mask(exclusion_region) exclusion_mask.data = 1. - exclusion_mask.data background_estimator = ReflectedRegionsBackgroundEstimator( obs_list=obs_list, on_region=on_region, exclusion_mask=exclusion_mask) background_estimator.run() plt.figure(figsize=(8, 8)) bkg_ex_plot = background_estimator.plot()
from astropy.modeling.models import Gaussian2D from astropy import units as u BINSZ = 0.02 sigma = 0.2 ampl = 1. / (2 * np.pi * (sigma / BINSZ) ** 2) sources = [Gaussian2D(ampl, 0, 0, sigma, sigma), Gaussian2D(ampl, 2, 0, sigma, sigma), Gaussian2D(ampl, 0, 2, sigma, sigma), Gaussian2D(ampl, 0, -2, sigma, sigma), Gaussian2D(ampl, -2, 0, sigma, sigma), Gaussian2D(ampl, 2, -2, sigma, sigma), Gaussian2D(ampl, -2, 2, sigma, sigma), Gaussian2D(ampl, -2, -2, sigma, sigma), Gaussian2D(ampl, 2, 2, sigma, sigma),] image = SkyImage.empty(nxpix=201, nypix=201, binsz=BINSZ) image.name = 'Flux' for source in sources: # Evaluate on cut out pos = SkyCoord(source.x_mean, source.y_mean, unit='deg', frame='galactic') cutout = image.cutout(pos, size=(3.2 * u.deg, 3.2 * u.deg)) c = cutout.coordinates() l, b = c.galactic.l.wrap_at('180d'), c.galactic.b cutout.data = source(l.deg, b.deg) image.paste(cutout) image.show()
on_region = CircleSkyRegion(center=target_position, radius=on_radius) # In[10]: # Define reference image centered on the target xref = target_position.galactic.l.value yref = target_position.galactic.b.value # size = 10 * u.deg # binsz = 0.02 # degree per pixel # npix = int((size / binsz).value) ref_image = SkyImage.empty( nxpix=800, nypix=600, binsz=0.02, xref=xref, yref=yref, proj='TAN', coordsys='GAL', ) print(ref_image) # ### Compute images # # We use the ring background estimation method, and an exclusion mask that excludes the bright source at the Galactic center. # In[11]: exclusion_mask = ref_image.region_mask(on_region) exclusion_mask.data = 1 - exclusion_mask.data exclusion_mask.plot()
"""Make a counts image with Gammapy.""" from gammapy.data import EventList from gammapy.image import SkyImage events = EventList.read('events.fits') image = SkyImage.empty( nxpix=400, nypix=400, binsz=0.02, xref=83.6, yref=22.0, coordsys='CEL', proj='TAN', ) image.fill_events(events) image.write('counts.fits')
"""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 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()
"""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)
# What data to analyse data_store = DataStore.from_dir('$GAMMAPY_EXTRA/test_datasets/cube/data') # Define runlist obs_table = Table() obs_table['OBS_ID'] = [23523, 23526, 23592] # There's a problem with the PSF for run 23559, so we don't use that run for now. # 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
#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)
"""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()