files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Fermi catalog and source classes."""
  import abc
  import warnings
  import numpy as np
  import astropy.units as u
  from astropy.table import Column, Table
  from astropy.time import Time
  from astropy.wcs import FITSFixedWarning
  from gammapy.estimators import FluxPoints, LightCurve
  from gammapy.modeling.models import (
      DiskSpatialModel,
      GaussianSpatialModel,
      Model,
      PointSpatialModel,
      SkyModel,
      TemplateSpatialModel,
  )
  from gammapy.utils.gauss import Gauss2DPDF
  from gammapy.utils.scripts import make_path
  from gammapy.utils.table import table_standardise_units_inplace
  from .core import SourceCatalog, SourceCatalogObject
  
  __all__ = [
      "SourceCatalogObject4FGL",
      "SourceCatalogObject3FGL",
      "SourceCatalogObject2FHL",
      "SourceCatalogObject3FHL",
      "SourceCatalog4FGL",
      "SourceCatalog3FGL",
      "SourceCatalog2FHL",
      "SourceCatalog3FHL",
  ]
  
  
  def compute_flux_points_ul(quantity, quantity_errp):
      """Compute UL value for fermi flux points.
  
      See https://arxiv.org/pdf/1501.02003.pdf (page 30)
      """
      return 2 * quantity_errp + quantity
  
  
  class SourceCatalogObjectFermiBase(SourceCatalogObject, abc.ABC):
      """Base class for Fermi-LAT catalogs."""
  
      asso = ["ASSOC1", "ASSOC2", "ASSOC_TEV", "ASSOC_GAM1", "ASSOC_GAM2", "ASSOC_GAM3"]
  
      def __str__(self):
          return self.info()
  
      def info(self, info="all"):
          """Summary info string.
  
          Parameters
          ----------
          info : {'all', 'basic', 'more', 'position', 'spectral','lightcurve'}
              Comma separated list of options
          """
          if info == "all":
              info = "basic,more,position,spectral,lightcurve"
  
          ss = ""
          ops = info.split(",")
          if "basic" in ops:
              ss += self
  
  [... the rest is omitted ...]
files: gammapy/catalog/fermi.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Fermi catalog and source classes."""
  import abc
  import warnings
  import numpy as np
  import astropy.units as u
  from astropy.table import Column, Table
  from astropy.time import Time
  from astropy.wcs import FITSFixedWarning
  from gammapy.estimators import FluxPoints, LightCurve
  from gammapy.modeling.models import (
      DiskSpatialModel,
      GaussianSpatialModel,
      Model,
      PointSpatialModel,
      SkyModel,
      TemplateSpatialModel,
  )
  from gammapy.utils.gauss import Gauss2DPDF
  from gammapy.utils.scripts import make_path
  from gammapy.utils.table import table_standardise_units_inplace
  from .core import SourceCatalog, SourceCatalogObject
  
  __all__ = [
      "SourceCatalogObject4FGL",
      "SourceCatalogObject3FGL",
      "SourceCatalogObject2FHL",
      "SourceCatalogObject3FHL",
      "SourceCatalog4FGL",
      "SourceCatalog3FGL",
      "SourceCatalog2FHL",
      "SourceCatalog3FHL",
  ]
  
  
  def compute_flux_points_ul(quantity, quantity_errp):
      """Compute UL value for fermi flux points.
  
      See https://arxiv.org/pdf/1501.02003.pdf (page 30)
      """
      return 2 * quantity_errp + quantity
  
  
  class SourceCatalogObjectFermiBase(SourceCatalogObject, abc.ABC):
      """Base class for Fermi-LAT catalogs."""
  
      asso = ["ASSOC1", "ASSOC2", "ASSOC_TEV", "ASSOC_GAM1", "ASSOC_GAM2", "ASSOC_GAM3"]
  
      def __str__(self):
          return self.info()
  
      def info(self, info="all"):
          """Summary info string.
  
          Parameters
          ----------
          info : {'all', 'basic', 'more', 'position', 'spectral','lightcurve'}
              Comma separated list of options
          """
          if info == "all":
              info = "basic,more,position,spectral,lightcurve"
  
          ss = ""
          ops = info.split(",")
          if "basic" in ops:
              ss += self
  
  [... the rest is omitted ...]
files: gammapy/catalog/fermi.py
files: # 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 import units as u
  from astropy.time import Time
  from astropy.utils.data import get_pkg_data_filename
  from gammapy.catalog import (
      SourceCatalog2FHL,
      SourceCatalog3FGL,
      SourceCatalog3FHL,
      SourceCatalog4FGL,
  )
  from gammapy.modeling.models import (
      ExpCutoffPowerLaw3FGLSpectralModel,
      LogParabolaSpectralModel,
      PowerLaw2SpectralModel,
      PowerLawSpectralModel,
      SuperExpCutoffPowerLaw3FGLSpectralModel,
      SuperExpCutoffPowerLaw4FGLSpectralModel,
  )
  from gammapy.utils.gauss import Gauss2DPDF
  from gammapy.utils.testing import (
      assert_quantity_allclose,
      assert_time_allclose,
      requires_data,
  )
  
  SOURCES_4FGL = [
      dict(
          idx=0,
          name="4FGL J0000.3-7355",
          str_ref_file="data/4fgl_J0000.3-7355.txt",
          spec_type=PowerLawSpectralModel,
          dnde=u.Quantity(2.9476e-11, "cm-2 s-1 GeV-1"),
          dnde_err=u.Quantity(5.3318e-12, "cm-2 s-1 GeV-1"),
      ),
      dict(
          idx=3,
          name="4FGL J0001.5+2113",
          str_ref_file="data/4fgl_J0001.5+2113.txt",
          spec_type=LogParabolaSpectralModel,
          dnde=u.Quantity(2.8545e-8, "cm-2 s-1 GeV-1"),
          dnde_err=u.Quantity(1.3324e-9, "cm-2 s-1 GeV-1"),
      ),
      dict(
          idx=7,
          name="4FGL J0002.8+6217",
          str_ref_file="data/4fgl_J0002.8+6217.txt",
          spec_type=SuperExpCutoffPowerLaw4
  
  [... the rest is omitted ...]
files: gammapy/catalog/tests/test_fermi.py
files: # 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 import units as u
  from astropy.time import Time
  from astropy.utils.data import get_pkg_data_filename
  from gammapy.catalog import (
      SourceCatalog2FHL,
      SourceCatalog3FGL,
      SourceCatalog3FHL,
      SourceCatalog4FGL,
  )
  from gammapy.modeling.models import (
      ExpCutoffPowerLaw3FGLSpectralModel,
      LogParabolaSpectralModel,
      PowerLaw2SpectralModel,
      PowerLawSpectralModel,
      SuperExpCutoffPowerLaw3FGLSpectralModel,
      SuperExpCutoffPowerLaw4FGLSpectralModel,
  )
  from gammapy.utils.gauss import Gauss2DPDF
  from gammapy.utils.testing import (
      assert_quantity_allclose,
      assert_time_allclose,
      requires_data,
  )
  
  SOURCES_4FGL = [
      dict(
          idx=0,
          name="4FGL J0000.3-7355",
          str_ref_file="data/4fgl_J0000.3-7355.txt",
          spec_type=PowerLawSpectralModel,
          dnde=u.Quantity(2.9476e-11, "cm-2 s-1 GeV-1"),
          dnde_err=u.Quantity(5.3318e-12, "cm-2 s-1 GeV-1"),
      ),
      dict(
          idx=3,
          name="4FGL J0001.5+2113",
          str_ref_file="data/4fgl_J0001.5+2113.txt",
          spec_type=LogParabolaSpectralModel,
          dnde=u.Quantity(2.8545e-8, "cm-2 s-1 GeV-1"),
          dnde_err=u.Quantity(1.3324e-9, "cm-2 s-1 GeV-1"),
      ),
      dict(
          idx=7,
          name="4FGL J0002.8+6217",
          str_ref_file="data/4fgl_J0002.8+6217.txt",
          spec_type=SuperExpCutoffPowerLaw4
  
  [... the rest is omitted ...]
files: gammapy/catalog/tests/test_fermi.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  import collections.abc
  import copy
  from os.path import split
  import numpy as np
  import astropy.units as u
  from astropy.table import Table
  import yaml
  from gammapy.modeling import Covariance, Parameter, Parameters
  from gammapy.utils.scripts import make_name, make_path
  
  
  def _set_link(shared_register, model):
      for param in model.parameters:
          name = param.name
          link_label = param._link_label_io
          if link_label is not None:
              if link_label in shared_register:
                  new_param = shared_register[link_label]
                  setattr(model, name, new_param)
              else:
                  shared_register[link_label] = param
      return shared_register
  
  
  __all__ = ["Model", "Models", "ProperModels"]
  
  
  class Model:
      """Model base class."""
  
      def __init__(self, **kwargs):
          # Copy default parameters from the class to the instance
          default_parameters = self.default_parameters.copy()
  
          for par in default_parameters:
              value = kwargs.get(par.name, par)
  
              if not isinstance(value, Parameter):
                  par.quantity = u.Quantity(value)
              else:
                  par = value
  
              setattr(self, par.name, par)
  
          self._covariance = Covariance(self.parameters)
  
      def __init_subclass__(cls, **kwargs):
          # Add parameters list on the model sub-class (not instances)
          cls.default_parameters = Parameters(
              [_ for _ in cls.__dict__.values() if isinstance(_, Parameter)]
          )
  
      @classmethod
      def from_parameters(cls, parameters, **kwargs):
          """Create model from parameter list
  
          Parameters
          ----------
          parameters : `Parameters`
              Parameters for init
  
          Returns
          -------
          model : `Model`
              Model instance
          """
          for par in parameters:
              kwargs[par.name] = par
          return cls(**kwargs)
  
      def _check_covariance(self):
          if not self.parameters == self._covariance.parameters:
              self._covariance = Covariance(self.parameters)
  
      @property
      def covariance(self):
          self._check_covariance()
          for par in self.parameters:
             
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/core.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  import collections.abc
  import copy
  from os.path import split
  import numpy as np
  import astropy.units as u
  from astropy.table import Table
  import yaml
  from gammapy.modeling import Covariance, Parameter, Parameters
  from gammapy.utils.scripts import make_name, make_path
  
  
  def _set_link(shared_register, model):
      for param in model.parameters:
          name = param.name
          link_label = param._link_label_io
          if link_label is not None:
              if link_label in shared_register:
                  new_param = shared_register[link_label]
                  setattr(model, name, new_param)
              else:
                  shared_register[link_label] = param
      return shared_register
  
  
  __all__ = ["Model", "Models", "ProperModels"]
  
  
  class Model:
      """Model base class."""
  
      def __init__(self, **kwargs):
          # Copy default parameters from the class to the instance
          default_parameters = self.default_parameters.copy()
  
          for par in default_parameters:
              value = kwargs.get(par.name, par)
  
              if not isinstance(value, Parameter):
                  par.quantity = u.Quantity(value)
              else:
                  par = value
  
              setattr(self, par.name, par)
  
          self._covariance = Covariance(self.parameters)
  
      def __init_subclass__(cls, **kwargs):
          # Add parameters list on the model sub-class (not instances)
          cls.default_parameters = Parameters(
              [_ for _ in cls.__dict__.values() if isinstance(_, Parameter)]
          )
  
      @classmethod
      def from_parameters(cls, parameters, **kwargs):
          """Create model from parameter list
  
          Parameters
          ----------
          parameters : `Parameters`
              Parameters for init
  
          Returns
          -------
          model : `Model`
              Model instance
          """
          for par in parameters:
              kwargs[par.name] = par
          return cls(**kwargs)
  
      def _check_covariance(self):
          if not self.parameters == self._covariance.parameters:
              self._covariance = Covariance(self.parameters)
  
      @property
      def covariance(self):
          self._check_covariance()
          for par in self.parameters:
             
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/core.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Spatial models."""
  import logging
  import numpy as np
  import scipy.integrate
  import scipy.special
  import astropy.units as u
  from astropy.coordinates import Angle, SkyCoord
  from astropy.coordinates.angle_utilities import angular_separation, position_angle
  from regions import (
      CircleAnnulusSkyRegion,
      EllipseSkyRegion,
      PointSkyRegion,
      PolygonSkyRegion,
  )
  from gammapy.maps import Map, WcsGeom
  from gammapy.modeling import Parameter, Parameters
  from gammapy.utils.gauss import Gauss2DPDF
  from gammapy.utils.scripts import make_path
  from .core import Model
  
  log = logging.getLogger(__name__)
  
  
  def compute_sigma_eff(lon_0, lat_0, lon, lat, phi, major_axis, e):
      """Effective radius, used for the evaluation of elongated models"""
      phi_0 = position_angle(lon_0, lat_0, lon, lat)
      d_phi = phi - phi_0
      minor_axis = Angle(major_axis * np.sqrt(1 - e ** 2))
  
      a2 = (major_axis * np.sin(d_phi)) ** 2
      b2 = (minor_axis * np.cos(d_phi)) ** 2
      denominator = np.sqrt(a2 + b2)
      sigma_eff = major_axis * minor_axis / denominator
      return minor_axis, sigma_eff
  
  
  class SpatialModel(Model):
      """Spatial model base class."""
  
      def __init__(self, **kwargs):
          frame = kwargs.pop("frame", "icrs")
          super().__init__(**kwargs)
          if not hasattr(self, "frame"):
              self.frame = frame
  
      def __call__(self, lon, lat):
          """Call evaluate method"""
          kwargs = {par.name: par.quantity for par in self.parameters}
          return self.evaluate(lon, lat, **kwargs)
  
      @property
      def position(self):
          """Spatial model center position"""
          lon = self.lon_0.quantity
          lat = self.lat_0.quantity
          return SkyCoord(lon,
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/spatial.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Spatial models."""
  import logging
  import numpy as np
  import scipy.integrate
  import scipy.special
  import astropy.units as u
  from astropy.coordinates import Angle, SkyCoord
  from astropy.coordinates.angle_utilities import angular_separation, position_angle
  from regions import (
      CircleAnnulusSkyRegion,
      EllipseSkyRegion,
      PointSkyRegion,
      PolygonSkyRegion,
  )
  from gammapy.maps import Map, WcsGeom
  from gammapy.modeling import Parameter, Parameters
  from gammapy.utils.gauss import Gauss2DPDF
  from gammapy.utils.scripts import make_path
  from .core import Model
  
  log = logging.getLogger(__name__)
  
  
  def compute_sigma_eff(lon_0, lat_0, lon, lat, phi, major_axis, e):
      """Effective radius, used for the evaluation of elongated models"""
      phi_0 = position_angle(lon_0, lat_0, lon, lat)
      d_phi = phi - phi_0
      minor_axis = Angle(major_axis * np.sqrt(1 - e ** 2))
  
      a2 = (major_axis * np.sin(d_phi)) ** 2
      b2 = (minor_axis * np.cos(d_phi)) ** 2
      denominator = np.sqrt(a2 + b2)
      sigma_eff = major_axis * minor_axis / denominator
      return minor_axis, sigma_eff
  
  
  class SpatialModel(Model):
      """Spatial model base class."""
  
      def __init__(self, **kwargs):
          frame = kwargs.pop("frame", "icrs")
          super().__init__(**kwargs)
          if not hasattr(self, "frame"):
              self.frame = frame
  
      def __call__(self, lon, lat):
          """Call evaluate method"""
          kwargs = {par.name: par.quantity for par in self.parameters}
          return self.evaluate(lon, lat, **kwargs)
  
      @property
      def position(self):
          """Spatial model center position"""
          lon = self.lon_0.quantity
          lat = self.lat_0.quantity
          return SkyCoord(lon,
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/spatial.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Spectral models for Gammapy."""
  import operator
  import numpy as np
  import scipy.optimize
  import scipy.special
  import astropy.units as u
  from astropy import constants as const
  from astropy.table import Table
  from gammapy.maps import MapAxis
  from gammapy.maps.utils import edges_from_lo_hi
  from gammapy.modeling import Covariance, Parameter, Parameters
  from gammapy.utils.integrate import evaluate_integral_pwl, trapz_loglog
  from gammapy.utils.interpolation import ScaledRegularGridInterpolator
  from gammapy.utils.scripts import make_path
  from .core import Model
  
  
  def integrate_spectrum(func, emin, emax, ndecade=100, intervals=False):
      """Integrate 1d function using the log-log trapezoidal rule.
  
      If scalar values for xmin and xmax are passed an oversampled grid is generated using the
      ``ndecade`` keyword argument. If xmin and xmax arrays are passed, no
      oversampling is performed and the integral is computed in the provided
      grid.
  
      Parameters
      ----------
      func : callable
          Function to integrate.
      emin : `~astropy.units.Quantity`
          Integration range minimum
      emax : `~astropy.units.Quantity`
          Integration range minimum
      ndecade : int, optional
          Number of grid points per decade used for the integration.
          Default : 100.
      intervals : bool, optional
          Return integrals in the grid not the sum, default: False
      """
      if emin.isscalar and emax.isscalar:
          energies = MapAxis.from_energy_bounds(
              emin=emin, emax=emax, nbin=ndecade, per_decade=True
          ).edges
      else:
          energies = edges_from_lo_hi(emin, emax)
  
      values = func(energies)
  
      integral = trapz_loglog(values, energies)
  
      if intervals:
          return integral
  
      return integral.sum()
  
  
  class SpectralModel(Model):
      """Spectral model base class."""
  
      def __call__(self, energy):
  
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/spectral.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Spectral models for Gammapy."""
  import operator
  import numpy as np
  import scipy.optimize
  import scipy.special
  import astropy.units as u
  from astropy import constants as const
  from astropy.table import Table
  from gammapy.maps import MapAxis
  from gammapy.maps.utils import edges_from_lo_hi
  from gammapy.modeling import Covariance, Parameter, Parameters
  from gammapy.utils.integrate import evaluate_integral_pwl, trapz_loglog
  from gammapy.utils.interpolation import ScaledRegularGridInterpolator
  from gammapy.utils.scripts import make_path
  from .core import Model
  
  
  def integrate_spectrum(func, emin, emax, ndecade=100, intervals=False):
      """Integrate 1d function using the log-log trapezoidal rule.
  
      If scalar values for xmin and xmax are passed an oversampled grid is generated using the
      ``ndecade`` keyword argument. If xmin and xmax arrays are passed, no
      oversampling is performed and the integral is computed in the provided
      grid.
  
      Parameters
      ----------
      func : callable
          Function to integrate.
      emin : `~astropy.units.Quantity`
          Integration range minimum
      emax : `~astropy.units.Quantity`
          Integration range minimum
      ndecade : int, optional
          Number of grid points per decade used for the integration.
          Default : 100.
      intervals : bool, optional
          Return integrals in the grid not the sum, default: False
      """
      if emin.isscalar and emax.isscalar:
          energies = MapAxis.from_energy_bounds(
              emin=emin, emax=emax, nbin=ndecade, per_decade=True
          ).edges
      else:
          energies = edges_from_lo_hi(emin, emax)
  
      values = func(energies)
  
      integral = trapz_loglog(values, energies)
  
      if intervals:
          return integral
  
      return integral.sum()
  
  
  class SpectralModel(Model):
      """Spectral model base class."""
  
      def __call__(self, energy):
  
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/spectral.py
files: # 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 gammapy.modeling.models import Model, Parameter, Parameters
  from gammapy.datasets import Datasets
  from gammapy.utils.testing import requires_data
  
  
  class MyModel(Model):
      """Simple model example"""
  
      x = Parameter("x", 1, "cm")
      y = Parameter("y", 2)
  
  
  class CoModel(Model):
      """Compound model example"""
  
      norm = Parameter("norm", 42, "cm")
  
      def __init__(self, m1, m2, norm=norm.quantity):
          self.m1 = m1
          self.m2 = m2
          super().__init__(norm=norm)
  
      @property
      def parameters(self):
          return Parameters([self.norm]) + self.m1.parameters + self.m2.parameters
  
  
  class WrapperModel(Model):
      """Wrapper compound model.
  
      Dynamically generated parameters in `__init__`,
      and a parameter name conflict with the wrapped
      model, both have a parameter called "y".
      """
  
      def __init__(self, m1, a=1, y=99):
          self.m1 = m1
          a = Parameter("a", a)
          y = Parameter("y", y)
          self.default_parameters = Parameters([a, y])
          super().__init__(a=a, y=y)
  
      @property
      def parameters(self):
          return Parameters([self.a, self.y]) + self.m1.parameters
  
  
  def test_model_class():
      assert isinstance(MyModel.parameters, property)
      assert MyModel.x.name == "x"
      assert MyModel.default_parameters["x"] is MyModel.x
  
  
  def test_model_class_par_init():
      x = Parameter("x", 4, "cm")
      y = Parameter("y", 10)
  
      model = MyModel(x=x, y=y)
  
      assert x is model.x
      assert y is model.y
  
  
  def test_model_init():
      m = MyModel()
      assert m.x.name == "x"
      assert m.x.value == 1
      assert m.x is m.parameters[0]
      assert m.y is m.parameters[1]
      assert m.parameters
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_core.py
files: # 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 gammapy.modeling.models import Model, Parameter, Parameters
  from gammapy.datasets import Datasets
  from gammapy.utils.testing import requires_data
  
  
  class MyModel(Model):
      """Simple model example"""
  
      x = Parameter("x", 1, "cm")
      y = Parameter("y", 2)
  
  
  class CoModel(Model):
      """Compound model example"""
  
      norm = Parameter("norm", 42, "cm")
  
      def __init__(self, m1, m2, norm=norm.quantity):
          self.m1 = m1
          self.m2 = m2
          super().__init__(norm=norm)
  
      @property
      def parameters(self):
          return Parameters([self.norm]) + self.m1.parameters + self.m2.parameters
  
  
  class WrapperModel(Model):
      """Wrapper compound model.
  
      Dynamically generated parameters in `__init__`,
      and a parameter name conflict with the wrapped
      model, both have a parameter called "y".
      """
  
      def __init__(self, m1, a=1, y=99):
          self.m1 = m1
          a = Parameter("a", a)
          y = Parameter("y", y)
          self.default_parameters = Parameters([a, y])
          super().__init__(a=a, y=y)
  
      @property
      def parameters(self):
          return Parameters([self.a, self.y]) + self.m1.parameters
  
  
  def test_model_class():
      assert isinstance(MyModel.parameters, property)
      assert MyModel.x.name == "x"
      assert MyModel.default_parameters["x"] is MyModel.x
  
  
  def test_model_class_par_init():
      x = Parameter("x", 4, "cm")
      y = Parameter("y", 10)
  
      model = MyModel(x=x, y=y)
  
      assert x is model.x
      assert y is model.y
  
  
  def test_model_init():
      m = MyModel()
      assert m.x.name == "x"
      assert m.x.value == 1
      assert m.x is m.parameters[0]
      assert m.y is m.parameters[1]
      assert m.parameters
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_core.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  import pytest
  import numpy as np
  from numpy.testing import assert_allclose
  import astropy.units as u
  from astropy.table import Table
  from astropy.utils.data import get_pkg_data_filename
  from gammapy.maps import Map, MapAxis
  from gammapy.modeling.models import (
      MODEL_REGISTRY,
      AbsorbedSpectralModel,
      Absorption,
      BackgroundModel,
      Model,
      Models,
  )
  from gammapy.utils.scripts import read_yaml, write_yaml
  from gammapy.utils.testing import requires_data
  
  
  @requires_data()
  def test_dict_to_skymodels():
      filename = get_pkg_data_filename("data/examples.yaml")
      models_data = read_yaml(filename)
      models = Models.from_dict(models_data)
  
      assert len(models) == 5
  
      model0 = models[0]
      assert isinstance(model0, BackgroundModel)
      assert model0.name == "background_irf"
  
      model0 = models[1]
      assert "ExpCutoffPowerLawSpectralModel" in model0.spectral_model.tag
      assert "PointSpatialModel" in model0.spatial_model.tag
  
      pars0 = model0.parameters
      assert pars0["index"].value == 2.1
      assert pars0["index"].unit == ""
      assert np.isnan(pars0["index"].max)
      assert np.isnan(pars0["index"].min)
      assert not pars0["index"].frozen
  
      assert pars0["lon_0"].value == -0.5
      assert pars0["lon_0"].unit == "deg"
      assert pars0["lon_0"].max == 180.0
      assert pars0["lon_0"].min == -180.0
      assert pars0["lon_0"].frozen
  
      assert pars0["lat_0"].value == -0.0005
      assert pars0["lat_0"].unit == "deg"
      assert pars0["lat_0"].max == 90.0
      assert pars0["lat_0"].min == -90.0
      assert pars0["lat_0"].frozen
  
      assert pars0["lambda_"].
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_io.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  import pytest
  import numpy as np
  from numpy.testing import assert_allclose
  import astropy.units as u
  from astropy.table import Table
  from astropy.utils.data import get_pkg_data_filename
  from gammapy.maps import Map, MapAxis
  from gammapy.modeling.models import (
      MODEL_REGISTRY,
      AbsorbedSpectralModel,
      Absorption,
      BackgroundModel,
      Model,
      Models,
  )
  from gammapy.utils.scripts import read_yaml, write_yaml
  from gammapy.utils.testing import requires_data
  
  
  @requires_data()
  def test_dict_to_skymodels():
      filename = get_pkg_data_filename("data/examples.yaml")
      models_data = read_yaml(filename)
      models = Models.from_dict(models_data)
  
      assert len(models) == 5
  
      model0 = models[0]
      assert isinstance(model0, BackgroundModel)
      assert model0.name == "background_irf"
  
      model0 = models[1]
      assert model0.spectral_model.tag == "ExpCutoffPowerLawSpectralModel"
      assert model0.spatial_model.tag == "PointSpatialModel"
  
      pars0 = model0.parameters
      assert pars0["index"].value == 2.1
      assert pars0["index"].unit == ""
      assert np.isnan(pars0["index"].max)
      assert np.isnan(pars0["index"].min)
      assert not pars0["index"].frozen
  
      assert pars0["lon_0"].value == -0.5
      assert pars0["lon_0"].unit == "deg"
      assert pars0["lon_0"].max == 180.0
      assert pars0["lon_0"].min == -180.0
      assert pars0["lon_0"].frozen
  
      assert pars0["lat_0"].value == -0.0005
      assert pars0["lat_0"].unit == "deg"
      assert pars0["lat_0"].max == 90.0
      assert pars0["lat_0"].min == -90.0
      assert pars0["lat_0"].frozen
  
      assert pars0["lambda_"].value ==
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_io.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  __all__ = ["Registry"]
  
  
  class Registry(list):
      """Registry class."""
  
      def get_cls(self, tag):
          for cls in self:
              if hasattr(cls, "tag") and tag in cls.tag:
                  return cls
          raise KeyError(f"No model found with tag: {tag!r}")
  
      def __str__(self):
          info = "Registry\n"
          info += "--------\n\n"
          tags = [_.tag[0] if isinstance(_.tag, list) else _.tag for _ in self]
          len_max = max([len(tag) for tag in tags])
  
          for item in self:
              info += f"\t{item.tag:{len_max}s}: {item.__name__}\n"
  
          return info.expandtabs(tabsize=2)
  
  
  [... the rest is omitted ...]
files: gammapy/utils/registry.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  
  __all__ = ["Registry"]
  
  
  class Registry(list):
      """Registry class."""
  
      def get_cls(self, tag):
          for cls in self:
              if hasattr(cls, "tag") and cls.tag == tag:
                  return cls
          raise KeyError(f"No model found with tag: {tag!r}")
  
      def __str__(self):
          info = "Registry\n"
          info += "--------\n\n"
  
          len_max = max([len(_.tag) for _ in self])
  
          for item in self:
              info += f"\t{item.tag:{len_max}s}: {item.__name__}\n"
  
          return info.expandtabs(tabsize=2)
  
  
  [... the rest is omitted ...]
files: gammapy/utils/registry.py