Example #1
0
    def select_sky_circle(self, center, radius, inverted=False):
        """Make an observation table, applying a cone selection.

        Apply a selection based on the separation between the cone center
        and the observation pointing stored in the table.

        If the inverted flag is activated, the selection is applied to
        keep all elements outside the selected range.

        Parameters
        ----------
        center : `~astropy.coordinate.SkyCoord`
            Cone center coordinate.
        radius : `~astropy.coordinate.Angle`
            Cone opening angle. The maximal separation allowed between the center and the observation
            pointing direction.
        inverted : bool, optional
            Invert selection: keep all entries outside the cone.

        Returns
        -------
        obs_table : `~gammapy.data.ObservationTable`
            Observation table after selection.
        """
        region = SphericalCircleSkyRegion(center=center, radius=radius)
        mask = region.contains(self.pointing_radec)
        if inverted:
            mask = np.invert(mask)
        return self[mask]
Example #2
0
def test_filter_events(observation):
    custom_filter = {
        "type": "custom",
        "opts": {
            "parameter": "ENERGY",
            "band": Quantity([0.8 * u.TeV, 10.0 * u.TeV])
        },
    }

    target_position = SkyCoord(ra=229.2, dec=-58.3, unit="deg", frame="icrs")
    region_radius = Angle("0.2 deg")
    region = SphericalCircleSkyRegion(center=target_position,
                                      radius=region_radius)
    region_filter = {"type": "sky_region", "opts": {"region": region}}

    time_filter = Time([53090.12, 53090.13], format="mjd", scale="tt")

    obs_filter = ObservationFilter(
        event_filters=[custom_filter, region_filter], time_filter=time_filter)

    events = observation.events
    filtered_events = obs_filter.filter_events(events)

    assert np.all((filtered_events.energy >= 0.8 * u.TeV)
                  & (filtered_events.energy < 10.0 * u.TeV))
    assert np.all((filtered_events.time >= time_filter[0])
                  & (filtered_events.time < time_filter[1]))
    assert np.all(
        region.center.separation(filtered_events.radec) < region_radius)
Example #3
0
class TestSphericalCircleSkyRegion:
    def setup(self):
        self.region = SphericalCircleSkyRegion(center=SkyCoord(
            10 * u.deg, 20 * u.deg),
                                               radius=10 * u.deg)

    def test_contains(self):
        coord = SkyCoord([20.1, 22] * u.deg, 20 * u.deg)
        mask = self.region.contains(coord)
        assert_equal(mask, [True, False])
Example #4
0
def test_run(observations, phase_bkg_maker):

    maker = SpectrumDatasetMaker()

    e_reco = np.logspace(0, 2, 5) * u.TeV
    e_true = np.logspace(-0.5, 2, 11) * u.TeV

    pos = SkyCoord("08h35m20.65525s", "-45d10m35.1545s", frame="icrs")
    radius = Angle(0.2, "deg")
    region = SphericalCircleSkyRegion(pos, radius)

    dataset_empty = SpectrumDataset.create(e_reco, e_true, region=region)

    obs = observations["111630"]
    dataset = maker.run(dataset_empty, obs)
    dataset_on_off = phase_bkg_maker.run(dataset, obs)

    assert_allclose(dataset_on_off.acceptance, 0.1)
    assert_allclose(dataset_on_off.acceptance_off, 0.3)

    assert_allclose(dataset_on_off.counts.data.sum(), 28)
    assert_allclose(dataset_on_off.counts_off.data.sum(), 57)
Example #5
0
def test_run(observations, phase_bkg_maker):

    maker = SpectrumDatasetMaker()

    e_reco = MapAxis.from_edges(np.logspace(0, 2, 5) * u.TeV, name="energy")
    e_true = MapAxis.from_edges(np.logspace(-0.5, 2, 11) * u.TeV,
                                name="energy_true")

    pos = SkyCoord("08h35m20.65525s", "-45d10m35.1545s", frame="icrs")
    radius = Angle(0.2, "deg")
    region = SphericalCircleSkyRegion(pos, radius)

    geom = RegionGeom.create(region=region, axes=[e_reco])
    dataset_empty = SpectrumDataset.create(geom=geom, energy_axis_true=e_true)

    obs = observations["111630"]
    dataset = maker.run(dataset_empty, obs)
    dataset_on_off = phase_bkg_maker.run(dataset, obs)

    assert_allclose(dataset_on_off.acceptance, 0.1)
    assert_allclose(dataset_on_off.acceptance_off, 0.3)

    assert_allclose(dataset_on_off.counts.data.sum(), 28)
    assert_allclose(dataset_on_off.counts_off.data.sum(), 57)
Example #6
0
 def setup(self):
     self.region = SphericalCircleSkyRegion(center=SkyCoord(
         10 * u.deg, 20 * u.deg),
                                            radius=10 * u.deg)
# In[ ]:


id_obs_vela = [111630]
obs_list_vela = data_store.get_observations(id_obs_vela)
print(obs_list_vela[0].events)


# Now that we have our observation, let's select the events in 0.2° radius around the pulsar position.

# In[ ]:


pos_target = SkyCoord(ra=128.836 * u.deg, dec=-45.176 * u.deg, frame="icrs")
on_radius = 0.2 * u.deg
on_region = SphericalCircleSkyRegion(pos_target, on_radius)

# Apply angular selection
events_vela = obs_list_vela[0].events.select_region(on_region)
print(events_vela)


# Let's load the phases of the selected events in a dedicated array.

# In[ ]:


phases = events_vela.table["PHASE"]

# Let's take a look at the first 10 phases
phases[:10]
Example #8
0
    def select_observations(self, selection=None):
        """Select subset of observations.

        Returns a new observation table representing the subset.

        There are 3 main kinds of selection criteria, according to the
        value of the **type** keyword in the **selection** dictionary:

        - sky regions

        - time intervals (min, max)

        - intervals (min, max) on any other parameter present in the
          observation table, that can be casted into an
          `~astropy.units.Quantity` object

        Allowed selection criteria are interpreted using the following
        keywords in the **selection** dictionary under the **type** key.

        - ``sky_circle`` is a circular region centered in the coordinate
           marked by the **lon** and **lat** keywords, and radius **radius**;
           uses `~gammapy.catalog.select_sky_circle`

        - ``time_box`` is a 1D selection criterion acting on the observation
          start time (**TSTART**); the interval is set via the
          **time_range** keyword; uses
          `~gammapy.data.ObservationTable.select_time_range`

        - ``par_box`` is a 1D selection criterion acting on any
          parameter defined in the observation table that can be casted
          into an `~astropy.units.Quantity` object; the parameter name
          and interval can be specified using the keywords **variable** and
          **value_range** respectively; min = max selects exact
          values of the parameter; uses
          `~gammapy.data.ObservationTable.select_range`

        In all cases, the selection can be inverted by activating the
        **inverted** flag, in which case, the selection is applied to keep all
        elements outside the selected range.

        A few examples of selection criteria are given below.

        Parameters
        ----------
        selection : dict
            Dictionary with a few keywords for applying selection cuts.

        Returns
        -------
        obs_table : `~gammapy.data.ObservationTable`
            Observation table after selection.

        Examples
        --------
        >>> selection = dict(type='sky_circle', frame='galactic',
        ...                  lon=Angle(0, 'deg'),
        ...                  lat=Angle(0, 'deg'),
        ...                  radius=Angle(5, 'deg'),
        ...                  border=Angle(2, 'deg'))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='time_box',
        ...                  time_range=Time(['2012-01-01T01:00:00', '2012-01-01T02:00:00']))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='par_box', variable='ALT',
        ...                  value_range=Angle([60., 70.], 'deg'))
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='par_box', variable='OBS_ID',
        ...                  value_range=[2, 5])
        >>> selected_obs_table = obs_table.select_observations(selection)

        >>> selection = dict(type='par_box', variable='N_TELS',
        ...                  value_range=[4, 4])
        >>> selected_obs_table = obs_table.select_observations(selection)
        """
        if "inverted" not in selection:
            selection["inverted"] = False

        if selection["type"] == "sky_circle":
            lon = Angle(selection["lon"], "deg")
            lat = Angle(selection["lat"], "deg")
            radius = Angle(selection["radius"])
            border = Angle(selection["border"])
            region = SphericalCircleSkyRegion(
                center=SkyCoord(lon, lat, frame=selection["frame"]),
                radius=radius + border,
            )
            mask = region.contains(self.pointing_radec)
            if selection["inverted"]:
                mask = np.invert(mask)
            return self[mask]
        elif selection["type"] == "time_box":
            return self.select_time_range("TSTART", selection["time_range"],
                                          selection["inverted"])
        elif selection["type"] == "par_box":
            return self.select_range(selection["variable"],
                                     selection["value_range"],
                                     selection["inverted"])
        else:
            raise ValueError(f"Invalid selection type: {selection['type']}")
Example #9
0
def on_region():
    """Example on_region for testing."""
    pos = SkyCoord("08h35m20.65525s", "-45d10m35.1545s", frame="icrs")
    radius = Angle(0.2, "deg")
    return SphericalCircleSkyRegion(pos, radius)
Example #10
0
events_3fhl.galactic
# events_3fhl.radec

# In[ ]:

events_3fhl.time

# In addition `EventList` provides convenience methods to filter the event lists. One possible use case is to find the highest energy event within a radius of 0.5 deg around the vela position:

# In[ ]:

# select all events within a radius of 0.5 deg around center
from gammapy.utils.regions import SphericalCircleSkyRegion

region = SphericalCircleSkyRegion(center, radius=0.5 * u.deg)
events_gc_3fhl = events_3fhl.select_region(region)

# sort events by energy
events_gc_3fhl.table.sort("ENERGY")

# and show highest energy photon
events_gc_3fhl.energy[-1].to("GeV")

# ### Exercises
#
# * Make a counts energy spectrum for the galactic center region, within a radius of 10 deg.

# In[ ]:

# ## Source catalogs