Repository: gammapy/gammapy

Issue:
BUG: test with declared minimal dependencies
I don't see mpl 3.4 is being tested, even though it should be supported according to `setup.py`. One test run into issues with it though:


```
$  pytest --doctest-modules gammapy/visualization

Gammapy test data availability:
gammapy-data ... no
Gammapy environment variables:
GAMMAPY_DATA = not set
Setting matplotlib backend to "agg" for the tests.
================================================= test session starts ==================================================
platform darwin -- Python 3.9.1, pytest-7.1.2, pluggy-0.13.1
WARNING: AstropyDeprecationWarning: The ignore_warnings class is deprecated and may be removed in a future version.
        Use pytest.mark.filterwarnings instead. [pytest_astropy_header.display]
WARNING: AstropyDeprecationWarning: The catch_warnings class is deprecated and may be removed in a future version.
        Use pytest.warns instead. [astropy.tests.helper]

Running tests with Astropy version 5.1.
Running tests in gammapy/visualization.

Date: 2022-06-17T17:04:03

Platform: macOS-10.16-x86_64-i386-64bit

Executable: /Users/bsipocz/.pyenv/versions/3.9.1/bin/python3.9

Full Python Version: 
3.9.1 (default, Jan 11 2021, 15:50:22) 
[Clang 10.0.0 (clang-1000.11.45.5)]

encodings: sys: utf-8, locale: UTF-8, filesystem: utf-8
byteorder: little
float info: dig: 15, mant_dig: 15

Package versions: 
Numpy: 1.23.0rc3
Scipy: 1.5.4
Matplotlib: 3.4.0
h5py: 3.1.0
Pandas: 1.1.5
cython: 0.29.24
iminuit: 2.11.2
matplotlib: 3.4.0
astropy: 5.1
regions: 0.6
healpy: 1.15.2
sherpa: not available
gammapy: 0.20.2.dev3+g5fdfee926.d20220617
naima: not available

Using Astropy options: remote_data: any.

rootdir: /Users/bsipocz/munka/devel/gammapy, configfile: setup.cfg
plugins: anyio-3.6.1, arraydiff-0.3, remotedata-0.3.2, requests-mock-1.9.3, mock-3.7.0, nbval-0.9.6, astropy-0.10.0, hypothesis-6.3.1, filter-subpackage-0.1.1, openfiles-0.5.0, doctestplus-0.11.1, astropy-header-0.1.2, cov-3.0.0
collected 8 items                                                                                                      

gammapy/visualization/cmap.py ..                                                                                 [ 25%]
gammapy/visualization/tests/test_cmap.py ..                                                                      [ 50%]
gammapy/visualization/tests/test_panel.py .                                                                      [ 62%]
gammapy/visualization/tests/test_utils.py F..                                                                    [100%]

======================================================= FAILURES =======================================================
_______________________________________ test_plot_spectrum_datasets_off_regions ________________________________________

    def test_plot_spectrum_datasets_off_regions():
        from gammapy.datasets import SpectrumDatasetOnOff
        from gammapy.maps import Map, RegionNDMap
    
        counts_off_1 = RegionNDMap.create("icrs;circle(0, 0.5, 0.2);circle(0.5, 0, 0.2)")
    
        counts_off_2 = RegionNDMap.create("icrs;circle(0.5, 0.5, 0.2);circle(0, 0, 0.2)")
    
        counts_off_3 = RegionNDMap.create("icrs;point(0.5, 0.5);point(0, 0)")
    
        m = Map.from_geom(geom=counts_off_1.geom.to_wcs_geom())
        ax = m.plot()
    
        dataset_1 = SpectrumDatasetOnOff(counts_off=counts_off_1)
    
        dataset_2 = SpectrumDatasetOnOff(counts_off=counts_off_2)
    
        dataset_3 = SpectrumDatasetOnOff(counts_off=counts_off_3)
    
        plot_spectrum_datasets_off_regions(
            ax=ax, datasets=[dataset_1, dataset_2, dataset_3]
        )
    
        print(ax.patches)
        print(len(ax.patches))
        assert_allclose(
>           ax.patches[0].get_edgecolor(), (0.121569, 0.466667, 0.705882, 1.0), rtol=1e-2
        )
E       IndexError: list index out of range

gammapy/visualization/tests/test_utils.py:40: IndexError
------------------------------------------------- Captured stdout call -------------------------------------------------
[]
0
=============================================== short test summary info ================================================
FAILED gammapy/visualization/tests/test_utils.py::test_plot_spectrum_datasets_off_regions - IndexError: list index ou...
============================================= 1 failed, 7 passed in 0.78s ==============================================
```



Discussion:
Double check after #4093.

Resolving patch:
diff --git a/gammapy/maps/core.py b/gammapy/maps/core.py
--- a/gammapy/maps/core.py
+++ b/gammapy/maps/core.py
@@ -1255,7 +1255,7 @@ def plot_grid(self, figsize=None, ncols=3, **kwargs):
                 if axis.name == "energy" or axis.name == "energy_true":
                     info = (
                         f"{energy_unit_format(axis.edges[idx])} - "
-                        "{energy_unit_format(axis.edges[idx+1])}"
+                        f"{energy_unit_format(axis.edges[idx+1])}"
                     )
                 else:
                     info = f"{axis.edges[idx]:.1f} - {axis.edges[idx + 1]:.1f} "


Test patch:
diff --git a/gammapy/analysis/tests/test_analysis.py b/gammapy/analysis/tests/test_analysis.py
--- a/gammapy/analysis/tests/test_analysis.py
+++ b/gammapy/analysis/tests/test_analysis.py
@@ -388,10 +388,10 @@ def test_analysis_3d():
     assert len(table) == 2
     dnde = table["dnde"].quantity
 
-    assert_allclose(dnde[0].value, 1.339052e-11, rtol=1e-2)
-    assert_allclose(dnde[-1].value, 2.772374e-13, rtol=1e-2)
-    assert_allclose(res["index"].value, 3.097613, rtol=1e-2)
-    assert_allclose(res["tilt"].value, -0.207792, rtol=1e-2)
+    assert_allclose(dnde[0].value, 1.2722e-11, rtol=1e-2)
+    assert_allclose(dnde[-1].value, 4.054128e-13, rtol=1e-2)
+    assert_allclose(res["index"].value, 2.772814, rtol=1e-2)
+    assert_allclose(res["tilt"].value, -0.133436, rtol=1e-2)
 
 
 @requires_data()
diff --git a/gammapy/makers/tests/test_spectrum.py b/gammapy/makers/tests/test_spectrum.py
--- a/gammapy/makers/tests/test_spectrum.py
+++ b/gammapy/makers/tests/test_spectrum.py
@@ -42,8 +42,10 @@ def observations_cta_dc1():
 
 @pytest.fixture()
 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")
+    e_reco = MapAxis.from_energy_edges(np.logspace(0, 2, 5) * u.TeV, name="energy")
+    e_true = MapAxis.from_energy_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)
 
@@ -60,8 +62,10 @@ def spectrum_dataset_magic_crab():
 
 @pytest.fixture()
 def spectrum_dataset_crab():
-    e_reco = MapAxis.from_edges(np.logspace(0, 2, 5) * u.TeV, name="energy")
-    e_true = MapAxis.from_edges(np.logspace(-0.5, 2, 11) * u.TeV, name="energy_true")
+    e_reco = MapAxis.from_energy_edges(np.logspace(0, 2, 5) * u.TeV)
+    e_true = MapAxis.from_energy_edges(
+        np.logspace(-0.5, 2, 11) * u.TeV, name="energy_true"
+    )
     geom = RegionGeom.create(
         "icrs;circle(83.63, 22.01, 0.11)", axes=[e_reco], binsz_wcs="0.01deg"
     )
@@ -70,7 +74,9 @@ def spectrum_dataset_crab():
 
 @pytest.fixture()
 def spectrum_dataset_crab_fine():
-    e_true = MapAxis.from_edges(np.logspace(-2, 2.5, 109) * u.TeV, name="energy_true")
+    e_true = MapAxis.from_energy_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)
@@ -123,8 +129,8 @@ def test_spectrum_dataset_maker_hess_dl3(spectrum_dataset_crab, observations_hes
         datasets.append(dataset)
 
     # Exposure
-    assert_allclose(datasets[0].exposure.data.sum(), 7374718644.757894)
-    assert_allclose(datasets[1].exposure.data.sum(), 6691006466.659032)
+    assert_allclose(datasets[0].exposure.data.sum(), 7.3111e09)
+    assert_allclose(datasets[1].exposure.data.sum(), 6.634534e09)
 
     # Background
     assert_allclose(datasets[0].npred_background().data.sum(), 7.7429157, rtol=1e-5)
@@ -217,7 +223,7 @@ def test_safe_mask_maker_dc1(spectrum_dataset_gc, observations_cta_dc1):
     maker = SpectrumDatasetMaker()
     dataset = maker.run(spectrum_dataset_gc, obs)
     dataset = safe_mask_maker.run(dataset, obs)
-    assert_allclose(dataset.energy_range[0], 3.162278, rtol=1e-3)
+    assert_allclose(dataset.energy_range[0], 1, rtol=1e-3)
     assert dataset.energy_range[0].unit == "TeV"
 
 
@@ -279,7 +285,7 @@ class TestSpectrumMakerChain:
             (
                 dict(containment_correction=False),
                 dict(
-                    n_on=125, sigma=18.953014, aeff=580254.9 * u.m**2, edisp=0.23635
+                    n_on=125, sigma=18.953014, aeff=580254.9 * u.m**2, edisp=0.235864
                 ),
             ),
             (
@@ -288,7 +294,7 @@ class TestSpectrumMakerChain:
                     n_on=125,
                     sigma=18.953014,
                     aeff=375314.356461 * u.m**2,
-                    edisp=0.23635,
+                    edisp=0.235864,
                 ),
             ),
         ],
diff --git a/gammapy/maps/wcs/tests/test_ndmap.py b/gammapy/maps/wcs/tests/test_ndmap.py
--- a/gammapy/maps/wcs/tests/test_ndmap.py
+++ b/gammapy/maps/wcs/tests/test_ndmap.py
@@ -6,7 +6,6 @@
 from astropy.convolution import Box2DKernel, Gaussian2DKernel
 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 PSFKernel, PSFMap
@@ -722,7 +721,7 @@ def get_npred_map():
     )
 
     spatial_model = GaussianSpatialModel(
-        lon_0="0 deg", lat_0="0 deg", sigma="0.2 deg", frame="galactic"
+        lon_0="0.015 deg", lat_0="-0.037 deg", sigma="0.2 deg", frame="galactic"
     )
     spectral_model = PowerLawSpectralModel(amplitude="1e-11 cm-2 s-1 TeV-1")
     skymodel = SkyModel(spatial_model=spatial_model, spectral_model=spectral_model)
@@ -739,17 +738,11 @@ def test_map_sampling():
 
     nmap = WcsNDMap(geom=eval.geom, data=npred.data)
     coords = nmap.sample_coord(n_events=2, random_state=0)
-    skycoord = coords.skycoord
 
-    events = Table()
-    events["RA_TRUE"] = skycoord.icrs.ra
-    events["DEC_TRUE"] = skycoord.icrs.dec
-    events["ENERGY_TRUE"] = coords["energy_true"]
-
-    assert len(events) == 2
-    assert_allclose(events["RA_TRUE"].data, [266.307081, 266.442255], rtol=1e-5)
-    assert_allclose(events["DEC_TRUE"].data, [-28.753408, -28.742696], rtol=1e-5)
-    assert_allclose(events["ENERGY_TRUE"].data, [2.755397, 1.72316], rtol=1e-5)
+    assert len(coords["lon"]) == 2
+    assert_allclose(coords.skycoord.icrs.ra.deg, [266.204197, 266.451241], rtol=1e-5)
+    assert_allclose(coords.skycoord.icrs.dec.deg, [-28.862369, -29.075469], rtol=1e-5)
+    assert_allclose(coords["energy_true"].data, [2.363293, 2.342388], rtol=1e-5)
 
     assert coords["lon"].unit == "deg"
     assert coords["lat"].unit == "deg"
diff --git a/gammapy/visualization/tests/test_utils.py b/gammapy/visualization/tests/test_utils.py
--- a/gammapy/visualization/tests/test_utils.py
+++ b/gammapy/visualization/tests/test_utils.py
@@ -1,8 +1,11 @@
 # Licensed under a 3-clause BSD style license - see LICENSE.rst
+import pytest
 import numpy as np
 from numpy.testing import assert_allclose
 from astropy.table import Table
+import matplotlib
 import matplotlib.pyplot as plt
+from packaging import version
 from gammapy.utils.testing import mpl_plot_check
 from gammapy.visualization import (
     plot_contour_line,
@@ -11,6 +14,10 @@
 )
 
 
+@pytest.mark.skipif(
+    version.parse(matplotlib.__version__) < version.parse("3.5"),
+    reason="Requires matplotlib 3.5 or higher",
+)
 def test_plot_spectrum_datasets_off_regions():
     from gammapy.datasets import SpectrumDatasetOnOff
     from gammapy.maps import Map, RegionNDMap
@@ -34,12 +41,11 @@ def test_plot_spectrum_datasets_off_regions():
         ax=ax, datasets=[dataset_1, dataset_2, dataset_3]
     )
 
-    assert_allclose(
-        ax.patches[0].get_edgecolor(), (0.121569, 0.466667, 0.705882, 1.0), rtol=1e-2
-    )
-    assert_allclose(
-        ax.patches[2].get_edgecolor(), (1.0, 0.498039, 0.054902, 1.0), rtol=1e-2
-    )
+    actual = ax.patches[0].get_edgecolor()
+    assert_allclose(actual, (0.121569, 0.466667, 0.705882, 1.0), rtol=1e-2)
+
+    actual = ax.patches[2].get_edgecolor()
+    assert_allclose(actual, (1.0, 0.498039, 0.054902, 1.0), rtol=1e-2)
     assert ax.lines[0].get_color() in ["green", "C0"]