Exemple #1
0
    def ctedispcube(self,log=False,debug=False, **kwargs):
        '''
        Create ctbkgcube instance with given parameters
        Parameters
        ---------
        log  : save or not the log file
        debug  : debug mode or not. This will print a lot of information
        '''
        self.info("Running ctedispcube to compute the edisp rate")

        self.ctedispcube = ct.ctedispcube()
        
        self._fill_app( self.ctedispcube,log=log,debug=debug, **kwargs)

        self.ctedispcube["incube"] = self.config['file']["cntcube"]
        self.ctedispcube["outcube"] = self.config['file']["edispcube"]

        if self.verbose:
            print self.ctedispcube

        self.ctedispcube.run()

        self.ctedispcube.save()
        self.info("Saved edisp cube to {0:s}".format(self.ctedispcube["outcube"]))

        del self.ctedispcube
    def _test_python(self):
        """
        Test ctedispcube from Python
        """
        # Set-up ctedispcube
        edispcube = ctools.ctedispcube()
        edispcube['inobs'] = self._events
        edispcube['incube'] = 'NONE'
        edispcube['outcube'] = 'ctedispcube_py1.fits'
        edispcube['caldb'] = self._caldb
        edispcube['irf'] = self._irf
        edispcube['ebinalg'] = 'LOG'
        edispcube['emin'] = 0.1
        edispcube['emax'] = 100
        edispcube['enumbins'] = 20
        edispcube['nxpix'] = 10
        edispcube['nypix'] = 10
        edispcube['binsz'] = 0.4
        edispcube['coordsys'] = 'CEL'
        edispcube['proj'] = 'CAR'
        edispcube['xref'] = 83.63
        edispcube['yref'] = 22.01
        edispcube['migramax'] = 2.0
        edispcube['migrabins'] = 10
        edispcube['logfile'] = 'ctedispcube_py1.log'
        edispcube['chatter'] = 2

        # Run ctedispcube tool
        edispcube.logFileOpen()  # Make sure we get a log file
        edispcube.run()
        edispcube.save()

        # Check result file
        self._check_result_file('ctedispcube_py1.fits')

        # Return
        return
Exemple #3
0
def stackedPipeline(
    name="Crab",
    obsfile="index.xml",
    l=0.01,
    b=0.01,
    emin=0.1,
    emax=100.0,
    enumbins=20,
    nxpix=200,
    nypix=200,
    binsz=0.02,
    coordsys="CEL",
    proj="CAR",
    caldb="prod2",
    irf="acdc1a",
    debug=False,
    inmodel="Crab",
    outmodel="results",
):
    """
    Simulation and stacked analysis pipeline
    
    Parameters
    ----------
    obs : `~gammalib.GObservations`
    Observation container
    ra : float, optional
    Right Ascension of counts cube centre (deg)
    dec : float, optional
    Declination of Region of counts cube centre (deg)
    emin : float, optional
    Minimum energy (TeV)
    emax : float, optional
    Maximum energy (TeV)
    enumbins : int, optional
    Number of energy bins
    nxpix : int, optional
    Number of pixels in X axis
    nypix : int, optional
    Number of pixels in Y axis
    binsz : float, optional
    Pixel size (deg)
    coordsys : str, optional
    Coordinate system
    proj : str, optional
    Coordinate projection
    debug : bool, optional
    Debug function
    """

    # Bin events into counts map
    bin = ctools.ctbin()
    bin["inobs"] = obsfile
    bin["ebinalg"] = "LOG"
    bin["emin"] = emin
    bin["emax"] = emax
    bin["enumbins"] = enumbins
    bin["nxpix"] = nxpix
    bin["nypix"] = nypix
    bin["binsz"] = binsz
    bin["coordsys"] = coordsys
    bin["proj"] = proj
    bin["xref"] = l
    bin["yref"] = b
    bin["debug"] = debug
    bin["outobs"] = "cntcube.fits"
    bin.execute()
    print("Datacube : done!")

    # Create exposure cube
    expcube = ctools.ctexpcube()
    # expcube['incube']=bin.obs()
    expcube["inobs"] = obsfile
    expcube["incube"] = "NONE"
    expcube["ebinalg"] = "LOG"
    expcube["caldb"] = caldb
    expcube["irf"] = irf
    expcube["emin"] = emin
    expcube["emax"] = emax
    expcube["enumbins"] = enumbins
    expcube["nxpix"] = nxpix
    expcube["nypix"] = nypix
    expcube["binsz"] = binsz
    expcube["coordsys"] = coordsys
    expcube["proj"] = proj
    expcube["xref"] = l
    expcube["yref"] = b
    expcube["debug"] = debug
    expcube["outcube"] = "cube_exp.fits"
    expcube.execute()
    print("Expcube : done!")

    # Create PSF cube
    psfcube = ctools.ctpsfcube()
    psfcube["inobs"] = obsfile
    psfcube["incube"] = "NONE"
    psfcube["ebinalg"] = "LOG"
    psfcube["caldb"] = caldb
    psfcube["irf"] = irf
    psfcube["emin"] = emin
    psfcube["emax"] = emax
    psfcube["enumbins"] = enumbins
    psfcube["nxpix"] = 10
    psfcube["nypix"] = 10
    psfcube["binsz"] = 1.0
    psfcube["coordsys"] = coordsys
    psfcube["proj"] = proj
    psfcube["xref"] = l
    psfcube["yref"] = b
    psfcube["debug"] = debug
    psfcube["outcube"] = "psf_cube.fits"
    psfcube.execute()
    print("Psfcube : done!")

    edispcube = ctools.ctedispcube()
    edispcube["inobs"] = obsfile
    edispcube["ebinalg"] = "LOG"
    edispcube["incube"] = "NONE"
    edispcube["caldb"] = caldb
    edispcube["irf"] = irf
    edispcube["xref"] = l
    edispcube["yref"] = b
    edispcube["proj"] = proj
    edispcube["coordsys"] = coordsys
    edispcube["binsz"] = 1.0
    edispcube["nxpix"] = 10
    edispcube["nypix"] = 10
    edispcube["emin"] = emin
    edispcube["emax"] = emax
    edispcube["enumbins"] = enumbins
    edispcube["outcube"] = "edisp_cube.fits"
    edispcube["debug"] = debug
    edispcube.execute()
    print("Edispcube : done!")

    # Create background cube
    bkgcube = ctools.ctbkgcube()
    bkgcube["inobs"] = obsfile
    bkgcube["incube"] = "cntcube.fits"
    bkgcube["caldb"] = caldb
    bkgcube["irf"] = irf
    bkgcube["debug"] = debug
    bkgcube["inmodel"] = str(inmodel)
    bkgcube["outcube"] = "bkg_cube.fits"
    bkgcube["outmodel"] = "bkg_cube.xml"
    bkgcube.execute()
    print("Bkgcube : done!")

    # Fix the instrumental background parameters
    bkgcube.models()["BackgroundModel"]["Prefactor"].fix()
    bkgcube.models()["BackgroundModel"]["Index"].fix()
    #
    #    # Attach background model to observation container
    bin.obs().models(bkgcube.models())
    #
    #
    #    # Set Exposure and Psf cube for first CTA observation
    #    # (ctbin will create an observation with a single container)
    bin.obs()[0].response(expcube.expcube(), psfcube.psfcube(),
                          edispcube.edispcube(), bkgcube.bkgcube())

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    #    like['inmodel']='bkg_cube.xml'
    like["edisp"] = True
    #    like['edispcube'] = 'edisp_cube.fits'
    #    like['expcube'] = 'cube_exp.fits'
    #    like['psfcube'] = 'psf_cube.fits'
    #    like['bkgcube'] = 'bkg_cube.fits'
    like["outmodel"] = str(outmodel)
    #    like['outcovmat']=inmodel+'_covmat.txt'
    like["debug"] = debug  # Switch this always on for results in console
    # like['statistic']='CSTAT'
    like.execute()
    print("Likelihood : done!")

    # Set the best-fit models (from ctlike) for the counts cube
    bin.obs().models(like.obs().models())

    # Obtain the best-fit butterfly
    try:
        butterfly = ctools.ctbutterfly(bin.obs())
        butterfly["srcname"] = name
        butterfly["inmodel"] = str(outmodel)
        butterfly["edisp"] = True
        butterfly["emin"] = emin
        butterfly["emax"] = emax
        butterfly["outfile"] = str(outmodel.parent) + "/" + str(
            outmodel.stem) + ".txt"
        butterfly[
            "debug"] = debug  # Switch this always on for results in console
        # like['statistic']='CSTAT'
        butterfly.execute()
        print("Butterfly : done!")
    except:
        print("I COULDN'T CALCULATE THE BUTTERFLY....")

    # Extract the spectrum
    try:
        csspec = cscripts.csspec(bin.obs())
        csspec["srcname"] = name
        csspec["inmodel"] = str(outmodel)
        csspec["method"] = "AUTO"
        csspec["ebinalg"] = "LOG"
        csspec["emin"] = emin
        csspec["emax"] = emax
        csspec["enumbins"] = 10
        csspec["edisp"] = True
        csspec["outfile"] = str(outmodel.parent) + "/" + str(
            outmodel.stem) + ".fits"
        csspec["debug"] = debug  # Switch this always on for results in console
        csspec.execute()
        print("Csspec : done!")
    except:
        print("I COULDN'T CALCULATE THE SPECTRUM....")

    # Return
    return
def prepare(obsname, bkgname, rad=2.0, emin=0.3, emax=50.0, ebins=20):
    """
    Prepare events for analysis

    Parameters
    ----------
    obsname : str
        Observation definition XML file
    bkgname : str
        Background model definition XML file
    rad : float, optional
        Selection radius (degrees)
    emin : float, optional
        Minimum energy for analysis (TeV)
    emax : float, optional
        Maximum energy for analysis (TeV)
    ebins : int, optional
        Number of energy bins
    """
    # Set filenames
    cntcube = 'rx_stacked%2.2d_cntcube.fits' % ebins
    expcube = 'rx_stacked%2.2d_expcube.fits' % ebins
    psfcube = 'rx_stacked%2.2d_psfcube.fits' % ebins
    edispcube = 'rx_stacked%2.2d_edispcube.fits' % ebins
    bkgcube = 'rx_stacked%2.2d_bkgcube.fits' % ebins
    obsname_binned = add_attribute(obsname, '_binned%2.2d' % ebins)
    bkgname_stacked = add_attribute(bkgname, '_stacked')
    obsname_stacked = add_attribute(obsname, '_stacked%2.2d' % ebins)
    obsname_stacked_edisp = add_attribute(obsname_stacked, '_edisp')

    # Generate background lookup
    generate_background_lookup()

    # Continue only if selected events do not exist
    if not os.path.isfile(obsname):

        # Setup task parameters
        select = ctools.ctselect()
        select['inobs'] = '$HESSDATA/obs/obs_rx.xml'
        select['outobs'] = obsname
        select['ra'] = 'UNDEF'
        select['dec'] = 'UNDEF'
        select['rad'] = rad
        select['tmin'] = 'UNDEF'
        select['tmax'] = 'UNDEF'
        select['emin'] = emin
        select['emax'] = emax
        select['usethres'] = 'DEFAULT'
        select['logfile'] = 'rx_hess_select_events.log'
        select.logFileOpen()

        # Select events
        select.execute()

    # Continue only if background model does not exist
    if not os.path.isfile(bkgname):

        # Setup task parameters
        bkg = cscripts.csbkgmodel()
        bkg['inobs'] = '$HESSDATA/obs/obs_rx.xml'
        bkg['outmodel'] = bkgname
        bkg['instrument'] = 'HESS'
        bkg['spatial'] = 'LOOKUP'
        bkg['slufile'] = 'off_lookup.fits'
        bkg['gradient'] = True
        bkg['spectral'] = 'NODES'
        bkg['ebinalg'] = 'LOG'
        bkg['emin'] = emin
        bkg['emax'] = 30.0
        bkg['enumbins'] = 8
        bkg['runwise'] = True
        bkg['rad'] = rad
        bkg['logfile'] = 'rx_hess_create_background.log'
        bkg.logFileOpen()

        # Generate background model
        bkg.execute()

    # Continue only if counts cube does not exist
    if not os.path.isfile(cntcube):

        # Setup task parameters
        ctbin = ctools.ctbin()
        ctbin['inobs'] = obsname
        ctbin['outobs'] = cntcube
        ctbin['ebinalg'] = 'LOG'
        ctbin['emin'] = emin
        ctbin['emax'] = emax
        ctbin['enumbins'] = ebins
        ctbin['coordsys'] = 'CEL'
        ctbin['proj'] = 'TAN'
        ctbin['xref'] = 258.1125
        ctbin['yref'] = -39.6867
        ctbin['nxpix'] = 300
        ctbin['nypix'] = 300
        ctbin['binsz'] = 0.02
        ctbin['logfile'] = 'rx_hess_create_cntcube.log'
        ctbin.logFileOpen()

        # Generate counts cube
        ctbin.execute()

    # Continue only if counts cubes for binned analysis do not exist
    if not os.path.isfile(obsname_binned):

        # Setup task parameters
        ctbin = ctools.ctbin()
        ctbin['inobs'] = obsname
        ctbin['outobs'] = obsname_binned
        ctbin['stack'] = False
        ctbin['usepnt'] = True
        ctbin['ebinalg'] = 'LOG'
        ctbin['emin'] = emin
        ctbin['emax'] = emax
        ctbin['enumbins'] = ebins
        ctbin['coordsys'] = 'CEL'
        ctbin['proj'] = 'TAN'
        ctbin['nxpix'] = 200
        ctbin['nypix'] = 200
        ctbin['binsz'] = 0.02
        ctbin['logfile'] = 'rx_hess_create_cntcube_binned.log'
        ctbin.logFileOpen()

        # Generate counts cubes
        ctbin.execute()

    # Continue only if exposure cube does not exist
    if not os.path.isfile(expcube):

        # Setup task parameters
        ctexpcube = ctools.ctexpcube()
        ctexpcube['inobs'] = obsname
        ctexpcube['incube'] = 'NONE'
        ctexpcube['ebinalg'] = 'LOG'
        ctexpcube['emin'] = 0.1  # Full energy range
        ctexpcube['emax'] = 100.0  # Full energy range
        ctexpcube['enumbins'] = 300  # Factor ~3 oversampling of IRF
        ctexpcube['coordsys'] = 'CEL'
        ctexpcube['proj'] = 'TAN'
        ctexpcube['xref'] = 258.1125
        ctexpcube['yref'] = -39.6867
        ctexpcube['nxpix'] = 300
        ctexpcube['nypix'] = 300
        ctexpcube['binsz'] = 0.02
        ctexpcube['outcube'] = expcube
        ctexpcube['logfile'] = 'rx_hess_create_expcube.log'
        ctexpcube.logFileOpen()

        # Generate exposure cube
        ctexpcube.execute()

    # Continue only if PSF cube does not exist
    if not os.path.isfile(psfcube):

        # Setup task parameters
        ctpsfcube = ctools.ctpsfcube()
        ctpsfcube['inobs'] = obsname
        ctpsfcube['incube'] = 'NONE'
        ctpsfcube['ebinalg'] = 'LOG'
        ctpsfcube['emin'] = 0.1  # Full energy range
        ctpsfcube['emax'] = 100.0  # Full energy range
        ctpsfcube['enumbins'] = 300  # Factor ~3 oversampling of IRF
        ctpsfcube['coordsys'] = 'CEL'
        ctpsfcube['proj'] = 'TAN'
        ctpsfcube['xref'] = 258.1125
        ctpsfcube['yref'] = -39.6867
        ctpsfcube['nxpix'] = 30
        ctpsfcube['nypix'] = 30
        ctpsfcube['binsz'] = 0.2
        ctpsfcube['amax'] = 0.7  # Full H.E.S.S. PSF range
        ctpsfcube['anumbins'] = 300  # Factor ~2 oversampling of IRF
        ctpsfcube['outcube'] = psfcube
        ctpsfcube['logfile'] = 'rx_hess_create_psfcube.log'
        ctpsfcube.logFileOpen()

        # Generate PSF cube
        ctpsfcube.execute()

    # Continue only if energy dispersion cube does not exist
    if not os.path.isfile(edispcube):

        # Setup task parameters
        ctedispcube = ctools.ctedispcube()
        ctedispcube['inobs'] = obsname
        ctedispcube['incube'] = 'NONE'
        ctedispcube['ebinalg'] = 'LOG'
        ctedispcube['emin'] = 0.1  # Full energy range
        ctedispcube['emax'] = 100.0  # Full energy range
        ctedispcube['enumbins'] = 300  # Factor ~3 oversampling of IRF
        ctedispcube['coordsys'] = 'CEL'
        ctedispcube['proj'] = 'TAN'
        ctedispcube['xref'] = 258.1125
        ctedispcube['yref'] = -39.6867
        ctedispcube['nxpix'] = 30
        ctedispcube['nypix'] = 30
        ctedispcube['binsz'] = 0.2
        ctedispcube['migramax'] = 5.0
        ctedispcube['migrabins'] = 300
        ctedispcube['outcube'] = edispcube
        ctedispcube['logfile'] = 'rx_hess_create_edispcube.log'
        ctedispcube.logFileOpen()

        # Generate energy dispersion cube
        ctedispcube.execute()

    # Continue only if background cube does not exist
    if not os.path.isfile(bkgcube):

        # Setup task parameters
        ctbkgcube = ctools.ctbkgcube()
        ctbkgcube['inobs'] = obsname
        ctbkgcube['incube'] = cntcube
        ctbkgcube['inmodel'] = bkgname
        ctbkgcube['outcube'] = bkgcube
        ctbkgcube['outmodel'] = bkgname_stacked
        ctbkgcube['logfile'] = 'rx_hess_create_bkgcube.log'
        ctbkgcube.logFileOpen()

        # Generate background cube
        ctbkgcube.execute()

    # Continue only if stacked observation definition XML file does not
    # exist
    if not os.path.isfile(obsname_stacked):

        # Build stacked observation
        run = gammalib.GCTAObservation(cntcube, expcube, psfcube, bkgcube)
        run.name('RX J1713.7-3946')
        run.instrument('HESS')

        # Append to observation container
        obs = gammalib.GObservations()
        obs.append(run)

        # Save observation container
        obs.save(obsname_stacked)

    # Continue only if stacked observation definition XML file with energy
    # energy dispersion enabled does not exist
    if not os.path.isfile(obsname_stacked_edisp):

        # Build stacked observation
        run = gammalib.GCTAObservation(cntcube, expcube, psfcube, edispcube,
                                       bkgcube)
        run.name('RX J1713.7-3946')
        run.instrument('HESS')

        # Append to observation container
        obs = gammalib.GObservations()
        obs.append(run)

        # Save observation container
        obs.save(obsname_stacked_edisp)

    # Continue only if stacked model definition XML file does exist
    if os.path.isfile(bkgname_stacked):

        # Load model definition XML files
        joint = gammalib.GModels(bkgname)
        stacked = gammalib.GModels(bkgname_stacked)

        # Get spectral component of joint file and remplace it as spectral
        # component of stacked file
        spectrum = joint[0].spectral()
        for i in range(spectrum.nodes()):
            spectrum.intensity(i, 1.0)
        spectrum.autoscale()
        stacked[0].spectral(spectrum)

        # Save stacked model
        stacked.save(bkgname_stacked)

    # Return
    return
Exemple #5
0
def edisp_cube(output_dir,
               map_coord,
               map_fov,
               emin,
               emax,
               enumbins,
               ebinalg,
               binsz=1.0,
               migramax=2.0,
               migrabins=100,
               logfile=None,
               silent=False):
    """
    Compute an energy dispersion cube.
    http://cta.irap.omp.eu/ctools/users/reference_manual/ctedispcube.html
    Note that the number of point in energy corresponds to the bin poles.

    Parameters
    ----------
    - output_dir (str): directory where to get input files and 
    save outputs
    - map_coord (float): a skycoord object that give the center of the map
    - map_fov (float): the field of view of the map (can be an 
    astropy.unit object, or in deg)
    - emin/emax (float): min and max energy in TeV
    - enumbins (int): the number of energy bins
    - ebinalg (str): the energy binning algorithm
    - binsz (float): map resolution in deg. Small variation of edisp, so 
    no need to set it to small values
    - migramax (float): Upper bound of ratio between reconstructed and 
    true photon energy.
    - migrabins (int): Number of migration bins.
    - silent (bool): use this keyword to print information

    Outputs
    --------
    - Ana_Edispcube.fits: the energy dispersion fits file
    """

    npix = utilities.npix_from_fov_def(map_fov.to_value('deg'), binsz)

    edcube = ctools.ctedispcube()

    edcube['inobs'] = output_dir + '/Ana_EventsSelected.xml'
    edcube['incube'] = 'NONE'  #output_dir+'/Ana_Countscube.fits'
    #edcube['caldb']    =
    #edcube['irf']      =
    edcube['outcube'] = output_dir + '/Ana_Edispcube.fits'
    edcube['ebinalg'] = ebinalg
    edcube['emin'] = emin.to_value('TeV')
    edcube['emax'] = emax.to_value('TeV')
    edcube['enumbins'] = enumbins
    edcube['ebinfile'] = 'NONE'
    edcube['addbounds'] = False
    edcube['usepnt'] = False
    edcube['nxpix'] = npix
    edcube['nypix'] = npix
    edcube['binsz'] = binsz
    edcube['coordsys'] = 'CEL'
    edcube['proj'] = 'TAN'
    edcube['xref'] = map_coord.icrs.ra.to_value('deg')
    edcube['yref'] = map_coord.icrs.dec.to_value('deg')
    edcube['migramax'] = migramax
    edcube['migrabins'] = migrabins
    if logfile is not None: edcube['logfile'] = logfile

    if logfile is not None: edcube.logFileOpen()
    edcube.execute()
    if logfile is not None: edcube.logFileClose()

    if not silent:
        print(edcube)
        print('')

    return edcube
Exemple #6
0
        bkgcube = ctools.ctbkgcube()
        bkgcube['inobs'] = 'events_nu_' + irf + '_' + str(
            int(tobscta)) + 's_' + str(i + 1) + '.fits'
        bkgcube['caldb'] = caldb
        bkgcube['irf'] = irf
        bkgcube['inmodel'] = 'nu_sources_' + str(i + 1) + '.xml'
        bkgcube['incube'] = 'cntcube_nu_' + irf + '_' + str(
            int(tobscta)) + 's_' + str(i + 1) + '.fits'
        bkgcube['outcube'] = 'bkgcube_nu_' + irf + '_' + str(
            int(tobscta)) + 's_' + str(i + 1) + '.fits'
        bkgcube['outmodel'] = 'stacked_nu_' + irf + '_' + str(
            int(tobscta)) + 's_' + str(i + 1) + '.xml'
        bkgcube['debug'] = debug
        bkgcube.execute()

        edispcube = ctools.ctedispcube()
        edispcube['inobs'] = 'events_nu_' + irf + '_' + str(
            int(tobscta)) + 's_' + str(i + 1) + '.fits'
        edispcube['caldb'] = caldb
        edispcube['irf'] = irf
        edispcube['incube'] = 'NONE'
        edispcube['ebinalg'] = 'LOG'
        edispcube['emin'] = 0.02
        edispcube['emax'] = 199.0
        edispcube['enumbins'] = 40
        edispcube['nxpix'] = 12
        edispcube['nypix'] = 12
        edispcube['binsz'] = 1.0
        edispcube['coordsys'] = 'CEL'
        edispcube['proj'] = 'CAR'
        edispcube['xref'] = ra
Exemple #7
0
def get_stacked_response(obs, xref, yref, binsz=0.05, nxpix=200, nypix=200,
                         emin=0.1, emax=100.0, enumbins=20, edisp=False,
                         coordsys='GAL', proj='TAN', addbounds=False,
                         log=False, debug=False, chatter=2):
    """
    Get stacked response cubes

    The number of energies bins are set to at least 30 bins per decade, and
    the "enumbins" parameter is only used if the number of bins is larger
    than 30 bins per decade.

    If the xref or yref arguments are "None" the response cube centre will be
    determined from the pointing information in the observation container.

    Parameters
    ----------
    obs : `~gammalib.GObservations`
        Observation container
    xref : float
        Right Ascension or Galactic longitude of response centre (deg)
    yref : float
        Declination or Galactic latitude of response centre (deg)
    binsz : float, optional
        Pixel size (deg/pixel)
    nxpix : int, optional
        Number of pixels in X direction
    nypix : int, optional
        Number of pixels in Y direction
    emin : float, optional
        Minimum energy (TeV)
    emax : float, optional
        Maximum energy (TeV)
    enumbins : int, optional
        Number of energy bins
    edisp : bool, optional
        Apply energy dispersion?
    coordsys : str, optional
        Coordinate system
    proj : str, optional
        Projection
    addbounds : bool, optional
        Add boundaries at observation energies
    log : bool, optional
        Create log file(s)
    debug : bool, optional
        Create console dump?
    chatter : int, optional
        Chatter level

    Returns
    -------
    result : dict
        Dictionary of response cubes
    """
    # If no xref and yref arguments have been specified then use the pointing
    # information
    if xref == None or yref == None:
        usepnt = True
    else:
        usepnt = False

    # Set number of energy bins to at least 30 per energy decade
    _enumbins = int((math.log10(emax) - math.log10(emin)) * 30.0)
    if enumbins > _enumbins:
        _enumbins = enumbins

    # Compute spatial binning for point spread function and energy dispersion
    # cubes. The spatial binning is 10 times coarser than the spatial binning
    # of the exposure and background cubes. At least 2 spatial are required.
    psf_binsz = 10.0 * binsz
    psf_nxpix = max(nxpix // 10, 2)  # Make sure result is int
    psf_nypix = max(nypix // 10, 2)  # Make sure result is int

    # Create exposure cube
    expcube = ctools.ctexpcube(obs)
    expcube['incube']    = 'NONE'
    expcube['usepnt']    = usepnt
    expcube['ebinalg']   = 'LOG'
    expcube['binsz']     = binsz
    expcube['nxpix']     = nxpix
    expcube['nypix']     = nypix
    expcube['enumbins']  = _enumbins
    expcube['emin']      = emin
    expcube['emax']      = emax
    expcube['coordsys']  = coordsys
    expcube['proj']      = proj
    expcube['addbounds'] = addbounds
    expcube['debug']     = debug
    expcube['chatter']   = chatter
    if not usepnt:
        expcube['xref'] = xref
        expcube['yref'] = yref
    if log:
        expcube.logFileOpen()
    expcube.run()

    # Create point spread function cube
    psfcube = ctools.ctpsfcube(obs)
    psfcube['incube']    = 'NONE'
    psfcube['usepnt']    = usepnt
    psfcube['ebinalg']   = 'LOG'
    psfcube['binsz']     = psf_binsz
    psfcube['nxpix']     = psf_nxpix
    psfcube['nypix']     = psf_nypix
    psfcube['enumbins']  = _enumbins
    psfcube['emin']      = emin
    psfcube['emax']      = emax
    psfcube['coordsys']  = coordsys
    psfcube['proj']      = proj
    psfcube['addbounds'] = addbounds
    psfcube['debug']     = debug
    psfcube['chatter']   = chatter
    if not usepnt:
        psfcube['xref'] = xref
        psfcube['yref'] = yref
    if log:
        psfcube.logFileOpen()
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(obs)
    bkgcube['incube']    = 'NONE'
    bkgcube['usepnt']    = usepnt
    bkgcube['ebinalg']   = 'LOG'
    bkgcube['binsz']     = binsz
    bkgcube['nxpix']     = nxpix
    bkgcube['nypix']     = nypix
    bkgcube['enumbins']  = _enumbins
    bkgcube['emin']      = emin
    bkgcube['emax']      = emax
    bkgcube['coordsys']  = coordsys
    bkgcube['proj']      = proj
    bkgcube['addbounds'] = addbounds
    bkgcube['debug']     = debug
    bkgcube['chatter']   = chatter
    if not usepnt:
        bkgcube['xref'] = xref
        bkgcube['yref'] = yref
    if log:
        bkgcube.logFileOpen()
    bkgcube.run()

    # If energy dispersion is requested then create energy dispersion cube
    if edisp:
        edispcube = ctools.ctedispcube(obs)
        edispcube['incube']    = 'NONE'
        edispcube['usepnt']    = usepnt
        edispcube['ebinalg']   = 'LOG'
        edispcube['binsz']     = psf_binsz
        edispcube['nxpix']     = psf_nxpix
        edispcube['nypix']     = psf_nypix
        edispcube['enumbins']  = _enumbins
        edispcube['emin']      = emin
        edispcube['emax']      = emax
        edispcube['coordsys']  = coordsys
        edispcube['proj']      = proj
        edispcube['addbounds'] = addbounds
        edispcube['debug']     = debug
        edispcube['chatter']   = chatter
        if not usepnt:
            edispcube['xref'] = xref
            edispcube['yref'] = yref
        if log:
            edispcube.logFileOpen()
        edispcube.run()

    # Build response dictionary
    response = {}
    response['expcube'] = expcube.expcube().copy()
    response['psfcube'] = psfcube.psfcube().copy()
    response['bkgcube'] = bkgcube.bkgcube().copy()
    response['models']  = bkgcube.models().copy()
    if edisp:
        response['edispcube'] = edispcube.edispcube().copy()

    # Return response cubes
    return response
Exemple #8
0
    def _bin_observation(self, obs):
        """
        Bin an observation is a binned analysis was requested.

        Args:
            obs: Observation container.

        Returns:
            Observation container with a binned.
        """
        # Header
        if self._logExplicit():
            self._log.header3("Binning events")

        # Bin events
        cntcube = ctools.ctbin(obs)
        cntcube["usepnt"] = False
        cntcube["ebinalg"] = "LOG"
        cntcube["xref"] = self["xref"].real()
        cntcube["yref"] = self["yref"].real()
        cntcube["binsz"] = self["binsz"].real()
        cntcube["nxpix"] = self["nxpix"].integer()
        cntcube["nypix"] = self["nypix"].integer()
        cntcube["enumbins"] = self["enumbins"].integer()
        cntcube["emin"] = self["emin"].real()
        cntcube["emax"] = self["emax"].real()
        cntcube["coordsys"] = self["coordsys"].string()
        cntcube["proj"] = self["proj"].string()
        cntcube.run()

        # Header
        if self._logExplicit():
            self._log.header3("Creating exposure cube")

        # Create exposure cube
        expcube = ctools.ctexpcube(obs)
        expcube["incube"] = "NONE"
        expcube["usepnt"] = False
        expcube["ebinalg"] = "LOG"
        expcube["xref"] = self["xref"].real()
        expcube["yref"] = self["yref"].real()
        expcube["binsz"] = self["binsz"].real()
        expcube["nxpix"] = self["nxpix"].integer()
        expcube["nypix"] = self["nypix"].integer()
        expcube["enumbins"] = self["enumbins"].integer()
        expcube["emin"] = self["emin"].real()
        expcube["emax"] = self["emax"].real()
        expcube["coordsys"] = self["coordsys"].string()
        expcube["proj"] = self["proj"].string()
        expcube.run()

        # Header
        if self._logExplicit():
            self._log.header3("Creating point spread function cube")

        # Compute spatial binning for point spread function and
        # energy dispersion cubes
        binsz = 10.0 * self["binsz"].real()
        nxpix = self["nxpix"].integer() // 10  # Make sure result is int
        nypix = self["nypix"].integer() // 10  # Make sure result is int
        if nxpix < 2:
            nxpix = 2
        if nypix < 2:
            nypix = 2

        # Create point spread function cube
        psfcube = ctools.ctpsfcube(obs)
        psfcube["incube"] = "NONE"
        psfcube["usepnt"] = False
        psfcube["ebinalg"] = "LOG"
        psfcube["xref"] = self["xref"].real()
        psfcube["yref"] = self["yref"].real()
        psfcube["binsz"] = binsz
        psfcube["nxpix"] = nxpix
        psfcube["nypix"] = nypix
        psfcube["enumbins"] = self["enumbins"].integer()
        psfcube["emin"] = self["emin"].real()
        psfcube["emax"] = self["emax"].real()
        psfcube["coordsys"] = self["coordsys"].string()
        psfcube["proj"] = self["proj"].string()
        psfcube.run()

        # Check if we need to include energy dispersion
        if self["edisp"].boolean():

            # Header
            if self._logExplicit():
                self._log.header3("Creating energy dispersion cube")

            # Create energy dispersion cube
            edispcube = ctools.ctedispcube(obs)
            edispcube["incube"] = "NONE"
            edispcube["usepnt"] = False
            edispcube["ebinalg"] = "LOG"
            edispcube["xref"] = self["xref"].real()
            edispcube["yref"] = self["yref"].real()
            edispcube["binsz"] = binsz
            edispcube["nxpix"] = nxpix
            edispcube["nypix"] = nypix
            edispcube["enumbins"] = self["enumbins"].integer()
            edispcube["emin"] = self["emin"].real()
            edispcube["emax"] = self["emax"].real()
            edispcube["coordsys"] = self["coordsys"].string()
            edispcube["proj"] = self["proj"].string()
            edispcube.run()

        # Header
        if self._logExplicit():
            self._log.header3("Creating background cube")

        # Create background cube
        bkgcube = ctools.ctbkgcube(obs)
        bkgcube["incube"] = "NONE"
        bkgcube["usepnt"] = False
        bkgcube["ebinalg"] = "LOG"
        bkgcube["xref"] = self["xref"].real()
        bkgcube["yref"] = self["yref"].real()
        bkgcube["binsz"] = self["binsz"].real()
        bkgcube["nxpix"] = self["nxpix"].integer()
        bkgcube["nypix"] = self["nypix"].integer()
        bkgcube["enumbins"] = self["enumbins"].integer()
        bkgcube["emin"] = self["emin"].real()
        bkgcube["emax"] = self["emax"].real()
        bkgcube["coordsys"] = self["coordsys"].string()
        bkgcube["proj"] = self["proj"].string()
        bkgcube.run()

        # Retrieve a new oberservation container
        new_obs = cntcube.obs().copy()

        # Get new models
        models = bkgcube.models()

        # Set stacked response
        if self["edisp"].boolean():
            new_obs[0].response(expcube.expcube(), psfcube.psfcube(),
                                edispcube.edispcube(), bkgcube.bkgcube())
        else:
            new_obs[0].response(expcube.expcube(), psfcube.psfcube(),
                                bkgcube.bkgcube())

        # Fix background models if required
        if self["fix_bkg"].boolean():
            for model in models:
                if model.classname() != "GModelSky":
                    for par in model:
                        par.fix()

        # Set models for new oberservation container
        new_obs.models(models)

        # Return new oberservation container
        return new_obs
Exemple #9
0
    def _set_stacked_irf(self):
        """
        Prepare stacked IRFs for stacked analysis
        """
        # Write header into logger
        if self._logTerse():
            self._log('\n')
            self._log.header1('Compute stacked response')

        # Set number of energy bins to at least 30 per energy decade
        enumbins = int((math.log10(self['emax'].real()) -
                        math.log10(self['emin'].real())) * 30.0)
        if self._enumbins > enumbins:
            enumbins = self._enumbins

        # Compute spatial binning for point spread function and
        # energy dispersion cubes
        binsz = 10.0 * self['binsz'].real()
        nxpix = self['npix'].integer() // 10  # Make sure result is int
        nypix = self['npix'].integer() // 10  # Make sure result is int
        if nxpix < 2:
            nxpix = 2
        if nypix < 2:
            nypix = 2

        # Get stacked exposure
        expcube = ctools.ctexpcube(self._obs)
        expcube['incube']   = 'NONE'
        expcube['usepnt']   = True
        expcube['ebinalg']  = 'LOG'
        expcube['binsz']    = self._binsz
        expcube['nxpix']    = self._npix
        expcube['nypix']    = self._npix
        expcube['enumbins'] = enumbins
        expcube['emin']     = self['emin'].real()
        expcube['emax']     = self['emax'].real()
        expcube['coordsys'] = self._coordsys
        expcube['proj']     = self._proj
        expcube['chatter']  = self._chatter
        expcube['debug']    = self._logDebug()
        expcube.run()

        # Notify exposure computation
        if self._logTerse():
            self._log('Computed exposure cube\n')

        # Get stacked Psf
        psfcube = ctools.ctpsfcube(self._obs)
        psfcube['incube']   = 'NONE'
        psfcube['usepnt']   = True
        psfcube['ebinalg']  = 'LOG'
        psfcube['binsz']    = binsz
        psfcube['nxpix']    = nxpix
        psfcube['nypix']    = nypix
        psfcube['enumbins'] = enumbins
        psfcube['emin']     = self['emin'].real()
        psfcube['emax']     = self['emax'].real()
        psfcube['coordsys'] = self._coordsys
        psfcube['proj']     = self._proj
        psfcube['chatter']  = self._chatter
        psfcube['debug']    = self._logDebug()
        psfcube.run()

        # Notify Psf computation
        if self._logTerse():
            self._log('Computed point spread function cube\n')

        # Optionally get stacked Edisp
        if self._edisp:
            edispcube = ctools.ctedispcube(self._obs)
            edispcube['incube']   = 'NONE'
            edispcube['usepnt']   = True
            edispcube['ebinalg']  = 'LOG'
            edispcube['binsz']    = binsz
            edispcube['nxpix']    = nxpix
            edispcube['nypix']    = nypix
            edispcube['enumbins'] = enumbins
            edispcube['emin']     = self['emin'].real()
            edispcube['emax']     = self['emax'].real()
            edispcube['coordsys'] = self._coordsys
            edispcube['proj']     = self._proj
            edispcube['chatter']  = self._chatter
            edispcube['debug']    = self._logDebug()
            edispcube.run()

            # Store result
            self._edispcube = edispcube.edispcube().copy()
            
            # Logging
            if self._logTerse():
                self._log('Computed energy dispersion cube\n')

        # Get stacked background
        bkgcube = ctools.ctbkgcube(self._obs)
        bkgcube['incube']   = 'NONE'
        bkgcube['usepnt']   = True
        bkgcube['ebinalg']  = 'LOG'
        bkgcube['binsz']    = self._binsz
        bkgcube['nxpix']    = self._npix
        bkgcube['nypix']    = self._npix
        bkgcube['enumbins'] = enumbins
        bkgcube['emin']     = self['emin'].real()
        bkgcube['emax']     = self['emax'].real()
        bkgcube['coordsys'] = self._coordsys
        bkgcube['proj']     = self._proj
        bkgcube['chatter']  = self._chatter
        bkgcube['debug']    = self._logDebug()
        bkgcube.run()

        # Notify background cube computation
        if self._logTerse():
            self._log('Computed background cube\n')

        # Store results
        self._exposure    = expcube.expcube().copy()
        self._psfcube     = psfcube.psfcube().copy()
        self._bckcube     = bkgcube.bkgcube().copy()
        self._stackmodels = bkgcube.models().copy()

        # Return
        return
Exemple #10
0
    def _test_python(self):
        """
        Test ctedispcube from Python
        """
        # Allocate ctedispcube
        edispcube = ctools.ctedispcube()

        # Check that empty ctedispcube tool holds an energy dispersion
        # cube that has no energy and migration bins
        self._check_cube(edispcube.edispcube(), nenergies=0, nmigras=0)

        # Check that saving does not nothing
        edispcube['outcube'] = 'ctedispcube_py0.fits'
        edispcube['logfile'] = 'ctedispcube_py0.log'
        edispcube.logFileOpen()
        edispcube.save()
        self.test_assert(not os.path.isfile('ctedispcube_py0.fits'),
             'Check that no energy dispersion cube has been created')

        # Check that clearing does not lead to an exception or segfault
        edispcube.clear()

        # Now set ctedispcube parameters
        edispcube['inobs']     = self._events
        edispcube['incube']    = 'NONE'
        edispcube['caldb']     = self._caldb
        edispcube['irf']       = self._irf
        edispcube['ebinalg']   = 'LOG'
        edispcube['emin']      = 0.1
        edispcube['emax']      = 100.0
        edispcube['enumbins']  = 20
        edispcube['nxpix']     = 10
        edispcube['nypix']     = 10
        edispcube['binsz']     = 0.4
        edispcube['coordsys']  = 'CEL'
        edispcube['proj']      = 'CAR'
        edispcube['xref']      = 83.63
        edispcube['yref']      = 22.01
        edispcube['migramax']  = 2.0
        edispcube['migrabins'] = 10
        edispcube['outcube']   = 'ctedispcube_py1.fits'
        edispcube['logfile']   = 'ctedispcube_py1.log'
        edispcube['chatter']   = 2

        # Run ctedispcube tool
        edispcube.logFileOpen()  # Make sure we get a log file
        edispcube.run()
        edispcube.save()

        # Check result file
        self._check_result_file('ctedispcube_py1.fits')

        # Copy ctedispcube tool
        cpy_edispcube = edispcube.copy()

        # Check energy dispersion cube of ctedispcube copy
        self._check_cube(cpy_edispcube.edispcube())

        # Execute copy of ctedispcube tool again, now with a higher chatter
        # level than before
        cpy_edispcube['emin']      = 0.2
        cpy_edispcube['emax']      = 150.0
        cpy_edispcube['outcube']   = 'ctedispcube_py2.fits'
        cpy_edispcube['logfile']   = 'ctedispcube_py2.log'
        cpy_edispcube['addbounds'] = True
        cpy_edispcube['chatter']   = 3
        cpy_edispcube.logFileOpen()  # Needed to get a new log file
        cpy_edispcube.execute()

        # Check result file
        self._check_result_file('ctedispcube_py2.fits', nenergies=23)

        # Now clear copy of ctedispcube tool
        cpy_edispcube.clear()

        # Check that the cleared copy has also cleared the energy dispersion
        # cube
        self._check_cube(cpy_edispcube.edispcube(), nenergies=0, nmigras=0)

        # Get mixed observation container
        obs = self._obs_mixed()

        # Set-up ctedispcube from observation container
        edispcube = ctools.ctedispcube(obs)
        edispcube['incube']    = 'NONE'
        edispcube['caldb']     = self._caldb
        edispcube['irf']       = self._irf
        edispcube['ebinalg']   = 'LOG'
        edispcube['emin']      = 0.1
        edispcube['emax']      = 100.0
        edispcube['enumbins']  = 20
        edispcube['nxpix']     = 10
        edispcube['nypix']     = 10
        edispcube['binsz']     = 0.4
        edispcube['coordsys']  = 'CEL'
        edispcube['proj']      = 'CAR'
        edispcube['xref']      = 83.63
        edispcube['yref']      = 22.01
        edispcube['migramax']  = 2.0
        edispcube['migrabins'] = 10
        edispcube['addbounds'] = True
        edispcube['outcube']   = 'ctedispcube_py3.fits'
        edispcube['logfile']   = 'ctedispcube_py3.log'
        edispcube['chatter']   = 4

        # Execute ctedispcube tool
        edispcube.logFileOpen()  # Make sure we get a log file
        edispcube.execute()

        # Check result file
        self._check_result_file('ctedispcube_py3.fits')

        # Return
        return
Exemple #11
0
def get_stacked_response(obs,
                         xref,
                         yref,
                         binsz=0.05,
                         nxpix=200,
                         nypix=200,
                         emin=0.1,
                         emax=100.0,
                         enumbins=20,
                         edisp=False,
                         coordsys='GAL',
                         proj='TAN',
                         addbounds=False,
                         log=False,
                         debug=False,
                         chatter=2):
    """
    Get stacked response cubes

    The number of energies bins are set to at least 30 bins per decade, and
    the "enumbins" parameter is only used if the number of bins is larger
    than 30 bins per decade.

    If the xref or yref arguments are "None" the response cube centre will be
    determined from the pointing information in the observation container.

    Parameters
    ----------
    obs : `~gammalib.GObservations`
        Observation container
    xref : float
        Right Ascension or Galactic longitude of response centre (deg)
    yref : float
        Declination or Galactic latitude of response centre (deg)
    binsz : float, optional
        Pixel size (deg/pixel)
    nxpix : int, optional
        Number of pixels in X direction
    nypix : int, optional
        Number of pixels in Y direction
    emin : float, optional
        Minimum energy (TeV)
    emax : float, optional
        Maximum energy (TeV)
    enumbins : int, optional
        Number of energy bins
    edisp : bool, optional
        Apply energy dispersion?
    coordsys : str, optional
        Coordinate system
    proj : str, optional
        Projection
    addbounds : bool, optional
        Add boundaries at observation energies
    log : bool, optional
        Create log file(s)
    debug : bool, optional
        Create console dump?
    chatter : int, optional
        Chatter level

    Returns
    -------
    result : dict
        Dictionary of response cubes
    """
    # If no xref and yref arguments have been specified then use the pointing
    # information
    if xref == None or yref == None:
        usepnt = True
    else:
        usepnt = False

    # Set number of energy bins to at least 30 per energy decade
    _enumbins = int((math.log10(emax) - math.log10(emin)) * 30.0)
    if enumbins > _enumbins:
        _enumbins = enumbins

    # Compute spatial binning for point spread function and energy dispersion
    # cubes. The spatial binning is 10 times coarser than the spatial binning
    # of the exposure and background cubes. At least 2 spatial are required.
    psf_binsz = 10.0 * binsz
    psf_nxpix = max(nxpix // 10, 2)  # Make sure result is int
    psf_nypix = max(nypix // 10, 2)  # Make sure result is int

    # Create exposure cube
    expcube = ctools.ctexpcube(obs)
    expcube['incube'] = 'NONE'
    expcube['usepnt'] = usepnt
    expcube['ebinalg'] = 'LOG'
    expcube['binsz'] = binsz
    expcube['nxpix'] = nxpix
    expcube['nypix'] = nypix
    expcube['enumbins'] = _enumbins
    expcube['emin'] = emin
    expcube['emax'] = emax
    expcube['coordsys'] = coordsys
    expcube['proj'] = proj
    expcube['addbounds'] = addbounds
    expcube['debug'] = debug
    expcube['chatter'] = chatter
    if not usepnt:
        expcube['xref'] = xref
        expcube['yref'] = yref
    if log:
        expcube.logFileOpen()
    expcube.run()

    # Create point spread function cube
    psfcube = ctools.ctpsfcube(obs)
    psfcube['incube'] = 'NONE'
    psfcube['usepnt'] = usepnt
    psfcube['ebinalg'] = 'LOG'
    psfcube['binsz'] = psf_binsz
    psfcube['nxpix'] = psf_nxpix
    psfcube['nypix'] = psf_nypix
    psfcube['enumbins'] = _enumbins
    psfcube['emin'] = emin
    psfcube['emax'] = emax
    psfcube['coordsys'] = coordsys
    psfcube['proj'] = proj
    psfcube['addbounds'] = addbounds
    psfcube['debug'] = debug
    psfcube['chatter'] = chatter
    if not usepnt:
        psfcube['xref'] = xref
        psfcube['yref'] = yref
    if log:
        psfcube.logFileOpen()
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(obs)
    bkgcube['incube'] = 'NONE'
    bkgcube['usepnt'] = usepnt
    bkgcube['ebinalg'] = 'LOG'
    bkgcube['binsz'] = binsz
    bkgcube['nxpix'] = nxpix
    bkgcube['nypix'] = nypix
    bkgcube['enumbins'] = _enumbins
    bkgcube['emin'] = emin
    bkgcube['emax'] = emax
    bkgcube['coordsys'] = coordsys
    bkgcube['proj'] = proj
    bkgcube['addbounds'] = addbounds
    bkgcube['debug'] = debug
    bkgcube['chatter'] = chatter
    if not usepnt:
        bkgcube['xref'] = xref
        bkgcube['yref'] = yref
    if log:
        bkgcube.logFileOpen()
    bkgcube.run()

    # If energy dispersion is requested then create energy dispersion cube
    if edisp:
        edispcube = ctools.ctedispcube(obs)
        edispcube['incube'] = 'NONE'
        edispcube['usepnt'] = usepnt
        edispcube['ebinalg'] = 'LOG'
        edispcube['binsz'] = psf_binsz
        edispcube['nxpix'] = psf_nxpix
        edispcube['nypix'] = psf_nypix
        edispcube['enumbins'] = _enumbins
        edispcube['emin'] = emin
        edispcube['emax'] = emax
        edispcube['coordsys'] = coordsys
        edispcube['proj'] = proj
        edispcube['addbounds'] = addbounds
        edispcube['debug'] = debug
        edispcube['chatter'] = chatter
        if not usepnt:
            edispcube['xref'] = xref
            edispcube['yref'] = yref
        if log:
            edispcube.logFileOpen()
        edispcube.run()

    # Build response dictionary
    response = {}
    response['expcube'] = expcube.expcube().copy()
    response['psfcube'] = psfcube.psfcube().copy()
    response['bkgcube'] = bkgcube.bkgcube().copy()
    response['models'] = bkgcube.models().copy()
    if edisp:
        response['edispcube'] = edispcube.edispcube().copy()

    # Return response cubes
    return response
Exemple #12
0
    def _test_python(self):
        """
        Test ctedispcube from Python
        """
        # Allocate ctedispcube
        edispcube = ctools.ctedispcube()

        # Check that empty ctedispcube tool holds an energy dispersion
        # cube that has no energy and migration bins
        self._check_cube(edispcube.edispcube(), nenergies=0, nmigras=0)

        # Check that saving does not nothing
        edispcube['outcube'] = 'ctedispcube_py0.fits'
        edispcube['logfile'] = 'ctedispcube_py0.log'
        edispcube.logFileOpen()
        edispcube.save()
        self.test_assert(
            not os.path.isfile('ctedispcube_py0.fits'),
            'Check that no energy dispersion cube has been created')

        # Check that clearing does not lead to an exception or segfault
        edispcube.clear()

        # Now set ctedispcube parameters
        edispcube['inobs'] = self._events
        edispcube['incube'] = 'NONE'
        edispcube['caldb'] = self._caldb
        edispcube['irf'] = self._irf
        edispcube['ebinalg'] = 'LOG'
        edispcube['emin'] = 1.0
        edispcube['emax'] = 100.0
        edispcube['enumbins'] = 5
        edispcube['nxpix'] = 10
        edispcube['nypix'] = 10
        edispcube['binsz'] = 0.4
        edispcube['coordsys'] = 'CEL'
        edispcube['proj'] = 'CAR'
        edispcube['xref'] = 83.63
        edispcube['yref'] = 22.01
        edispcube['migramax'] = 2.0
        edispcube['migrabins'] = 10
        edispcube['outcube'] = 'ctedispcube_py1.fits'
        edispcube['logfile'] = 'ctedispcube_py1.log'
        edispcube['chatter'] = 2

        # Run ctedispcube tool
        edispcube.logFileOpen()  # Make sure we get a log file
        edispcube.run()
        edispcube.save()

        # Check result file
        self._check_result_file('ctedispcube_py1.fits')

        # Copy ctedispcube tool
        cpy_edispcube = edispcube.copy()

        # Check energy dispersion cube of ctedispcube copy
        self._check_cube(cpy_edispcube.edispcube())

        # Execute copy of ctedispcube tool again, now with a higher chatter
        # level than before
        cpy_edispcube['emin'] = 0.2
        cpy_edispcube['emax'] = 150.0
        cpy_edispcube['outcube'] = 'ctedispcube_py2.fits'
        cpy_edispcube['logfile'] = 'ctedispcube_py2.log'
        cpy_edispcube['addbounds'] = True
        cpy_edispcube['chatter'] = 3
        cpy_edispcube.logFileOpen()  # Needed to get a new log file
        cpy_edispcube.execute()

        # Check result file
        self._check_result_file('ctedispcube_py2.fits', nenergies=8)

        # Now clear copy of ctedispcube tool
        cpy_edispcube.clear()

        # Check that the cleared copy has also cleared the energy dispersion
        # cube
        self._check_cube(cpy_edispcube.edispcube(), nenergies=0, nmigras=0)

        # Get mixed observation container
        obs = self._obs_mixed()

        # Set-up ctedispcube from observation container
        edispcube = ctools.ctedispcube(obs)
        edispcube['incube'] = 'NONE'
        edispcube['caldb'] = self._caldb
        edispcube['irf'] = self._irf
        edispcube['ebinalg'] = 'LOG'
        edispcube['emin'] = 1.0
        edispcube['emax'] = 100.0
        edispcube['enumbins'] = 5
        edispcube['nxpix'] = 10
        edispcube['nypix'] = 10
        edispcube['binsz'] = 0.4
        edispcube['coordsys'] = 'CEL'
        edispcube['proj'] = 'CAR'
        edispcube['xref'] = 83.63
        edispcube['yref'] = 22.01
        edispcube['migramax'] = 2.0
        edispcube['migrabins'] = 10
        edispcube['addbounds'] = True
        edispcube['outcube'] = 'ctedispcube_py3.fits'
        edispcube['logfile'] = 'ctedispcube_py3.log'
        edispcube['chatter'] = 4

        # Execute ctedispcube tool
        edispcube.logFileOpen()  # Make sure we get a log file
        edispcube.execute()

        # Check result file
        self._check_result_file('ctedispcube_py3.fits')

        # Set-up ctexpcube from event list and counts cube
        edispcube = ctools.ctedispcube()
        edispcube['inobs'] = self._events
        edispcube['incube'] = self._cntcube
        edispcube['caldb'] = self._caldb
        edispcube['irf'] = self._irf
        edispcube['migramax'] = 2.0
        edispcube['migrabins'] = 10
        edispcube['outcube'] = 'ctedispcube_py4.fits'
        edispcube['logfile'] = 'ctedispcube_py4.log'
        edispcube['chatter'] = 2

        # Run ctedispcube tool
        edispcube.logFileOpen()  # Make sure we get a log file
        edispcube.execute()

        # Check result file
        self._check_result_file('ctedispcube_py4.fits')

        # Return
        return