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
  
  
  
  [... 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
  
  
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/core.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Cube models (axes: lon, lat, energy)."""
  import copy
  from pathlib import Path
  import numpy as np
  import astropy.units as u
  from gammapy.maps import Map, MapAxis, RegionGeom, WcsGeom
  from gammapy.modeling import Covariance, Parameter, Parameters
  from gammapy.modeling.parameter import _get_parameters_str
  from gammapy.utils.scripts import make_name, make_path
  from gammapy.utils.fits import LazyFitsData, HDULocation
  from .core import Model, Models
  from .spatial import SpatialModel
  from .spectral import SpectralModel, PowerLawNormSpectralModel
  from .temporal import TemporalModel
  
  
  class SkyModelBase(Model):
      """Sky model base class"""
  
      def __add__(self, other):
          if isinstance(other, (Models, list)):
              return Models([self, *other])
          elif isinstance(other, (SkyModel, BackgroundModel)):
              return Models([self, other])
          else:
              raise TypeError(f"Invalid type: {other!r}")
  
      def __radd__(self, model):
          return self.__add__(model)
  
      def __call__(self, lon, lat, energy, time=None):
          return self.evaluate(lon, lat, energy, time)
  
      def evaluate_geom(self, geom, gti=None):
          coords = geom.get_coord(frame=self.frame)
          return self(coords.lon, coords.lat, coords["energy_true"])
  
  
  class SkyModel(SkyModelBase):
      """Sky model component.
  
      This model represents a factorised sky model.
      It has `~gammapy.modeling.Parameters`
      combining the spatial and spectral parameters.
  
      Parameters
      ---------
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/cube.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Cube models (axes: lon, lat, energy)."""
  import copy
  from pathlib import Path
  import numpy as np
  import astropy.units as u
  from gammapy.maps import Map, MapAxis, RegionGeom, WcsGeom
  from gammapy.modeling import Covariance, Parameter, Parameters
  from gammapy.modeling.parameter import _get_parameters_str
  from gammapy.utils.scripts import make_name, make_path
  from gammapy.utils.fits import LazyFitsData, HDULocation
  from .core import Model, Models
  from .spatial import SpatialModel
  from .spectral import SpectralModel, PowerLawNormSpectralModel
  from .temporal import TemporalModel
  
  
  class SkyModelBase(Model):
      """Sky model base class"""
  
      def __add__(self, other):
          if isinstance(other, (Models, list)):
              return Models([self, *other])
          elif isinstance(other, (SkyModel, BackgroundModel)):
              return Models([self, other])
          else:
              raise TypeError(f"Invalid type: {other!r}")
  
      def __radd__(self, model):
          return self.__add__(model)
  
      def __call__(self, lon, lat, energy, time=None):
          return self.evaluate(lon, lat, energy, time)
  
      def evaluate_geom(self, geom, gti=None):
          coords = geom.get_coord(frame=self.frame)
          return self(coords.lon, coords.lat, coords["energy_true"])
  
  
  class SkyModel(SkyModelBase):
      """Sky model component.
  
      This model represents a factorised sky model.
      It has `~gammapy.modeling.Parameters`
      combining the spatial and spectral parameters.
  
      Parameters
      ---------
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/cube.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.utils import lazyproperty
  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
  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."""
  
      _type = "spatial"
  
      def __init__(self, **kwargs):
          frame = kwargs.pop("frame", "icrs")
          super().__init
  
  [... 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.utils import lazyproperty
  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
  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."""
      _type = "spatial"
  
      def __init__(self, **kwargs):
          frame = kwargs.pop("frame", "icrs")
          super().__init__(
  
  [... 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 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
  
  [... 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 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
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/spectral.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Time-dependent models."""
  import numpy as np
  import scipy.interpolate
  from astropy import units as u
  from astropy.table import Table
  from astropy.time import Time
  from astropy.utils import lazyproperty
  from gammapy.modeling import Parameter
  from gammapy.utils.random import InverseCDFSampler, get_random_state
  from gammapy.utils.scripts import make_path
  from gammapy.utils.time import time_ref_from_dict
  from .core import Model
  
  
  # TODO: make this a small ABC to define a uniform interface.
  class TemporalModel(Model):
      """Temporal model base class.
      evaluates on  astropy.time.Time objects"""
  
      _type = "temporal"
  
      def __call__(self, time):
          """Evaluate model
  
          Parameters
          ----------
          time : `~astropy.time.Time`
              Time object
          """
          kwargs = {par.name: par.quantity for par in self.parameters}
          time = u.Quantity(time.mjd, "day")
          return self.evaluate(time, **kwargs)
  
      @property
      def type(self):
          return self._type
  
      @staticmethod
      def time_sum(t_min, t_max):
          """
          Total time between t_min and t_max
  
          Parameters
          ----------
          t_min, t_max: `~astropy.time.Time`
              Lower and upper bound of integration range
  
          Returns
          -------
          time_sum : `~astropy.time.TimeDelta`
              Summed time in the intervals.
  
          """
          diff = t_max - t_min
          # TODO: this is a work-around for https://github.com/astropy/astropy/issues/10501
          return u.Quantity(np.sum(diff.to_value("day")), "day")
  
      def plot(self,
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/temporal.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  """Time-dependent models."""
  import numpy as np
  import scipy.interpolate
  from astropy import units as u
  from astropy.table import Table
  from astropy.time import Time
  from astropy.utils import lazyproperty
  from gammapy.modeling import Parameter
  from gammapy.utils.random import InverseCDFSampler, get_random_state
  from gammapy.utils.scripts import make_path
  from gammapy.utils.time import time_ref_from_dict
  from .core import Model
  
  
  # TODO: make this a small ABC to define a uniform interface.
  class TemporalModel(Model):
      """Temporal model base class.
      evaluates on  astropy.time.Time objects"""
      _type = "temporal"
  
      def __call__(self, time):
          """Evaluate model
  
          Parameters
          ----------
          time : `~astropy.time.Time`
              Time object
          """
          kwargs = {par.name: par.quantity for par in self.parameters}
          time = u.Quantity(time.mjd, "day")
          return self.evaluate(time, **kwargs)
  
      @property
      def type(self):
          return self._type
  
      @staticmethod
      def time_sum(t_min, t_max):
          """
          Total time between t_min and t_max
  
          Parameters
          ----------
          t_min, t_max: `~astropy.time.Time`
              Lower and upper bound of integration range
  
          Returns
          -------
          time_sum : `~astropy.time.TimeDelta`
              Summed time in the intervals.
  
          """
          diff = t_max - t_min
          # TODO: this is a work-around for https://github.com/astropy/astropy/issues/10501
          return u.Quantity(np.sum(diff.to_value("day")), "day")
  
      def plot(self,
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/temporal.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
  
  [... 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
  
  [... 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.time import Time
  from gammapy.data.gti import GTI
  from gammapy.datasets.map import MapEvaluator
  from gammapy.irf import EDispKernel, PSFKernel
  from gammapy.maps import Map, MapAxis, WcsGeom
  from gammapy.modeling.models import (
      BackgroundModel,
      ConstantSpectralModel,
      ConstantTemporalModel,
      GaussianSpatialModel,
      Models,
      PointSpatialModel,
      PowerLawSpectralModel,
      PowerLawNormSpectralModel,
      TemplateSpatialModel,
      CompoundSpectralModel,
      SkyModel,
      create_fermi_isotropic_diffuse_model,
  )
  from gammapy.utils.testing import requires_data
  
  
  @pytest.fixture(scope="session")
  def sky_model():
      spatial_model = GaussianSpatialModel(
          lon_0="3 deg", lat_0="4 deg", sigma="3 deg", frame="galactic"
      )
      spectral_model = PowerLawSpectralModel(
          index=2, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
      )
      temporal_model = ConstantTemporalModel()
      return SkyModel(
          spatial_model=spatial_model,
          spectral_model=spectral_model,
          temporal_model=temporal_model,
          name="source-1",
      )
  
  
  @pytest.fixture(scope="session")
  def gti():
      start = [1, 3, 5] * u.day
      stop = [2, 3.5, 6] * u.day
      t_ref = Time
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_cube.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.time import Time
  from gammapy.data.gti import GTI
  from gammapy.datasets.map import MapEvaluator
  from gammapy.irf import EDispKernel, PSFKernel
  from gammapy.maps import Map, MapAxis, WcsGeom
  from gammapy.modeling.models import (
      BackgroundModel,
      ConstantSpectralModel,
      ConstantTemporalModel,
      GaussianSpatialModel,
      Models,
      PointSpatialModel,
      PowerLawSpectralModel,
      PowerLawNormSpectralModel,
      TemplateSpatialModel,
      CompoundSpectralModel,
      SkyModel,
      create_fermi_isotropic_diffuse_model,
  )
  from gammapy.utils.testing import requires_data
  
  
  @pytest.fixture(scope="session")
  def sky_model():
      spatial_model = GaussianSpatialModel(
          lon_0="3 deg", lat_0="4 deg", sigma="3 deg", frame="galactic"
      )
      spectral_model = PowerLawSpectralModel(
          index=2, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
      )
      temporal_model = ConstantTemporalModel()
      return SkyModel(
          spatial_model=spatial_model,
          spectral_model=spectral_model,
          temporal_model=temporal_model,
          name="source-1",
      )
  
  
  @pytest.fixture(scope="session")
  def gti():
      start = [1, 3, 5] * u.day
      stop = [2, 3.5, 6] * u.day
      t_ref = Time
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_cube.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,
      PowerLawSpectralModel,
      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
  
  [... 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 "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 ==
  
  [... 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
  import operator
  from numpy.testing import assert_allclose
  import astropy.units as u
  from gammapy.maps import MapAxis
  from gammapy.modeling.models import (
      SPECTRAL_MODEL_REGISTRY,
      AbsorbedSpectralModel,
      Absorption,
      ConstantSpectralModel,
      CompoundSpectralModel,
      ExpCutoffPowerLaw3FGLSpectralModel,
      ExpCutoffPowerLawSpectralModel,
      ExpCutoffPowerLawNormSpectralModel,
      GaussianSpectralModel,
      LogParabolaSpectralModel,
      LogParabolaNormSpectralModel,
      NaimaSpectralModel,
      PowerLaw2SpectralModel,
      PowerLawSpectralModel,
      PowerLawNormSpectralModel,
      BrokenPowerLawSpectralModel,
      SmoothBrokenPowerLawSpectralModel,
      SuperExpCutoffPowerLaw4FGLSpectralModel,
      TemplateSpectralModel,
  )
  from gammapy.utils.testing import (
      assert_quantity_allclose,
      mpl_plot_check,
      requires_data,
      requires_dependency,
  )
  
  
  def table_model():
      energy = MapAxis.from_energy_bounds(0.1 * u.TeV, 100 * u.TeV, 1000).center
  
      model = PowerLawSpectralModel(
          index=2.3, amplitude="4 cm-2 s-1 TeV-1", reference="1 TeV"
      )
      dnde = model(energy)
  
      return TemplateSpectralModel(energy, dnde)
  
  
  TEST_MODELS = [
      dict(
          name="powerlaw",
          model=PowerLawSpectralModel(
              index=2.3 * u.Unit(""),
              amplitude=4 / u.cm ** 2
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_spectral.py
files: # Licensed under a 3-clause BSD style license - see LICENSE.rst
  import pytest
  import numpy as np
  import operator
  from numpy.testing import assert_allclose
  import astropy.units as u
  from gammapy.maps import MapAxis
  from gammapy.modeling.models import (
      SPECTRAL_MODEL_REGISTRY,
      AbsorbedSpectralModel,
      Absorption,
      ConstantSpectralModel,
      CompoundSpectralModel,
      ExpCutoffPowerLaw3FGLSpectralModel,
      ExpCutoffPowerLawSpectralModel,
      ExpCutoffPowerLawNormSpectralModel,
      GaussianSpectralModel,
      LogParabolaSpectralModel,
      LogParabolaNormSpectralModel,
      NaimaSpectralModel,
      PowerLaw2SpectralModel,
      PowerLawSpectralModel,
      PowerLawNormSpectralModel,
      BrokenPowerLawSpectralModel,
      SmoothBrokenPowerLawSpectralModel,
      SuperExpCutoffPowerLaw4FGLSpectralModel,
      TemplateSpectralModel,
  )
  from gammapy.utils.testing import (
      assert_quantity_allclose,
      mpl_plot_check,
      requires_data,
      requires_dependency,
  )
  
  
  def table_model():
      energy = MapAxis.from_energy_bounds(0.1 * u.TeV, 100 * u.TeV, 1000).center
  
      model = PowerLawSpectralModel(
          index=2.3, amplitude="4 cm-2 s-1 TeV-1", reference="1 TeV"
      )
      dnde = model(energy)
  
      return TemplateSpectralModel(energy, dnde)
  
  
  TEST_MODELS = [
      dict(
          name="powerlaw",
          model=PowerLawSpectralModel(
              index=2.3 * u.Unit(""),
              amplitude=4 / u.cm ** 2
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_spectral.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.table import Table
  from astropy.time import Time
  from gammapy.data.gti import GTI
  from gammapy.modeling.models import (
      ConstantTemporalModel,
      ExpDecayTemporalModel,
      GaussianTemporalModel,
      LightCurveTemplateTemporalModel,
      PowerLawSpectralModel,
      SkyModel,
  )
  from gammapy.utils.scripts import make_path
  from gammapy.utils.testing import requires_data, requires_dependency, mpl_plot_check
  
  
  # TODO: add light-curve test case from scratch
  # only use the FITS one for I/O (or not at all)
  @pytest.fixture(scope="session")
  def light_curve():
      path = "$GAMMAPY_DATA/tests/models/light_curve/lightcrv_PKSB1222+216.fits"
      return LightCurveTemplateTemporalModel.read(path)
  
  
  @requires_data()
  def test_light_curve_str(light_curve):
      ss = str(light_curve)
      assert "LightCurveTemplateTemporalModel" in ss
  
  
  @requires_data()
  def test_light_curve_evaluate(light_curve):
      t = Time(59500, format="mjd")
      val = light_curve(t)
      assert_allclose(val, 0.015512, rtol=1e-5)
  
      t = Time(46300, format="mjd")
      val = light_curve.evaluate(t.mjd, ext=3)
      assert_allclose(val, 0.01551196, rtol=1e-5)
  
  
  def rate(x, c="1e4 s"):
      c = u
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_temporal.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.table import Table
  from astropy.time import Time
  from gammapy.data.gti import GTI
  from gammapy.modeling.models import (
      ConstantTemporalModel,
      ExpDecayTemporalModel,
      GaussianTemporalModel,
      LightCurveTemplateTemporalModel,
      PowerLawSpectralModel,
      SkyModel,
  )
  from gammapy.utils.scripts import make_path
  from gammapy.utils.testing import requires_data, requires_dependency, mpl_plot_check
  
  
  # TODO: add light-curve test case from scratch
  # only use the FITS one for I/O (or not at all)
  @pytest.fixture(scope="session")
  def light_curve():
      path = "$GAMMAPY_DATA/tests/models/light_curve/lightcrv_PKSB1222+216.fits"
      return LightCurveTemplateTemporalModel.read(path)
  
  
  @requires_data()
  def test_light_curve_str(light_curve):
      ss = str(light_curve)
      assert "LightCurveTemplateTemporalModel" in ss
  
  
  @requires_data()
  def test_light_curve_evaluate(light_curve):
      t = Time(59500, format="mjd")
      val = light_curve(t)
      assert_allclose(val, 0.015512, rtol=1e-5)
  
      t = Time(46300, format="mjd")
      val = light_curve.evaluate(t.mjd, ext=3)
      assert_allclose(val, 0.01551196, rtol=1e-5)
  
  
  def rate(x, c="1e4 s"):
      c = u
  
  [... the rest is omitted ...]
files: gammapy/modeling/models/tests/test_temporal.py