Example #1
0
    def to_wcs_nd_map(self, energy_axis_mode='center'):
        """Convert to a `gammapy.maps.WcsNDMap`.

        There is no copy of the ``data`` or ``wcs`` object, this conversion is cheap.

        This is meant to help migrate code using `SkyCube`
        over to the new maps classes.
        """
        from gammapy.maps import WcsNDMap, WcsGeom, MapAxis

        if energy_axis_mode == 'center':
            energy = self.energies(mode='center')
            energy_axis = MapAxis.from_nodes(energy.value, unit=energy.unit)
        elif energy_axis_mode == 'edges':
            energy = self.energies(mode='edges')
            energy_axis = MapAxis.from_edges(energy.value, unit=energy.unit)
        else:
            raise ValueError('Invalid energy_axis_mode: {}'.format(energy_axis_mode))

        # Axis order in SkyCube: energy, lat, lon
        npix = (self.data.shape[2], self.data.shape[1])

        geom = WcsGeom(wcs=self.wcs, npix=npix, axes=[energy_axis])

        # TODO: change maps and SkyCube to have a unit attribute
        # For now, SkyCube is a mix of numpy array and quantity in `data`
        # and we just strip the unit here
        data = np.asarray(self.data)
        # unit = getattr(self.data, 'unit', None)

        return WcsNDMap(geom=geom, data=data)
Example #2
0
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.table import Table
from regions import CircleSkyRegion, PointSkyRegion, RectangleSkyRegion
from gammapy.datasets.map import MapEvaluator
from gammapy.irf import EnergyDependentMultiGaussPSF, PSFKernel
from gammapy.maps import Map, MapAxis, MapCoord, WcsGeom, WcsNDMap
from gammapy.maps.utils import fill_poisson
from gammapy.modeling.models import (
    GaussianSpatialModel,
    PowerLawSpectralModel,
    SkyModel,
)
from gammapy.utils.testing import mpl_plot_check, requires_data, requires_dependency

axes1 = [MapAxis(np.logspace(0.0, 3.0, 3), interp="log", name="spam")]
axes2 = [
    MapAxis(np.logspace(0.0, 3.0, 3), interp="log"),
    MapAxis(np.logspace(1.0, 3.0, 4), interp="lin"),
]
skydir = SkyCoord(110.0, 75.0, unit="deg", frame="icrs")

wcs_allsky_test_geoms = [
    (None, 10.0, "galactic", "AIT", skydir, None),
    (None, 10.0, "galactic", "AIT", skydir, axes1),
    (None, [10.0, 20.0], "galactic", "AIT", skydir, axes1),
    (None, 10.0, "galactic", "AIT", skydir, axes2),
    (None, [[10.0, 20.0, 30.0], [10.0, 20.0,
                                 30.0]], "galactic", "AIT", skydir, axes2),
]
Example #3
0
def make_all_models():
    """Make an instance of each model, for testing."""
    yield Model.create("ConstantSpatialModel", "spatial")
    map_constantmodel = Map.create(npix=(10, 20), unit="sr-1")
    yield Model.create("TemplateSpatialModel",
                       "spatial",
                       map=map_constantmodel)
    yield Model.create("DiskSpatialModel",
                       "spatial",
                       lon_0="1 deg",
                       lat_0="2 deg",
                       r_0="3 deg")
    yield Model.create("gauss",
                       "spatial",
                       lon_0="1 deg",
                       lat_0="2 deg",
                       sigma="3 deg")
    yield Model.create("PointSpatialModel",
                       "spatial",
                       lon_0="1 deg",
                       lat_0="2 deg")
    yield Model.create(
        "ShellSpatialModel",
        "spatial",
        lon_0="1 deg",
        lat_0="2 deg",
        radius="3 deg",
        width="4 deg",
    )
    yield Model.create("ConstantSpectralModel",
                       "spectral",
                       const="99 cm-2 s-1 TeV-1")
    yield Model.create(
        "CompoundSpectralModel",
        "spectral",
        model1=Model.create("PowerLawSpectralModel", "spectral"),
        model2=Model.create("PowerLawSpectralModel", "spectral"),
        operator=np.add,
    )
    yield Model.create("PowerLawSpectralModel", "spectral")
    yield Model.create("PowerLawNormSpectralModel", "spectral")
    yield Model.create("PowerLaw2SpectralModel", "spectral")
    yield Model.create("ExpCutoffPowerLawSpectralModel", "spectral")
    yield Model.create("ExpCutoffPowerLawNormSpectralModel", "spectral")
    yield Model.create("ExpCutoffPowerLaw3FGLSpectralModel", "spectral")
    yield Model.create("SuperExpCutoffPowerLaw3FGLSpectralModel", "spectral")
    yield Model.create("SuperExpCutoffPowerLaw4FGLSpectralModel", "spectral")
    yield Model.create("LogParabolaSpectralModel", "spectral")
    yield Model.create("LogParabolaNormSpectralModel", "spectral")
    yield Model.create("TemplateSpectralModel",
                       "spectral",
                       energy=[1, 2] * u.cm,
                       values=[3, 4] * u.cm)  # TODO: add unit validation?
    yield Model.create(
        "PiecewiseNormSpectralModel",
        "spectral",
        energy=[1, 2] * u.cm,
        norms=[3, 4] * u.cm,
    )
    yield Model.create("GaussianSpectralModel", "spectral")
    # TODO: yield Model.create("EBLAbsorptionNormSpectralModel")
    # TODO: yield Model.create("NaimaSpectralModel")
    # TODO: yield Model.create("ScaleSpectralModel")
    yield Model.create("ConstantTemporalModel", "temporal")
    yield Model.create("LinearTemporalModel", "temporal")
    yield Model.create("PowerLawTemporalModel", "temporal")
    yield Model.create("SineTemporalModel", "temporal")
    yield Model.create("LightCurveTemplateTemporalModel", "temporal", Table())
    yield Model.create(
        "SkyModel",
        spatial_model=Model.create("ConstantSpatialModel", "spatial"),
        spectral_model=Model.create("PowerLawSpectralModel", "spectral"),
    )
    m1 = Map.create(npix=(10, 20, 30),
                    axes=[MapAxis.from_nodes([1, 2] * u.TeV, name="energy")])
    yield Model.create("TemplateSpatialModel", "spatial", map=m1)
    m2 = Map.create(npix=(10, 20, 30),
                    axes=[MapAxis.from_edges([1, 2] * u.TeV, name="energy")])
    yield Model.create("TemplateNPredModel", map=m2)
"""Plot an energy dispersion using a gaussian parametrisation"""
import matplotlib.pyplot as plt
from gammapy.irf import EDispKernel
from gammapy.maps import MapAxis

energy_axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=10)
energy_axis_true = MapAxis.from_energy_bounds(
    "0.5 TeV", "30 TeV", nbin=10, per_decade=True, name="energy_true"
)


edisp = EDispKernel.from_gauss(
    energy_axis=energy_axis, energy_axis_true=energy_axis_true, sigma=0.1, bias=0
)
edisp.peek()
plt.show()
Example #5
0
# Or we can also retrieve the solid angle per pixel of the map:

# In[ ]:

wcs_geom.solid_angle()

# ### 1.3 Adding Non-Spatial Axes
#
# In many analysis scenarios we would like to add extra dimension to the maps to study e.g. energy or time dependency of the data. Those non-spatial dimensions are handled with the `MapAxis` object. Let us first define an energy axis, with 4 bins:

# In[ ]:

energy_axis = MapAxis.from_bounds(1,
                                  100,
                                  nbin=4,
                                  unit="TeV",
                                  name="energy",
                                  interp="log")
print(energy_axis)

# Where `interp='log'` specifies that a logarithmic spacing is used between the bins, equivalent to `np.logspace(0, 2, 4)`. This `MapAxis` object we can now pass to `Map.create()` using the `axes=` argument:

# In[ ]:

m_cube = Map.create(binsz=0.02,
                    width=(10, 5),
                    coordsys="GAL",
                    axes=[energy_axis])
print(m_cube.geom)

# Now we see that besides `lon` and `lat` the map has an additional axes named `energy` with 4 bins. The total dimension of the map is now `ndim=3`.
Example #6
0
def simulate():

    irfs = load_cta_irfs(
        "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
    )

    center = SkyCoord(0.0, 0.0, unit="deg", frame="galactic")
    energy_reco = MapAxis.from_edges(np.logspace(-1.0, 1.0, 10),
                                     unit="TeV",
                                     name="energy",
                                     interp="log")
    pointing = SkyCoord(0.5, 0.5, unit="deg", frame="galactic")
    geom = WcsGeom.create(
        skydir=center,
        binsz=0.02,
        width=(4, 4),
        frame="galactic",
        axes=[energy_reco],
    )
    energy_true = MapAxis.from_edges(np.logspace(-1.5, 1.5, 30),
                                     unit="TeV",
                                     name="energy_true",
                                     interp="log")

    spectral_model = PowerLawSpectralModel(index=3,
                                           amplitude="1e-11 cm-2 s-1 TeV-1",
                                           reference="1 TeV")
    temporal_model = ExpDecayTemporalModel(t0="6 h", t_ref=gti_t0.mjd * u.d)
    spatial_model = GaussianSpatialModel(lon_0="0.2 deg",
                                         lat_0="0.1 deg",
                                         sigma="0.3 deg",
                                         frame="galactic")
    model_simu = SkyModel(
        spectral_model=spectral_model,
        spatial_model=spatial_model,
        temporal_model=temporal_model,
        name="model-simu",
    )

    lvtm = np.ones(N_OBS) * 1.0 * u.hr
    tstart = 1.0 * u.hr

    datasets = []
    for i in range(N_OBS):
        obs = Observation.create(
            pointing=pointing,
            livetime=lvtm[i],
            tstart=tstart,
            irfs=irfs,
            reference_time=gti_t0,
        )
        empty = MapDataset.create(geom,
                                  name=f"dataset_{i}",
                                  energy_axis_true=energy_true)
        maker = MapDatasetMaker(
            selection=["exposure", "background", "psf", "edisp"])
        maker_safe_mask = SafeMaskMaker(methods=["offset-max"],
                                        offset_max=4.0 * u.deg)
        dataset = maker.run(empty, obs)
        dataset = maker_safe_mask.run(dataset, obs)
        dataset.models = [
            model_simu,
            FoVBackgroundModel(dataset_name=dataset.name)
        ]
        dataset.fake()
        datasets.append(dataset)
        tstart = tstart + 2.0 * u.hr

    return datasets
Example #7
0
def test_wcsgeom_squash():
    axis = MapAxis.from_nodes([1, 2, 3], name="test-axis")
    geom = WcsGeom.create(npix=(3, 3), axes=[axis])
    geom_squashed = geom.squash(axis="test-axis")
    assert geom_squashed.data_shape == (1, 3, 3)
Example #8
0
def spectrum_dataset_crab_fine():
    e_true = MapAxis.from_edges(np.logspace(-2, 2.5, 109) * u.TeV,
                                name="energy_true")
    e_reco = MapAxis.from_energy_edges(np.logspace(-2, 2, 73) * u.TeV)
    geom = RegionGeom.create("icrs;circle(83.63, 22.01, 0.11)", axes=[e_reco])
    return SpectrumDataset.create(geom=geom, energy_axis_true=e_true)
Example #9
0
def test_repr(region):
    axis = MapAxis.from_edges([1, 3.162278, 10] * u.TeV, name="energy", interp="log")
    geom = RegionGeom.create(region, axes=[axis])

    assert "RegionGeom" in repr(geom)
    assert "CircleSkyRegion" in repr(geom)
Example #10
0
def test_downsample(region):
    axis = MapAxis.from_edges([1, 3.162278, 10] * u.TeV, name="energy", interp="log")
    geom = RegionGeom.create(region, axes=[axis])
    geom_down = geom.downsample(factor=2, axis_name="energy")

    assert_allclose(geom_down.axes[0].edges.value, [1.0, 10.0], rtol=1e-5)
Example #11
0
def energy_axis():
    return MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=3)
Example #12
0
def test_interp_to_geom():
    energy = MapAxis.from_energy_bounds("1 TeV",
                                        "300 TeV",
                                        nbin=5,
                                        name="energy")
    energy_target = MapAxis.from_energy_bounds("1 TeV",
                                               "300 TeV",
                                               nbin=7,
                                               name="energy")
    value = 30
    coords = {
        "skycoord": SkyCoord("0 deg", "0 deg"),
        "energy": energy_target.center[3]
    }

    # WcsNDMap
    geom_wcs = WcsGeom.create(npix=(5, 3),
                              proj="CAR",
                              binsz=60,
                              axes=[energy],
                              skydir=(0, 0))
    wcs_map = Map.from_geom(geom_wcs, unit="")
    wcs_map.data = value * np.ones(wcs_map.data.shape)

    wcs_geom_target = WcsGeom.create(skydir=(0, 0),
                                     width=(10, 10),
                                     binsz=0.1 * u.deg,
                                     axes=[energy_target])
    interp_wcs_map = wcs_map.interp_to_geom(wcs_geom_target, method="linear")

    assert_allclose(interp_wcs_map.get_by_coord(coords)[0], value, atol=1e-7)
    assert isinstance(interp_wcs_map, WcsNDMap)
    assert interp_wcs_map.geom == wcs_geom_target

    # HpxNDMap
    geom_hpx = HpxGeom.create(binsz=60, axes=[energy], skydir=(0, 0))
    hpx_map = Map.from_geom(geom_hpx, unit="")
    hpx_map.data = value * np.ones(hpx_map.data.shape)

    hpx_geom_target = HpxGeom.create(skydir=(0, 0),
                                     width=10,
                                     binsz=0.1 * u.deg,
                                     axes=[energy_target])
    interp_hpx_map = hpx_map.interp_to_geom(hpx_geom_target)

    assert_allclose(interp_hpx_map.get_by_coord(coords)[0], value, atol=1e-7)
    assert isinstance(interp_hpx_map, HpxNDMap)
    assert interp_hpx_map.geom == hpx_geom_target

    # Preserving the counts
    geom_initial = WcsGeom.create(
        skydir=(20, 20),
        width=(5, 5),
        binsz=0.2 * u.deg,
    )

    test_map = Map.from_geom(geom_initial, unit="")
    test_map.data = value * np.ones(test_map.data.shape)
    geom_target = WcsGeom.create(
        skydir=(20, 20),
        width=(5, 5),
        binsz=0.1 * u.deg,
    )
    new_map = test_map.interp_to_geom(geom_target, preserve_counts=True)
    assert np.floor(np.sum(new_map.data)) == np.sum(test_map.data)
Example #13
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_equal
import astropy.units as u
from astropy.coordinates import SkyCoord
from astropy.units import Quantity, Unit
from gammapy.maps import HpxGeom, HpxNDMap, Map, MapAxis, TimeMapAxis, WcsGeom, WcsNDMap
from gammapy.utils.testing import mpl_plot_check, requires_dependency

pytest.importorskip("healpy")

map_axes = [
    MapAxis.from_bounds(1.0, 10.0, 3, interp="log", name="energy"),
    MapAxis.from_bounds(0.1, 1.0, 4, interp="log", name="time"),
]

mapbase_args = [
    (0.1, 10.0, "wcs", SkyCoord(0.0, 30.0, unit="deg"), None, ""),
    (0.1, 10.0, "wcs", SkyCoord(0.0, 30.0, unit="deg"), map_axes[:1], ""),
    (0.1, 10.0, "wcs", SkyCoord(0.0, 30.0, unit="deg"), map_axes, "m^2"),
    (0.1, 10.0, "hpx", SkyCoord(0.0, 30.0, unit="deg"), None, ""),
    (0.1, 10.0, "hpx", SkyCoord(0.0, 30.0, unit="deg"), map_axes[:1], ""),
    (0.1, 10.0, "hpx", SkyCoord(0.0, 30.0, unit="deg"), map_axes, "s^2"),
]

mapbase_args_with_axes = [_ for _ in mapbase_args if _[4] is not None]


@pytest.mark.parametrize(
    ("binsz", "width", "map_type", "skydir", "axes", "unit"), mapbase_args)
l = 150.57
b = -13.26

target = SkyCoord(l, b, unit="deg", frame="galactic")
offset = 1.0 * u.deg
on_region_radius = Angle("1.0 deg")
pointing = target.directional_offset_by(position_angle=0 * u.deg,
                                        separation=offset)
on_region = CircleSkyRegion(center=target, radius=on_region_radius)

# Energy axis in TeV
emin = 30 / 1000
emax = 100
energy_axis = MapAxis.from_energy_bounds(emin,
                                         emax,
                                         10,
                                         unit="TeV",
                                         name="energy")

# Define spectral model
JFAC = 3.03e18 * u.Unit("GeV2 cm-5")
mDM = 10000 * u.Unit("GeV")
channel = "b"
redshift = 0.017284
spectral_model = DarkMatterAnnihilationSpectralModel(mass=mDM,
                                                     channel=channel,
                                                     jfactor=JFAC,
                                                     z=redshift)

# If want to consider EBL, uncomment following to lines and in the following change spectral_model->model_simu
#absorption = EBLAbsorptionNormSpectralModel.read_builtin("dominguez", redshift=redshift)
Example #15
0
def geom(ebounds, binsz=0.5):
    skydir = SkyCoord(0, -1, unit="deg", frame="galactic")
    energy_axis = MapAxis.from_edges(ebounds, name="energy", unit="TeV", interp="log")
    return WcsGeom.create(
        skydir=skydir, binsz=binsz, width=(10, 5), frame="galactic", axes=[energy_axis]
    )
Example #16
0
def test_interpolate_map_dataset():
    energy = MapAxis.from_energy_bounds("1 TeV", "300 TeV", nbin=5, name="energy")
    energy_true = MapAxis.from_nodes(
        np.logspace(-1, 3, 20), name="energy_true", interp="log", unit="TeV"
    )

    # make dummy map IRFs
    geom_allsky = WcsGeom.create(
        npix=(5, 3), proj="CAR", binsz=60, axes=[energy], skydir=(0, 0)
    )
    geom_allsky_true = geom_allsky.drop("energy").to_cube([energy_true])

    # background
    geom_background = WcsGeom.create(
        skydir=(0, 0), width=(5, 5), binsz=0.2 * u.deg, axes=[energy]
    )
    value = 30
    bkg_map = Map.from_geom(geom_background, unit="")
    bkg_map.data = value * np.ones(bkg_map.data.shape)

    # effective area - with a gradient that also depends on energy
    aeff_map = Map.from_geom(geom_allsky_true, unit="cm2 s")
    ra_arr = np.arange(aeff_map.data.shape[1])
    dec_arr = np.arange(aeff_map.data.shape[2])
    for i in np.arange(aeff_map.data.shape[0]):
        aeff_map.data[i, :, :] = (
            (i + 1) * 10 * np.meshgrid(dec_arr, ra_arr)[0]
            + 10 * np.meshgrid(dec_arr, ra_arr)[1]
            + 10
        )
    aeff_map.meta["TELESCOP"] = "HAWC"

    # psf map
    width = 0.2 * u.deg
    rad_axis = MapAxis.from_nodes(np.linspace(0, 2, 50), name="rad", unit="deg")
    psfMap = PSFMap.from_gauss(energy_true, rad_axis, width)

    # edispmap
    edispmap = EDispKernelMap.from_gauss(
        energy, energy_true, sigma=0.1, bias=0.0, geom=geom_allsky
    )

    # events and gti
    nr_ev = 10
    ev_t = Table()
    gti_t = Table()

    ev_t["EVENT_ID"] = np.arange(nr_ev)
    ev_t["TIME"] = nr_ev * [Time("2011-01-01 00:00:00", scale="utc", format="iso")]
    ev_t["RA"] = np.linspace(-1, 1, nr_ev) * u.deg
    ev_t["DEC"] = np.linspace(-1, 1, nr_ev) * u.deg
    ev_t["ENERGY"] = np.logspace(0, 2, nr_ev) * u.TeV

    gti_t["START"] = [Time("2010-12-31 00:00:00", scale="utc", format="iso")]
    gti_t["STOP"] = [Time("2011-01-02 00:00:00", scale="utc", format="iso")]

    events = EventList(ev_t)
    gti = GTI(gti_t)

    # define observation
    obs = Observation(
        obs_id=0,
        obs_info={},
        gti=gti,
        aeff=aeff_map,
        edisp=edispmap,
        psf=psfMap,
        bkg=bkg_map,
        events=events,
        obs_filter=None,
    )

    # define analysis geometry
    geom_target = WcsGeom.create(
        skydir=(0, 0), width=(5, 5), binsz=0.1 * u.deg, axes=[energy]
    )

    maker = MapDatasetMaker(
        selection=["exposure", "counts", "background", "edisp", "psf"]
    )
    dataset = MapDataset.create(
        geom=geom_target, energy_axis_true=energy_true, name="test"
    )
    dataset = maker.run(dataset, obs)

    # test counts
    assert dataset.counts.data.sum() == nr_ev

    # test background
    assert np.floor(np.sum(dataset.npred_background().data)) == np.sum(bkg_map.data)
    coords_bg = {"skycoord": SkyCoord("0 deg", "0 deg"), "energy": energy.center[0]}
    assert_allclose(
        dataset.npred_background().get_by_coord(coords_bg)[0], 7.5, atol=1e-4
    )

    # test effective area
    coords_aeff = {
        "skycoord": SkyCoord("0 deg", "0 deg"),
        "energy_true": energy_true.center[0],
    }
    assert_allclose(
        aeff_map.get_by_coord(coords_aeff)[0],
        dataset.exposure.interp_by_coord(coords_aeff)[0],
        atol=1e-3,
    )

    # test edispmap
    pdfmatrix_preinterp = edispmap.get_edisp_kernel(
        SkyCoord("0 deg", "0 deg")
    ).pdf_matrix
    pdfmatrix_postinterp = dataset.edisp.get_edisp_kernel(
        SkyCoord("0 deg", "0 deg")
    ).pdf_matrix
    assert_allclose(pdfmatrix_preinterp, pdfmatrix_postinterp, atol=1e-7)

    # test psfmap
    geom_psf = geom_target.drop("energy").to_cube([energy_true])
    psfkernel_preinterp = psfMap.get_psf_kernel(
        SkyCoord("0 deg", "0 deg"), geom_psf, max_radius=2 * u.deg
    ).data
    psfkernel_postinterp = dataset.psf.get_psf_kernel(
        SkyCoord("0 deg", "0 deg"), geom_psf, max_radius=2 * u.deg
    ).data
    assert_allclose(psfkernel_preinterp, psfkernel_postinterp, atol=1e-4)
Example #17
0
def spectrum_dataset_gc():
    e_reco = MapAxis.from_edges(np.logspace(0, 2, 5) * u.TeV, name="energy")
    e_true = MapAxis.from_edges(np.logspace(-1, 2, 13) * u.TeV,
                                name="energy_true")
    geom = RegionGeom.create("galactic;circle(0, 0, 0.11)", axes=[e_reco])
    return SpectrumDataset.create(geom=geom, energy_axis_true=e_true)
Example #18
0
def test_axis():
    return MapAxis.from_nodes([1,2], unit="", name="test")
Example #19
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
import astropy.units as u
from astropy.coordinates import Angle, SkyCoord
from astropy.io import fits
from gammapy.maps import Map, MapAxis, WcsGeom
from gammapy.maps.wcs import _check_width

axes1 = [MapAxis(np.logspace(0.0, 3.0, 3), interp="log", name="energy")]
axes2 = [
    MapAxis(np.logspace(0.0, 3.0, 3), interp="log", name="energy"),
    MapAxis(np.logspace(1.0, 3.0, 4), interp="lin"),
]
skydir = SkyCoord(110.0, 75.0, unit="deg", frame="icrs")

wcs_allsky_test_geoms = [
    (None, 10.0, "galactic", "AIT", skydir, None),
    (None, 10.0, "galactic", "AIT", skydir, axes1),
    (None, [10.0, 20.0], "galactic", "AIT", skydir, axes1),
    (None, 10.0, "galactic", "AIT", skydir, axes2),
    (None, [[10.0, 20.0, 30.0], [10.0, 20.0, 30.0]], "galactic", "AIT", skydir, axes2),
]

wcs_partialsky_test_geoms = [
    (10, 0.1, "galactic", "AIT", skydir, None),
    (10, 0.1, "galactic", "AIT", skydir, axes1),
    (10, [0.1, 0.2], "galactic", "AIT", skydir, axes1),
]
Example #20
0
def test_wcs_geom_pad():
    axis = MapAxis.from_bounds(0, 1, nbin=1, name="axis", unit="")
    geom = WcsGeom.create(skydir=(0, 0), npix=10, binsz=0.1, axes=[axis])

    geom_pad = geom.pad(axis_name="axis", pad_width=1)
    assert_allclose(geom_pad.axes["axis"].edges, [-1, 0, 1, 2])
Example #21
0
def test_get_axis_index_by_name():
    e_axis = MapAxis.from_edges([1, 5], name="energy")
    geom = WcsGeom.create(width=5, binsz=1.0, axes=[e_axis])
    assert geom.get_axis_index_by_name("Energy") == 0
    with pytest.raises(ValueError):
        geom.get_axis_index_by_name("time")
Example #22
0
selected_obs_table = data_store.obs_table.select_observations(selection)

# We can now retrieve the relevant observations by passing their `obs_id` to the`~gammapy.data.DataStore.get_observations()` method.

# In[ ]:

observations = data_store.get_observations(selected_obs_table["OBS_ID"])

# ## Preparing reduced datasets geometry
#
# Now we define a reference geometry for our analysis, We choose a WCS based geometry with a binsize of 0.02 deg and also define an energy axis:

# In[ ]:

energy_axis = MapAxis.from_edges(np.logspace(0.0, 1.0, 4),
                                 unit="TeV",
                                 name="energy",
                                 interp="log")
geom = WcsGeom.create(
    skydir=(83.633, 22.014),
    binsz=0.02,
    width=(2, 2),
    coordsys="CEL",
    proj="CAR",
    axes=[energy_axis],
)

# Reduced IRFs are defined in true energy (i.e. not measured energy).
energy_axis_true = MapAxis.from_edges(np.logspace(-0.3, 1.3, 10),
                                      unit="TeV",
                                      name="energy",
                                      interp="log")
Example #23
0
    "disk-pwlsimple", "point-pwltest"
]

DPI = 120

# observation config
IRF_FILE = "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits"
#IRF_FILE = "$GAMMAPY_DATA/cta-prod3b/caldb/data/cta/prod3b-v2/bcf/South_z20_50h/irf_file.fits"

POINTING = SkyCoord(0.0, 0.5, frame="galactic", unit="deg")
LIVETIME = 1 * u.hr
GTI_TABLE = GTI.create(start=0 * u.s, stop=LIVETIME.to(u.s))

# dataset config
ENERGY_AXIS = MapAxis.from_energy_bounds("0.1 TeV",
                                         "100 TeV",
                                         nbin=10,
                                         per_decade=True)
ENERGY_AXIS_TRUE = MapAxis.from_energy_bounds("0.03 TeV",
                                              "300 TeV",
                                              nbin=20,
                                              per_decade=True)
MIGRA_AXIS = MapAxis.from_bounds(0.5,
                                 2,
                                 nbin=150,
                                 node_type="edges",
                                 name="migra")

WCS_GEOM = WcsGeom.create(skydir=POINTING,
                          width=(4, 4),
                          binsz=0.02,
                          frame="galactic",
E_ref = 1e6 #MeV
Ecut = 19e6 # cutoff in MeV

### interpolate the function of index, fluxes and normalizations
d = np.linspace(0.0,1.55,100)

### Position of the pulsar
ra_0_psr = 276.554417
dec_0_psr = -13.580028
position_psr = SkyCoord(ra_0_psr, dec_0_psr, frame='icrs', unit='deg')

### Position of the map center
position = SkyCoord(276.4, -13.966667, frame='icrs', unit='deg')

### Energy axes and size
energy_axis = MapAxis.from_bounds(0.2e5, 250e6, 40, interp='log', name='energy', unit='MeV')

enlarger = 1.2
r_0 = rad_interpolate(energy_axis.center) * u.deg * enlarger
r_0 = np.where(r_0>=0, r_0, 0) * u.deg

### Fill the index and normalization at the positions of the pixels
binsize=0.02
eccentricity = 0.69
ang = 45.
width = 3.

m_wcs = WcsGeom.create(binsz=binsize, coordsys="CEL",
                       skydir=position_psr,
                       width=width*u.deg,
                       axes=[energy_axis])
Example #25
0
# In[ ]:

obs_cols = ["OBS_ID", "GLON_PNT", "GLAT_PNT", "LIVETIME"]
data_store.obs_table.select_obs_id(obs_id)[obs_cols]

# ## Make sky images
#
# ### Define map geometry
#
# Select the target position and define an ON region for the spectral analysis

# In[ ]:

axis = MapAxis.from_edges(np.logspace(-1.0, 1.0, 10),
                          unit="TeV",
                          name="energy",
                          interp="log")
geom = WcsGeom.create(skydir=(0, 0),
                      npix=(500, 400),
                      binsz=0.02,
                      coordsys="GAL",
                      axes=[axis])
geom

# ### Compute images
#
# Exclusion mask currently unused. Remove here or move to later in the tutorial?

# In[ ]:

target_position = SkyCoord(0, 0, unit="deg", frame="galactic")
Example #26
0
spectral_model_1 = PowerLaw(
    index=3, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)

spectral_model_2 = PowerLaw(
    index=3, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)

sky_model_1 = SkyModel(spatial_model=spatial_model_1, spectral_model=spectral_model_1)

sky_model_2 = SkyModel(spatial_model=spatial_model_2, spectral_model=spectral_model_2)

models = sky_model_1 + sky_model_2

# Define map geometry
axis = MapAxis.from_edges(np.logspace(-1.0, 1.0, 10), unit="TeV")
geom = WcsGeom.create(
    skydir=(0, 0), binsz=0.02, width=(2, 2), coordsys="GAL", axes=[axis]
)


# Define some observation parameters
# we are not simulating many pointings / observations
pointing = SkyCoord(0.2, 0.5, unit="deg", frame="galactic")
livetime = 20 * u.hour

exposure_map = make_map_exposure_true_energy(
    pointing=pointing, livetime=livetime, aeff=aeff, geom=geom
)

evaluator = MapEvaluator(model=models, exposure=exposure_map)
Example #27
0
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io import fits
from regions import CircleSkyRegion
from gammapy.maps import HpxGeom, HpxMap, HpxNDMap, Map, MapAxis, WcsGeom
from gammapy.utils.testing import mpl_plot_check, requires_data, requires_dependency
from gammapy.maps.utils import find_bintable_hdu
from gammapy.maps.hpx import HpxConv
from gammapy.irf import PSFKernel, PSFMap

pytest.importorskip("healpy")

axes1 = [MapAxis(np.logspace(0.0, 3.0, 3), interp="log")]

hpx_test_allsky_geoms = [
    (8, False, "galactic", None, None),
    (8, False, "galactic", None, axes1),
    ([4, 8], False, "galactic", None, axes1),
]

hpx_test_partialsky_geoms = [
    ([4, 8], False, "galactic", "DISK(110.,75.,30.)", axes1),
    (8, False, "galactic", "DISK(110.,75.,10.)",
     [MapAxis(np.logspace(0.0, 3.0, 4))]),
    (
        8,
        False,
        "galactic",
Example #28
0
 "pars",
 [
     {
         "energy": None,
         "rad": None,
         "energy_shape": 32,
         "psf_energy": 0.8659643,
         "rad_shape": 144,
         "psf_rad": 0.0015362848,
         "psf_exposure": 3.14711e12,
         "psf_value_shape": (32, 144),
         "psf_value": 4369.96391,
     },
     {
         "energy":
         MapAxis.from_energy_bounds(1, 10, 100, "TeV", name="energy_true"),
         "rad":
         None,
         "energy_shape":
         100,
         "psf_energy":
         1.428893959,
         "rad_shape":
         144,
         "psf_rad":
         0.0015362848,
         "psf_exposure":
         4.723409e12,
         "psf_value_shape": (100, 144),
         "psf_value":
         3714.303683,
Example #29
0
    def plot_ts_profiles(
        self,
        ax=None,
        sed_type="dnde",
        add_cbar=True,
        **kwargs,
    ):
        """Plot fit statistic SED profiles as a density plot.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            Axis object to plot on.
        sed_type : {"dnde", "flux", "eflux", "e2dnde"}
            Sed type
        add_cbar : bool
            Whether to add a colorbar to the plot.
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.pcolormesh`

        Returns
        -------
        ax : `~matplotlib.axes.Axes`
            Axis object
        """
        import matplotlib.pyplot as plt

        if ax is None:
            ax = plt.gca()

        if not self.norm.geom.is_region:
            raise ValueError(
                "Plotting only supported for region based flux points")

        if not self.geom.axes.is_unidimensional:
            raise ValueError(
                "Profile plotting is only supported for unidimensional maps")

        axis = self.geom.axes.primary_axis

        if isinstance(axis, TimeMapAxis) and not axis.is_contiguous:
            axis = axis.to_contiguous()

        yunits = kwargs.pop("yunits", DEFAULT_UNIT[sed_type])

        flux_ref = getattr(self, sed_type + "_ref").to(yunits)

        ts = self.ts_scan

        norm_min, norm_max = ts.geom.axes["norm"].bounds.to_value("")

        flux = MapAxis.from_bounds(norm_min * flux_ref.value.min(),
                                   norm_max * flux_ref.value.max(),
                                   nbin=500,
                                   interp=axis.interp,
                                   unit=flux_ref.unit)

        norm = flux.center / flux_ref.reshape((-1, 1))

        coords = ts.geom.get_coord()
        coords["norm"] = norm
        coords[axis.name] = axis.center.reshape((-1, 1))

        z = ts.interp_by_coord(coords, values_scale="stat-profile")

        kwargs.setdefault("vmax", 0)
        kwargs.setdefault("vmin", -4)
        kwargs.setdefault("zorder", 0)
        kwargs.setdefault("cmap", "Blues")
        kwargs.setdefault("linewidths", 0)
        kwargs.setdefault("shading", "auto")

        # clipped values are set to NaN so that they appear white on the plot
        z[-z < kwargs["vmin"]] = np.nan

        with quantity_support():
            caxes = ax.pcolormesh(axis.as_plot_edges, flux.edges, -z.T,
                                  **kwargs)

        axis.format_plot_xaxis(ax=ax)

        ax.set_ylabel(f"{sed_type} ({ax.yaxis.units})")
        ax.set_yscale("log")

        if add_cbar:
            label = "Fit statistic difference"
            ax.figure.colorbar(caxes, ax=ax, label=label)

        return ax
Example #30
0
def geom():
    axis = MapAxis.from_edges(np.logspace(-1, 1, 3), unit=u.TeV, name="energy")
    return WcsGeom.create(skydir=(0, 0),
                          npix=(5, 4),
                          frame="galactic",
                          axes=[axis])
Example #31
0
def test_plot_grid():
    axis = MapAxis([0, 1, 2], node_type="edges")
    m = WcsNDMap.create(binsz=0.1 * u.deg, width=1 * u.deg, axes=[axis])
    with mpl_plot_check():
        m.plot_grid()
Example #32
0
                            reference="1 TeV")

spectral_model_2 = PowerLaw(index=3,
                            amplitude="1e-11 cm-2 s-1 TeV-1",
                            reference="1 TeV")

sky_model_1 = SkyModel(spatial_model=spatial_model_1,
                       spectral_model=spectral_model_1)

sky_model_2 = SkyModel(spatial_model=spatial_model_2,
                       spectral_model=spectral_model_2)

models = sky_model_1 + sky_model_2

# Define map geometry
axis = MapAxis.from_edges(np.logspace(-1.0, 1.0, 10), unit="TeV")
geom = WcsGeom.create(skydir=(0, 0),
                      binsz=0.02,
                      width=(2, 2),
                      coordsys="GAL",
                      axes=[axis])

# Define some observation parameters
# we are not simulating many pointings / observations
pointing = SkyCoord(0.2, 0.5, unit="deg", frame="galactic")
livetime = 20 * u.hour

exposure_map = make_map_exposure_true_energy(pointing=pointing,
                                             livetime=livetime,
                                             aeff=aeff,
                                             geom=geom)