import gammalib
import ctools
import cscripts

"""
Explanation: Generating a background model from the data
In this tutorial you will learn to generate a background model from the data
The public H.E.S.S. data do not contain a model for the instrumental background. We can generate one from the data using the csbkgmodel script.
We start with the usual imports.
End of explanation
"""


obsfile  = 'obs_crab_selected.xml'
outmodel = 'bkgmodel.xml'
bkgmodel = cscripts.csbkgmodel()
bkgmodel['inobs']      = obsfile
bkgmodel['outmodel']   = outmodel
bkgmodel['instrument'] = 'HESS'
bkgmodel['spatial']    = 'LOOKUP'
bkgmodel['slufile']    = '$CTOOLS/share/models/hess_bkg_lookup.fits'
bkgmodel['gradient']   = True
bkgmodel['spectral']   = 'NODES'
bkgmodel['ebinalg']    = 'LOG'
bkgmodel['emin']       = 0.7
bkgmodel['emax']       = 30.0
bkgmodel['enumbins']   = 8
bkgmodel['runwise']    = True
bkgmodel.execute()

"""
Explanation: We will use the same events selected in a previous tutorial. For the spatial part we will model the background as a radial Gaussian modified by a bi-linear gradient. For the spectral part we will use a piece-wise power law with 8 nodes between 0.7 TeV and 30 TeV. Note that for a reasonable background fit the nodes should be within the energy range covered by the observations and where there are enough photon counts to constrain the model, hence the upper energy bound at 30 TeV.
End of explanation
"""


print(gammalib.GModels(outmodel))

"""
Explanation: Let's look at the resulting background model.
End of explanation
"""


