internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: gammapy/gammapy

Issue:
Error while printing catalogs
```
from gammapy.catalog import *
catalog = SourceCatalog4FGL()
print(catalog)
```

gives an error
```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/var/folders/v4/62d6cvbj72qbyw23mq2pwxl00000gn/T/ipykernel_17380/3277138734.py in <module>
      1 catalog = SourceCatalog4FGL()
----> 2 print(catalog)

~/Gammapy-dev/gammapy/gammapy/catalog/core.py in __str__(self)
    110     def __str__(self):
    111         return (
--> 112             f"{self.__class__.__name__}:\n"
    113             f"    name: {self.name}\n"
    114             f"    description: {self.description}\n"

AttributeError: 'SourceCatalog4FGL' object has no attribute 'name'
```

This happens for all catalogs


Discussion:

Resolving patch:
diff --git a/gammapy/catalog/core.py b/gammapy/catalog/core.py
--- a/gammapy/catalog/core.py
+++ b/gammapy/catalog/core.py
@@ -99,6 +99,11 @@ def description(cls):
         """Catalog description (str)."""
         pass
 
+    @property
+    @abc.abstractmethod
+    def tag(self):
+        pass
+
     source_object_class = SourceCatalogObject
     """Source class (`SourceCatalogObject`)."""
 
@@ -110,7 +115,7 @@ def __init__(self, table, source_name_key="Source_Name", source_name_alias=()):
     def __str__(self):
         return (
             f"{self.__class__.__name__}:\n"
-            f"    name: {self.name}\n"
+            f"    name: {self.tag}\n"
             f"    description: {self.description}\n"
             f"    sources: {len(self.table)}\n"
         )


Test patch:
diff --git a/gammapy/catalog/tests/test_core.py b/gammapy/catalog/tests/test_core.py
--- a/gammapy/catalog/tests/test_core.py
+++ b/gammapy/catalog/tests/test_core.py
@@ -12,6 +12,7 @@ class SomeSourceCatalog(SourceCatalog):
     """Minimal test source catalog class for unit tests."""
 
     name = "test123"
+    tag = "test123"
     description = "Test source catalog"
 
 
@@ -29,6 +30,7 @@ def setup(self):
 
     def test_str(self):
         assert "description" in str(self.cat)
+        assert "name" in str(self.cat)
 
     def test_table(self):
         assert_allclose(self.cat.table["RA"][1], 43.3)
diff --git a/gammapy/catalog/tests/test_hess.py b/gammapy/catalog/tests/test_hess.py
--- a/gammapy/catalog/tests/test_hess.py
+++ b/gammapy/catalog/tests/test_hess.py
@@ -33,6 +33,10 @@ def test_source_table(cat):
         assert cat.tag == "hgps"
         assert len(cat.table) == 78
 
+    @staticmethod
+    def test_str(cat):
+        assert "name: hgps" in str(cat.__str__())
+
     @staticmethod
     def test_positions(cat):
         assert len(cat.positions) == 78
Repository: gammapy/gammapy

Issue:
FluxEstimator._set_norm_parameter crashes
**Gammapy version**
0.19

**Bug description**
Any code passing trough the "scan" branch of `FluxPointsEstimator._nan_result()` will crash due the invocation of `_set_norm_parameter` without the argument `scaled_parameter`.

**Expected behavior**
Either `_nan_result` passing the correct arguments, or `_set_norm_parameter` properly handling its default arguments.



Discussion:
Thanks @Tobychev.  The test for missing energy intervals currently does not execute scan. This needs to be added.

One issue with `FluxEstimator._set_norm_estimator` is that it shouldn't fail with its default argument `scaled_parameter=None`. A possible default behavior is to force `norm` range to be positive. This could provide a solution to #3690 as well in case no `scale_parameter` is unambiguously found. 


Resolving patch:
diff --git a/gammapy/estimators/flux.py b/gammapy/estimators/flux.py
--- a/gammapy/estimators/flux.py
+++ b/gammapy/estimators/flux.py
@@ -113,10 +113,12 @@ def get_scale_model(self, models):
         ref_model = models[self.source].spectral_model
         scale_model = ScaleSpectralModel(ref_model)
 
-        if "amplitude" in ref_model.parameters.names:
-            scaled_parameter = ref_model.parameters["amplitude"]
+        for scaled_parameter in ref_model.parameters:
+            if scaled_parameter.is_norm:
+                break
         else:
-            scaled_parameter = ref_model.parameters["norm"]
+            raise ValueError(f"{self.tag} requires a 'norm' or 'amplitude' parameter"
+                             " in the model to run")
 
         scale_model.norm = self._set_norm_parameter(scale_model.norm, scaled_parameter)
         return scale_model


Test patch:
Repository: gammapy/gammapy

Issue:
Change the first dataset name in `.info_table()`
**Is your feature request related to a problem? Please describe.**
When the method `.info_table()` is used in a Datasets object, the name of the first dataset in the output table is always "stacked". This rename is done even if the parameter `cumulative` of `.info_table()` is set to False.

**Describe the solution you'd like**
Keep the original name of the first dataset in the returned table if `cumulative`=False and only use "stacked" when `cumulative`=True.




Discussion:
Thanks @aaguasca ! I think the issue is addressed in https://github.com/gammapy/gammapy/pull/3498. But maybe we can implement the fix independently before...
I did not know it, sorry. If you want to do so, I am happy to help.

Resolving patch:
diff --git a/gammapy/datasets/core.py b/gammapy/datasets/core.py
--- a/gammapy/datasets/core.py
+++ b/gammapy/datasets/core.py
@@ -484,7 +484,8 @@ def info_table(self, cumulative=False):
         if not self.is_all_same_type:
             raise ValueError("Info table not supported for mixed dataset type.")
 
-        stacked = self[0].to_masked(name="stacked")
+        name = "stacked" if cumulative else self[0].name
+        stacked = self[0].to_masked(name=name)
 
         rows = [stacked.info_dict()]
 


Test patch:
diff --git a/gammapy/datasets/tests/test_datasets.py b/gammapy/datasets/tests/test_datasets.py
--- a/gammapy/datasets/tests/test_datasets.py
+++ b/gammapy/datasets/tests/test_datasets.py
@@ -1,8 +1,9 @@
 # Licensed under a 3-clause BSD style license - see LICENSE.rst
 import pytest
 from numpy.testing import assert_allclose
-from gammapy.datasets import Datasets
+from gammapy.datasets import Datasets, SpectrumDatasetOnOff
 from gammapy.modeling.tests.test_fit import MyDataset
+from gammapy.utils.testing import requires_data
 
 
 @pytest.fixture(scope="session")
@@ -40,7 +41,7 @@ def test_names(datasets):
     assert datasets.names == ["test-1", "test-2"]
 
 
-def test_Datasets_mutation():
+def test_datasets_mutation():
     dat = MyDataset(name="test-1")
     dats = Datasets([MyDataset(name="test-2"), MyDataset(name="test-3")])
     dats2 = Datasets([MyDataset(name="test-4"), MyDataset(name="test-5")])
@@ -61,7 +62,28 @@ def test_Datasets_mutation():
 
     with pytest.raises(ValueError, match="Dataset names must be unique"):
         dats.append(dat)
+
     with pytest.raises(ValueError, match="Dataset names must be unique"):
         dats.insert(0, dat)
+
     with pytest.raises(ValueError, match="Dataset names must be unique"):
         dats.extend(dats2)
+
+
+@requires_data()
+def test_datasets_info_table():
+    datasets_hess = Datasets()
+
+    for obs_id in [23523, 23526]:
+        dataset = SpectrumDatasetOnOff.read(
+            f"$GAMMAPY_DATA/joint-crab/spectra/hess/pha_obs{obs_id}.fits"
+        )
+        datasets_hess.append(dataset)
+
+    table = datasets_hess.info_table()
+    assert table["name"][0] == "23523"
+    assert table["name"][1] == "23526"
+
+    table = datasets_hess.info_table(cumulative=True)
+    assert table["name"][0] == "stacked"
+    assert table["name"][1] == "stacked"
Repository: gammapy/gammapy

Issue:
Bad rendering of Super Exponential Cutoff Power Law Model used for 4FGL-DR3 equations in docs
**Gammapy version**
dev

**Bug description**

The latex rendering of equations in the following doc page is broken. 
https://docs.gammapy.org/dev/user-guide/model-gallery/spectral/plot_super_exp_cutoff_powerlaw_4fgl.html

I think that it is due to the `\a`that appears multiple times in `\frac`, but I am not really sure as I don't understand HTML.

Bad rendering of Super Exponential Cutoff Power Law Model used for 4FGL-DR3 equations in docs
**Gammapy version**
dev

**Bug description**

The latex rendering of equations in the following doc page is broken. 
https://docs.gammapy.org/dev/user-guide/model-gallery/spectral/plot_super_exp_cutoff_powerlaw_4fgl.html

I think that it is due to the `\a`that appears multiple times in `\frac`, but I am not really sure as I don't understand HTML.



Discussion:

Resolving patch:
diff --git a/examples/models/spectral/plot_super_exp_cutoff_powerlaw_4fgl.py b/examples/models/spectral/plot_super_exp_cutoff_powerlaw_4fgl.py
--- a/examples/models/spectral/plot_super_exp_cutoff_powerlaw_4fgl.py
+++ b/examples/models/spectral/plot_super_exp_cutoff_powerlaw_4fgl.py
@@ -10,16 +10,7 @@
 
 .. math::
 
-
-    \phi(e) =
-            \begin{cases}
-                \phi_0 \cdot \left(\frac{E}{E_0}\right)^{\frac{\a}{\Gamma_2} -\Gamma_1} \cdot \exp \left(
-                  \frac{\a}{\Gamma_2^2} \left( 1 - \left(\frac{E}{E_0}\right)^{\frac{\a}{\Gamma_2} \right)
-              \right)&
-                              \\
-                \phi_0 \cdot \left(\frac{E}{E_0}\right)^{ -\Gamma_1 - \frac{\a}{2} \ln \frac{E}{E_0} - \frac{\a \Gamma_2}{6} \ln^2 \frac{E}{E_0} - \frac{\a \Gamma_2^2}{24} \ln^3 \frac{E}{E_0}}\\
-                0 & \text{for } \left| \Gamma_2 \ln \frac{E}{E_0}  \right|
-            \end{cases}
+\phi(E) = \begin{cases} \phi_0 \cdot \left(\frac{E}{E_0}\right)^{\frac{a}{\Gamma_2} -\Gamma_1} \cdot \exp \left( \frac{a}{\Gamma_2^2}\left( 1 - \left(\frac{E}{E_0}\right)^{\Gamma_2} \right) \right) \\ \phi_0 \cdot \left(\frac{E}{E_0}\right)^{ -\Gamma_1 - \frac{a}{2} \ln \frac{E}{E_0} - \frac{a \Gamma_2}{6} \ln^2 \frac{E}{E_0} - \frac{a \Gamma_2^2}{24} \ln^3 \frac{E}{E_0}} & \text{for } \left| \Gamma_2 \ln \frac{E}{E_0} \right| < 10^{-2} \end{cases}
 
 See Equation (2) and (3) in https://arxiv.org/pdf/2201.11184.pdf
 """


Test patch:
Repository: gammapy/gammapy

Issue:
Miswritten if condition in pointing.py
**Gammapy version**
gammapy 1.1

**Bug description**
Miswritten if condition (never enter the elif) in gammapy/data/pointing.py

```
if self.mode is PointingMode.POINTING:
            header["OBS_MODE"] = "POINTING"
            header["RA_PNT"] = self.fixed_icrs.ra.deg, u.deg.to_string("fits")
            header["DEC_PNT"] = self.fixed_icrs.dec.deg, u.deg.to_string("fits")
elif self.mode is PointingMode.POINTING:
            header["OBS_MODE"] = "DRIFT"
            header["AZ_PNT"] = self.fixed_altaz.az.deg, u.deg.to_string("fits")
            header["ALT_PNT"] = self.fixed_altaz.alt.deg, u.deg.to_string("fits")
```

`elif self.mode is PointingMode.POINTING` should likely be `elif self.mode is PointingMode.DRIFT`

**Other information**
Also in the dev version :
https://github.com/gammapy/gammapy/blob/daa25abce5d6ff081ba332d5d24a86f2b7a2aa2c/gammapy/data/pointing.py#L303C1-L311C1



Discussion:
Merci! We will respond to your issue shortly. In the meantime, try `import gammapy; gammapy.song()`

Resolving patch:
diff --git a/gammapy/data/pointing.py b/gammapy/data/pointing.py
--- a/gammapy/data/pointing.py
+++ b/gammapy/data/pointing.py
@@ -304,7 +304,7 @@ def to_fits_header(self, format="gadf", version="0.3", time_ref=None):
             header["OBS_MODE"] = "POINTING"
             header["RA_PNT"] = self.fixed_icrs.ra.deg, u.deg.to_string("fits")
             header["DEC_PNT"] = self.fixed_icrs.dec.deg, u.deg.to_string("fits")
-        elif self.mode is PointingMode.POINTING:
+        elif self.mode is PointingMode.DRIFT:
             header["OBS_MODE"] = "DRIFT"
             header["AZ_PNT"] = self.fixed_altaz.az.deg, u.deg.to_string("fits")
             header["ALT_PNT"] = self.fixed_altaz.alt.deg, u.deg.to_string("fits")


Test patch:
diff --git a/gammapy/data/tests/test_pointing.py b/gammapy/data/tests/test_pointing.py
--- a/gammapy/data/tests/test_pointing.py
+++ b/gammapy/data/tests/test_pointing.py
@@ -54,6 +54,12 @@ def test_fixed_pointing_icrs():
     assert u.isclose(back_trafo.dec, fixed_icrs.dec).all()
     assert np.all(u.isclose(fixed_icrs.ra, icrs.ra))
 
+    header = pointing.to_fits_header()
+
+    assert header["OBS_MODE"] == "POINTING"
+    assert header["RA_PNT"] == fixed_icrs.ra.deg
+    assert header["DEC_PNT"] == fixed_icrs.dec.deg
+
 
 def test_fixed_pointing_info_altaz():
     """Test new api of FixedPointingInfo in AltAz (DRIFT)"""
@@ -99,6 +105,12 @@ def test_fixed_pointing_info_altaz():
     assert u.isclose(back_trafo.alt, fixed_altaz.alt).all()
     assert u.isclose(back_trafo.az, fixed_altaz.az, atol=1e-10 * u.deg).all()
 
+    header = pointing.to_fits_header()
+
+    assert header["OBS_MODE"] == "DRIFT"
+    assert header["AZ_PNT"] == fixed_altaz.az.deg
+    assert header["ALT_PNT"] == fixed_altaz.alt.deg
+
 
 @requires_data()
 def test_read_gadf_drift():
Repository: gammapy/gammapy

Issue:
Remove deprecated features
This is a reminder issue to remove the features deprecated since 1.1 before the next release


Discussion:

Resolving patch:
diff --git a/gammapy/utils/table.py b/gammapy/utils/table.py
--- a/gammapy/utils/table.py
+++ b/gammapy/utils/table.py
@@ -3,12 +3,10 @@
 import numpy as np
 from astropy.table import Table
 from astropy.units import Quantity
-from .deprecation import deprecated
 from .units import standardise_unit
 
 __all__ = [
     "hstack_columns",
-    "table_from_row_data",
     "table_row_to_dict",
     "table_standardise_units_copy",
     "table_standardise_units_inplace",
@@ -92,30 +90,3 @@ def table_row_to_dict(row, make_quantity=True):
             val = Quantity(val, unit=col.unit)
         data[name] = val
     return data
-
-
-@deprecated("v1.1", alternative="astropy.table.Table")
-def table_from_row_data(rows, **kwargs):
-    """Helper function to create table objects from row data.
-
-    Works with quantities.
-
-    Parameters
-    ----------
-    rows : list
-        List of row data (each row a dictionary).
-    """
-    table = Table(**kwargs)
-
-    if len(rows) == 0:
-        return table
-
-    colnames = list(rows[0].keys())
-
-    for name in colnames:
-        coldata = [_[name] for _ in rows]
-        if isinstance(rows[0][name], Quantity):
-            coldata = Quantity(coldata, unit=rows[0][name].unit)
-        table[name] = coldata
-
-    return table


Test patch:
diff --git a/gammapy/utils/tests/test_table.py b/gammapy/utils/tests/test_table.py
--- a/gammapy/utils/tests/test_table.py
+++ b/gammapy/utils/tests/test_table.py
@@ -1,14 +1,8 @@
 # Licensed under a 3-clause BSD style license - see LICENSE.rst
 import pytest
-from numpy.testing import assert_allclose
 import astropy.units as u
 from astropy.table import Column, Table
-from gammapy.utils.deprecation import GammapyDeprecationWarning
-from gammapy.utils.table import (
-    table_from_row_data,
-    table_row_to_dict,
-    table_standardise_units_copy,
-)
+from gammapy.utils.table import table_row_to_dict, table_standardise_units_copy
 
 
 def test_table_standardise_units():
@@ -40,14 +34,3 @@ def test_table_row_to_dict(table):
     actual = table_row_to_dict(table[1])
     expected = {"a": 2, "b": 2 * u.m, "c": "yy"}
     assert actual == expected
-
-
-def test_table_from_row_data():
-    rows = [dict(a=1, b=1 * u.m, c="x"), dict(a=2, b=2 * u.km, c="yy")]
-
-    with pytest.warns(GammapyDeprecationWarning):
-        table = table_from_row_data(rows)
-
-    assert isinstance(table, Table)
-    assert table["b"].unit == "m"
-    assert_allclose(table["b"].data, [1, 2000])
Repository: gammapy/gammapy

Issue:
Remove deprecated features
This is a reminder issue to remove the features deprecated since 1.1 before the next release


Discussion:

Resolving patch:
diff --git a/examples/tutorials/api/datasets.py b/examples/tutorials/api/datasets.py
--- a/examples/tutorials/api/datasets.py
+++ b/examples/tutorials/api/datasets.py
@@ -145,7 +145,7 @@
 
 ######################################################################
 # To further explore the contents of a `Dataset`, you can use
-# e.g. `~gammapy.datasets.MapDataset.info_dict()`
+# e.g. `~gammapy.datasets.MapDataset.info_dict()`
 #
 
 ######################################################################
@@ -171,7 +171,7 @@
 
 
 ######################################################################
-# Of course you can also access IRF related maps, e.g. the psf as
+# Of course you can also access IRF related maps, e.g. the psf as
 # `~gammapy.irf.PSFMap`:
 #
 
@@ -235,7 +235,7 @@
 # use:
 #
 
-npred_source = dataset_cta.npred_signal(model_name="gc")
+npred_source = dataset_cta.npred_signal(model_names=["gc"])
 npred_source.sum_over_axes().plot()
 plt.show()
 
@@ -263,7 +263,7 @@
 #    according to the specified selection cuts, and should not be changed
 #    by the user.
 # -  During modelling and fitting, the user might want to additionally
-#    ignore some parts of a reduced dataset, e.g. to restrict the fit to a
+#    ignore some parts of a reduced dataset, e.g. to restrict the fit to a
 #    specific energy range or to ignore parts of the region of interest.
 #    This should be done by applying the `~gammapy.datasets.MapDataset.mask_fit`. To see details of
 #    applying masks, please refer to :ref:`masks-for-fitting`.
diff --git a/gammapy/datasets/evaluator.py b/gammapy/datasets/evaluator.py
--- a/gammapy/datasets/evaluator.py
+++ b/gammapy/datasets/evaluator.py
@@ -527,7 +527,7 @@ def peek(self, figsize=(12, 15)):
         if self.needs_update:
             raise AttributeError(
                 "The evaluator needs to be updated first. Execute "
-                "`MapDataset.npred_signal(model_name=...)` before calling this method."
+                "`MapDataset.npred_signal(model_names=...)` before calling this method."
             )
 
         nrows = 1
diff --git a/gammapy/datasets/map.py b/gammapy/datasets/map.py
--- a/gammapy/datasets/map.py
+++ b/gammapy/datasets/map.py
@@ -18,7 +18,6 @@
     get_wstat_mu_bkg,
     wstat,
 )
-from gammapy.utils.deprecation import deprecated_renamed_argument
 from gammapy.utils.fits import HDULocation, LazyFitsData
 from gammapy.utils.random import get_random_state
 from gammapy.utils.scripts import make_name, make_path
@@ -489,7 +488,6 @@ def _background_parameters_changed(self):
             self._background_parameters_cached = values
         return changed
 
-    @deprecated_renamed_argument("model_name", "model_names", "1.1")
     def npred_signal(self, model_names=None, stack=True):
         """Model predicted signal counts.
 


Test patch:
Repository: gammapy/gammapy

Issue:
Remove deprecated features
This is a reminder issue to remove the features deprecated since 1.1 before the next release


Discussion:

Resolving patch:
diff --git a/gammapy/modeling/fit.py b/gammapy/modeling/fit.py
--- a/gammapy/modeling/fit.py
+++ b/gammapy/modeling/fit.py
@@ -4,7 +4,6 @@
 import logging
 import numpy as np
 from astropy.table import Table
-from gammapy.utils.deprecation import deprecated
 from gammapy.utils.pbar import progress_bar
 from .covariance import Covariance
 from .iminuit import (
@@ -144,15 +143,6 @@ def _repr_html_(self):
         except AttributeError:
             return f"<pre>{html.escape(str(self))}</pre>"
 
-    @property
-    @deprecated(
-        "v1.1",
-        message="The IMinuit object is attached to the OptimizeResult object instead.",
-    )
-    def minuit(self):
-        """Iminuit object."""
-        return self._minuit
-
     @staticmethod
     def _parse_datasets(datasets):
         from gammapy.datasets import Datasets
diff --git a/gammapy/modeling/models/spatial.py b/gammapy/modeling/models/spatial.py
--- a/gammapy/modeling/models/spatial.py
+++ b/gammapy/modeling/models/spatial.py
@@ -20,7 +20,6 @@
 import matplotlib.pyplot as plt
 from gammapy.maps import HpxNDMap, Map, MapCoord, WcsGeom, WcsNDMap
 from gammapy.modeling import Parameter, Parameters
-from gammapy.utils.deprecation import deprecated
 from gammapy.utils.gauss import Gauss2DPDF
 from gammapy.utils.interpolation import interpolation_scale
 from gammapy.utils.regions import region_circle_to_ellipse, region_to_frame
@@ -309,29 +308,6 @@ def plot(self, ax=None, geom=None, **kwargs):
             )
         return m.plot(ax=ax, **kwargs)
 
-    @deprecated("v1.0.1", alternative="plot_interactive")
-    def plot_interative(self, ax=None, geom=None, **kwargs):
-        """Plot spatial model.
-
-        Parameters
-        ----------
-        ax : `~matplotlib.axes.Axes`, optional
-            Matplotlib axes. Default is None.
-        geom : `~gammapy.maps.WcsGeom`, optional
-            Geometry to use for plotting. Default is None.
-        **kwargs : dict
-            Keyword arguments passed to `~gammapy.maps.WcsMap.plot()`.
-
-        Returns
-        -------
-        ax : `~matplotlib.axes.Axes`, optional
-            Matplotlib axes.
-        """
-        m = self._get_plot_map(geom)
-        if m.geom.is_image:
-            raise TypeError("Use .plot() for 2D Maps")
-        m.plot_interactive(ax=ax, **kwargs)
-
     def plot_interactive(self, ax=None, geom=None, **kwargs):
         """Plot spatial model.
 
@@ -1464,12 +1440,6 @@ def plot(self, ax=None, geom=None, **kwargs):
             geom = self.map.geom
         super().plot(ax=ax, geom=geom, **kwargs)
 
-    @deprecated("v1.0.1", alternative="plot_interactive")
-    def plot_interative(self, ax=None, geom=None, **kwargs):
-        if geom is None:
-            geom = self.map.geom
-        super().plot_interactive(ax=ax, geom=geom, **kwargs)
-
     def plot_interactive(self, ax=None, geom=None, **kwargs):
         if geom is None:
             geom = self.map.geom


Test patch:
Repository: gammapy/gammapy

Issue:
Writing of TemplateNPredModel allows no overwrite
The option `overwrite` is not passed to this line https://github.com/gammapy/gammapy/blob/6321261682b83528858a57baa34fd21b1100b9f4/gammapy/modeling/models/cube.py#L1007  
As a result an error is raised if the map is already written and one cannot overwrite it even if the option in the .write method is set to True
Expected: `self.map.write(self.filename, overwrite=overwrite)`


Discussion:

Resolving patch:
diff --git a/gammapy/modeling/models/cube.py b/gammapy/modeling/models/cube.py
--- a/gammapy/modeling/models/cube.py
+++ b/gammapy/modeling/models/cube.py
@@ -1004,7 +1004,7 @@ def write(self, overwrite=False):
         elif os.path.isfile(make_path(self.filename)) and not overwrite:
             log.warning("Template file already exits, and overwrite is False")
         else:
-            self.map.write(self.filename)
+            self.map.write(self.filename, overwrite=overwrite)
 
     @classmethod
     def from_dict(cls, data, **kwargs):


Test patch:
diff --git a/gammapy/modeling/models/tests/test_cube.py b/gammapy/modeling/models/tests/test_cube.py
--- a/gammapy/modeling/models/tests/test_cube.py
+++ b/gammapy/modeling/models/tests/test_cube.py
@@ -250,6 +250,7 @@ def test_background_model_io(tmpdir, background):
     filename = str(tmpdir / "test-bkg-file.fits")
     bkg = TemplateNPredModel(background, filename=filename)
     bkg.spectral_model.norm.value = 2.0
+    bkg.write(overwrite=False)
     bkg.write(overwrite=True)
     bkg_dict = bkg.to_dict()
     bkg_read = bkg.from_dict(bkg_dict)