def test_TemplateSpectralModel_compound(): energy = [1.00e06, 1.25e06, 1.58e06, 1.99e06] * u.MeV values = [4.39e-7, 1.96e-7, 8.80e-7, 3.94e-7] * u.Unit("MeV-1 s-1 sr-1") template = TemplateSpectralModel(energy=energy, values=values) correction = PowerLawNormSpectralModel(norm=2) model = CompoundSpectralModel(template, correction, operator=operator.mul) assert np.allclose(model(energy), 2 * values) model_mul = template * correction assert isinstance(model_mul, CompoundSpectralModel) assert np.allclose(model_mul(energy), 2 * values) model_dict = model.to_dict() assert model_dict["spectral"]["operator"] == "mul" model_class = SPECTRAL_MODEL_REGISTRY.get_cls(model_dict["spectral"]["type"]) new_model = model_class.from_dict(model_dict) assert isinstance(new_model, CompoundSpectralModel) assert np.allclose(new_model(energy), 2 * values)
from astropy import units as u import matplotlib.pyplot as plt from gammapy.modeling.models import ( CompoundSpectralModel, LogParabolaSpectralModel, Models, PowerLawSpectralModel, SkyModel, ) energy_range = [0.1, 100] * u.TeV pwl = PowerLawSpectralModel( index=2.0, amplitude="1e-12 cm-2 s-1 TeV-1", reference="1 TeV" ) lp = LogParabolaSpectralModel( amplitude="1e-12 cm-2 s-1 TeV-1", reference="10 TeV", alpha=2.0, beta=1.0 ) model = CompoundSpectralModel(pwl, lp, operator.add) model.plot(energy_range) plt.grid(which="both") # %% # YAML representation # ------------------- # Here is an example YAML file using the model: model = SkyModel(spectral_model=model, name="compound-model") models = Models([model]) print(models.to_yaml())