Example #1
0
def test_exponential_cutoff_power_law():
    model = ExponentialCutoffPowerLaw(
        amplitude=Q(1e-11, 'cm^-2 s^-1 TeV^-1'),
        e_0=Q(1, 'TeV'),
        alpha=2,
        e_cutoff=Q('3 TeV'),
    )
def get_model_gammapy(config):
    if config['model']['template'] == 'Shell2D':
        spatial_model = Shell2D(
            amplitude=1,
            x_0=config['model']['ra'],
            y_0=config['model']['dec'],
            r_in=config['model']['rin'],
            width=config['model']['width'],
            # Note: for now we need spatial models that are normalised
            # to integrate to 1 or results will be incorrect!!!
            normed=True,
        )
    if config['model']['template'] == 'Sphere2D':
        spatial_model = Sphere2D(
            amplitude=1,
            x_0=config['model']['ra'],
            y_0=config['model']['dec'],
            r_0=config['model']['rad'],
            # Note: for now we need spatial models that are normalised
            # to integrate to 1 or results will be incorrect!!!
            normed=True,
        )

    if config['model']['template'] == 'Gauss2D':
        spatial_model = Gauss2DPDF(
            #amplitude=1,
            #x_0=config['model']['ra'],
            #y_0=config['model']['dec'],
            sigma=config['model']['sigma'],
            # Note: for now we need spatial models that are normalised
            # to integrate to 1 or results will be incorrect!!!
            #normed=True,
        )
                             
    if config['model']['spectrum'] == 'pl':
        spectral_model = PowerLaw(
            amplitude=config['model']['prefactor'] * u.Unit('cm-2 s-1 TeV-1'), 
            index=config['model']['index'],
            reference=config['model']['pivot_energy'] * u.Unit('TeV'),
        )
    if config['model']['spectrum'] == 'ecpl':
        spectral_model = ExponentialCutoffPowerLaw(
            amplitude=config['model']['prefactor'] * u.Unit('cm-2 s-1 TeV-1'),
            index=config['model']['index'],
            reference=config['model']['pivot_energy'] * u.Unit('TeV'),
            lambda_=config['model']['cutoff'] * u.Unit('TeV-1'),
        )

    if config['model']['spectrum'] == 'LogParabola':
        spectral_model = LogParabola(
            amplitude=config['model']['prefactor'] * u.Unit('cm-2 s-1 TeV-1'),
            alpha=config['model']['alphapar'],
            beta=config['model']['beta'],
            reference=config['model']['pivot_energy'] * u.Unit('TeV'),
        )
                                               
    return CombinedModel3D(
        spatial_model=spatial_model,
        spectral_model=spectral_model,
    )
Example #3
0
def test_integrate_spectrum_ecpl():
    """
    Test ecpl integration. Regression test for
    https://github.com/gammapy/gammapy/issues/687
    """
    ecpl = ExponentialCutoffPowerLaw(
        index=2.3,
        amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"),
        reference=1 * u.TeV,
        lambda_=0.1 / u.TeV,
    )
    ecpl.parameters.set_parameter_errors({
        "index":
        0.2,
        "amplitude":
        1e-13 * u.Unit("cm-2 s-1 TeV-1")
    })
    emin, emax = 1 * u.TeV, 1e10 * u.TeV
    res = ecpl.integral_error(emin, emax)

    assert res.unit == "cm-2 s-1"
    assert_allclose(res.value, [5.95657824e-13, 9.27830251e-14], rtol=1e-5)
Example #4
0
    def setup(self):
        path = "$GAMMAPY_DATA/joint-crab/spectra/hess/"
        obs1 = SpectrumDatasetOnOff.from_ogip_files(path + "pha_obs23523.fits")
        obs2 = SpectrumDatasetOnOff.from_ogip_files(path + "pha_obs23592.fits")
        self.obs_list = [obs1, obs2]

        self.pwl = PowerLaw(index=2,
                            amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"),
                            reference=1 * u.TeV)

        self.ecpl = ExponentialCutoffPowerLaw(
            index=2,
            amplitude=1e-12 * u.Unit("cm-2 s-1 TeV-1"),
            reference=1 * u.TeV,
            lambda_=0.1 / u.TeV,
        )
Example #5
0
def get_model_gammapy(config):
    if config['model']['template1'] == 'Shell2D':
        spatial_model = Shell2D(
            amplitude=1,
            x_0=config['model']['ra1'],
            y_0=config['model']['dec1'],
            r_in=config['model']['rin1'],
            width=config['model']['width1'],
            # Note: for now we need spatial models that are normalised
            # to integrate to 1 or results will be incorrect!!!
            normed=True,
        )
    if config['model']['template1'] == 'Sphere2D':
        spatial_model = Sphere2D(
            amplitude=1,
            x_0=config['model']['ra1'],
            y_0=config['model']['dec1'],
            r_0=config['model']['rad'],
            # Note: for now we need spatial models that are normalised
            # to integrate to 1 or results will be incorrect!!!
            normed=True,
        )

    if config['model']['spectrum1'] == 'pl':
        spectral_model = PowerLaw(
            amplitude=config['model']['prefactor1'] * u.Unit('cm-2 s-1 TeV-1'),
            index=config['model']['index1'],
            reference=config['model']['pivot_energy1'] * u.Unit('TeV'),
        )
    if config['model']['spectrum1'] == 'ecpl':
        spectral_model = ExponentialCutoffPowerLaw(
            amplitude=config['model']['prefactor1'] * u.Unit('cm-2 s-1 TeV-1'),
            index=config['model']['index1'],
            reference=config['model']['pivot_energy1'] * u.Unit('TeV'),
            lambda_=config['model']['cutoff'] * u.Unit('TeV-1'),
        )

    return CombinedModel3D(
        spatial_model=spatial_model,
        spectral_model=spectral_model,
    )
Example #6
0
    def _get_spec_model(self, data):
        from uncertainties import ufloat
        spec_type = data['spec_type']

        # TODO: what about systematic errors?
        index = ufloat(data['spec_index'], data['spec_index_err'])
        amplitude = ufloat(data['spec_norm'], data['spec_norm_err'])
        reference = data['spec_ref']

        if spec_type == 'pl':
            model = PowerLaw(index, amplitude, reference)
        elif spec_type == 'pl2':
            model = PowerLaw2(amplitude, index, reference, 1E10)
        elif spec_type == 'ecpl':
            lambda_ = 1. / ufloat(data['spec_ecut'], data['spec_ecut_err'])
            model = ExponentialCutoffPowerLaw(index, amplitude, reference,
                                              lambda_)
        else:
            # return generic model, as all parameters are NaN it will
            # evaluate to NaN
            model = PowerLaw(index, amplitude, reference)
        return model
Example #7
0
#
# Here we will start by simulating an observation using the `simulate_dataset` method.

# In[ ]:

irfs = load_cta_irfs(
    "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits")

# In[ ]:

# Define sky model to simulate the data
spatial_model = SkyGaussian(lon_0="0 deg", lat_0="0 deg", sigma="0.2 deg")

spectral_model = ExponentialCutoffPowerLaw(
    index=2,
    amplitude="3e-12 cm-2 s-1 TeV-1",
    reference="1 TeV",
    lambda_="0.05 TeV-1",
)

sky_model_simu = SkyModel(spatial_model=spatial_model,
                          spectral_model=spectral_model)
print(sky_model_simu)

# In[ ]:

# Define map geometry
axis = MapAxis.from_edges(np.logspace(-1, 2, 30),
                          unit="TeV",
                          name="energy",
                          interp="log")
geom = WcsGeom.create(skydir=(0, 0),
Example #8
0
background_diffuse = BackgroundModel.from_skymodel(diffuse_model,
                                                   exposure=maps["exposure"],
                                                   psf=psf_kernel)

# In[ ]:

background_irf = BackgroundModel(maps["background"], norm=1.0, tilt=0.0)
background_total = background_irf + background_diffuse

# In[ ]:

spatial_model = SkyPointSource(lon_0="-0.05 deg", lat_0="-0.05 deg")
spectral_model = ExponentialCutoffPowerLaw(
    index=2 * u.Unit(""),
    amplitude=3e-12 * u.Unit("cm-2 s-1 TeV-1"),
    reference=1.0 * u.TeV,
    lambda_=0.1 / u.TeV,
)

model_ecpl = SkyModel(spatial_model=spatial_model,
                      spectral_model=spectral_model)

# In[ ]:

dataset_combined = MapDataset(
    model=model_ecpl,
    counts=maps["counts"],
    exposure=maps["exposure"],
    background_model=background_total,
    psf=psf_kernel,
    edisp=edisp,
lambda_= 0.07 * u.Unit('TeV-1')            ### HESS: 0.07 ## MAGIC: 0.05263 (1/Ecutoff)      ### Needed with: 'ExponentialCutoffPowerLaw'
amplitude= 3.23e-11  * u.Unit('cm-2 s-1 TeV-1') ### HEGRA: 2.83e-11 HESS: 3.76e-11 MAGIC: 3.23e-11  HESSII: 1.79e-10 ### Needed for: All models
reference= 1.0 * u.TeV     ### HEGRA, HESS, MAGIC: 1        HESSII: 0.521    ### Needed for: All models
alphapar= 2.47 * u.Unit('')  ### MAGIC: 2.47 HESSII: 2.1      ### Needed for: 'LogParabola'
beta= 0.104 * u.Unit('')   ### MAGIC: 0.24/np.log(10) HESSII: 0.24          ### Needed for: 'LogParabola'

#######################################################################

######## Define Flare model

flare_index = 3.161 * u.Unit('')
flare_amplitude = 3.320e-11 * u.Unit('cm-2 s-1 TeV-1')
flare_reference = 1.25 * u.TeV
lambda_flare = 0.0 * u.Unit('TeV-1')

flare_model = ExponentialCutoffPowerLaw(index=flare_index, amplitude=flare_amplitude, reference=flare_reference,lambda_ = lambda_flare)


if spectype == 'LogParabola':
    neb_model = LogParabola(amplitude=amplitude, reference=reference, alpha=alphapar, beta=beta)    ###MAGIC   HESSII

elif spectype == 'ExponentialCutoffPowerLaw':
    neb_model = ExponentialCutoffPowerLaw(index=index, amplitude=amplitude, reference=reference, lambda_=lambda_) ## HESS

elif spectype == 'PowerLaw':
    neb_model = PowerLaw(index=index, amplitude=amplitude, reference=reference)    ### HEGRA

else:
    raise ValueError('Spectra Model must be either "LogParabola", "PowerLaw", or "ExponentialCutoffPowerLaw"')

def main():
    
    #Low energy of spectral fitting range.
    lo_fit_energ = 0.1 * u.Unit('TeV')
    hi_fit_energ = 10 * u.Unit('TeV')
    
    #If you want an internal estimation of a high energy limit for the fitting range: est_hi_lim = 'yes'. If 'no' the hi_fit_energ will be used.
    est_hi_lim = 'yes'
    
    # Read ON and OFF cubes
    filename_on = 'non_cube.fits.gz' # non_cube_convolved.fits
    cube_on = SkyCube.read(filename_on)
    
    ann_filename_off = 'noff_withpuls_cube.fits.gz'
    ann_cube_off = SkyCube.read(ann_filename_off)
    circ_filename_off = 'noff_withneb_cube.fits.gz'
    circ_cube_off = SkyCube.read(circ_filename_off)
    
    # Read config and IRFs
    config = read_config('config.yaml')
    irfs = get_irfs(config)
    offset = Angle(config['selection']['offset_fov'] * u.deg)
    livetime = u.Quantity(config['pointing']['livetime']).to('second')
    alpha_obs = 1.
    binsz = config['binning']['binsz']
    aeff = irfs['aeff'].to_effective_area_table(offset = offset, energy = cube_on.energies('edges'))
    edisp = irfs['edisp'].to_energy_dispersion(offset = offset, e_true = aeff.energy.bins, e_reco = cube_on.energies('edges') )
    
    # Define circular on/off Regions parameters
    on_pos = SkyCoord(83.6333 * u.deg, 22.0144 * u.deg, frame='icrs')
    on_sizes = np.ones(20) * binsz * u.deg
    
    off_pos = SkyCoord(83.6333 * u.deg, 22.0144 * u.deg, frame='icrs')
    off_sizes = on_sizes * np.sqrt(1./alpha_obs)
    
    # Make Annular region
    on_rad_sizes = np.ones(len(on_sizes)) * 0.1 * binsz * u.deg
    off_rad_sizes = on_rad_sizes * np.sqrt(1./alpha_obs)
    widths = np.ones(len(on_sizes)) * 22 * binsz * u.deg
    out_rad_sizes = on_rad_sizes + widths
    
    ann_on_data, ann_off_data, ann_stats = make_annular_spectrum(on_pos, off_pos, on_rad_sizes, off_rad_sizes, out_rad_sizes, cube_on, ann_cube_off, alpha_obs)
    
    # Make circular region
    circ_on_data, circ_off_data, circ_stats = make_circular_spectrum(on_pos, off_pos, on_sizes, off_sizes, cube_on, circ_cube_off, alpha_obs)

    # Undo "holes" in circ/ann_stats
    if np.max(np.where(circ_stats == 1)) + 1 != circ_stats.sum():
        circ_stats[0:np.max(np.where(circ_stats == 1)) + 1][circ_stats[0:np.max(np.where(circ_stats == 1)) + 1] == 0] = 1.
    if np.max(np.where(ann_stats == 1)) + 1 != ann_stats.sum():
        ann_stats[0:np.max(np.where(ann_stats == 1)) + 1][ann_stats[0:np.max(np.where(ann_stats == 1)) + 1] == 0] = 1.
    
    # Make on/off vector
    ann_on_vector = PHACountsSpectrum(energy_lo = cube_on.energies('edges')[:-1], energy_hi= cube_on.energies('edges')[1:], data= ann_on_data['value'].data * ann_stats * u.ct, backscal = on_sizes[0].value, meta={'EXPOSURE' : livetime.value})
    circ_on_vector = PHACountsSpectrum(energy_lo = cube_on.energies('edges')[:-1], energy_hi= cube_on.energies('edges')[1:], data= circ_on_data['value'].data * circ_stats * u.ct, backscal = on_sizes[0].value, meta={'EXPOSURE' : livetime.value})
    
    
    ann_off_vector = PHACountsSpectrum(energy_lo = ann_cube_off.energies('edges')[:-1], energy_hi= ann_cube_off.energies('edges')[1:], data= ann_off_data['value'].data * ann_stats * u.ct, backscal = off_sizes[0].value, meta={'EXPOSURE' : livetime.value, 'OFFSET' : 0.3 * u.deg})
    circ_off_vector = PHACountsSpectrum(energy_lo = circ_cube_off.energies('edges')[:-1], energy_hi= circ_cube_off.energies('edges')[1:], data= circ_off_data['value'].data * circ_stats * u.ct, backscal = off_sizes[0].value, meta={'EXPOSURE' : livetime.value, 'OFFSET' : 0.3 * u.deg})

    # Make SpectrumObservation

    ann_sed_table = SpectrumObservation(on_vector = ann_on_vector, off_vector = ann_off_vector, aeff = aeff, edisp = edisp)
    circ_sed_table = SpectrumObservation(on_vector = circ_on_vector, off_vector = circ_off_vector, aeff = aeff, edisp = edisp)

    ##Debug
    #print(ann_stats)
    #print(circ_stats)
    
    # Define Spectral Model

    model2fit1 = LogParabola(amplitude=1e-11 * u.Unit('cm-2 s-1 TeV-1'), reference=1 * u.TeV, alpha=2.5 * u.Unit(''), beta=0.1 * u.Unit(''))
    model2fit2 = ExponentialCutoffPowerLaw(index = 1. * u.Unit(''), amplitude = 1e-11 * u.Unit('cm-2 s-1 TeV-1'), reference= 1 * u.TeV,  lambda_= 0. * u.Unit('TeV-1'))
    model2fit3 = PowerLaw(index= 2.5 * u.Unit(''), amplitude= 5e-11 * u.Unit('cm-2 s-1 TeV-1'), reference= 0.15 * u.TeV)

    model2fit3.parameters['amplitude'].parmin = 1e-12
    model2fit3.parameters['amplitude'].parmax = 1e-10
    
    model2fit3.parameters['index'].parmin = 2.0
    model2fit3.parameters['index'].parmax = 4.0

    #Models to fit the circular and annular observations
    models_ann_fit = [model2fit1, model2fit2, model2fit3]
    models_circ_fit = [model2fit1, model2fit2, model2fit3]
    
    # Fit
    if est_hi_lim = 'yes':
        hi_fit_energ = cube_on.energies('edges')[int(np.sum(ann_stats))]
Example #11
0
def test_ecpl_integrate():
    # regression test to check the numerical integration for small energy bins
    ecpl = ExponentialCutoffPowerLaw()
    value = ecpl.integral(1 * u.TeV, 1.1 * u.TeV)
    assert_quantity_allclose(value, 8.380714e-14 * u.Unit("s-1 cm-2"))
Example #12
0
def fpe_ecpl():
    return create_fpe(ExponentialCutoffPowerLaw(lambda_="1 TeV-1"))
Example #13
0
ax = flux_points.plot(energy_power=2)
result_pwl.model.plot(energy_range=[1e-4, 1e2] * u.TeV, ax=ax, energy_power=2)
result_pwl.model.plot_error(energy_range=[1e-4, 1e2] * u.TeV,
                            ax=ax,
                            energy_power=2)
ax.set_ylim(1e-13, 1e-11)

# ## Exponential Cut-Off Powerlaw Fit
#
# Next we fit an [exponential cut-off power](https://docs.gammapy.org/0.10/api/gammapy.spectrum.models.ExponentialCutoffPowerLaw.html#gammapy.spectrum.models.ExponentialCutoffPowerLaw) law to the data.

# In[ ]:

ecpl = ExponentialCutoffPowerLaw(
    index=2,
    amplitude="1e-12 cm-2 s-1 TeV-1",
    reference="1 TeV",
    lambda_="0.1 TeV-1",
)

# We run the fitter again by passing the flux points and the `ecpl` model instance:

# In[ ]:

fitter = FluxPointFit(ecpl, flux_points, stat="chi2assym")
result_ecpl = fitter.run()
print(result_ecpl.model)

# We plot the data and best fit model:

# In[ ]:
Example #14
0
ax = flux_points.plot(energy_power=2)
result_pwl['best-fit-model'].plot(energy_range=[1e-4, 1e2] * u.TeV, ax=ax, energy_power=2)
result_pwl['best-fit-model'].plot_error(energy_range=[1e-4, 1e2] * u.TeV, ax=ax, energy_power=2)
ax.set_ylim(1e-13, 1e-11)


# ## Exponential Cut-Off Powerlaw Fit
# 
# Next we fit an [exponential cut-off power](http://docs.gammapy.org/dev/api/gammapy.spectrum.models.ExponentialCutoffPowerLaw.html#gammapy.spectrum.models.ExponentialCutoffPowerLaw) law to the data.

# In[14]:


ecpl = ExponentialCutoffPowerLaw(
    index=2. * u.Unit(''),
    amplitude=1e-12 * u.Unit('cm-2 s-1 TeV-1'),
    reference=1. * u.TeV,
    lambda_=0. / u.TeV
)


# We run the fitter again by passing the flux points and the `ecpl` model instance:

# In[15]:


result_ecpl = fitter.run(flux_points, ecpl)
print(result_ecpl['best-fit-model'])


# In[16]:
Example #15
0
# assign covariance for plotting
pwl.parameters.covariance = result_pwl.parameters.covariance

pwl.plot_error(energy_range=[1e-4, 1e2] * u.TeV, ax=ax, energy_power=2)
ax.set_ylim(1e-13, 1e-11)

# ## Exponential Cut-Off Powerlaw Fit
#
# Next we fit an [exponential cut-off power](https://docs.gammapy.org/0.11/api/gammapy.spectrum.models.ExponentialCutoffPowerLaw.html#gammapy.spectrum.models.ExponentialCutoffPowerLaw) law to the data.

# In[ ]:

ecpl = ExponentialCutoffPowerLaw(
    index=1.8,
    amplitude="2e-12 cm-2 s-1 TeV-1",
    reference="1 TeV",
    lambda_="0.1 TeV-1",
)

# We run the fitter again by passing the flux points and the `ecpl` model instance:

# In[ ]:

dataset_ecpl = FluxPointsDataset(ecpl, flux_points, likelihood="chi2assym")
fitter = Fit(dataset_ecpl)
result_ecpl = fitter.run()
print(ecpl)

# We plot the data and best fit model:

# In[ ]:
reference = 1.0 * u.TeV  ### HEGRA, HESS, MAGIC: 1        HESSII: 0.521    ### Needed for: All models
alphapar = 2.47 * u.Unit(
    '')  ### MAGIC: 2.47 HESSII: 2.1      ### Needed for: 'LogParabola'
beta = 0.104 * u.Unit(
    ''
)  ### MAGIC: 0.24/np.log(10) HESSII: 0.24          ### Needed for: 'LogParabola'

######## Define Flare model

flare_index = 3.669 * u.Unit('')
flare_amplitude = 1.597e-12 * u.Unit('cm-2 s-1 TeV-1')
flare_reference = 1.25 * u.TeV
lambda_flare = 0.0 * u.Unit('TeV-1')

flare_model = ExponentialCutoffPowerLaw(index=flare_index,
                                        amplitude=flare_amplitude,
                                        reference=flare_reference,
                                        lambda_=lambda_flare)
#flare_model = PowerLaw(index=flare_index, amplitude=flare_amplitude, reference=flare_reference)

#######################################################################

# Model

if spectype == 'PowerLaw':
    neb_model = PowerLaw(index=index, amplitude=amplitude,
                         reference=reference)  ### HEGRA

elif spectype == 'LogParabola':
    neb_model = LogParabola(amplitude=amplitude,
                            reference=reference,
                            alpha=alphapar,
Example #17
0
     name="powerlaw2",
     model=PowerLaw2(
         amplitude=u.Quantity(2.9227116204223784, "cm-2 s-1"),
         index=2.3 * u.Unit(""),
         emin=1 * u.TeV,
         emax=10 * u.TeV,
     ),
     val_at_2TeV=u.Quantity(4 * 2.0 ** (-2.3), "cm-2 s-1 TeV-1"),
     integral_1_10TeV=u.Quantity(2.9227116204223784, "cm-2 s-1"),
     eflux_1_10TeV=u.Quantity(6.650836884969039, "TeV cm-2 s-1"),
 ),
 dict(
     name="ecpl",
     model=ExponentialCutoffPowerLaw(
         index=1.6 * u.Unit(""),
         amplitude=4 / u.cm ** 2 / u.s / u.TeV,
         reference=1 * u.TeV,
         lambda_=0.1 / u.TeV,
     ),
     val_at_2TeV=u.Quantity(1.080321705479446, "cm-2 s-1 TeV-1"),
     integral_1_10TeV=u.Quantity(3.765838739678921, "cm-2 s-1"),
     eflux_1_10TeV=u.Quantity(9.901735870666526, "TeV cm-2 s-1"),
     e_peak=4 * u.TeV,
 ),
 dict(
     name="ecpl_3fgl",
     model=ExponentialCutoffPowerLaw3FGL(
         index=2.3 * u.Unit(""),
         amplitude=4 / u.cm ** 2 / u.s / u.TeV,
         reference=1 * u.TeV,
         ecut=10 * u.TeV,
     ),