Beispiel #1
0
    def ctbkgcube(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 ctbkgcube to compute the predicted background rate")

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

        self.ctbkgcube["incube"] = self.config['file']["cntcube"]
        self.ctbkgcube["outcube"] = self.config['file']["bkgcube"]

        self.ctbkgcube["outmodel"] = self.config['out']+"/binned_models.xml"
        self.config["file"]["inmodel"] = self.config['out']+"/binned_models.xml"

        if self.verbose:
            print self.ctbkgcube

        self.ctbkgcube.run()

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

        self.ctbkgcube
Beispiel #2
0
    def test_functional(self):
        """
        Test ctbkgcube functionnality.
        """
        # Set-up ctbkgcube
        bkgcube = ctools.ctbkgcube()
        bkgcube["inobs"].filename(self.events_name)
        bkgcube["inmodel"].filename(self.bkg_model)
        bkgcube["incube"].filename("NONE")
        bkgcube["outcube"].filename("bkgcube.fits")
        bkgcube["outmodel"].filename("bkgcube.xml")
        bkgcube["caldb"].string(self.caldb)
        bkgcube["irf"].string(self.irf)
        bkgcube["ebinalg"].string("LOG")
        bkgcube["emin"].real(0.1)
        bkgcube["emax"].real(100.0)
        bkgcube["enumbins"].integer(20)
        bkgcube["nxpix"].integer(10)
        bkgcube["nypix"].integer(10)
        bkgcube["binsz"].real(0.4)
        bkgcube["coordsys"].string("CEL")
        bkgcube["proj"].string("CAR")
        bkgcube["xref"].real(83.63)
        bkgcube["yref"].real(22.01)
        
        # Run tool
        self.test_try("Run ctbkgcube")
        try:
            bkgcube.run()
            self.test_try_success()
        except:
            self.test_try_failure("Exception occured in ctbkgcube.")

        # Save background cube
        self.test_try("Save background cube")
        try:
            bkgcube.save()
            self.test_try_success()
        except:
            self.test_try_failure("Exception occured in saving background cube.")

        # Return
        return
Beispiel #3
0
    def test_functional(self):
        """
        Test ctbkgcube functionnality.
        """
        # Set-up ctbkgcube
        bkgcube = ctools.ctbkgcube()
        bkgcube["inobs"]    = self.events_name
        bkgcube["inmodel"]  = self.bkg_model
        bkgcube["incube"]   = "NONE"
        bkgcube["outcube"]  = "bkgcube.fits"
        bkgcube["outmodel"] = "bkgcube.xml"
        bkgcube["caldb"]    = self.caldb
        bkgcube["irf"]      = self.irf
        bkgcube["ebinalg"]  = "LOG"
        bkgcube["emin"]     = 0.1
        bkgcube["emax"]     = 100
        bkgcube["enumbins"] = 20
        bkgcube["nxpix"]    = 10
        bkgcube["nypix"]    = 10
        bkgcube["binsz"]    = 0.4
        bkgcube["coordsys"] = "CEL"
        bkgcube["proj"]     = "CAR"
        bkgcube["xref"]     = 83.63
        bkgcube["yref"]     = 22.01

        # Run tool
        self.test_try("Run ctbkgcube")
        try:
            bkgcube.run()
            self.test_try_success()
        except:
            self.test_try_failure("Exception occured in ctbkgcube.")

        # Save background cube
        self.test_try("Save background cube")
        try:
            bkgcube.save()
            self.test_try_success()
        except:
            self.test_try_failure("Exception occured in saving background cube.")

        # Return
        return
Beispiel #4
0
def makeCubes(cfg):
    """
    makes exposure, psf and bkg cubes
    """
    outputdir = cfg.getValue('general', 'outputdir')

    if cfg.getValue('general', 'anatype') == 'binned':
        # create exposure map
        expcube = ctools.ctexpcube()
        expcube["inobs"] = outputdir + '/' + cfg.getValue('ctselect', 'output')
        expcube["incube"] = outputdir + '/' + cfg.getValue('ctbin', 'output')
        expcube["outcube"] = outputdir + '/' + \
            cfg.getValue('ctexpcube', 'output')

        expcube.run()
        expcube.save()

        # create exposure map
        psfcube = ctools.ctpsfcube()
        psfcube["inobs"] = outputdir + '/' + cfg.getValue('ctselect', 'output')
        psfcube["incube"] = outputdir + '/' + cfg.getValue('ctbin', 'output')
        psfcube["outcube"] = outputdir + '/' + \
            cfg.getValue('ctpsfcube', 'output')

        psfcube.run()
        psfcube.save()

        # create background cube
        bkgcube = ctools.ctbkgcube()
        bkgcube["inobs"] = outputdir + '/' + cfg.getValue('ctselect', 'output')
        bkgcube["inmodel"] = outputdir + '/' + \
            cfg.getValue('csiactobs', 'model_output')
        bkgcube["incube"] = outputdir + '/' + cfg.getValue('ctbin', 'output')
        bkgcube["outcube"] = outputdir + '/' + \
            cfg.getValue('ctbkgcube', 'output_cube')
        bkgcube["outmodel"] = outputdir + '/' + \
            cfg.getValue('ctbkgcube', 'output_model')
        bkgcube["debug"] = True
        bkgcube["chatter"] = 4
        bkgcube.run()
        bkgcube.save()
Beispiel #5
0
def bkg_cube(output_dir, logfile=None, silent=False):
    """
    Compute a background cube.
    http://cta.irap.omp.eu/ctools/users/reference_manual/ctbkgcube.html

    Parameters
    ----------
    - output_dir (str): directory where to get input files and 
    save outputs
    - silent (bool): use this keyword to print information

    Outputs
    --------
    - Ana_Bkgcube.fits: the fits bkg cube image
    - Ana_Model_Intput_Stack.xml: the xml input model model after
    including the stacked background
    """

    bkgcube = ctools.ctbkgcube()

    bkgcube['inobs'] = output_dir + '/Ana_EventsSelected.xml'
    bkgcube['incube'] = output_dir + '/Ana_Countscube.fits'
    bkgcube['inmodel'] = output_dir + '/Ana_Model_Input_Unstack.xml'
    #bkgcube['caldb']    =
    #bkgcube['irf']      =
    bkgcube['outcube'] = output_dir + '/Ana_Bkgcube.fits'
    bkgcube['outmodel'] = output_dir + '/Ana_Model_Input_Stack.xml'
    if logfile is not None: bkgcube['logfile'] = logfile

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

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

    return bkgcube
def stacked_pipeline(model_name, duration):
    """
    Stacked analysis pipeline.
    """
    # Set script parameters
    caldb = "prod2"
    irf = "South_50h"
    ra = 83.63
    dec = 22.01
    rad_sim = 10.0
    tstart = 0.0
    tstop = duration
    emin = 0.1
    emax = 100.0
    enumbins = 40
    nxpix = 200
    nypix = 200
    binsz = 0.02
    coordsys = "CEL"
    proj = "CAR"

    # Get start CPU time
    cpu_start = time.clock()

    # Simulate events
    sim = ctools.ctobssim()
    sim["inmodel"] = model_name
    sim["caldb"] = caldb
    sim["irf"] = irf
    sim["ra"] = ra
    sim["dec"] = dec
    sim["rad"] = rad_sim
    sim["tmin"] = tstart
    sim["tmax"] = tstop
    sim["emin"] = emin
    sim["emax"] = emax
    sim.run()

    # Bin events into counts map
    bin = ctools.ctbin(sim.obs())
    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"] = ra
    bin["yref"] = dec
    bin.run()

    # Create exposure cube
    expcube = ctools.ctexpcube(sim.obs())
    expcube["incube"] = "NONE"
    expcube["caldb"] = caldb
    expcube["irf"] = irf
    expcube["ebinalg"] = "LOG"
    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"] = ra
    expcube["yref"] = dec
    expcube.run()

    # Create PSF cube
    psfcube = ctools.ctpsfcube(sim.obs())
    psfcube["incube"] = "NONE"
    psfcube["caldb"] = caldb
    psfcube["irf"] = irf
    psfcube["ebinalg"] = "LOG"
    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"] = ra
    psfcube["yref"] = dec
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(sim.obs())
    bkgcube["incube"] = "NONE"
    bkgcube["ebinalg"] = "LOG"
    bkgcube["emin"] = emin
    bkgcube["emax"] = emax
    bkgcube["enumbins"] = enumbins
    bkgcube["nxpix"] = 10
    bkgcube["nypix"] = 10
    bkgcube["binsz"] = 1.0
    bkgcube["coordsys"] = coordsys
    bkgcube["proj"] = proj
    bkgcube["xref"] = ra
    bkgcube["yref"] = dec
    bkgcube.run()

    # 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(),
                          bkgcube.bkgcube())

    # Get ctlike start CPU time
    cpu_ctlike = time.clock()

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    like.run()

    # Get stop CPU time and compute elapsed times
    cpu_stop = time.clock()
    cpu_elapsed = cpu_stop - cpu_start
    cpu_ctlike = cpu_stop - cpu_ctlike

    # Return
    return cpu_elapsed, cpu_ctlike
Beispiel #7
0
    def run(self):
        """
        Run the script.
        """
        # Switch screen logging on in debug mode
        if self.logDebug():
            self.log.cout(True)

        # Get parameters
        self.get_parameters()
        
        #  Write input parameters into logger
        if self.logTerse():
            self.log_parameters()
            self.log("\n")
        
        # Write observation into logger
        if self.logTerse():
            self.log("\n")
            self.log.header1("Observation")
            self.log(str(self.obs))
            self.log("\n")

        # Write header
        if self.logTerse():
            self.log("\n")
            self.log.header1("Adjust model parameters")

        # Adjust model parameters dependent on input user parameters
        for model in self.obs.models():
            
            # Set TS flag for all models to false.
            # Source of interest will be set to true later
            model.tscalc(False)
            
            # Log model name
            if self.logExplicit():
                self.log.header3(model.name())
            
            # Deal with the source of interest    
            if model.name() == self.m_srcname:
                if self.m_calc_ts:
                    model.tscalc(True)
                
            elif self.m_fix_bkg and not model.classname() == "GModelSky":
                for par in model:
                    if par.is_free() and self.logExplicit():
                        self.log(" Fixing \""+par.name()+"\"\n")
                    par.fix()
        
            elif self.m_fix_srcs and model.classname() == "GModelSky":
                for par in model:
                    if par.is_free() and self.logExplicit():
                        self.log(" Fixing \""+par.name()+"\"\n")
                    par.fix()
        
        # Write header
        if self.logTerse():
            self.log("\n")
            self.log.header1("Generate lightcurve")      
        
        # Initialise FITS Table with extension "LIGHTCURVE"
        table = gammalib.GFitsBinTable(self.m_tbins.size())
        table.extname("LIGHTCURVE")
        
        # Add Header for compatibility with gammalib.GMWLSpectrum
        table.card("INSTRUME", "CTA", "Name of Instrument")
        table.card("TELESCOP", "CTA", "Name of Telescope")
             
        # Create FITS table columns        
        MJD = gammalib.GFitsTableDoubleCol("MJD", self.m_tbins.size())
        MJD.unit("days")
        e_MJD = gammalib.GFitsTableDoubleCol("e_MJD", self.m_tbins.size())
        e_MJD.unit("days")
        
        # Create a FITS column for every free parameter
        columns = []
        for par in self.obs.models()[self.m_srcname]:
            if par.is_free():
                col = gammalib.GFitsTableDoubleCol(par.name(), self.m_tbins.size())
                col.unit(par.unit())
                columns.append(col)
                e_col = gammalib.GFitsTableDoubleCol("e_"+par.name(), self.m_tbins.size())
                e_col.unit(par.unit())
                columns.append(e_col)
        
        # Create TS and upper limit columns
        TSvalues    = gammalib.GFitsTableDoubleCol("TS", self.m_tbins.size())
        ulim_values = gammalib.GFitsTableDoubleCol("UpperLimit", self.m_tbins.size())
        ulim_values.unit("ph/cm2/s")

        # Loop over energy bins
        for i in range(self.m_tbins.size()):

            # Log information
            if self.logTerse():
                self.log("\n")
                self.log.header2("Time bin "+str(i))

            # Get time boundaries
            tmin = self.m_tbins.tstart(i)
            tmax = self.m_tbins.tstop(i)
            
            # Compute time bin center and time width
            tmean   = (tmin + tmax)
            tmean  *= 0.5
            twidth  = (tmax - tmin)
            twidth *= 0.5 

            # Store time as MJD
            MJD[i] = tmean.mjd()
            e_MJD[i] = twidth.days()
            
            # Log information
            if self.logExplicit():
                self.log.header3("Selecting events")
                     
            # Select events
            select = ctools.ctselect(self.obs)
            select["emin"].real(self.m_emin)    
            select["emax"].real(self.m_emax) 
            select["tmin"].real(tmin.convert(select.time_reference()))
            select["tmax"].real(tmax.convert(select.time_reference()))
            select["rad"].value("UNDEFINED")
            select["ra"].value("UNDEFINED")
            select["dec"].value("UNDEFINED")
            select.run()  

            # Retrieve observation
            obs = select.obs()
             
            # Binned analysis
            if self.m_binned:

                # Header
                if self.logTerse():
                    self.log.header3("Binning events")
                
                # Bin events
                bin = ctools.ctbin(select.obs())
                bin["usepnt"].boolean(False)
                bin["ebinalg"].string("LOG")
                bin["xref"].real(self.m_xref)
                bin["yref"].real(self.m_yref)
                bin["binsz"].real(self.m_binsz)
                bin["nxpix"].integer(self.m_nxpix)
                bin["nypix"].integer(self.m_nypix)
                bin["enumbins"].integer(self.m_ebins)
                bin["emin"].real(self.m_emin)
                bin["emax"].real(self.m_emax)        
                bin["coordsys"].string(self.m_coordsys)
                bin["proj"].string(self.m_proj)            
                bin.run()
                
                # Header
                if self.logTerse():
                    self.log.header3("Creating exposure cube")
                
                # Create exposure cube
                expcube = ctools.ctexpcube(select.obs())
                expcube["incube"].filename("NONE")
                expcube["usepnt"].boolean(False)
                expcube["ebinalg"].string("LOG")
                expcube["xref"].real(self.m_xref)
                expcube["yref"].real(self.m_yref)
                expcube["binsz"].real(self.m_binsz)
                expcube["nxpix"].integer(self.m_nxpix)
                expcube["nypix"].integer(self.m_nypix)
                expcube["enumbins"].integer(self.m_ebins)
                expcube["emin"].real(self.m_emin)
                expcube["emax"].real(self.m_emax)   
                expcube["coordsys"].string(self.m_coordsys)
                expcube["proj"].string(self.m_proj)               
                expcube.run()
                
                # Header
                if self.logTerse():
                    self.log.header3("Creating PSF cube")
                
                # Create psf cube
                psfcube = ctools.ctpsfcube(select.obs())
                psfcube["incube"].filename("NONE")
                psfcube["usepnt"].boolean(False)
                psfcube["ebinalg"].string("LOG")
                psfcube["xref"].real(self.m_xref)
                psfcube["yref"].real(self.m_yref)
                psfcube["binsz"].real(self.m_binsz)
                psfcube["nxpix"].integer(self.m_nxpix)
                psfcube["nypix"].integer(self.m_nypix)
                psfcube["enumbins"].integer(self.m_ebins)
                psfcube["emin"].real(self.m_emin)
                psfcube["emax"].real(self.m_emax)    
                psfcube["coordsys"].string(self.m_coordsys)
                psfcube["proj"].string(self.m_proj)               
                psfcube.run()
                
                # Header
                if self.logTerse():
                    self.log.header3("Creating background cube")
                
                # Create background cube
                bkgcube = ctools.ctbkgcube(select.obs())
                bkgcube["incube"].filename("NONE")
                bkgcube["usepnt"].boolean(False)
                bkgcube["ebinalg"].string("LOG")
                bkgcube["xref"].real(self.m_xref)
                bkgcube["yref"].real(self.m_yref)
                bkgcube["binsz"].real(self.m_binsz)
                bkgcube["nxpix"].integer(self.m_nxpix)
                bkgcube["nypix"].integer(self.m_nypix)
                bkgcube["enumbins"].integer(self.m_ebins)
                bkgcube["emin"].real(self.m_emin)
                bkgcube["emax"].real(self.m_emax)   
                bkgcube["coordsys"].string(self.m_coordsys)
                bkgcube["proj"].string(self.m_proj)                
                bkgcube.run()
                
                # Set new binned observation
                obs = bin.obs()
                
                # Set precomputed binned response
                obs[0].response(expcube.expcube(), psfcube.psfcube(), bkgcube.bkgcube())

                # Get new models
                models = bkgcube.models()
                
                # Fix background models if required
                if self.m_fix_bkg:
                    for model in models:
                        if not model.classname() == "GModelSky":
                            for par in model:
                                par.fix()
                                
                # Set new models to binned observation           
                obs.models(models)
                
            # Header
            if self.logTerse():
                self.log.header3("Performing fit")
                             
            # Likelihood
            like = ctools.ctlike(obs)
            like.run()
            
            # Skip bin if no event was present
            if like.obs().logL() == 0.0:
                
                # Log information
                if self.logTerse():
                    self.log("No event in this time bin. Bin is skipped\n")

                # Set all values to 0
                for col in columns:
                    col[i] = 0.0
                TSvalues[i]    = 0.0
                ulim_values[i] = 0.0
                continue
                         
            # Get results
            fitted_models = like.obs().models()
            source        = fitted_models[self.m_srcname]

            # Calculate Upper Limit            
            ulimit_value = -1.0
            if self.m_calc_ulimit:
                
                # Logging information
                if self.logTerse():
                    self.log.header3("Computing upper limit")
                  
                # Create upper limit object  
                ulimit = ctools.ctulimit(like.obs())
                ulimit["srcname"].string(self.m_srcname)
                ulimit["eref"].real(1.0)
                
                # Try to run upper limit and catch exceptions
                try:
                    ulimit.run()
                    ulimit_value = ulimit.flux_ulimit()
                except:
                    if self.logTerse():
                        self.log("Upper limit calculation failed\n")
                    ulimit_value = -1.0
            
            # Get TS value
            TS = -1.0
            if self.m_calc_ts:
                TS = source.ts() 
            
            # Set values for storage
            TSvalues[i] = TS
            
            # Set FITS column values
            for col in columns:
                if "e_" == col.name()[:2]:
                    col[i] = source.spectral()[col.name()[2:]].error()
                else:
                    col[i] = source.spectral()[col.name()].value()
            
            # Store upper limit value if available
            if ulimit_value > 0.0:
                ulim_values[i] = ulimit_value
         
            # Log information
            if self.logExplicit(): 
                self.log.header3("Results of bin "+str(i)+": MJD "+str(tmin.mjd())+"-"+str(tmax.mjd()))
                for col in columns:
                    if "e_" == col.name()[:2]:
                        continue
                    value = source.spectral()[col.name()].value()
                    error = source.spectral()[col.name()].error()
                    unit = source.spectral()[col.name()].unit()
                    self.log(" > "+col.name()+": "+str(value)+" +- "+str(error)+" "+unit+"\n")
                if self.m_calc_ts and TSvalues[i] > 0.0:
                    self.log(" > TS = "+str(TS)+" \n")
                if self.m_calc_ulimit and ulim_values[i] > 0.0:
                    self.log(" > UL = "+str(ulim_values[i])+" [ph/cm2/s]")
                self.log("\n")

        # Append filles columns to fits table    
        table.append(MJD)
        table.append(e_MJD)
        for col in columns:
            table.append(col)
        table.append(TSvalues)
        table.append(ulim_values)
        
        # Create the FITS file now
        self.fits = gammalib.GFits()
        self.fits.append(table)
            
        # Return
        return
Beispiel #8
0
    def run(self):
        """
        Run the script.
        """
        # Switch screen logging on in debug mode
        if self.logDebug():
            self.log.cout(True)

        # Get parameters
        self.get_parameters()
        
        #  Write input parameters into logger
        if self.logTerse():
            self.log_parameters()
            self.log("\n")
        
        # Write observation into logger
        if self.logTerse():
            self.log("\n")
            self.log.header1("Observation")
            self.log(str(self.obs))
            self.log("\n")

        # Write header
        if self.logTerse():
            self.log("\n")
            self.log.header1("Adjust model parameters")

        # Adjust model parameters dependent on input user parameters
        for model in self.obs.models():
            
            # Set TS flag for all models to false.
            # Source of interest will be set to true later
            model.tscalc(False)
            
            # Log model name
            if self.logExplicit():
                self.log.header3(model.name())
            
            # Deal with the source of interest    
            if model.name() == self.m_srcname:
                for par in model:
                    if par.is_free() and self.logExplicit():
                        self.log(" Fixing \""+par.name()+"\"\n")
                    par.fix()
                if par.is_fixed() and self.logExplicit():
                    self.log(" Freeing \""+par.name()+"\"\n")
                model.spectral()[0].free()
                if self.m_calc_ts:
                    model.tscalc(True)
                
            elif self.m_fix_bkg and not model.classname() == "GModelSky":
                for par in model:
                    if par.is_free() and self.logExplicit():
                        self.log(" Fixing \""+par.name()+"\"\n")
                    par.fix()
        
            elif self.m_fix_srcs and model.classname() == "GModelSky":
                for par in model:
                    if par.is_free() and self.logExplicit():
                        self.log(" Fixing \""+par.name()+"\"\n")
                    par.fix()
        
        # Write header
        if self.logTerse():
            self.log("\n")
            self.log.header1("Generate spectrum")      
        
        # Initialise FITS Table with extension "SPECTRUM"
        table = gammalib.GFitsBinTable(self.m_ebounds.size())
        table.extname("SPECTRUM")
        
        # Add Header for compatibility with gammalib.GMWLSpectrum
        table.card("INSTRUME", "CTA", "Name of Instrument")
        table.card("TELESCOP", "CTA", "Name of Telescope")
        
        # Create FITS table columns
        energy      = gammalib.GFitsTableDoubleCol("Energy", self.m_ebounds.size())
        energy.unit("TeV")
        energy_low  = gammalib.GFitsTableDoubleCol("ed_Energy", self.m_ebounds.size())
        energy_low.unit("TeV")
        energy_high  = gammalib.GFitsTableDoubleCol("eu_Energy", self.m_ebounds.size())
        energy_high.unit("TeV")
        flux        = gammalib.GFitsTableDoubleCol("Flux", self.m_ebounds.size())
        flux.unit("erg/cm2/s")
        flux_err    = gammalib.GFitsTableDoubleCol("e_Flux", self.m_ebounds.size())
        flux_err.unit("erg/cm2/s")
        TSvalues    = gammalib.GFitsTableDoubleCol("TS", self.m_ebounds.size())
        ulim_values = gammalib.GFitsTableDoubleCol("UpperLimit", self.m_ebounds.size())
        ulim_values.unit("erg/cm2/s")

        # Loop over energy bins
        for i in range(self.m_ebounds.size()):

            # Log information
            if self.logTerse():
                self.log("\n")
                self.log.header2("Energy bin "+str(i))

            # Get energy boundaries
            emin      = self.m_ebounds.emin(i)
            emax      = self.m_ebounds.emax(i)
            elogmean  = self.m_ebounds.elogmean(i)
            elogmean2 = elogmean.MeV() * elogmean.MeV()    
                        
            # Store energy as TeV
            energy[i] = elogmean.TeV()
            
            # Store energy errors
            energy_low[i]  = (elogmean - emin).TeV()
            energy_high[i] = (emax - elogmean).TeV()
            
            # Log information
            if self.logExplicit():
                    self.log.header3("Selecting events")
            
            # Select events
            select = ctools.ctselect(self.obs)
            select["emin"].real(emin.TeV())    
            select["emax"].real(emax.TeV()) 
            select["tmin"].value("UNDEFINED")
            select["tmax"].value("UNDEFINED")
            select["rad"].value("UNDEFINED")
            select["ra"].value("UNDEFINED")
            select["dec"].value("UNDEFINED")
            select.run()  

            # Retrieve observation
            obs = select.obs()

            # Binned analysis
            if self.m_binned:

                # Header
                if self.logTerse():
                    self.log.header3("Binning events")
                
                # Bin events
                bin = ctools.ctbin(select.obs())
                bin["usepnt"].boolean(False)
                bin["ebinalg"].string("LOG")
                bin["xref"].real(self.m_xref)
                bin["yref"].real(self.m_yref)
                bin["binsz"].real(self.m_binsz)
                bin["nxpix"].integer(self.m_nxpix)
                bin["nypix"].integer(self.m_nypix)
                bin["enumbins"].integer(self.m_ebins)
                bin["emin"].real(emin.TeV())
                bin["emax"].real(emax.TeV())        
                bin["coordsys"].string(self.m_coordsys)
                bin["proj"].string(self.m_proj)            
                bin.run()
                
                # Header
                if self.logTerse():
                    self.log.header3("Creating exposure cube")
                
                # Create exposure cube
                expcube = ctools.ctexpcube(select.obs())
                expcube["incube"].filename("NONE")
                expcube["usepnt"].boolean(False)
                expcube["ebinalg"].string("LOG")
                expcube["xref"].real(self.m_xref)
                expcube["yref"].real(self.m_yref)
                expcube["binsz"].real(self.m_binsz)
                expcube["nxpix"].integer(self.m_nxpix)
                expcube["nypix"].integer(self.m_nypix)
                expcube["enumbins"].integer(self.m_ebins)
                expcube["emin"].real(emin.TeV())
                expcube["emax"].real(emax.TeV()) 
                expcube["coordsys"].string(self.m_coordsys)
                expcube["proj"].string(self.m_proj)               
                expcube.run()
                
                # Header
                if self.logTerse():
                    self.log.header3("Creating PSF cube")
                
                # Create psf cube
                psfcube = ctools.ctpsfcube(select.obs())
                psfcube["incube"].filename("NONE")
                psfcube["usepnt"].boolean(False)
                psfcube["ebinalg"].string("LOG")
                psfcube["xref"].real(self.m_xref)
                psfcube["yref"].real(self.m_yref)
                psfcube["binsz"].real(self.m_binsz)
                psfcube["nxpix"].integer(self.m_nxpix)
                psfcube["nypix"].integer(self.m_nypix)
                psfcube["enumbins"].integer(self.m_ebins)
                psfcube["emin"].real(emin.TeV())
                psfcube["emax"].real(emax.TeV())  
                psfcube["coordsys"].string(self.m_coordsys)
                psfcube["proj"].string(self.m_proj)               
                psfcube.run()
                
                # Header
                if self.logTerse():
                    self.log.header3("Creating background cube")
                
                # Create background cube
                bkgcube = ctools.ctbkgcube(select.obs())
                bkgcube["incube"].filename("NONE")
                bkgcube["usepnt"].boolean(False)
                bkgcube["ebinalg"].string("LOG")
                bkgcube["xref"].real(self.m_xref)
                bkgcube["yref"].real(self.m_yref)
                bkgcube["binsz"].real(self.m_binsz)
                bkgcube["nxpix"].integer(self.m_nxpix)
                bkgcube["nypix"].integer(self.m_nypix)
                bkgcube["enumbins"].integer(self.m_ebins)
                bkgcube["emin"].real(emin.TeV())
                bkgcube["emax"].real(emax.TeV()) 
                bkgcube["coordsys"].string(self.m_coordsys)
                bkgcube["proj"].string(self.m_proj)                
                bkgcube.run()
                
                # Set new binned observation
                obs = bin.obs()
                
                # Set precomputed binned response
                obs[0].response(expcube.expcube(), psfcube.psfcube(), bkgcube.bkgcube())

                # Get new models
                models = bkgcube.models()
                
                # Fix background models if required
                if self.m_fix_bkg:
                    for model in models:
                        if not model.classname() == "GModelSky":
                            for par in model:
                                par.fix()
                                
                # Set new models to binned observation           
                obs.models(models)
                
            # Header
            if self.logTerse():
                self.log.header3("Performing fit")
                             
            # Likelihood
            like = ctools.ctlike(obs)
            like.run()
            
            # Skip bin if no event was present
            if like.obs().logL() == 0.0:
                
                # Log information
                if self.logTerse():
                    self.log("No event in this bin. Bin is skipped\n")

                # Set all values to 0
                flux[i]        = 0.0
                flux_err[i]    = 0.0
                TSvalues[i]    = 0.0
                ulim_values[i] = 0.0
                continue
                         
            # Get results
            fitted_models = like.obs().models()
            source        = fitted_models[self.m_srcname]

            # Calculate Upper Limit            
            ulimit_value = -1.0
            if self.m_calc_ulimit:
                
                # Logging information
                if self.logTerse():
                    self.log.header3("Computing upper limit")
                  
                # Create upper limit object  
                ulimit = ctools.ctulimit(like.obs())
                ulimit["srcname"].string(self.m_srcname)
                ulimit["eref"].real(elogmean.TeV())
                
                # Try to run upper limit and catch exceptions
                try:
                    ulimit.run()
                    ulimit_value = ulimit.diff_ulimit()
                except:
                    if self.logTerse():
                        self.log("Upper limit calculation failed\n")
                    ulimit_value = -1.0
            
            # Get TS value
            TS = -1.0
            if self.m_calc_ts:
                TS = source.ts() 
              
            # Get differential flux    
            fitted_flux = source.spectral().eval(elogmean,gammalib.GTime())
            
            # Compute flux error
            parvalue  = source.spectral()[0].value()
            rel_error = source.spectral()[0].error()/parvalue        
            e_flux    = fitted_flux*rel_error
            
            # Set values for storage
            TSvalues[i] = TS
            
            # Convert fluxes to nuFnu
            flux[i]     = fitted_flux * elogmean2 * gammalib.MeV2erg
            flux_err[i] = e_flux      * elogmean2 * gammalib.MeV2erg
            if ulimit_value > 0.0:
                ulim_values[i] = ulimit_value * elogmean2 * gammalib.MeV2erg
         
            # Log information
            if self.logExplicit(): 
                self.log("Bin "+str(i)+" ["+str(emin.TeV())+"-"+str(emax.TeV())+"] TeV: ")
                self.log("Flux = "+str(flux[i]))
                self.log(" +- "+str(flux_err[i])+" [erg/cm2/s]")
                if self.m_calc_ts and TSvalues[i] > 0.0:
                    self.log(", TS = "+str(TS))
                if self.m_calc_ulimit and ulim_values[i] > 0.0:
                    self.log(", UL = "+str(ulim_values[i])+" [erg/cm2/s]")
                self.log("\n")

        # Append filles columns to fits table    
        table.append(energy)
        table.append(energy_low)
        table.append(energy_high)
        table.append(flux)
        table.append(flux_err)
        table.append(TSvalues)
        table.append(ulim_values)
        
        # Create the FITS file now
        self.fits = gammalib.GFits()
        self.fits.append(table)
            
        # Return
        return
Beispiel #9
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 stacked_pipeline(duration):
    """
    Cube-style analysis pipeline.
    """
    # Set script parameters
    model_name  = "${CTOOLS}/share/models/crab.xml"
    caldb       = "prod2"
    irf         = "South_50h"
    ra          =   83.63
    dec         =   22.01
    rad_sim     =   10.0
    tstart      =    0.0
    tstop       = duration
    emin        =    0.1
    emax        =  100.0
    enumbins    =   20
    nxpix       =  200
    nypix       =  200
    binsz       =    0.02
    coordsys    = "CEL"
    proj        = "CAR"

    # Get start CPU time
    tstart = time.clock()

    # Simulate events
    sim = ctools.ctobssim()
    sim["inmodel"].filename(model_name)
    sim["caldb"].string(caldb)
    sim["irf"].string(irf)
    sim["ra"].real(ra)
    sim["dec"].real(dec)
    sim["rad"].real(rad_sim)
    sim["tmin"].real(tstart)
    sim["tmax"].real(tstop)
    sim["emin"].real(emin)
    sim["emax"].real(emax)
    sim.run()

    # Bin events into counts map
    bin = ctools.ctbin(sim.obs())
    bin["ebinalg"].string("LOG")
    bin["emin"].real(emin)
    bin["emax"].real(emax)
    bin["enumbins"].integer(enumbins)
    bin["nxpix"].integer(nxpix)
    bin["nypix"].integer(nypix)
    bin["binsz"].real(binsz)
    bin["coordsys"].string(coordsys)
    bin["proj"].string(proj)
    bin["xref"].real(ra)
    bin["yref"].real(dec)
    bin.run()

    # Create exposure cube
    expcube = ctools.ctexpcube(sim.obs())
    expcube["incube"].filename("NONE")
    expcube["caldb"].string(caldb)
    expcube["irf"].string(irf)
    expcube["ebinalg"].string("LOG")
    expcube["emin"].real(emin)
    expcube["emax"].real(emax)
    expcube["enumbins"].integer(enumbins)
    expcube["nxpix"].integer(nxpix)
    expcube["nypix"].integer(nypix)
    expcube["binsz"].real(binsz)
    expcube["coordsys"].string(coordsys)
    expcube["proj"].string(proj)
    expcube["xref"].real(ra)
    expcube["yref"].real(dec)
    expcube.run()

    # Create PSF cube
    psfcube = ctools.ctpsfcube(sim.obs())
    psfcube["incube"].filename("NONE")
    psfcube["caldb"].string(caldb)
    psfcube["irf"].string(irf)
    psfcube["ebinalg"].string("LOG")
    psfcube["emin"].real(emin)
    psfcube["emax"].real(emax)
    psfcube["enumbins"].integer(enumbins)
    psfcube["nxpix"].integer(10)
    psfcube["nypix"].integer(10)
    psfcube["binsz"].real(1.0)
    psfcube["coordsys"].string(coordsys)
    psfcube["proj"].string(proj)
    psfcube["xref"].real(ra)
    psfcube["yref"].real(dec)
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(sim.obs())
    bkgcube["incube"].filename("NONE")
    bkgcube["ebinalg"].string("LOG")
    bkgcube["emin"].real(emin)
    bkgcube["emax"].real(emax)
    bkgcube["enumbins"].integer(enumbins)
    bkgcube["nxpix"].integer(10)
    bkgcube["nypix"].integer(10)
    bkgcube["binsz"].real(1.0)
    bkgcube["coordsys"].string(coordsys)
    bkgcube["proj"].string(proj)
    bkgcube["xref"].real(ra)
    bkgcube["yref"].real(dec)
    bkgcube.run()

    # 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(), bkgcube.bkgcube())

    # Get ctlike start CPU time
    tctlike = time.clock()

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    like.run()

    # Get stop CPU time
    tstop    = time.clock()
    telapsed = tstop - tstart
    tctlike  = tstop - tctlike
	
    # Return
    return telapsed, tctlike
Beispiel #11
0
    def set_stacked_irf(self):
        """
        For stacked analysis prepare stacked irfs
        """
        # Write header into logger
        if self.logTerse():
            self.log("\n")
            self.log.header1("Compute stacked response")

        # Get stacked exposure
        expcube = ctools.ctexpcube(self.obs)
        expcube["incube"]   = "NONE"
        expcube["usepnt"]   = True
        expcube["ebinalg"]  = "LOG"
        expcube["binsz"]    = self.m_binsz
        expcube["nxpix"]    = self.m_npix
        expcube["nypix"]    = self.m_npix
        expcube["enumbins"] = self.m_enumbins
        expcube["emin"]     = self["emin"].real()
        expcube["emax"]     = self["emax"].real()
        expcube["coordsys"] = self.m_coordsys
        expcube["proj"]     = self.m_proj
        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"]    = self.m_binsz*10.0
        psfcube["nxpix"]    = self.m_npix/10
        psfcube["nypix"]    = self.m_npix/10
        psfcube["enumbins"] = self.m_enumbins
        psfcube["emin"]     = self["emin"].real()
        psfcube["emax"]     = self["emax"].real()
        psfcube["coordsys"] = self.m_coordsys
        psfcube["proj"]     = self.m_proj
        psfcube.run()

        # Notify Psf computation
        if self.logTerse():
            self.log("Computed Psf cube\n")

        # Get stacked background
        bkgcube = ctools.ctbkgcube(self.obs)
        bkgcube["incube"]   = "NONE"
        bkgcube["usepnt"]   = True
        bkgcube["ebinalg"]  = "LOG"
        bkgcube["binsz"]    = self.m_binsz
        bkgcube["nxpix"]    = self.m_npix
        bkgcube["nypix"]    = self.m_npix
        bkgcube["enumbins"] = self.m_enumbins
        bkgcube["emin"]     = self["emin"].real()
        bkgcube["emax"]     = self["emax"].real()
        bkgcube["coordsys"] = self.m_coordsys
        bkgcube["proj"]     = self.m_proj
        bkgcube.run()

        # Notify background cube computation
        if self.logTerse():
            self.log("Computed background cube\n")

        # Store results
        self.m_exposure    = expcube.expcube().copy()
        self.m_psfcube     = psfcube.psfcube().copy()
        self.m_bckcube     = bkgcube.bkgcube().copy()
        self.m_stackmodels = bkgcube.models().copy()

        # Return
        return
def run_pipeline(obs,
                 ra=83.63,
                 dec=22.01,
                 emin=0.1,
                 emax=100.0,
                 enumbins=20,
                 nxpix=200,
                 nypix=200,
                 binsz=0.02,
                 coordsys='CEL',
                 proj='CAR',
                 model='data/crab.xml',
                 caldb='prod2',
                 irf='South_0.5h',
                 debug=False):
    """
    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
    model : str, optional
        Model definition XML file
    caldb : str, optional
        Calibration database path
    irf : str, optional
        Instrument response function
    debug : bool, optional
        Debug function
    """
    # Simulate events
    sim = ctools.ctobssim(obs)
    sim['debug'] = debug
    sim['outevents'] = 'obs.xml'
    sim.execute()

    # Bin events into counts map
    bin = ctools.ctbin()
    bin['inobs'] = 'obs.xml'
    bin['outcube'] = 'cntcube.fits'
    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'] = ra
    bin['yref'] = dec
    bin['debug'] = debug
    bin.execute()

    # Create exposure cube
    expcube = ctools.ctexpcube()
    expcube['inobs'] = 'obs.xml'
    expcube['incube'] = 'cntcube.fits'
    expcube['outcube'] = 'expcube.fits'
    expcube['caldb'] = caldb
    expcube['irf'] = irf
    expcube['ebinalg'] = 'LOG'
    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'] = ra
    expcube['yref'] = dec
    expcube['debug'] = debug
    expcube.execute()

    # Create PSF cube
    psfcube = ctools.ctpsfcube()
    psfcube['inobs'] = 'obs.xml'
    psfcube['incube'] = 'NONE'
    psfcube['outcube'] = 'psfcube.fits'
    psfcube['caldb'] = caldb
    psfcube['irf'] = irf
    psfcube['ebinalg'] = 'LOG'
    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'] = ra
    psfcube['yref'] = dec
    psfcube['debug'] = debug
    psfcube.execute()

    # Create background cube
    bkgcube = ctools.ctbkgcube()
    bkgcube['inobs'] = 'obs.xml'
    bkgcube['inmodel'] = model
    bkgcube['incube'] = 'NONE'
    bkgcube['outcube'] = 'bkgcube.fits'
    bkgcube['outmodel'] = 'model_bkg.xml'
    bkgcube['caldb'] = caldb
    bkgcube['irf'] = irf
    bkgcube['ebinalg'] = 'LOG'
    bkgcube['emin'] = emin
    bkgcube['emax'] = emax
    bkgcube['enumbins'] = enumbins
    bkgcube['nxpix'] = 10
    bkgcube['nypix'] = 10
    bkgcube['binsz'] = 1.0
    bkgcube['coordsys'] = coordsys
    bkgcube['proj'] = proj
    bkgcube['xref'] = ra
    bkgcube['yref'] = dec
    bkgcube['debug'] = debug
    bkgcube.execute()

    # Perform maximum likelihood fitting
    like = ctools.ctlike()
    like['inobs'] = 'cntcube.fits'
    like['inmodel'] = 'model_bkg.xml'
    like['outmodel'] = 'fit_results.xml'
    like['expcube'] = 'expcube.fits'
    like['psfcube'] = 'psfcube.fits'
    like['bkgcube'] = 'bkgcube.fits'
    like['caldb'] = caldb
    like['irf'] = irf
    like['debug'] = True  # Switch this always on for results in console
    like.execute()

    # Return
    return
Beispiel #13
0
def stacked_pipeline(model_name, duration):
    """
    Stacked analysis pipeline.
    """
    # Set script parameters
    caldb       = "prod2"
    irf         = "South_50h"
    ra          =   83.63
    dec         =   22.01
    rad_sim     =   10.0
    tstart      =    0.0
    tstop       = duration
    emin        =    0.1
    emax        =  100.0
    enumbins    =   40
    nxpix       =  200
    nypix       =  200
    binsz       =    0.02
    coordsys    = "CEL"
    proj        = "CAR"

    # Get start CPU time
    cpu_start = time.clock()

    # Simulate events
    sim = ctools.ctobssim()
    sim["inmodel"] = model_name
    sim["caldb"]   = caldb
    sim["irf"]     = irf
    sim["ra"]      = ra
    sim["dec"]     = dec
    sim["rad"]     = rad_sim
    sim["tmin"]    = tstart
    sim["tmax"]    = tstop
    sim["emin"]    = emin
    sim["emax"]    = emax
    sim.run()

    # Bin events into counts map
    bin = ctools.ctbin(sim.obs())
    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"]     = ra
    bin["yref"]     = dec
    bin.run()

    # Create exposure cube
    expcube = ctools.ctexpcube(sim.obs())
    expcube["incube"]   = "NONE"
    expcube["caldb"]    = caldb
    expcube["irf"]      = irf
    expcube["ebinalg"]  = "LOG"
    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"]     = ra
    expcube["yref"]     = dec
    expcube.run()

    # Create PSF cube
    psfcube = ctools.ctpsfcube(sim.obs())
    psfcube["incube"]   = "NONE"
    psfcube["caldb"]    = caldb
    psfcube["irf"]      = irf
    psfcube["ebinalg"]  = "LOG"
    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"]     = ra
    psfcube["yref"]     = dec
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(sim.obs())
    bkgcube["incube"]   = "NONE"
    bkgcube["ebinalg"]  = "LOG"
    bkgcube["emin"]     = emin
    bkgcube["emax"]     = emax
    bkgcube["enumbins"] = enumbins
    bkgcube["nxpix"]    = 10
    bkgcube["nypix"]    = 10
    bkgcube["binsz"]    = 1.0
    bkgcube["coordsys"] = coordsys
    bkgcube["proj"]     = proj
    bkgcube["xref"]     = ra
    bkgcube["yref"]     = dec
    bkgcube.run()

    # 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(), bkgcube.bkgcube())

    # Get ctlike start CPU time
    cpu_ctlike = time.clock()

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    like.run()

    # Get stop CPU time and compute elapsed times
    cpu_stop    = time.clock()
    cpu_elapsed = cpu_stop - cpu_start
    cpu_ctlike  = cpu_stop - cpu_ctlike

    # Return
    return cpu_elapsed, cpu_ctlike
Beispiel #14
0
def run_pipeline(obs, ra=83.63, dec=22.01, emin=0.1, emax=100.0, \
                 enumbins=20, nxpix=200, nypix=200, binsz=0.02, \
                 coordsys="CEL", proj="CAR", debug=False):
    """
    Simulation and stacked analysis pipeline.

    Keywords:
     ra       - RA of cube centre [deg] (default: 83.6331)
     dec      - DEC of cube centre [deg] (default: 22.0145)
     emin     - Minimum energy of cube [TeV] (default: 0.1)
     emax     - Maximum energy of cube [TeV] (default: 100.0)
     enumbins - Number of energy bins in cube (default: 20)
     nxpix    - Number of RA pixels in cube (default: 200)
     nypix    - Number of DEC pixels in cube (default: 200)
     binsz    - Spatial cube bin size [deg] (default: 0.02)
     coordsys - Cube coordinate system (CEL or GAL)
     proj     - Cube World Coordinate System (WCS) projection
     debug    - Enable debugging (default: False)
    """
    # Simulate events
    sim = ctools.ctobssim(obs)
    sim["debug"].boolean(debug)
    sim.run()

    # Bin events into counts map
    bin = ctools.ctbin(sim.obs())
    bin["ebinalg"].string("LOG")
    bin["emin"].real(emin)
    bin["emax"].real(emax)
    bin["enumbins"].integer(enumbins)
    bin["nxpix"].integer(nxpix)
    bin["nypix"].integer(nypix)
    bin["binsz"].real(binsz)
    bin["coordsys"].string(coordsys)
    bin["proj"].string(proj)
    bin["xref"].real(ra)
    bin["yref"].real(dec)
    bin["debug"].boolean(debug)
    bin.run()

    # Create exposure cube
    expcube = ctools.ctexpcube(sim.obs())
    expcube["incube"].filename("NONE")
    expcube["ebinalg"].string("LOG")
    expcube["emin"].real(emin)
    expcube["emax"].real(emax)
    expcube["enumbins"].integer(enumbins)
    expcube["nxpix"].integer(nxpix)
    expcube["nypix"].integer(nypix)
    expcube["binsz"].real(binsz)
    expcube["coordsys"].string(coordsys)
    expcube["proj"].string(proj)
    expcube["xref"].real(ra)
    expcube["yref"].real(dec)
    expcube["debug"].boolean(debug)
    expcube.run()

    # Create PSF cube
    psfcube = ctools.ctpsfcube(sim.obs())
    psfcube["incube"].filename("NONE")
    psfcube["ebinalg"].string("LOG")
    psfcube["emin"].real(emin)
    psfcube["emax"].real(emax)
    psfcube["enumbins"].integer(enumbins)
    psfcube["nxpix"].integer(10)
    psfcube["nypix"].integer(10)
    psfcube["binsz"].real(1.0)
    psfcube["coordsys"].string(coordsys)
    psfcube["proj"].string(proj)
    psfcube["xref"].real(ra)
    psfcube["yref"].real(dec)
    psfcube["debug"].boolean(debug)
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(sim.obs())
    bkgcube["incube"].filename("NONE")
    bkgcube["ebinalg"].string("LOG")
    bkgcube["emin"].real(emin)
    bkgcube["emax"].real(emax)
    bkgcube["enumbins"].integer(enumbins)
    bkgcube["nxpix"].integer(10)
    bkgcube["nypix"].integer(10)
    bkgcube["binsz"].real(1.0)
    bkgcube["coordsys"].string(coordsys)
    bkgcube["proj"].string(proj)
    bkgcube["xref"].real(ra)
    bkgcube["yref"].real(dec)
    bkgcube["debug"].boolean(debug)
    bkgcube.run()

    # 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(), bkgcube.bkgcube())

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    like["debug"].boolean(True) # Switch this always on for results in console
    like.run()
	
    # Return
    return
Beispiel #15
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
Beispiel #16
0
    def _test_python(self):
        """
        Test ctbkgcube from Python
        """
        # Allocate ctbkgcube
        bkgcube = ctools.ctbkgcube()

        # Check that empty ctbkgcube tool holds a background cube that has
        # no energy bins
        self._check_cube(bkgcube.bkgcube(), nenergies=0)

        # Check that saving does not nothing
        bkgcube['outcube']  = 'ctbkgcube_py0.fits'
        bkgcube['outmodel'] = 'ctbkgcube_py0.xml'
        bkgcube['logfile']  = 'ctbkgcube_py0.log'
        bkgcube.logFileOpen()
        bkgcube.save()
        self.test_assert(not os.path.isfile('ctbkgcube_py0.fits'),
             'Check that no background cube has been created')

        # Check model container
        self._check_models(gammalib.GModels('ctbkgcube_py0.xml'), nmodels=0)

        # Check saving with empty file names
        bkgcube['outcube']  = ''
        bkgcube['outmodel'] = ''
        bkgcube['logfile']  = 'ctbkgcube_py1.log'
        bkgcube.logFileOpen()
        bkgcube.save()

        # Check saving with "none" model definiton name
        bkgcube['outcube']  = ''
        bkgcube['outmodel'] = 'NONE'
        bkgcube['logfile']  = 'ctbkgcube_py2.log'
        bkgcube.logFileOpen()
        bkgcube.save()

        # Check that publish method with user name does not lead to an
        # exception or segfault
        bkgcube.publish('My background cube')

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

        # Now set ctbkgcube parameters
        bkgcube['inobs']    = self._events
        bkgcube['inmodel']  = self._model
        bkgcube['incube']   = 'NONE'
        bkgcube['caldb']    = self._caldb
        bkgcube['irf']      = self._irf
        bkgcube['ebinalg']  = 'LOG'
        bkgcube['emin']     = 0.1
        bkgcube['emax']     = 100.0
        bkgcube['enumbins'] = 20
        bkgcube['nxpix']    = 10
        bkgcube['nypix']    = 10
        bkgcube['binsz']    = 0.4
        bkgcube['coordsys'] = 'CEL'
        bkgcube['proj']     = 'CAR'
        bkgcube['xref']     = 83.63
        bkgcube['yref']     = 22.01
        bkgcube['outcube']  = 'ctbkgcube_py3.fits'
        bkgcube['outmodel'] = 'ctbkgcube_py3.xml'
        bkgcube['logfile']  = 'ctbkgcube_py3.log'
        bkgcube['chatter']  = 2

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

        # Check result files
        self._check_result_files('ctbkgcube_py3')

        # Copy ctbkgcube tool
        cpy_bkgcube = bkgcube.copy()

        # Check background cube and model container of ctbkgcube copy
        self._check_cube(cpy_bkgcube.bkgcube())
        self._check_models(cpy_bkgcube.models())

        # Execute copy of ctbkgcube tool again, now with a higher chatter
        # level than before. In addition, use counts cube to define the
        # background cube
        cpy_bkgcube['incube']    = self._cntcube
        cpy_bkgcube['outcube']   = 'ctbkgcube_py4.fits'
        cpy_bkgcube['outmodel']  = 'ctbkgcube_py4.xml'
        cpy_bkgcube['logfile']   = 'ctbkgcube_py4.log'
        cpy_bkgcube['chatter']   = 3
        cpy_bkgcube['publish']   = True
        cpy_bkgcube['addbounds'] = True
        cpy_bkgcube.logFileOpen()   # Make sure we get a log file
        cpy_bkgcube.execute()

        # Check result files
        self._check_result_files('ctbkgcube_py4')

        # Now clear copy of ctbkgcube tool
        cpy_bkgcube.clear()

        # Check that the cleared copy has also cleared the background cube
        # and model container
        self._check_cube(cpy_bkgcube.bkgcube(), nenergies=0)
        self._check_models(cpy_bkgcube.models(), nmodels=0)

        # Get mixel observation container
        obs = self._obs_mixed()
        obs.models(gammalib.GModels(self._model))

        # Set-up ctbkgcube from observation container
        bkgcube = ctools.ctbkgcube(obs)
        bkgcube['incube']    = ''
        bkgcube['caldb']     = self._caldb
        bkgcube['irf']       = self._irf
        bkgcube['ebinalg']   = 'LOG'
        bkgcube['emin']      = 0.2
        bkgcube['emax']      = 150.0
        bkgcube['enumbins']  = 20
        bkgcube['nxpix']     = 10
        bkgcube['nypix']     = 10
        bkgcube['binsz']     = 0.4
        bkgcube['coordsys']  = 'CEL'
        bkgcube['proj']      = 'CAR'
        bkgcube['xref']      = 83.63
        bkgcube['yref']      = 22.01
        bkgcube['outcube']   = 'ctbkgcube_py5.fits'
        bkgcube['outmodel']  = 'ctbkgcube_py5.xml'
        bkgcube['logfile']   = 'ctbkgcube_py5.log'
        bkgcube['addbounds'] = True
        bkgcube['chatter']   = 4

        # Execute ctbkgcube tool
        bkgcube.logFileOpen()   # Make sure we get a log file
        bkgcube.execute()

        # Check result files
        self._check_result_files('ctbkgcube_py5', nenergies=23)

        # Return
        return
Beispiel #17
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
Beispiel #18
0
def run_pipeline(obs, ra=83.63, dec=22.01, emin=0.1, emax=100.0, \
                 enumbins=20, nxpix=200, nypix=200, binsz=0.02, \
                 coordsys="CEL", proj="CAR", \
                 model="${CTOOLS}/share/models/crab.xml", \
                 caldb="prod2", irf="South_50h", \
                 debug=False):
    """
    Simulation and stacked analysis pipeline.

    Keywords:
     ra       - RA of cube centre [deg] (default: 83.6331)
     dec      - DEC of cube centre [deg] (default: 22.0145)
     emin     - Minimum energy of cube [TeV] (default: 0.1)
     emax     - Maximum energy of cube [TeV] (default: 100.0)
     enumbins - Number of energy bins in cube (default: 20)
     nxpix    - Number of RA pixels in cube (default: 200)
     nypix    - Number of DEC pixels in cube (default: 200)
     binsz    - Spatial cube bin size [deg] (default: 0.02)
     coordsys - Cube coordinate system (CEL or GAL)
     proj     - Cube World Coordinate System (WCS) projection
     debug    - Enable debugging (default: False)
    """
    # Simulate events
    sim = ctools.ctobssim(obs)
    sim["debug"].boolean(debug)
    sim["outevents"].filename("obs.xml")
    sim.execute()

    # Bin events into counts map
    bin = ctools.ctbin()
    bin["inobs"].filename("obs.xml")
    bin["outcube"].filename("cntcube.fits")
    bin["ebinalg"].string("LOG")
    bin["emin"].real(emin)
    bin["emax"].real(emax)
    bin["enumbins"].integer(enumbins)
    bin["nxpix"].integer(nxpix)
    bin["nypix"].integer(nypix)
    bin["binsz"].real(binsz)
    bin["coordsys"].string(coordsys)
    bin["proj"].string(proj)
    bin["xref"].real(ra)
    bin["yref"].real(dec)
    bin["debug"].boolean(debug)
    bin.execute()

    # Create exposure cube
    expcube = ctools.ctexpcube()
    expcube["inobs"].filename("obs.xml")
    expcube["incube"].filename("cntcube.fits")
    expcube["outcube"].filename("expcube.fits")
    expcube["caldb"].string(caldb)
    expcube["irf"].string(irf)
    expcube["ebinalg"].string("LOG")
    expcube["emin"].real(emin)
    expcube["emax"].real(emax)
    expcube["enumbins"].integer(enumbins)
    expcube["nxpix"].integer(nxpix)
    expcube["nypix"].integer(nypix)
    expcube["binsz"].real(binsz)
    expcube["coordsys"].string(coordsys)
    expcube["proj"].string(proj)
    expcube["xref"].real(ra)
    expcube["yref"].real(dec)
    expcube["debug"].boolean(debug)
    expcube.execute()

    # Create PSF cube
    psfcube = ctools.ctpsfcube()
    psfcube["inobs"].filename("obs.xml")
    psfcube["incube"].filename("NONE")
    psfcube["outcube"].filename("psfcube.fits")
    psfcube["caldb"].string(caldb)
    psfcube["irf"].string(irf)
    psfcube["ebinalg"].string("LOG")
    psfcube["emin"].real(emin)
    psfcube["emax"].real(emax)
    psfcube["enumbins"].integer(enumbins)
    psfcube["nxpix"].integer(10)
    psfcube["nypix"].integer(10)
    psfcube["binsz"].real(1.0)
    psfcube["coordsys"].string(coordsys)
    psfcube["proj"].string(proj)
    psfcube["xref"].real(ra)
    psfcube["yref"].real(dec)
    psfcube["debug"].boolean(debug)
    psfcube.execute()

    # Create background cube
    bkgcube = ctools.ctbkgcube()
    bkgcube["inobs"].filename("obs.xml")
    bkgcube["inmodel"].filename(model)
    bkgcube["incube"].filename("cntcube.fits")
    bkgcube["outcube"].filename("bkgcube.fits")
    bkgcube["outmodel"].filename("model_bkg.xml")
    bkgcube["caldb"].string(caldb)
    bkgcube["irf"].string(irf)
    bkgcube["ebinalg"].string("LOG")
    bkgcube["emin"].real(emin)
    bkgcube["emax"].real(emax)
    bkgcube["enumbins"].integer(enumbins)
    bkgcube["nxpix"].integer(10)
    bkgcube["nypix"].integer(10)
    bkgcube["binsz"].real(1.0)
    bkgcube["coordsys"].string(coordsys)
    bkgcube["proj"].string(proj)
    bkgcube["xref"].real(ra)
    bkgcube["yref"].real(dec)
    bkgcube["debug"].boolean(debug)
    bkgcube.execute()

    # Perform maximum likelihood fitting
    like = ctools.ctlike()
    like["inobs"].filename("cntcube.fits")
    like["inmodel"].filename("model_bkg.xml")
    like["outmodel"].filename("fit_results.xml")
    like["expcube"].filename("expcube.fits")
    like["psfcube"].filename("psfcube.fits")
    like["bkgcube"].filename("bkgcube.fits")
    like["caldb"].string(caldb)
    like["irf"].string(irf)
    like["debug"].boolean(True) # Switch this always on for results in console
    like.execute()
	
    # Return
    return
Beispiel #19
0
    def _test_python(self):
        """
        Test ctbkgcube from Python
        """
        # Allocate ctbkgcube
        bkgcube = ctools.ctbkgcube()

        # Check that empty ctbkgcube tool holds a background cube that has
        # no energy bins
        self._check_cube(bkgcube.bkgcube(), nebounds=0)

        # Check that saving does not nothing
        bkgcube['outcube'] = 'ctbkgcube_py0.fits'
        bkgcube['outmodel'] = 'ctbkgcube_py0.xml'
        bkgcube['logfile'] = 'ctbkgcube_py0.log'
        bkgcube.logFileOpen()
        bkgcube.save()
        self.test_assert(not os.path.isfile('ctbkgcube_py0.fits'),
                         'Check that no background cube has been created')

        # Check model container
        self._check_models(gammalib.GModels('ctbkgcube_py0.xml'), nmodels=0)

        # Check saving with empty file names
        bkgcube['outcube'] = ''
        bkgcube['outmodel'] = ''
        bkgcube['logfile'] = 'ctbkgcube_py1.log'
        bkgcube.logFileOpen()
        bkgcube.save()

        # Check saving with "none" model definiton name
        bkgcube['outcube'] = ''
        bkgcube['outmodel'] = 'NONE'
        bkgcube['logfile'] = 'ctbkgcube_py2.log'
        bkgcube.logFileOpen()
        bkgcube.save()

        # Check that publish method with user name does not lead to an
        # exception or segfault
        bkgcube.publish('My background cube')

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

        # Now set ctbkgcube parameters
        bkgcube['inobs'] = self._events
        bkgcube['incube'] = self._cntcube
        bkgcube['inmodel'] = self._model
        bkgcube['caldb'] = self._caldb
        bkgcube['irf'] = self._irf
        bkgcube['outcube'] = 'ctbkgcube_py3.fits'
        bkgcube['outmodel'] = 'ctbkgcube_py3.xml'
        bkgcube['logfile'] = 'ctbkgcube_py3.log'
        bkgcube['chatter'] = 2

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

        # Check result files
        self._check_result_files('ctbkgcube_py3')

        # Copy ctbkgcube tool
        cpy_bkgcube = bkgcube.copy()

        # Check background cube and model container of ctbkgcube copy
        self._check_cube(cpy_bkgcube.bkgcube())
        self._check_models(cpy_bkgcube.models())

        # Execute copy of ctbkgcube tool again, now with a higher chatter
        # level than before. In addition, publish the background cube.
        cpy_bkgcube['outcube'] = 'ctbkgcube_py4.fits'
        cpy_bkgcube['outmodel'] = 'ctbkgcube_py4.xml'
        cpy_bkgcube['logfile'] = 'ctbkgcube_py4.log'
        cpy_bkgcube['chatter'] = 3
        cpy_bkgcube['publish'] = True
        cpy_bkgcube.logFileOpen()  # Make sure we get a log file
        cpy_bkgcube.execute()

        # Check result files
        self._check_result_files('ctbkgcube_py4')

        # Now clear copy of ctbkgcube tool
        cpy_bkgcube.clear()

        # Check that the cleared copy has also cleared the background cube
        # and model container
        self._check_cube(cpy_bkgcube.bkgcube(), nebounds=0)
        self._check_models(cpy_bkgcube.models(), nmodels=0)

        # Get mixel observation container
        obs = self._obs_mixed()
        obs.models(gammalib.GModels(self._model))

        # Set-up ctbkgcube from observation container
        bkgcube = ctools.ctbkgcube(obs)
        bkgcube['incube'] = self._cntcube
        bkgcube['caldb'] = self._caldb
        bkgcube['irf'] = self._irf
        bkgcube['outcube'] = 'ctbkgcube_py5.fits'
        bkgcube['outmodel'] = 'ctbkgcube_py5.xml'
        bkgcube['logfile'] = 'ctbkgcube_py5.log'
        bkgcube['chatter'] = 4

        # Execute ctbkgcube tool
        bkgcube.logFileOpen()  # Make sure we get a log file
        bkgcube.execute()

        # Check result files
        self._check_result_files('ctbkgcube_py5')

        # Return
        return
Beispiel #20
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
Beispiel #21
0
        psfcube['emin'] = 0.02
        psfcube['emax'] = 199.0
        psfcube['enumbins'] = 40
        psfcube['nxpix'] = 12
        psfcube['nypix'] = 12
        psfcube['binsz'] = 1.0
        psfcube['coordsys'] = 'CEL'
        psfcube['proj'] = 'CAR'
        psfcube['xref'] = ra
        psfcube['yref'] = dec
        psfcube['outcube'] = 'psfcube_nu_' + irf + '_' + str(
            int(tobscta)) + 's_' + str(i + 1) + '.fits'
        psfcube['debug'] = debug
        psfcube.execute()

        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()
Beispiel #22
0
def run_pipeline(obs, ra=83.63, dec=22.01, emin=0.1, emax=100.0,
                 enumbins=20, nxpix=200, nypix=200, binsz=0.02,
                 coordsys="CEL", proj="CAR", debug=False):
    """
    Simulation and stacked analysis pipeline.

    Keywords:
     ra       - RA of cube centre [deg] (default: 83.6331)
     dec      - DEC of cube centre [deg] (default: 22.0145)
     emin     - Minimum energy of cube [TeV] (default: 0.1)
     emax     - Maximum energy of cube [TeV] (default: 100.0)
     enumbins - Number of energy bins in cube (default: 20)
     nxpix    - Number of RA pixels in cube (default: 200)
     nypix    - Number of DEC pixels in cube (default: 200)
     binsz    - Spatial cube bin size [deg] (default: 0.02)
     coordsys - Cube coordinate system (CEL or GAL)
     proj     - Cube World Coordinate System (WCS) projection
     debug    - Enable debugging (default: False)
    """
    # Simulate events
    sim = ctools.ctobssim(obs)
    sim["debug"] = debug
    sim.run()

    # Bin events into counts map
    bin = ctools.ctbin(sim.obs())
    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"]     = ra
    bin["yref"]     = dec
    bin["debug"]    = debug
    bin.run()

    # Create exposure cube
    expcube = ctools.ctexpcube(sim.obs())
    expcube["incube"]   = "NONE"
    expcube["ebinalg"]  = "LOG"
    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"]     = ra
    expcube["yref"]     = dec
    expcube["debug"]    = debug
    expcube.run()

    # Create PSF cube
    psfcube = ctools.ctpsfcube(sim.obs())
    psfcube["incube"]   = "NONE"
    psfcube["ebinalg"]  = "LOG"
    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"]     = ra
    psfcube["yref"]     = dec
    psfcube["debug"]    = debug
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(sim.obs())
    bkgcube["incube"]   = "NONE"
    bkgcube["ebinalg"]  = "LOG"
    bkgcube["emin"]     = emin
    bkgcube["emax"]     = emax
    bkgcube["enumbins"] = enumbins
    bkgcube["nxpix"]    = 10
    bkgcube["nypix"]    = 10
    bkgcube["binsz"]    = 1.0
    bkgcube["coordsys"] = coordsys
    bkgcube["proj"]     = proj
    bkgcube["xref"]     = ra
    bkgcube["yref"]     = dec
    bkgcube["debug"]    = debug
    bkgcube.run()

    # 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(), bkgcube.bkgcube())

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    like["debug"] = True # Switch this always on for results in console
    like.run()

    # 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
Beispiel #24
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
Beispiel #25
0
def run_pipeline(obs, ra=83.63, dec=22.01, emin=0.1, emax=100.0,
                 enumbins=20, nxpix=200, nypix=200, binsz=0.02,
                 coordsys="CEL", proj="CAR",
                 model="${CTOOLS}/share/models/crab.xml",
                 caldb="prod2", irf="South_50h",
                 debug=False):
    """
    Simulation and stacked analysis pipeline.

    Keywords:
     ra       - RA of cube centre [deg] (default: 83.6331)
     dec      - DEC of cube centre [deg] (default: 22.0145)
     emin     - Minimum energy of cube [TeV] (default: 0.1)
     emax     - Maximum energy of cube [TeV] (default: 100.0)
     enumbins - Number of energy bins in cube (default: 20)
     nxpix    - Number of RA pixels in cube (default: 200)
     nypix    - Number of DEC pixels in cube (default: 200)
     binsz    - Spatial cube bin size [deg] (default: 0.02)
     coordsys - Cube coordinate system (CEL or GAL)
     proj     - Cube World Coordinate System (WCS) projection
     debug    - Enable debugging (default: False)
    """
    # Simulate events
    sim = ctools.ctobssim(obs)
    sim["debug"]     = debug
    sim["outevents"] = "obs.xml"
    sim.execute()

    # Bin events into counts map
    bin = ctools.ctbin()
    bin["inobs"]    = "obs.xml"
    bin["outcube"]  = "cntcube.fits"
    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"]     = ra
    bin["yref"]     = dec
    bin["debug"]    = debug
    bin.execute()

    # Create exposure cube
    expcube = ctools.ctexpcube()
    expcube["inobs"]    = "obs.xml"
    expcube["incube"]   = "cntcube.fits"
    expcube["outcube"]  = "expcube.fits"
    expcube["caldb"]    = caldb
    expcube["irf"]      = irf
    expcube["ebinalg"]  = "LOG"
    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"]     = ra
    expcube["yref"]     = dec
    expcube["debug"]    = debug
    expcube.execute()

    # Create PSF cube
    psfcube = ctools.ctpsfcube()
    psfcube["inobs"]    = "obs.xml"
    psfcube["incube"]   = "NONE"
    psfcube["outcube"]  = "psfcube.fits"
    psfcube["caldb"]    = caldb
    psfcube["irf"]      = irf
    psfcube["ebinalg"]  = "LOG"
    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"]     = ra
    psfcube["yref"]     = dec
    psfcube["debug"]    = debug
    psfcube.execute()

    # Create background cube
    bkgcube = ctools.ctbkgcube()
    bkgcube["inobs"]    = "obs.xml"
    bkgcube["inmodel"]  = model
    bkgcube["incube"]   = "cntcube.fits"
    bkgcube["outcube"]  = "bkgcube.fits"
    bkgcube["outmodel"] = "model_bkg.xml"
    bkgcube["caldb"]    = caldb
    bkgcube["irf"]      = irf
    bkgcube["ebinalg"]  = "LOG"
    bkgcube["emin"]     = emin
    bkgcube["emax"]     = emax
    bkgcube["enumbins"] = enumbins
    bkgcube["nxpix"]    = 10
    bkgcube["nypix"]    = 10
    bkgcube["binsz"]    = 1.0
    bkgcube["coordsys"] = coordsys
    bkgcube["proj"]     = proj
    bkgcube["xref"]     = ra
    bkgcube["yref"]     = dec
    bkgcube["debug"]    = debug
    bkgcube.execute()

    # Perform maximum likelihood fitting
    like = ctools.ctlike()
    like["inobs"]    = "cntcube.fits"
    like["inmodel"]  = "model_bkg.xml"
    like["outmodel"] = "fit_results.xml"
    like["expcube"]  = "expcube.fits"
    like["psfcube"]  = "psfcube.fits"
    like["bkgcube"]  = "bkgcube.fits"
    like["caldb"]    = caldb
    like["irf"]      = irf
    like["debug"]    = True # Switch this always on for results in console
    like.execute()

    # Return
    return
Beispiel #26
0
def run_pipeline(obs, ra=83.63, dec=22.01, emin=0.1, emax=100.0,
                 enumbins=20, nxpix=200, nypix=200, binsz=0.02,
                 coordsys='CEL', proj='CAR', debug=False):
    """
    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
    """
    # Simulate events
    sim = ctools.ctobssim(obs)
    sim['debug']     = debug
    sim.run()

    # Bin events into counts map
    bin = ctools.ctbin(sim.obs())
    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']     = ra
    bin['yref']     = dec
    bin['debug']    = debug
    bin.run()

    # Create exposure cube
    expcube = ctools.ctexpcube(sim.obs())
    expcube['incube']   = 'NONE'
    expcube['ebinalg']  = 'LOG'
    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']     = ra
    expcube['yref']     = dec
    expcube['debug']    = debug
    expcube.run()

    # Create PSF cube
    psfcube = ctools.ctpsfcube(sim.obs())
    psfcube['incube']   = 'NONE'
    psfcube['ebinalg']  = 'LOG'
    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']     = ra
    psfcube['yref']     = dec
    psfcube['debug']    = debug
    psfcube.run()

    # Create background cube
    bkgcube = ctools.ctbkgcube(sim.obs())
    bkgcube['incube']   = 'NONE'
    bkgcube['ebinalg']  = 'LOG'
    bkgcube['emin']     = emin
    bkgcube['emax']     = emax
    bkgcube['enumbins'] = enumbins
    bkgcube['nxpix']    = 10
    bkgcube['nypix']    = 10
    bkgcube['binsz']    = 1.0
    bkgcube['coordsys'] = coordsys
    bkgcube['proj']     = proj
    bkgcube['xref']     = ra
    bkgcube['yref']     = dec
    bkgcube['debug']    = debug
    bkgcube.run()

    # 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(), bkgcube.bkgcube())

    # Perform maximum likelihood fitting
    like = ctools.ctlike(bin.obs())
    like['debug'] = True # Switch this always on for results in console
    like.run()

    # Return
    return