Beispiel #1
0
    def fit_point(self, model, energy_group, energy_ref):
        from gammapy.spectrum import SpectrumFit

        fit = SpectrumFit(self.obs, model)
        erange = energy_group.energy_range

        # TODO: Notice channels contained in energy_group
        fit.fit_range = erange.min, erange.max

        log.debug('Calling Sherpa fit for flux point '
                  ' in energy range:\n{}'.format(fit))

        fit.fit()
        fit.est_errors()

        # First result contain correct model
        res = fit.result[0]

        e_max = energy_group.energy_range.max
        e_min = energy_group.energy_range.min
        diff_flux, diff_flux_err = res.model.evaluate_error(energy_ref)
        return OrderedDict(
            e_ref=energy_ref,
            e_min=e_min,
            e_max=e_max,
            dnde=diff_flux.to('m-2 s-1 TeV-1'),
            dnde_err=diff_flux_err.to('m-2 s-1 TeV-1'),
        )
Beispiel #2
0
    def fit_point(self, model, energy_group, energy_ref):
        from gammapy.spectrum import SpectrumFit

        # TODO: The code below won't work because SpectrumFit only accepts
        # gammapy models. Add Parameter class to freeze index
        # sherpa_model = model.to_sherpa()
        # sherpa_model.gamma.freeze()
        #fit = SpectrumFit(self.obs, sherpa_model)
        fit = SpectrumFit(self.obs, model)

        erange = energy_group.energy_range
        # TODO: Notice channels contained in energy_group
        fit.fit_range = erange.min, 0.9999 * erange.max

        log.debug('Calling Sherpa fit for flux point '
                  ' in energy range:\n{}'.format(fit))

        fit.fit()
        fit.est_errors()

        # First result contain correct model
        res = fit.result[0]

        e_max = energy_group.energy_range.max
        e_min = energy_group.energy_range.min
        diff_flux, diff_flux_err = res.model.evaluate_error(energy_ref)
        return OrderedDict(
            e_ref=energy_ref,
            e_min=e_min,
            e_max=e_max,
            dnde=diff_flux.to('m-2 s-1 TeV-1'),
            dnde_err=diff_flux_err.to('m-2 s-1 TeV-1'),
        )
Beispiel #3
0
def test_spectral_model_absorbed_by_ebl():
    # Observation parameters
    obs_param = ObservationParameters(alpha=0.2 * u.Unit(''),
                                      livetime=5. * u.h,
                                      emin=0.08 * u.TeV,
                                      emax=12 * u.TeV)

    # Target, PKS 2155-304 from 3FHL
    name = 'test'
    absorption = Absorption.read(
        '$GAMMAPY_EXTRA/datasets/ebl/ebl_dominguez11.fits.gz')
    pwl = PowerLaw(index=3. * u.Unit(''),
                   amplitude=1.e-12 * u.Unit('1/(cm2 s TeV)'),
                   reference=1. * u.TeV)

    input_model = AbsorbedSpectralModel(spectral_model=pwl,
                                        absorption=absorption,
                                        parameter=0.2)

    target = Target(name=name, model=input_model)

    # Performance
    filename = '$GAMMAPY_EXTRA/datasets/cta/perf_prod2/point_like_non_smoothed/South_5h.fits.gz'
    cta_perf = CTAPerf.read(filename)

    # Simulation
    simu = CTAObservationSimulation.simulate_obs(perf=cta_perf,
                                                 target=target,
                                                 obs_param=obs_param)

    # Model we want to fit
    pwl_model = PowerLaw(index=2.5 * u.Unit(''),
                         amplitude=1.e-12 * u.Unit('1/(cm2 s TeV)'),
                         reference=1. * u.TeV)
    model = AbsorbedSpectralModel(spectral_model=pwl_model,
                                  absorption=absorption,
                                  parameter=0.2)

    # fit
    fit = SpectrumFit(obs_list=SpectrumObservationList([simu]),
                      model=model,
                      stat='wstat')
    fit.fit()
    fit.est_errors()
    result = fit.result[0]
Beispiel #4
0
def test_spectral_model_absorbed_by_ebl():
    # Observation parameters
    obs_param = ObservationParameters(alpha=0.2 * u.Unit(''),
                                      livetime=5. * u.h,
                                      emin=0.08 * u.TeV,
                                      emax=12 * u.TeV)

    # Target, PKS 2155-304 from 3FHL
    name = 'test'
    absorption = Absorption.read('$GAMMAPY_EXTRA/datasets/ebl/ebl_dominguez11.fits.gz')
    pwl = PowerLaw(index=3. * u.Unit(''),
                   amplitude=1.e-12 * u.Unit('1/(cm2 s TeV)'),
                   reference=1. * u.TeV)

    input_model = AbsorbedSpectralModel(spectral_model=pwl,
                                        absorption=absorption,
                                        parameter=0.2)

    target = Target(name=name, model=input_model)

    # Performance
    filename = '$GAMMAPY_EXTRA/datasets/cta/perf_prod2/point_like_non_smoothed/South_5h.fits.gz'
    cta_perf = CTAPerf.read(filename)

    # Simulation
    simu = CTAObservationSimulation.simulate_obs(perf=cta_perf,
                                                 target=target,
                                                 obs_param=obs_param)

    # Model we want to fit
    pwl_model = PowerLaw(index=2.5 * u.Unit(''),
                         amplitude=1.e-12 * u.Unit('1/(cm2 s TeV)'),
                         reference=1. * u.TeV)
    model = AbsorbedSpectralModel(spectral_model=pwl_model,
                                  absorption=absorption,
                                  parameter=0.2)

    # fit
    fit = SpectrumFit(obs_list=SpectrumObservationList([simu]),
                      model=model,
                      stat='wstat')
    fit.fit()
    fit.est_errors()
    result = fit.result[0]
# ### Model fit
#
# The next step is to fit a spectral model, using all data (i.e. a "global" fit, using all energies).

# In[26]:

model = models.PowerLaw(
    index=2 * u.Unit(''),
    amplitude=1e-11 * u.Unit('cm-2 s-1 TeV-1'),
    reference=1 * u.TeV,
)

fit = SpectrumFit(extract.observations, model)
fit.fit()
fit.est_errors()
print(fit.result[0])

# ### Spectral points
#
# Finally, let's compute spectral points. The method used is to first choose an energy binning, and then to do a 1-dim likelihood fit / profile to compute the flux and flux error.

# In[27]:

# Flux points are computed on stacked observation
stacked_obs = extract.observations.stack()
print(stacked_obs)

ebounds = EnergyBounds.equal_log_spacing(1, 40, 4, unit=u.TeV)

seg = SpectrumEnergyGroupMaker(obs=stacked_obs)
    
    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))]
    
    for k in range(len(models_ann_fit)):
        fit_source = SpectrumFit(obs_list = ann_sed_table, model=models_ann_fit[k],forward_folded=True, fit_range=(lo_fit_energ,hi_fit_energ))
        fit_source.fit()
        fit_source.est_errors()
        results = fit_source.result
        ax0, ax1 = results[0].plot(figsize=(8,8))
        print(results[0])
    
    if est_hi_lim = 'yes':
        hi_fit_energ = cube_on.energies('edges')[int(np.sum(circ_stats))]

    for k in range(len(models_circ_fit)):
        fit_source = SpectrumFit(obs_list = circ_sed_table, model=models_circ_fit[k],forward_folded=True, fit_range=(lo_fit_energ,hi_fit_energ))
        fit_source.fit()
        fit_source.est_errors()
        results = fit_source.result
        print(results[0])

extraction.run(obs_list=crablist, bkg_estimate=background_estimator.result, outdir=ANALYSIS_DIR)
extraction.write(obs_list=crablist, bkg_estimate=background_estimator.result, outdir=ANALYSIS_DIR)
extraction.write(crablist)
extraction.write(crablist, bkg_estimate=background_estimator.result, outdir=ANALYSIS_DIR)
extraction.write(crablist, background_estimator.result, outdir=ANALYSIS_DIR)
get_ipython().magic(u'pinfo extraction.write')
extraction.observations[0].peek()
model = PowerLaw(
    index=2 * u.Unit(''),
    amplitude=2e-11 * u.Unit('cm-2 s-1 TeV-1'),
    reference=1 * u.TeV,
)

joint_fit = SpectrumFit(obs_list=extraction.observations, model=model)
joint_fit.fit()
joint_fit.est_errors()
#fit.run(outdir = ANALYSIS_DIR)

joint_result = joint_fit.result
ax0, ax1 = joint_result[0].plot(figsize=(8,8))
ax0.set_ylim(0, 20)
print(joint_result[0])
plt.show()
ebounds = [0.3, 1.1, 3, 10.1, 30] * u.TeV

stacked_obs = extraction.observations.stack()

seg = SpectrumEnergyGroupMaker(obs=stacked_obs)
seg.compute_range_safe()
seg.compute_groups_fixed(ebounds=ebounds)
Indiv_best_fit_index = []
best_fit_index = []

i = 0

while i < n_obs:
    sim_result = (sim1.result[i], sim2.result[i])
    #FIT SPECTRA:
    pwl.parameters['index'].parmax = 10

    for obs in sim_result:
        fit = SpectrumFit(obs, pwl.copy(), stat='wstat')
        fit.model.parameters['index'].value = 2
        fit.fit()
        fit.est_errors()
        Indiv_best_fit_index.append(
            fit.result[0].model.parameters['index'].value)
        #print(fit.result[0])
        #print(' Indiv_best_fit_index = ', Indiv_best_fit_index)

    #i+=1
    #STACK SPECTRA 2 by 2
    # Add the two spectra
    obs_stacker = SpectrumObservationStacker(sim_result)
    #print('sim_result is the list = ',sim_result)
    obs_stacker.run()

    fit_stacked = SpectrumFit(obs_stacker.stacked_obs,
                              pwl.copy(),
                              stat='wstat')
model2fit1.parameters['beta'].parmin = 0.0
model2fit1.parameters['beta'].parmax = 10.0
model2fit1.parameters['amplitude'].parmin = 1e-14
model2fit1.parameters['amplitude'].parmax = 1e-5

model2fit2.parameters['index'].parmin = 0.1
model2fit2.parameters['index'].parmax = 5.0
model2fit2.parameters['lambda_'].parmin = 0.001
model2fit2.parameters['lambda_'].parmax = 100
model2fit2.parameters['amplitude'].parmin = 1.0e-14
model2fit2.parameters['amplitude'].parmax = 1.0e-3

model2fit3.parameters['index'].parmin = 1.0
model2fit3.parameters['index'].parmax = 7.0
model2fit3.parameters['amplitude'].parmin = 1.0e-14
model2fit3.parameters['amplitude'].parmax = 1.0e-4

models2fit = [model2fit3]  #,model2fit2,model2fit3]

for k in range(len(models2fit)):
    fit_crab = SpectrumFit(obs_list=simu,
                           model=models2fit[k],
                           fit_range=(1.0 * u.TeV, 55 * u.TeV),
                           stat="cash")
    fit_crab.fit()
    fit_crab.est_errors()
    results = fit_crab.result
    #ax0, ax1 = results[0].plot(figsize=(8,8))
    #plt.show()
    print(results[0])