Skip to content

Commit

Permalink
Merge branch 'main' into info_fermi_catalog
Browse files Browse the repository at this point in the history
  • Loading branch information
bkhelifi authored Oct 17, 2024
2 parents 5f34898 + 0b2c129 commit 1545062
Show file tree
Hide file tree
Showing 13 changed files with 95 additions and 38 deletions.
7 changes: 4 additions & 3 deletions examples/tutorials/analysis-1d/cta_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
- `~gammapy.estimators.SensitivityEstimator`
"""

from cycler import cycler
import numpy as np
import astropy.units as u
Expand Down Expand Up @@ -182,13 +183,11 @@
#



fig, ax = plt.subplots()

ax.set_prop_cycle(cycler("marker", "s*v") + cycler("color", "rgb"))

for criterion in ("significance", "gamma", "bkg"):

mask = sensitivity_table["criterion"] == criterion
t = sensitivity_table[mask]

Expand Down Expand Up @@ -264,7 +263,9 @@
#

flux_points = FluxPoints.from_table(
sensitivity_table, sed_type="e2dnde", reference_model=sensitivity_estimator.spectrum
sensitivity_table,
sed_type="e2dnde",
reference_model=sensitivity_estimator.spectral_model,
)
print(
f"Integral sensitivity in {livetime:.2f} above {energy_axis.edges[0]:.2e} "
Expand Down
16 changes: 9 additions & 7 deletions gammapy/estimators/map/asmooth.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from gammapy.utils.pbar import progress_bar
from ..core import Estimator
from ..utils import estimate_exposure_reco_energy
from gammapy.utils.deprecation import deprecated_renamed_argument

__all__ = ["ASmoothMapEstimator"]

Expand All @@ -37,8 +38,8 @@ class ASmoothMapEstimator(Estimator):
Smoothing scales.
kernel : `astropy.convolution.Kernel`
Smoothing kernel.
spectrum : `~gammapy.modeling.models.SpectralModel`
Spectral model assumption.
spectral_model : `~gammapy.modeling.models.SpectralModel`, optional
Spectral model assumption. Default is power-law with spectral index of 2.
method : {'lima', 'asmooth'}
Significance estimation method. Default is 'lima'.
threshold : float
Expand All @@ -63,19 +64,20 @@ class ASmoothMapEstimator(Estimator):

tag = "ASmoothMapEstimator"

@deprecated_renamed_argument("spectrum", "spectral_model", "v1.3")
def __init__(
self,
scales=None,
kernel=Gaussian2DKernel,
spectrum=None,
spectral_model=None,
method="lima",
threshold=5,
energy_edges=None,
):
if spectrum is None:
spectrum = PowerLawSpectralModel()
if spectral_model is None:
spectral_model = PowerLawSpectralModel(index=2)

self.spectrum = spectrum
self.spectral_model = spectral_model

if scales is None:
scales = self.get_scales(n_scales=9, kernel=kernel)
Expand Down Expand Up @@ -231,7 +233,7 @@ def estimate_maps(self, dataset):
background = dataset_image.background.data[0]

if dataset_image.exposure is not None:
exposure = estimate_exposure_reco_energy(dataset_image, self.spectrum)
exposure = estimate_exposure_reco_energy(dataset_image, self.spectral_model)
else:
exposure = None

Expand Down
5 changes: 5 additions & 0 deletions gammapy/estimators/map/tests/test_asmooth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from gammapy.estimators import ASmoothMapEstimator
from gammapy.maps import Map, MapAxis, WcsNDMap
from gammapy.utils.testing import requires_data
from gammapy.modeling.models import PowerLawSpectralModel
from gammapy.utils.deprecation import GammapyDeprecationWarning


@pytest.fixture(scope="session")
Expand Down Expand Up @@ -39,6 +41,9 @@ def test_asmooth(input_dataset_simple):
kernel = Tophat2DKernel
scales = ASmoothMapEstimator.get_scales(3, factor=2, kernel=kernel) * 0.1 * u.deg

with pytest.warns(GammapyDeprecationWarning):
ASmoothMapEstimator(scales=scales, spectrum=PowerLawSpectralModel())

asmooth = ASmoothMapEstimator(
scales=scales, kernel=kernel, method="lima", threshold=2.5
)
Expand Down
14 changes: 8 additions & 6 deletions gammapy/estimators/points/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from gammapy.modeling.models import PowerLawSpectralModel, SkyModel
from .core import FluxPoints
from .sed import FluxPointsEstimator
from gammapy.utils.deprecation import deprecated_renamed_argument

__all__ = ["FluxProfileEstimator"]

Expand All @@ -22,7 +23,7 @@ class FluxProfileEstimator(FluxPointsEstimator):
----------
regions : list of `~regions.SkyRegion`
Regions to use.
spectrum : `~gammapy.modeling.models.SpectralModel`, optional
spectral_model : `~gammapy.modeling.models.SpectralModel`, optional
Spectral model to compute the fluxes or brightness.
Default is power-law with spectral index of 2.
n_jobs : int, optional
Expand Down Expand Up @@ -89,18 +90,19 @@ class FluxProfileEstimator(FluxPointsEstimator):

tag = "FluxProfileEstimator"

def __init__(self, regions, spectrum=None, **kwargs):
@deprecated_renamed_argument("spectrum", "spectral_model", "v1.3")
def __init__(self, regions, spectral_model=None, **kwargs):
if len(regions) <= 1:
raise ValueError(
"Please provide at least two regions for flux profile estimation."
)

self.regions = regions

if spectrum is None:
spectrum = PowerLawSpectralModel()
if spectral_model is None:
spectral_model = PowerLawSpectralModel()

self.spectrum = spectrum
self.spectral_model = spectral_model
super().__init__(**kwargs)

@property
Expand Down Expand Up @@ -170,7 +172,7 @@ def _run_region(self, datasets, region):
.to_region_nd_map(region, func=np.sum, weights=dataset_map.mask_safe)
.data
)
datasets_to_fit.models = SkyModel(self.spectrum, name="test-source")
datasets_to_fit.models = SkyModel(self.spectral_model, name="test-source")
estimator = self.copy()
estimator.n_jobs = self._n_child_jobs
return estimator._run_flux_points(datasets_to_fit)
Expand Down
21 changes: 12 additions & 9 deletions gammapy/estimators/points/sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from gammapy.modeling.models import PowerLawSpectralModel, SkyModel
from gammapy.stats import WStatCountsStatistic
from ..core import Estimator
from gammapy.utils.deprecation import deprecated_renamed_argument

__all__ = ["SensitivityEstimator"]

Expand All @@ -20,8 +21,8 @@ class SensitivityEstimator(Estimator):
Parameters
----------
spectrum : `SpectralModel`
Spectral model assumption. Default is Power Law with index 2.
spectral_model : `~gammapy.modeling.models.SpectralModel`, optional
Spectral model assumption. Default is power-law with spectral index of 2.
n_sigma : float, optional
Minimum significance. Default is 5.
gamma_min : float, optional
Expand All @@ -37,18 +38,20 @@ class SensitivityEstimator(Estimator):

tag = "SensitivityEstimator"

@deprecated_renamed_argument("spectrum", "spectral_model", "v1.3")
def __init__(
self,
spectrum=None,
spectral_model=None,
n_sigma=5.0,
gamma_min=10,
bkg_syst_fraction=0.05,
):
if spectral_model is None:
spectral_model = PowerLawSpectralModel(
index=2, amplitude="1 cm-2 s-1 TeV-1"
)

if spectrum is None:
spectrum = PowerLawSpectralModel(index=2, amplitude="1 cm-2 s-1 TeV-1")

self.spectrum = spectrum
self.spectral_model = spectral_model
self.n_sigma = n_sigma
self.gamma_min = gamma_min
self.bkg_syst_fraction = bkg_syst_fraction
Expand Down Expand Up @@ -100,12 +103,12 @@ def estimate_min_e2dnde(self, excess, dataset):
"""
energy = dataset._geom.axes["energy"].center

dataset.models = SkyModel(spectral_model=self.spectrum)
dataset.models = SkyModel(spectral_model=self.spectral_model)
npred = dataset.npred_signal()

phi_0 = excess / npred

dnde_model = self.spectrum(energy=energy)
dnde_model = self.spectral_model(energy=energy)
dnde = phi_0.data[:, 0, 0] * dnde_model * energy**2
return dnde.to("erg / (cm2 s)")

Expand Down
9 changes: 9 additions & 0 deletions gammapy/estimators/points/tests/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
make_orthogonal_rectangle_sky_regions,
)
from gammapy.utils.testing import requires_data, requires_dependency
from gammapy.utils.deprecation import GammapyDeprecationWarning


def get_simple_dataset_on_off():
Expand Down Expand Up @@ -54,13 +55,21 @@ def test_profile_content():
wcs = mapdataset_onoff.counts.geom.wcs
boxes = make_horizontal_boxes(wcs)

with pytest.warns(GammapyDeprecationWarning):
FluxProfileEstimator(
regions=boxes,
energy_edges=[0.1, 1, 10] * u.TeV,
spectrum=PowerLawSpectralModel(),
)

prof_maker = FluxProfileEstimator(
regions=boxes,
energy_edges=[0.1, 1, 10] * u.TeV,
selection_optional="all",
n_sigma=1,
n_sigma_ul=3,
)

result = prof_maker.run(mapdataset_onoff)

imp_prof = result.to_table(sed_type="flux")
Expand Down
8 changes: 7 additions & 1 deletion gammapy/estimators/points/tests/test_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from gammapy.estimators import FluxPoints, SensitivityEstimator
from gammapy.irf import EDispKernelMap
from gammapy.maps import MapAxis, RegionNDMap
from gammapy.modeling.models import PowerLawSpectralModel
from gammapy.utils.deprecation import GammapyDeprecationWarning


@pytest.fixture()
Expand Down Expand Up @@ -37,6 +39,10 @@ def test_cta_sensitivity_estimator(spectrum_dataset, caplog):
acceptance=RegionNDMap.from_geom(geom=geom, data=1),
acceptance_off=RegionNDMap.from_geom(geom=geom, data=5),
)
with pytest.warns(GammapyDeprecationWarning):
SensitivityEstimator(
gamma_min=25, bkg_syst_fraction=0.075, spectrum=PowerLawSpectralModel()
)

sens = SensitivityEstimator(gamma_min=25, bkg_syst_fraction=0.075)
table = sens.run(dataset_on_off)
Expand Down Expand Up @@ -89,7 +95,7 @@ def test_integral_estimation(spectrum_dataset, caplog):
sens = SensitivityEstimator(gamma_min=25, bkg_syst_fraction=0.075)
table = sens.run(dataset_on_off)
flux_points = FluxPoints.from_table(
table, sed_type="e2dnde", reference_model=sens.spectrum
table, sed_type="e2dnde", reference_model=sens.spectral_model
)

assert_allclose(table["excess"].data.squeeze(), 270540, rtol=1e-3)
Expand Down
12 changes: 7 additions & 5 deletions gammapy/irf/psf/kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import matplotlib.pyplot as plt
from gammapy.maps import Map
from gammapy.modeling.models import PowerLawSpectralModel
from gammapy.utils.deprecation import deprecated_renamed_argument

__all__ = ["PSFKernel"]

Expand Down Expand Up @@ -161,12 +162,13 @@ def write(self, *args, **kwargs):
"""Write the Map object which contains the PSF kernel to file."""
self.psf_kernel_map.write(*args, **kwargs)

def to_image(self, spectrum=None, exposure=None, keepdims=True):
@deprecated_renamed_argument("spectrum", "spectral_model", "v1.3")
def to_image(self, spectral_model=None, exposure=None, keepdims=True):
"""Transform 3D PSFKernel into a 2D PSFKernel.
Parameters
----------
spectrum : `~gammapy.modeling.models.SpectralModel`, optional
spectral_model : `~gammapy.modeling.models.SpectralModel`, optional
Spectral model to compute the weights.
Default is power-law with spectral index of 2.
exposure : `~astropy.units.Quantity` or `~numpy.ndarray`, optional
Expand All @@ -184,8 +186,8 @@ def to_image(self, spectrum=None, exposure=None, keepdims=True):
"""
map = self.psf_kernel_map

if spectrum is None:
spectrum = PowerLawSpectralModel(index=2.0)
if spectral_model is None:
spectral_model = PowerLawSpectralModel(index=2.0)

if exposure is None:
exposure = np.ones(map.geom.axes[0].center.shape)
Expand All @@ -200,7 +202,7 @@ def to_image(self, spectrum=None, exposure=None, keepdims=True):
if "energy" in name:
energy_name = name
energy_edges = map.geom.axes[energy_name].edges
weights = spectrum.integral(
weights = spectral_model.integral(
energy_min=energy_edges[:-1], energy_max=energy_edges[1:], intervals=True
)
weights *= exposure
Expand Down
12 changes: 7 additions & 5 deletions gammapy/irf/psf/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from ..core import IRFMap
from .core import PSF
from .kernel import PSFKernel
from gammapy.utils.deprecation import deprecated_renamed_argument

__all__ = ["PSFMap", "RecoPSFMap"]

Expand Down Expand Up @@ -447,12 +448,13 @@ def from_gauss(cls, energy_axis_true, rad_axis=None, sigma=0.1 * u.deg, geom=Non
)
return cls(psf_map=psf_map, exposure_map=exposure_map)

def to_image(self, spectrum=None, keepdims=True):
@deprecated_renamed_argument("spectrum", "spectral_model", "v1.3")
def to_image(self, spectral_model=None, keepdims=True):
"""Reduce to a 2D map after weighing with the associated exposure and a spectrum.
Parameters
----------
spectrum : `~gammapy.modeling.models.SpectralModel`, optional
spectral_model : `~gammapy.modeling.models.SpectralModel`, optional
Spectral model to compute the weights.
Default is power-law with spectral index of 2.
keepdims : bool, optional
Expand All @@ -466,10 +468,10 @@ def to_image(self, spectrum=None, keepdims=True):
"""
from gammapy.makers.utils import _map_spectrum_weight

if spectrum is None:
spectrum = PowerLawSpectralModel(index=2.0)
if spectral_model is None:
spectral_model = PowerLawSpectralModel(index=2.0)

exp_weighed = _map_spectrum_weight(self.exposure_map, spectrum)
exp_weighed = _map_spectrum_weight(self.exposure_map, spectral_model)
exposure = exp_weighed.sum_over_axes(
axes_names=[self.energy_name], keepdims=keepdims
)
Expand Down
6 changes: 5 additions & 1 deletion gammapy/irf/psf/tests/test_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
import astropy.units as u
from gammapy.irf import PSFKernel
from gammapy.maps import MapAxis, WcsGeom
from gammapy.modeling.models import DiskSpatialModel
from gammapy.modeling.models import DiskSpatialModel, PowerLawSpectralModel
from gammapy.utils.testing import mpl_plot_check
from gammapy.utils.deprecation import GammapyDeprecationWarning


@pytest.fixture
Expand Down Expand Up @@ -51,6 +52,9 @@ def test_psf_kernel_to_image():
kernel1 = PSFKernel.from_spatial_model(disk_1, geom, max_radius=rad_max, factor=4)
kernel2 = PSFKernel.from_spatial_model(disk_2, geom, max_radius=rad_max, factor=4)

with pytest.warns(GammapyDeprecationWarning):
kernel1.to_image(spectrum=PowerLawSpectralModel())

kernel1.psf_kernel_map.data[1, :, :] = kernel2.psf_kernel_map.data[1, :, :]

kernel_image_1 = kernel1.to_image()
Expand Down
5 changes: 5 additions & 0 deletions gammapy/irf/psf/tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from gammapy.makers.utils import make_map_exposure_true_energy, make_psf_map
from gammapy.maps import Map, MapAxis, MapCoord, RegionGeom, WcsGeom
from gammapy.utils.testing import mpl_plot_check, requires_data
from gammapy.modeling.models import PowerLawSpectralModel
from gammapy.utils.deprecation import GammapyDeprecationWarning


@pytest.fixture(scope="session")
Expand Down Expand Up @@ -423,6 +425,9 @@ def test_psf_map_write_gtpsf(tmpdir):
def test_to_image():
psfmap = make_test_psfmap(0.15 * u.deg)

with pytest.warns(GammapyDeprecationWarning):
psfmap.to_image(spectrum=PowerLawSpectralModel())

psf2D = psfmap.to_image()
assert_allclose(psf2D.psf_map.geom.data_shape, (1, 100, 25, 25))
assert_allclose(psf2D.exposure_map.geom.data_shape, (1, 1, 25, 25))
Expand Down
Loading

0 comments on commit 1545062

Please sign in to comment.