Repository: gammapy/gammapy

Issue:
Models are lost in FluxProfileEstimator
**Gammapy version**
gammapy 1.0.1

**Bug description**
All models attached to my datasets are discarded when I calculate a flux profile with `FluxProfileEstimator`.

**Expected behavior**
The predicted counts from the models should become part of the background when `to_spectrum_datasets` is called in `FluxProfileEstimator.run()`





Discussion:

Resolving patch:
diff --git a/gammapy/estimators/points/profile.py b/gammapy/estimators/points/profile.py
--- a/gammapy/estimators/points/profile.py
+++ b/gammapy/estimators/points/profile.py
@@ -1,5 +1,6 @@
 # Licensed under a 3-clause BSD style license - see LICENSE.rst
 """Tools to create profiles (i.e. 1D "slices" from 2D images)."""
+import numpy as np
 from astropy import units as u
 from regions import CircleAnnulusSkyRegion
 from gammapy.datasets import Datasets
@@ -133,12 +134,20 @@ def run(self, datasets):
         profile : `~gammapy.estimators.FluxPoints`
             Profile flux points.
         """
+
         datasets = Datasets(datasets=datasets)
 
         maps = []
-
         for region in self.regions:
             datasets_to_fit = datasets.to_spectrum_datasets(region=region)
+            for dataset_spec, dataset_map in zip(datasets_to_fit, datasets):
+                dataset_spec.background.data = (
+                    dataset_map.npred()
+                    .to_region_nd_map(
+                        region, func=np.sum, weights=dataset_map.mask_safe
+                    )
+                    .data
+                )
             datasets_to_fit.models = SkyModel(self.spectrum, name="test-source")
             fp = super().run(datasets_to_fit)
             maps.append(fp)


Test patch:
diff --git a/gammapy/estimators/points/tests/test_profile.py b/gammapy/estimators/points/tests/test_profile.py
--- a/gammapy/estimators/points/tests/test_profile.py
+++ b/gammapy/estimators/points/tests/test_profile.py
@@ -8,12 +8,14 @@
 from gammapy.data import GTI
 from gammapy.datasets import MapDatasetOnOff
 from gammapy.estimators import FluxPoints, FluxProfileEstimator
+from gammapy.estimators.points.tests.test_sed import simulate_map_dataset
 from gammapy.maps import MapAxis, WcsGeom
 from gammapy.modeling.models import PowerLawSpectralModel
 from gammapy.utils.regions import (
     make_concentric_annulus_sky_regions,
     make_orthogonal_rectangle_sky_regions,
 )
+from gammapy.utils.testing import requires_data
 
 
 def get_simple_dataset_on_off():
@@ -184,3 +186,35 @@ def test_regions_init():
 
     with pytest.raises(ValueError):
         FluxProfileEstimator(regions=[region])
+
+
+@requires_data()
+def test_profile_with_model_or_mask():
+    dataset = simulate_map_dataset(name="test-map-pwl")
+
+    geom = dataset.counts.geom
+    regions = make_concentric_annulus_sky_regions(
+        center=geom.center_skydir,
+        radius_max=0.2 * u.deg,
+    )
+
+    prof_maker = FluxProfileEstimator(
+        regions,
+        selection_optional="all",
+        energy_edges=[0.1, 10] * u.TeV,
+        n_sigma_ul=3,
+        sum_over_energy_groups=True,
+    )
+    result = prof_maker.run(dataset)
+    imp_prof = result.to_table(sed_type="flux", format="profile")
+    assert_allclose(imp_prof[7]["npred_excess"], [[-1.115967]], rtol=1e-3)
+
+    dataset.models = None
+    result = prof_maker.run(dataset)
+    imp_prof = result.to_table(sed_type="flux", format="profile")
+    assert_allclose(imp_prof[7]["npred_excess"], [[112.95312]], rtol=1e-3)
+
+    dataset.mask_fit = ~geom.region_mask([regions[7]])
+    result = prof_maker.run(dataset)
+    imp_prof = result.to_table(sed_type="flux", format="profile")
+    assert_allclose(imp_prof[7]["npred_excess"], [[0]], rtol=1e-3)