Exemplo n.º 1
0
def test_psf_table():
    '''Test our psf is readable by gammapy'''
    pytest.importorskip('gammapy')
    from pyirf.io import create_psf_table_hdu
    from pyirf.utils import cone_solid_angle
    from gammapy.irf import PSF3D

    e_bins = np.geomspace(0.1, 100, 31) * u.TeV
    source_bins = np.linspace(0, 1, 101) * u.deg
    fov_bins = [0, 1, 2, 3] * u.deg
    psf = np.zeros((30, 100, 3))
    psf[:, 0, :] = 1
    psf = psf / cone_solid_angle(source_bins[1])

    for point_like in [True, False]:
        with tempfile.NamedTemporaryFile(suffix='.fits') as f:
            hdu = create_psf_table_hdu(psf,
                                       e_bins,
                                       source_bins,
                                       fov_bins,
                                       point_like=point_like)

            fits.HDUList([fits.PrimaryHDU(), hdu]).writeto(f.name)

            # test reading with gammapy works
            psf3d = PSF3D.read(f.name, 'PSF')

            # gammapy does not transpose psf when reading from fits,
            # unlike how it handles effective area and edisp
            # see https://github.com/gammapy/gammapy/issues/3025
            assert u.allclose(psf, psf3d.psf_value.T, atol=1e-16 / u.sr)
Exemplo n.º 2
0
def test_psf_table_gammapy(psf_hdu):
    '''Test our psf is readable by gammapy'''
    from gammapy.irf import PSF3D

    psf, hdu = psf_hdu

    with tempfile.NamedTemporaryFile(suffix='.fits') as f:
        fits.HDUList([fits.PrimaryHDU(), hdu]).writeto(f.name)

        # test reading with gammapy works
        psf3d = PSF3D.read(f.name, 'PSF')
        assert u.allclose(psf, psf3d.psf_value, atol=1e-16 / u.sr)
Exemplo n.º 3
0
def test_psf_table_gammapy(psf_hdu):
    '''Test our psf is readable by gammapy'''
    from gammapy.irf import PSF3D

    psf, hdu = psf_hdu

    with tempfile.NamedTemporaryFile(suffix='.fits') as f:
        fits.HDUList([fits.PrimaryHDU(), hdu]).writeto(f.name)

        # test reading with gammapy works
        psf3d = PSF3D.read(f.name, 'PSF')

        # gammapy does not transpose psf when reading from fits,
        # unlike how it handles effective area and edisp
        # see https://github.com/gammapy/gammapy/issues/3025
        assert u.allclose(psf, psf3d.psf_value.T, atol=1e-16 / u.sr)
Exemplo n.º 4
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}")
Exemplo n.º 5
0
def psf_3d_plot(irf_file_path, ax=None, hdu="PSF"):
    if not ax:
        fig = plt.figure(figsize=(10, 7), )
        ax = fig.add_subplot(111, projection='3d')

    psf = PSF3D.read(irf_file_path, hdu=hdu)
    energy_reco = np.logspace(-2, 2, 20) * u.TeV
    offsets = np.linspace(0, 6, 7) * u.deg

    d = np.linspace(0.01, 1.1, 11)[1::2]
    ticks = np.log10(d)
    # ticks = np.append(ticks, 1 + ticks)

    X, Y = np.meshgrid(energy_reco, offsets)
    Z = []
    for x in energy_reco:
        zs = psf.containment_radius(x, offsets, fraction=0.68)
        Z.append(zs)

    Z = np.vstack(Z).T
    ax.plot_surface(np.log10(X.to_value('TeV')),
                    Y,
                    np.log10(Z),
                    cmap='viridis',
                    linewidth=1,
                    antialiased=True)

    ax.xaxis.set_major_locator(mticker.FixedLocator([-2, -1, 0, 1, 2]))
    ax.zaxis.set_major_locator(mticker.FixedLocator(ticks))

    ax.zaxis.set_major_formatter(mticker.FuncFormatter(_log_scale_formatter))
    ax.xaxis.set_major_formatter(mticker.FuncFormatter(_log_tick_formatter))
    ax.set_zlim([-1, 0.4])
    ax.set_ylabel('Offset in FoV / deg')
    ax.set_zlabel('Angular Resolution / deg')
    ax.set_xlabel('Reconstructed Energy / TeV')
    return ax
Exemplo n.º 6
0
"""Plot the PSF at a given offset from the camera center"""
import matplotlib.pyplot as plt
from astropy.coordinates import Angle
from gammapy.irf import PSF3D

filename = "$GAMMAPY_DATA/hess-dl3-dr1/data/hess_dl3_dr1_obs_id_020136.fits.gz"
psf = PSF3D.read(filename, hdu="PSF")
# offset at which we want to examine the PSF
offset = Angle("0.5 deg") 
psf_table = psf.to_energy_dependent_table_psf(offset)
psf_table.plot_psf_vs_rad()
plt.show()
Exemplo n.º 7
0
def load_psf():
    """Load a test PSF."""
    filename = '$GAMMAPY_EXTRA/test_datasets/psf_table_023523.fits.gz'
    print('Reading {}'.format(filename))

    return PSF3D.read(filename)
Exemplo n.º 8
0
def psf_3d():
    filename = "$GAMMAPY_DATA/hess-dl3-dr1/data/hess_dl3_dr1_obs_id_023523.fits.gz"
    return PSF3D.read(filename, hdu="PSF")
Exemplo n.º 9
0
 def setup(self):
     filename = "$GAMMAPY_DATA/tests/hess-hap-hd-prod3/psf_table.fits.gz"
     self.psf = PSF3D.read(filename)
Exemplo n.º 10
0
def load_psf():
    """Load a test PSF."""
    filename = '$GAMMAPY_EXTRA/test_datasets/psf_table_023523.fits.gz'
    print('Reading {}'.format(filename))

    return PSF3D.read(filename)
Exemplo n.º 11
0
def test_psf_3d_write(psf_3d, tmp_path):
    psf_3d.write(tmp_path / "tmp.fits")
    psf_3d = PSF3D.read(tmp_path / "tmp.fits", hdu=1)

    assert_allclose(psf_3d.energy_axis_true.edges[0].value, 0.01)
Exemplo n.º 12
0
def psf_3d():
    filename = "$GAMMAPY_DATA/tests/psf_table_023523.fits.gz"
    return PSF3D.read(filename)
Exemplo n.º 13
0
def test_psf_3d_write(psf_3d, tmpdir):
    filename = str(tmpdir / "temp.fits")
    psf_3d.write(filename)
    psf_3d = PSF3D.read(filename)

    assert_allclose(psf_3d.energy_lo[0].value, 0.02)