Exemple #1
0
    def from_eventlist(cls, event_list, bins):
        """Create CountsSpectrum from fits 'EVENTS' extension (`CountsSpectrum`).

        Subsets of the event list should be chosen via the appropriate methods
        in `~gammapy.data.EventList`.

        Parameters
        ----------
        event_list : `~astropy.io.fits.BinTableHDU, `gammapy.data.EventListDataSet`,
                     `gammapy.data.EventList`, str (filename)
        bins : `gammapy.spectrum.energy.EnergyBounds`
            Energy bin edges
        """

        if isinstance(event_list, fits.BinTableHDU):
            event_list = EventList.read(event_list)
        elif isinstance(event_list, EventListDataset):
            event_list = event_list.event_list
        elif isinstance(event_list, str):
            event_list = EventList.read(event_list, hdu='EVENTS')

        energy = Energy(event_list.energy).to(bins.unit)
        val, dummy = np.histogram(energy, bins.value)
        livetime = event_list.observation_live_time_duration

        return cls(val, bins, livetime)
Exemple #2
0
    def test_write(self):
        # Without GTI
        self.events.write("test.fits", overwrite=True)
        read_again = EventList.read("test.fits")

        # the meta dictionaries match because the input one
        # already has the EXTNAME keyword
        assert self.events.table.meta == read_again.table.meta
        assert (self.events.table == read_again.table).all()

        dummy_events = EventList(Table())
        dummy_events.write("test.fits", overwrite=True)
        read_again = EventList.read("test.fits")
        assert read_again.table.meta['EXTNAME'] == "EVENTS"
        assert read_again.table.meta['HDUCLASS'] == "GADF"
        assert read_again.table.meta['HDUCLAS1'] == "EVENTS"

        # With GTI
        gti = GTI.read(
            "$GAMMAPY_DATA/hess-dl3-dr1/data/hess_dl3_dr1_obs_id_020136.fits.gz"
        )
        self.events.write("test.fits", overwrite=True, gti=gti)
        read_again_ev = EventList.read("test.fits")
        read_again_gti = GTI.read("test.fits")

        assert self.events.table.meta == read_again_ev.table.meta
        assert (self.events.table == read_again_ev.table).all()
        assert gti.table.meta == read_again_gti.table.meta
        assert (gti.table == read_again_gti.table).all()

        # test that it won't work if gti is not a GTI
        with pytest.raises(TypeError):
            self.events.write("test.fits", overwrite=True, gti=gti.table)
        # test that it won't work if format is not "gadf"
        with pytest.raises(ValueError):
            self.events.write("test.fits", overwrite=True, format='something')
        # test that it won't work if the basic headers are wrong
        with pytest.raises(ValueError):
            dummy_events = EventList(Table())
            dummy_events.table.meta['HDUCLAS1'] = 'response'
            dummy_events.write("test.fits", overwrite=True)
        with pytest.raises(ValueError):
            dummy_events = EventList(Table())
            dummy_events.table.meta['HDUCLASS'] = "ogip"
            dummy_events.write("test.fits", overwrite=True)

        # test that it works when the srings are right but lowercase
        dummy_events = EventList(Table())
        dummy_events.table.meta['HDUCLASS'] = "gadf"
        dummy_events.table.meta['HDUCLAS1'] = "events"
        dummy_events.write("test.fits", overwrite=True)
Exemple #3
0
    def load(self):
        """Load HDU as appropriate class.

        TODO: this should probably go via an extensible registry.
        """
        from gammapy.irf import IRF_REGISTRY

        hdu_class = self.hdu_class
        filename = self.path()
        hdu = self.hdu_name

        if hdu_class == "events":
            from gammapy.data import EventList

            return EventList.read(filename, hdu=hdu)
        elif hdu_class == "gti":
            from gammapy.data import GTI

            return GTI.read(filename, hdu=hdu)
        elif hdu_class == "map":
            from gammapy.maps import Map

            return Map.read(filename, hdu=hdu, format=self.format)
        else:
            cls = IRF_REGISTRY.get_cls(hdu_class)

            return cls.read(filename, hdu=hdu)
Exemple #4
0
def main(input_files, verbose, output):
    setup_logging(verbose=verbose)

    eventlist_list = []
    for f in input_files:
        eventlist_list.append(EventList.read(f))
    events = eventlist_list[0]
    for e in eventlist_list[1:]:
        events.stack(e)

    figures = []
    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_energy(ax=ax)

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_energy_offset(ax=ax)

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_offset2_distribution(ax=ax)

    figures.append(plt.figure())
    ax = figures[-1].add_subplot(1, 1, 1)
    events.plot_time(ax=ax)

    if output is None:
        plt.show()
    else:
        with PdfPages(output) as pdf:
            for fig in figures:
                fig.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
                pdf.savefig(fig)
def extract_spectra_fermi(target_position, on_radius):
    """Extract 1d spectra for Fermi-LAT"""
    log.info("Extracting 1d spectra for Fermi-LAT")
    events = EventList.read("data/fermi/events.fits.gz")
    exposure = HpxNDMap.read("data/fermi/exposure_cube.fits.gz")
    psf = EnergyDependentTablePSF.read("data/fermi/psf.fits.gz")

    valid_range = (config.energy_bins >= 30 * u.GeV) * (config.energy_bins <=
                                                        2 * u.TeV)
    energy = config.energy_bins[valid_range]

    bkg_estimate = ring_background_estimate(
        pos=target_position,
        on_radius=on_radius,
        inner_radius=1 * u.deg,
        outer_radius=2 * u.deg,
        events=events,
    )

    extract = SpectrumExtractionFermi1D(
        events=events,
        exposure=exposure,
        psf=psf,
        bkg_estimate=bkg_estimate,
        target_position=target_position,
        on_radius=on_radius,
        energy=energy,
    )
    obs = extract.run()

    path = "results/spectra/fermi"
    log.info(f"Writing to {path}")
    obs.write(path, use_sherpa=True, overwrite=True)
Exemple #6
0
def test_region_nd_map_fill_events(region_map):
    filename = "$GAMMAPY_DATA/hess-dl3-dr1/data/hess_dl3_dr1_obs_id_023523.fits.gz"
    events = EventList.read(filename)
    region_map = Map.from_geom(region_map.geom)
    region_map.fill_events(events)

    assert_allclose(region_map.data.sum(), 665)
Exemple #7
0
def extract_spectra_fermi(target_position, on_radius):
    """Extract 1d spectra for Fermi-LAT"""
    log.info("Extracting 1d spectra for Fermi-LAT")
    events = EventList.read("data/fermi/events.fits.gz")
    exposure = HpxNDMap.read("data/fermi/exposure_cube.fits.gz")
    psf = EnergyDependentTablePSF.read("data/fermi/psf.fits.gz")

    emin, emax, dex = 0.03, 2, 0.1
    num = int(np.log10(emax / emin) / dex)
    energy = np.logspace(start=np.log10(emin), stop=np.log10(emax),
                         num=num) * u.TeV

    bkg_estimate = fermi_ring_background_extract(events, target_position,
                                                 on_radius)

    extract = SpectrumExtractionFermi1D(
        events=events,
        exposure=exposure,
        psf=psf,
        bkg_estimate=bkg_estimate,
        target_position=target_position,
        on_radius=on_radius,
        energy=energy,
        containment_correction=True,
    )
    obs = extract.run()

    path = f"{config.repo_path}/results/spectra/fermi"
    log.info(f"Writing to {path}")
    obs.write(path, use_sherpa=True, overwrite=True)
 def __init__(self,
              evt_file="$JOINT_CRAB/data/fermi/events.fits.gz",
              exp_file="$JOINT_CRAB/data/fermi/exposure_cube.fits.gz",
              psf_file="$JOINT_CRAB/data/fermi/psf.fits.gz",
              max_psf_radius='0.5 deg'):
     # Read data
     self.events = EventList.read(evt_file)
     self.exposure = HpxNDMap.read(exp_file)
     self.exposure.unit = u.Unit('cm2s')  # no unit stored on map...
     self.psf = EnergyDependentTablePSF.read(psf_file)
Exemple #9
0
 def __init__(
     self,
     evt_file="../data/joint-crab/fermi/events.fits.gz",
     exp_file="../data/joint-crab/fermi/exposure_cube.fits.gz",
     psf_file="../data/joint-crab/fermi/psf.fits.gz",
 ):
     # Read data
     self.events = EventList.read(evt_file)
     self.exposure = HpxNDMap.read(exp_file)
     self.exposure.unit = u.Unit("cm2s")  # no unit stored on map...
     self.psf = PSFMap.read(psf_file, format="gtpsf")
Exemple #10
0
def read_dataset(filename_dataset, filename_model, obs_id):
    log.info(f"Reading {filename_dataset}")
    dataset = MapDataset.read(filename_dataset)

    filename_events = get_filename_events(filename_dataset, filename_model, obs_id)
    log.info(f"Reading {filename_events}")
    events = EventList.read(filename_events)

    counts = Map.from_geom(WCS_GEOM)
    counts.fill_events(events)
    dataset.counts = counts
    return dataset
 def __init__(
     self,
     evt_file="../data/joint-crab/fermi/events.fits.gz",
     exp_file="../data/joint-crab/fermi/exposure_cube.fits.gz",
     psf_file="../data/joint-crab/fermi/psf.fits.gz",
     max_psf_radius="0.5 deg",
 ):
     # Read data
     self.events = EventList.read(evt_file)
     self.exposure = HpxNDMap.read(exp_file)
     self.exposure.unit = u.Unit("cm2s")  # no unit stored on map...
     self.psf = EnergyDependentTablePSF.read(psf_file)
Exemple #12
0
def image_bin(event_file,
              reference_file,
              out_file,
              overwrite):
    """Bin events into an image."""

    log.info('Reading {}'.format(event_file))
    events = EventList.read(event_file)

    reference_image = fits.open(reference_file)[0]
    out_image = bin_events_in_image(events, reference_image)

    log.info('Writing {}'.format(out_file))
    out_image.writeto(out_file, clobber=overwrite)
Exemple #13
0
    def load(self):
        """Load HDU as appropriate class.

        TODO: this should probably go via an extensible registry.
        """
        hdu_class = self.hdu_class
        filename = self.path()
        hdu = self.hdu_name

        if hdu_class == "events":
            from gammapy.data import EventList

            return EventList.read(filename, hdu=hdu)
        elif hdu_class == "gti":
            from gammapy.data import GTI

            return GTI.read(filename, hdu=hdu)
        elif hdu_class == "aeff_2d":
            from gammapy.irf import EffectiveAreaTable2D

            return EffectiveAreaTable2D.read(filename, hdu=hdu)
        elif hdu_class == "edisp_2d":
            from gammapy.irf import EnergyDispersion2D

            return EnergyDispersion2D.read(filename, hdu=hdu)
        elif hdu_class == "psf_table":
            from gammapy.irf import PSF3D

            return PSF3D.read(filename, hdu=hdu)
        elif hdu_class == "psf_3gauss":
            from gammapy.irf import EnergyDependentMultiGaussPSF

            return EnergyDependentMultiGaussPSF.read(filename, hdu=hdu)
        elif hdu_class == "psf_king":
            from gammapy.irf import PSFKing

            return PSFKing.read(filename, hdu=hdu)
        elif hdu_class == "bkg_2d":
            from gammapy.irf import Background2D

            return Background2D.read(filename, hdu=hdu)
        elif hdu_class == "bkg_3d":
            from gammapy.irf import Background3D

            return Background3D.read(filename, hdu=hdu)
        else:
            raise ValueError(f"Invalid hdu_class: {hdu_class}")
Exemple #14
0
def make_counts_image(energy_band):
    """Apply event selections and bin event positions into a counts image."""
    event_list = EventList.read(TOTAL_EVENTS_FILE)
    n_events = len(event_list)
    print('Number of events: {}'.format(n_events))
    print('Applying energy band selection: {}'.format(energy_band))
    event_list = event_list.select_energy(energy_band)
    n_events_selected = len(event_list)
    fraction = 100 * n_events_selected / n_events
    print('Number of events: {}. Fraction: {:.1f}%'.format(n_events_selected, fraction))

    print('Filling counts image ...')
    header = fits.getheader(REF_IMAGE)
    image = event_list.fill_counts_header(header)

    print('Writing {}'.format(COUNTS_IMAGE))
    image.writeto(COUNTS_IMAGE, clobber=True)
Exemple #15
0
def cli_image_bin(event_file, reference_file, out_file, overwrite):
    """Bin events into an image.

    You have to give the event, reference and out FITS filename.
    """
    log.info("Executing cli_image_bin")

    log.info("Reading {}".format(event_file))
    events = EventList.read(event_file)

    log.info("Reading {}".format(reference_file))
    m_ref = Map.read(reference_file)

    counts_map = Map.from_geom(m_ref.geom)
    fill_map_counts(counts_map, events)

    log.info("Writing {}".format(out_file))
    counts_map.write(out_file, overwrite=overwrite)
from gammapy.data import EventList
from gammapy.irf import EnergyDependentTablePSF, EnergyDispersion
from gammapy.maps import Map, MapAxis, WcsNDMap, WcsGeom
from gammapy.spectrum.models import TableModel, PowerLaw
from gammapy.image.models import SkyPointSource, SkyDiffuseConstant
from gammapy.cube.models import SkyModel, SkyDiffuseCube, BackgroundModel
from gammapy.cube import MapDataset, PSFKernel
from gammapy.utils.fitting import Fit

# ## Events
#
# To load up the Fermi-LAT event list, use the [gammapy.data.EventList](https://docs.gammapy.org/0.12/api/gammapy.data.EventList.html) class:

# In[ ]:

events = EventList.read(
    "$GAMMAPY_DATA/fermi_3fhl/fermi_3fhl_events_selected.fits.gz")
print(events)

# The event data is stored in a [astropy.table.Table](http://docs.astropy.org/en/stable/api/astropy.table.Table.html) object. In case of the Fermi-LAT event list this contains all the additional information on positon, zenith angle, earth azimuth angle, event class, event type etc.

# In[ ]:

events.table.colnames

# In[ ]:

events.table[:5][["ENERGY", "RA", "DEC"]]

# In[ ]:

print(events.time[0].iso)
Exemple #17
0
 def setup(self):
     filename = (
         "$GAMMAPY_DATA/tests/unbundled/hess/run_0023037_hard_eventlist.fits.gz"
     )
     self.events = EventList.read(filename)

def make_healpix_image(events, nside, sigma):
    theta = np.deg2rad(90 - events['B'])
    phi = np.deg2rad(events['L'])
    bins = np.arange(hp.nside2npix(nside) + 1) - 0.5
    data = hp.ang2pix(nside, theta, phi)
    counts, _ = np.histogram(data, bins)
    counts = hp.smoothing(counts, sigma=sigma)

    return counts


if __name__ == '__main__':
    filename = '/Users/deil/code/fhee/data/2fhl_events.fits.gz'
    events = EventList.read(filename)
    events.meta['EUNIT'] = 'GeV'

    counts = make_healpix_image(events, nside=256, sigma=0.001)

    filename = '2fhl_counts_healpix.fits.gz'
    print('Writing {}'.format(filename))
    hp.write_map(filename, m=counts)
    # import matplotlib.pyplot as plt
    # hp.mollview(counts, title="Mollview image RING")
    # plt.show()

    # m = np.arange(hp.nside2npix(NSIDE))
    # zeros = np.zeros(hp.nside2npix(NSIDE))
    # hp.mollview(m, title="Mollview image RING")
    # print (len(counts) == hp.nside2npix(NSIDE))
# ## EVENT data
#
# First, the EVENT data (RA, DEC, ENERGY, TIME of each photon or hadronic background event) is in the `data` folder, with one observation per file. The "baseline" refers to the assumed CTA array that was used to simulate the observations. The number in the filename is the observation identifier `OBS_ID` of the observation. Observations are ~ 30 minutes, pointing at a fixed location on the sky.

# In[ ]:

get_ipython().system('ls -1 $GAMMAPY_DATA/cta-1dc/data/baseline/gps')

# Let's open up the first event list using the Gammapy `EventList` class, which contains the ``EVENTS`` table data via the ``table`` attribute as an Astropy `Table` object.

# In[ ]:

from gammapy.data import EventList

path = "$GAMMAPY_DATA/cta-1dc/data/baseline/gps/gps_baseline_110380.fits"
events = EventList.read(path)

# In[ ]:

type(events)

# In[ ]:

type(events.table)

# In[ ]:

# First event (using [] for "indexing")
events.table[0]

# In[ ]:
# In[8]:

get_ipython().system('ls $CTADATA/data/baseline/gps | head -n3')

# In[9]:

# There's 3270 observations and 11 GB of event data for the gps dataset
get_ipython().system('ls $CTADATA/data/baseline/gps | wc -l')
get_ipython().system('du -hs $CTADATA/data/baseline/gps')

# Let's open up the first event list using the Gammapy `EventList` class, which contains the ``EVENTS`` table data via the ``table`` attribute as an Astropy `Table` object.

# In[10]:

from gammapy.data import EventList
events = EventList.read('$CTADATA/data/baseline/gps/gps_baseline_110000.fits')
print(type(events))
print(type(events.table))

# In[11]:

# First event (using [] for "indexing")
events.table[0]

# In[12]:

# First few events (using [] for "slicing")
events.table[:2]

# In[13]:
# coding: utf-8
from gammapy.data import EventList
filename = '$GAMMAPY_EXTRA/test_datasets/unbundled/hess/run_0023037_hard_eventlist.fits.gz'
events=EventList.read(filename)
events
filename = '$GAMMAPY_EXTRA/datasets/fermi_2fhl/2fhl_events.fits.gz'
events.observation_live_time_duration
print(events.observation_live_time_duration)
print(events.observation_dead_time_fraction)
print(events.observation_time_duration)
events.observation_time_duration * events.observation_dead_time_fraction
1577.0 s - 56.39856698736619 s
1577.0  - 56.39856698736619 
1.0-0.0357632003725
0.9642367996275 * events.observation_time_duration
Exemple #22
0
#
# * Read event lists from FITS files
# * Access and work with the `EventList` attributes such as `.table` and `.energy`
# * Filter events lists using convenience methods
#
# Let's start with the import from the [gammapy.data](http://docs.gammapy.org/dev/data/index.html) submodule:

# In[17]:

from gammapy.data import EventList

# Very similar to the `SkyImage` class an event list can be created, by passing a filename to the `.read()` method:

# In[18]:

events_2fhl = EventList.read(
    '$GAMMAPY_EXTRA/datasets/fermi_2fhl/2fhl_events.fits.gz')

# This time the actual data is stored as an [astropy.table.Table](http://docs.astropy.org/en/stable/api/astropy.table.Table.html#astropy.table.Table) object. It can be accessed with `.table` attribute:

# In[19]:

events_2fhl.table

# Let's try to find the total number of events contained int the list. This doesn't work:
#

# In[20]:

print('Total number of events: {}'.format(len(events_2fhl.table)))

# Because Gammapy objects don't redefine properties, that are accessible from the underlying Astropy of Numpy data object.
Exemple #23
0
    def __init__(self, selection="short", savefig=True):
        self.datadir = "$GAMMAPY_DATA"
        self.resdir = "./res"
        self.savefig = savefig

        # event list
        self.events = EventList.read(
            self.datadir + "/fermi_3fhl/fermi_3fhl_events_selected.fits.gz")
        # psf
        self.psf = EnergyDependentTablePSF.read(
            self.datadir + "/fermi_3fhl/fermi_3fhl_psf_gc.fits.gz")

        # mask margin
        psf_r99max = self.psf.containment_radius(10 * u.GeV, fraction=0.99)
        self.psf_margin = np.ceil(psf_r99max.value[0] * 10) / 10.0

        # energies
        self.dlb = 1 / 8.0
        El_extra = 10**np.arange(3.8, 6.51, 0.1)  # MeV
        self.logEc_extra = (np.log10(El_extra)[1:] +
                            np.log10(El_extra)[:-1]) / 2.0
        self.El_flux = [10.0, 20.0, 50.0, 150.0, 500.0, 2000.0]
        El_fit = 10**np.arange(1, 3.31, 0.1)
        self.energy_axis = MapAxis.from_edges(El_fit,
                                              name="energy",
                                              unit="GeV",
                                              interp="log")

        # background iso
        infile = Path(self.datadir + "/fermi_3fhl/iso_P8R2_SOURCE_V6_v06.txt")
        outfile = Path(self.resdir + "/iso_P8R2_SOURCE_V6_v06_extra.txt")
        self.model_iso = extrapolate_iso(infile, outfile, self.logEc_extra)

        # regions selection
        file3fhl = self.datadir + "/catalogs/fermi/gll_psch_v13.fit.gz"
        self.FHL3 = SourceCatalog3FHL(file3fhl)
        hdulist = fits.open(make_path(file3fhl))
        self.ROIs = hdulist["ROIs"].data
        Scat = hdulist[1].data
        order = np.argsort(Scat.Signif_Avg)[::-1]
        ROIs_ord = Scat.ROI_num[order]

        if selection == "short":
            self.ROIs_sel = [430, 135, 118, 212, 277, 42, 272, 495]
            # Crab, Vela, high-lat, +some fast regions
        elif selection == "long":
            # get small regions with few sources among the most significant
            indexes = np.unique(ROIs_ord, return_index=True)[1]
            ROIs_ord = [ROIs_ord[index] for index in sorted(indexes)]
            self.ROIs_sel = [
                kr for kr in ROIs_ord
                if sum(Scat.ROI_num == kr) <= 4 and self.ROIs.RADIUS[kr] < 6
            ][:100]
        elif selection == "debug":
            self.ROIs_sel = [135]  # Vela region

        # fit options
        self.optimize_opts = {
            "backend": "minuit",
            "tol": 10.0,
            "strategy": 2,
        }

        # calculate flux points only for sources significant above this threshold
        self.sig_cut = 8.0

        # diagnostics stored to produce plots and outputs
        self.diags = {
            "message": [],
            "stat": [],
            "params": {},
            "errel": {},
            "compatibility": {},
            "cat_fp_sel": [],
        }
        self.diags["errel"]["flux_points"] = []
        keys = [
            "PL_tags",
            "PL_index",
            "PL_amplitude",
            "LP_tags",
            "LP_alpha",
            "LP_beta",
            "LP_amplitude",
        ]
        for key in keys:
            self.diags["params"][key] = []
Exemple #24
0
 def setup_class(self):
     self.events = EventList.read(
         "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-events.fits.gz")
Exemple #25
0
"""Example of how to create an ObservationCTA from CTA's 1DC"""
from gammapy.data import ObservationCTA, EventList, GTI
from gammapy.irf import (
    EnergyDependentMultiGaussPSF,
    EffectiveAreaTable2D,
    EnergyDispersion2D,
    Background3D,
)

filename = "$GAMMAPY_DATA/cta-1dc/data/baseline/gps/gps_baseline_110380.fits"
event_list = EventList.read(filename)
gti = GTI.read(filename)

filename = "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
aeff = EffectiveAreaTable2D.read(filename)
bkg = Background3D.read(filename)
edisp = EnergyDispersion2D.read(filename, hdu="Energy Dispersion")
psf = EnergyDependentMultiGaussPSF.read(filename, hdu="Point Spread Function")

obs = ObservationCTA(
    obs_id=event_list.table.meta["OBS_ID"],
    events=event_list,
    gti=gti,
    psf=psf,
    aeff=aeff,
    edisp=edisp,
    bkg=bkg,
    pointing_radec=event_list.pointing_radec,
    observation_live_time_duration=event_list.observation_live_time_duration,
    observation_dead_time_fraction=event_list.observation_dead_time_fraction,
)
Exemple #26
0
# The quick-look `events.peek()` plot below shows that CTA has a field of view of a few degrees, and two energy thresholds, one significantly below 100 GeV where the CTA large-size telescopes (LSTs) detect events, and a second one near 100 GeV where teh mid-sized telescopes (MSTs) start to detect events.
# 
# Note that most events are "hadronic background" due to cosmic ray showers in the atmosphere that pass the gamma-hadron selection cuts for this analysis configuration. Since this is simulated data, column `MC_ID` is available that gives an emission component identifier code, and the EVENTS header in `events.table.meta` can be used to look up which `MC_ID` corresponds to which emission component.

# In[ ]:


events = observation.events
events


# In[ ]:


events = EventList.read(
    "$GAMMAPY_DATA/cta-1dc/data/baseline/gps/gps_baseline_110380.fits"
)
events


# In[ ]:


events.table[:5]


# In[ ]:


events.peek()
Exemple #27
0
    def __init__(self, selection="short", savefig=True):
        log.info("Executing __init__()")
        self.resdir = BASE_PATH / "results"
        self.savefig = savefig

        # event list
        self.events = EventList.read(
            "$GAMMAPY_DATA/fermi_3fhl/fermi_3fhl_events_selected.fits.gz"
        )
        # psf
        self.psf = EnergyDependentTablePSF.read(
            "$GAMMAPY_DATA/fermi_3fhl/fermi_3fhl_psf_gc.fits.gz"
        )

        # mask margin
        psf_r99max = self.psf.containment_radius(10 * u.GeV, fraction=0.99)
        self.psf_margin = np.ceil(psf_r99max.value[0] * 10) / 10.0

        # energies
        self.El_flux = [10.0, 20.0, 50.0, 150.0, 500.0, 2000.0]
        El_fit = 10 ** np.arange(1, 3.31, 0.1)
        self.energy_axis = MapAxis.from_edges(
            El_fit, name="energy", unit="GeV", interp="log"
        )

        # iso norm=0.92 see paper appendix A
        self.model_iso = create_fermi_isotropic_diffuse_model(
            filename="data/iso_P8R2_SOURCE_V6_v06_extrapolated.txt",
            norm=0.92,
            interp_kwargs={"fill_value": None},
        )
        # regions selection
        file3fhl = "$GAMMAPY_DATA/catalogs/fermi/gll_psch_v13.fit.gz"
        self.FHL3 = SourceCatalog3FHL(file3fhl)
        hdulist = fits.open(make_path(file3fhl))
        self.ROIs = hdulist["ROIs"].data
        Scat = hdulist[1].data
        order = np.argsort(Scat.Signif_Avg)[::-1]
        ROIs_ord = Scat.ROI_num[order]

        if selection == "short":
            self.ROIs_sel = [430, 135, 118, 212, 277, 42, 272, 495]
            # Crab, Vela, high-lat, +some fast regions
        elif selection == "long":
            # get small regions with few sources among the most significant
            indexes = np.unique(ROIs_ord, return_index=True)[1]
            ROIs_ord = [ROIs_ord[index] for index in sorted(indexes)]
            self.ROIs_sel = [
                kr
                for kr in ROIs_ord
                if sum(Scat.ROI_num == kr) <= 4 and self.ROIs.RADIUS[kr] < 6
            ][:100]
        elif selection == "debug":
            self.ROIs_sel = [135]  # Vela region
        else:
            raise ValueError(f"Invalid selection: {selection!r}")

        # fit options
        self.optimize_opts = {
            "backend": "minuit",
            "optimize_opts": {"tol": 10.0, "strategy": 2},
        }

        # calculate flux points only for sources significant above this threshold
        self.sig_cut = 8.0

        # diagnostics stored to produce plots and outputs
        self.diags = {
            "message": [],
            "stat": [],
            "params": {},
            "errel": {},
            "compatibility": {},
            "cat_fp_sel": [],
        }
        self.diags["errel"]["flux_points"] = []
        keys = [
            "PL_tags",
            "PL_index",
            "PL_amplitude",
            "LP_tags",
            "LP_alpha",
            "LP_beta",
            "LP_amplitude",
        ]
        for key in keys:
            self.diags["params"][key] = []
Exemple #28
0
def counts_skyimage_2fhl(**kwargs):
	log.info('Computing counts map.')
	events = EventList.read('2fhl_events.fits.gz')
	counts = SkyMap.empty('Counts', **kwargs)
	counts.fill(events)
	return counts
Exemple #29
0
 def setup_class(self):
     self.events = EventList.read(
         "$GAMMAPY_DATA/hess-dl3-dr1/data/hess_dl3_dr1_obs_id_020136.fits.gz"
     )
def counts_skyimage_2fhl(**kwargs):
    log.info("Computing counts map.")
    events = EventList.read("2fhl_events.fits.gz")
    counts = SkyMap.empty("Counts", **kwargs)
    counts.fill(events)
    return counts
Exemple #31
0
from gammapy.maps import Map, MapAxis, WcsNDMap, WcsGeom
from gammapy.spectrum.models import TableModel, PowerLaw, ConstantModel
from gammapy.image.models import SkyPointSource, SkyDiffuseConstant
from gammapy.cube.models import SkyModel, SkyDiffuseCube
from gammapy.cube import MapEvaluator, MapFit, PSFKernel


# ## Events
# 
# To load up the Fermi-LAT event list, use the [gammapy.data.EventList](http://docs.gammapy.org/dev/api/gammapy.data.EventList.html) class:

# In[ ]:


events = EventList.read(
    "$GAMMAPY_FERMI_LAT_DATA/3fhl/allsky/fermi_3fhl_events_selected.fits.gz"
)
print(events)


# The event data is stored in a [astropy.table.Table](http://docs.astropy.org/en/stable/api/astropy.table.Table.html) object. In case of the Fermi-LAT event list this contains all the additional information on positon, zenith angle, earth azimuth angle, event class, event type etc.

# In[ ]:


events.table.colnames


# In[ ]:

Exemple #32
0
 def setup(self):
     self.event_list = EventList.read(
         "$GAMMAPY_DATA/cta-1dc/data/baseline/gps/gps_baseline_111140.fits")
Exemple #33
0
#
# * Read event lists from FITS files
# * Access and work with the `EventList` attributes such as `.table` and `.energy`
# * Filter events lists using convenience methods
#
# Let's start with the import from the [gammapy.data](http://docs.gammapy.org/dev/data/index.html) submodule:

# In[ ]:

from gammapy.data import EventList

# Very similar to the sky map class an event list can be created, by passing a filename to the `.read()` method:

# In[ ]:

events_2fhl = EventList.read("$GAMMAPY_DATA/fermi_2fhl/2fhl_events.fits.gz")

# This time the actual data is stored as an [astropy.table.Table](http://docs.astropy.org/en/stable/api/astropy.table.Table.html#astropy.table.Table) object. It can be accessed with `.table` attribute:

# In[ ]:

events_2fhl.table

# Let's try to find the total number of events contained int the list. This doesn't work:
#

# In[ ]:

print("Total number of events: {}".format(len(events_2fhl.table)))

# Because Gammapy objects don't redefine properties, that are accessible from the underlying Astropy of Numpy data object.
Exemple #34
0
#
# * Read event lists from FITS files
# * Access and work with the `EventList` attributes such as `.table` and `.energy`
# * Filter events lists using convenience methods
#
# Let's start with the import from the `~gammapy.data` submodule:

# In[ ]:

from gammapy.data import EventList

# Very similar to the sky map class an event list can be created, by passing a filename to the `~gammapy.data.EventList.read()` method:

# In[ ]:

events_3fhl = EventList.read(
    "$GAMMAPY_DATA/fermi-3fhl-gc/fermi-3fhl-gc-events.fits.gz")

# This time the actual data is stored as an [astropy.table.Table](http://docs.astropy.org/en/stable/api/astropy.table.Table.html) object. It can be accessed with `.table` attribute:

# In[ ]:

events_3fhl.table

# You can do *len* over event_3fhl.table to find the total number of events.

# In[ ]:

len(events_3fhl.table)

# And we can access any other attribute of the `Table` object as well:
"""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')