コード例 #1
0
ファイル: LikeFit.py プロジェクト: chankeh/CTAtools
    def ctmodel(self, log=False, debug=False):
        '''
        Create ctmodel 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 ctmodel to create model map")
        if self.m_obs:
            model = ct.ctmodel(self.m_obs)
        else:
            model = ct.ctmodel()

            for k in self.config.keys():
                try:
                    for kk in self.config[k].keys():
                        if model._has_par(kk):
                            model[kk] = self.config[k][kk]
                except:
                    if model._has_par(k):
                        model[k] = self.config[k]

            model["inobs"] = join(self.workdir,
                                  self.config['file']["selectedevent"])
            model["incube"] = join(self.workdir, self.config['file']["cube"])
            model["outcube"] = join(self.workdir, self.config['file']["model"])

        # Optionally open the log file
        if log:
            model.logFileOpen()

        # Optionally switch-on debugging model
        if debug:
            model["debug"].boolean(True)

        if self.verbose:
            print model

        # Run ctbin application. This will loop over all observations in
        # the container and bin the events in counts maps
        model.run()
        model.save()
        if self.m_obs:
            # Make a deep copy of the observation that will be returned
            # (the ctbin object will go out of scope one the function is
            # left)
            self.m_obs = model.obs().copy()
コード例 #2
0
    def ctmodel(self,obsXml= None, log=False,debug=False, **kwargs):
        '''
        Create ctmodel 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 ctmodel to create model map")

        self.model= ct.ctmodel()

        self._fill_app( self.model,log=log,debug=debug, **kwargs)

        self.model["incube"] = join(self.outdir,self.config['file']["cntcube"])
        self.model["outcube"] = join(self.outdir,self.config['file']["model"])

        if self.verbose:
            print self.model

        # Run ctmodel application. This will loop over all observations in
        # the container and bin the events in counts maps
        self.model.run()
        self.model.save()
        self.info("Saved Model cube to {0:s}".format(self.model["outcube"]))

        del self.model
コード例 #3
0
def create_modcube(obs, cntcube):
    """
    Create model cube

    Parameters
    ----------
    obs : `~gammalib.GObservations`
        Observation container
    cntcube : `~gammalib.GCTAEventCube`
        Counts cube

    Returns
    -------
    modcube : `~gammalib.GCTAEventCube`
        Model cube
    """
    # Setup task parameters
    ctmodel = ctools.ctmodel(obs)
    ctmodel.cube(cntcube)

    # Generate model cube
    ctmodel.run()

    # Extract model cube
    modcube = ctmodel.cube().copy()

    # Return model cube
    return modcube
コード例 #4
0
    def _sim(self, seed):
        """
        Return a simulated observation container

        Parameters
        ----------
        seed : int
            Random number generator seed

        Returns
        -------
        sim : `~gammalib.GObservations`
            Simulated observation container
        """
        # If observation is a counts cube then simulate events from the counts
        # cube model ...
        if self.obs().size() == 1 and self.obs()[0].eventtype() == 'CountsCube':

            # If no counts cube model exists then compute it now
            if self._model == None:
                model            = ctools.ctmodel(self.obs())
                model['debug']   = self['debug'].boolean()
                model['chatter'] = self['chatter'].integer()
                model.run()
                self._model = model.cube().copy() # Save copy for persistence

            # Allocate random number generator
            ran = gammalib.GRan()

            # Get copy of model map
            counts = self._model.counts().copy()

            # Randomize counts
            for i in range(counts.npix()):
                counts[i] = ran.poisson(counts[i])

            # Copy observations
            sim = self.obs().copy()

            # Set counts map
            sim[0].events().counts(counts)

        # ... otherwise simuate events from the observation container (works
        # only for event lists
        else:
            sim = obsutils.sim(self.obs(),
                               seed     = seed,
                               log      = self._log_clients,
                               debug    = self['debug'].boolean(),
                               nthreads = 1)

        # Return simulated observation
        return sim
コード例 #5
0
ファイル: cstsdist.py プロジェクト: ctools/ctools
    def _sim(self, seed):
        """
        Return a simulated observation container

        Parameters
        ----------
        seed : int
            Random number generator seed

        Returns
        -------
        sim : `~gammalib.GObservations`
            Simulated observation container
        """
        # If observation is a counts cube then simulate events from the counts
        # cube model ...
        if self.obs().size() == 1 and self.obs()[0].eventtype() == 'CountsCube':

            # If no counts cube model exists then compute it now
            if self._model == None:
                model            = ctools.ctmodel(self.obs())
                model['debug']   = self['debug'].boolean()
                model['chatter'] = self['chatter'].integer()
                model.run()
                self._model = model.cube().copy() # Save copy for persistence

            # Allocate random number generator
            ran = gammalib.GRan()

            # Get copy of model map
            counts = self._model.counts().copy()

            # Randomize counts
            for i in range(counts.npix()):
                counts[i] = ran.poisson(counts[i])

            # Copy observations
            sim = self.obs().copy()

            # Set counts map
            sim[0].events().counts(counts)

        # ... otherwise simuate events from the observation container (works
        # only for event lists
        else:
            sim = obsutils.sim(self.obs(),
                               seed  = seed,
                               log   = self._log_clients,
                               debug = self['debug'].boolean())

        # Return simulated observation
        return sim
コード例 #6
0
ファイル: test_ctmodel.py プロジェクト: jdevin/ctools
    def test_functional(self):
        """
        Test ctmodel functionnality.
        """
        # Set-up ctmodel from scratch
        model = ctools.ctmodel()
        model["incube"]   = "NONE"
        model["outcube"]  = "modmap.fits"
        model["inmodel"]  = self.model_name
        model["inobs"]    = "NONE"
        model["expcube"]  = "NONE"
        model["psfcube"]  = "NONE"
        model["bkgcube"]  = "NONE"
        model["caldb"]    = self.caldb
        model["irf"]      = self.irf
        model["rad"]      = 5
        model["ra"]       = 83.63
        model["dec"]      = 22.01
        model["tmin"]     = 0
        model["tmax"]     = 1800
        model["emin"]     = 0.1
        model["emax"]     = 100
        model["enumbins"] = 20
        model["nxpix"]    = 200
        model["nypix"]    = 200
        model["binsz"]    = 0.02
        model["coordsys"] = "CEL"
        model["proj"]     = "CAR"
        model["xref"]     = 83.63
        model["yref"]     = 22.01

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

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

        # Return
        return
コード例 #7
0
ファイル: test_ctmodel.py プロジェクト: lyang54/ctools
    def test_functional(self):
        """
        Test ctmodel functionnality.
        """
        # Set-up ctmodel from scratch
        model = ctools.ctmodel()
        model["incube"].filename("NONE")
        model["outcube"].filename("modmap.fits")
        model["inmodel"].filename(self.model_name)
        model["inobs"].filename("NONE")
        model["expcube"].filename("NONE")
        model["psfcube"].filename("NONE")
        model["bkgcube"].filename("NONE")
        model["caldb"].string(self.caldb)
        model["irf"].string(self.irf)
        model["rad"].real(5.0)
        model["ra"].real(83.63)
        model["dec"].real(22.01)
        model["tmin"].real(0.0)
        model["tmax"].real(1800.0)
        model["emin"].real(0.1)
        model["emax"].real(100.0)
        model["enumbins"].integer(20)
        model["nxpix"].integer(200)
        model["nypix"].integer(200)
        model["binsz"].real(0.02)
        model["coordsys"].string("CEL")
        model["proj"].string("CAR")
        model["xref"].real(83.63)
        model["yref"].real(22.01)
        
        # Run tool
        self.test_try("Run ctmodel")
        try:
            model.run()
            self.test_try_success()
        except:
            self.test_try_failure("Exception occured in ctmodel.")

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

        # Return
        return
コード例 #8
0
ファイル: acceptance.py プロジェクト: rbuehler/IACTbackground
def sim(src="cCrab"):  #bkg, Crabbkg
    "Simulates acceptance ccube and model cube"
    print 30 * "-" + "\n", "Simulating", src + "\n" + 30 * "-"
    #Simulate observation
    sim = ctools.ctobssim()
    sim["inmodel"] = modeldir + src + ".xml"
    sim["outevents"] = outdir + "events_" + src + ".fits"
    sim["caldb"] = caldb
    sim["irf"] = irf
    sim["ra"] = ra
    sim["dec"] = dec
    sim["rad"] = 10.0
    sim["tmin"] = 0.0
    sim["tmax"] = tsim
    sim["emin"] = emin
    sim["emax"] = emax
    sim["edisp"] = False
    sim.execute()

    #Bin data into a cube
    ctbin = ctools.ctbin()
    ctbin["inobs"] = outdir + "events_" + src + ".fits"
    ctbin["outcube"] = outdir + "ccube_" + src + ".fits"
    ctbin["ebinalg"] = "LOG"
    ctbin["emin"] = emin
    ctbin["emax"] = emax
    ctbin["enumbins"] = enumbins
    ctbin["nxpix"] = npix
    ctbin["nypix"] = npix
    ctbin["binsz"] = binsz
    ctbin["coordsys"] = "CEL"
    ctbin["xref"] = ra
    ctbin["yref"] = dec
    ctbin["proj"] = "AIT"
    ctbin.execute()

    #Create model cube
    ctmodel = ctools.ctmodel()
    ctmodel["inobs"] = outdir + "events_" + src + ".fits"
    ctmodel["inmodel"] = modeldir + src + ".xml"
    ctmodel["incube"] = outdir + "ccube_" + src + ".fits"
    ctmodel["caldb"] = "prod2"
    ctmodel["caldb"] = caldb
    ctmodel["irf"] = irf
    ctmodel["outcube"] = outdir + "mcube_" + src + ".fits"
    ctmodel["edisp"] = False
    ctmodel.execute()
コード例 #9
0
ファイル: test_ctmodel.py プロジェクト: xxxhycl2010/ctools
    def _test_python(self):
        """
        Test ctmodel from Python
        """
        # Set-up ctmodel from scratch
        model = ctools.ctmodel()
        model['incube'] = 'NONE'
        model['outcube'] = 'ctmodel_py1.fits'
        model['inmodel'] = self._model
        model['inobs'] = 'NONE'
        model['expcube'] = 'NONE'
        model['psfcube'] = 'NONE'
        model['bkgcube'] = 'NONE'
        model['caldb'] = self._caldb
        model['irf'] = self._irf
        model['rad'] = 5
        model['ra'] = 83.63
        model['dec'] = 22.01
        model['tmin'] = 0
        model['tmax'] = 1800
        model['emin'] = 0.1
        model['emax'] = 100
        model['enumbins'] = 20
        model['nxpix'] = 200
        model['nypix'] = 200
        model['binsz'] = 0.02
        model['coordsys'] = 'CEL'
        model['proj'] = 'CAR'
        model['xref'] = 83.63
        model['yref'] = 22.01
        model['logfile'] = 'ctmodel_py1.log'
        model['chatter'] = 2

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

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

        # Return
        return
コード例 #10
0
ファイル: csresmap.py プロジェクト: ctools/ctools
    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 observation into logger
        self._log_observations(gammalib.NORMAL, self.obs(), 'Observation')

        # If a counts and model cube are specified then load them as sky map
        if self._use_maps:
            countmap = gammalib.GSkyMap(self['inobs'].filename())
            modelmap = gammalib.GSkyMap(self['modcube'].filename())

        # ... otherwise build a counts cube and model cube
        else:

            # Do not build counts cube if we have already one in the observation
            # container
            if self._skip_binning:
                cta_counts_cube = gammalib.GCTAEventCube(self.obs()[0].events())

            # ... otherwise generate one now from the event list
            else:

                # Write header
                self._log_header1(gammalib.TERSE, 'Generate binned map (ctbin)')

                # Create countsmap
                binning = ctools.ctbin(self.obs())
                binning['xref']     = self['xref'].real()
                binning['yref']     = self['yref'].real()
                binning['proj']     = self['proj'].string()
                binning['coordsys'] = self['coordsys'].string()
                binning['ebinalg']  = self['ebinalg'].string()
                binning['nxpix']    = self['nxpix'].integer()
                binning['nypix']    = self['nypix'].integer()
                binning['binsz']    = self['binsz'].real()
                if self['ebinalg'].string() == 'FILE':
                    binning['ebinfile'] = self['ebinfile'].filename().file()
                else:
                    binning['enumbins'] = self['enumbins'].integer()
                    binning['emin']     = self['emin'].real()
                    binning['emax']     = self['emax'].real()
                binning['chatter']  = self['chatter'].integer()
                binning['clobber']  = self['clobber'].boolean()
                binning['debug']    = self['debug'].boolean()
                binning.run()

                # Retrieve counts cube
                cta_counts_cube = binning.cube()

            # Assign GCTAEventCube to skymap
            countmap = cta_counts_cube.counts()

            # Write header
            self._log_header1(gammalib.TERSE, 'Generate model map (ctmodel)')

            # Create model map
            model = ctools.ctmodel(self.obs())
            model.cube(cta_counts_cube)
            model['chatter'] = self['chatter'].integer()
            model['clobber'] = self['clobber'].boolean()
            model['debug']   = self['debug'].boolean()
            model['edisp']   = self['edisp'].boolean()
            model.run()

            # Get model map into GSkyMap object
            modelmap = model.cube().counts().copy()

        # Calculate residual maps
        # Note that we need a special
        # construct here to avoid memory leaks. This seems to be a SWIG feature
        # as SWIG creates a new object when calling binning.cube()
        countmap1 = countmap.copy()
        countmap1.stack_maps()
        modelmap.stack_maps()
        self._resmap = obsutils.residuals(self,countmap1,modelmap)

        # Optionally publish map
        if self['publish'].boolean():
            self.publish()

        # Return
        return
コード例 #11
0
ファイル: csresmap.py プロジェクト: jdevin/ctools
    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")

        # Use input file directly if given
        if self.m_use_maps:
            countmap = gammalib.GSkyMap(self["inobs"].filename())
            modelmap = gammalib.GSkyMap(self.m_modcube)

        else:

            if self.m_skip_binning:
                cta_counts_cube = gammalib.GCTAEventCube(self.obs[0].events().clone())   

            else:

                # Write header
                if self.logTerse():
                    self.log("\n")
                    self.log.header1("Generate binned map (ctbin)")

                # Create countsmap
                bin = ctools.ctbin(self.obs)
                bin["nxpix"].integer(self.m_nxpix)
                bin["nypix"].integer(self.m_nypix)
                bin["proj"].string(self.m_proj)
                bin["coordsys"].string(self.m_coordsys)
                bin["xref"].real(self.m_xref)
                bin["yref"].real(self.m_yref)
                bin["enumbins"].integer(self.m_enumbins)
                bin["ebinalg"].string(self.m_ebinalg)
                bin["emin"].real(self.m_emin)
                bin["emax"].real(self.m_emax)
                bin["binsz"].real(self.m_binsz)
                bin["chatter"].integer(self.m_chatter)
                bin["clobber"].boolean(self.m_clobber)
                bin["debug"].boolean(self.m_debug)
                bin.run()

                # Retrieve counts cube
                cta_counts_cube = bin.cube()

            # Assign GCTAEventCube to skymap
            countmap = cta_counts_cube.map()

            # Write header
            if self.logTerse():
                self.log("\n")
                self.log.header1("Generate model map (ctmodel)")

            # Create model map
            model = ctools.ctmodel(self.obs)
            model.cube(cta_counts_cube)
            model["chatter"].integer(self.m_chatter)
            model["clobber"].boolean(self.m_clobber)
            model["debug"].boolean(self.m_debug)
            model["edisp"].boolean(self.m_edisp)
            model.run()

            # Get model map into GSkyMap object
            modelmap = model.cube().map().copy()


        # Store counts map as residual map. Note that we need a
        # special construct here to avoid memory leaks. This seems
        # to be a SWIG feature as SWIG creates a new object when
        # calling bin.cube()
        #residualmap = bin.cube().map() 
        self.resmap = countmap.copy()
        self.resmap.stack_maps()
        modelmap.stack_maps()

        # Continue calculations depending on given algorithm
        if self.m_algorithm == "SUB":

            # Subtract maps 
            self.resmap -= modelmap

        elif self.m_algorithm == "SUBDIV":

            # Subtract and divide by model map
            self.resmap -= modelmap
            self.resmap /= modelmap
            #for pixel in modelmap:
            #    if pixel != 0.0:
            #        pixel = 1.0/pixel
            #self.resmap *= modelmap

        elif self.m_algorithm == "SUBDIVSQRT":

            # subtract and divide by sqrt of model map
            self.resmap -= modelmap
            self.resmap /= modelmap.sqrt()
            #for pixel in modelmap:
            #    if pixel != 0.0:
            #        pixel = 1.0/math.sqrt(pixel)
            #self.resmap *= modelmap

        else:

            # Raise error if algorithm is unkown
            raise TypeError("Algorithm \""+self.m_algorithm+"\" not known")

        # Return
        return
コード例 #12
0
def model_cube(output_dir,
               map_reso,
               map_coord,
               map_fov,
               emin,
               emax,
               enumbins,
               ebinalg,
               edisp=False,
               stack=True,
               inmodel_usr=None,
               outmap_usr=None,
               logfile=None,
               silent=False):
    """
    Compute a model cube.
    http://cta.irap.omp.eu/ctools/users/reference_manual/ctmodel.html

    Parameters
    ----------
    - output_dir (str): directory where to get input files and 
    save outputs
    - map_reso (float): the resolution of the map (can be an
    astropy.unit object, or in deg)
    - map_coord (float): a skycoord object that give the center of the map
    - map_fov (float): the field of view of the map (can be an 
    astropy.unit object, or in deg)
    - emin/emax (float): min and max energy in TeV
    - enumbins (int): the number of energy bins
    - ebinalg (str): the energy binning algorithm
    - stack (bool): do we use stacking of individual event files or not
    - inmodel_usr (str): use this keyword to pass non default inmodel
    - outmap_usr (str): use this keyword to pass non default outmap
    - silent (bool): use this keyword to print information

    Outputs
    --------
    """

    npix = utilities.npix_from_fov_def(map_fov, map_reso)

    model = ctools.ctmodel()

    if stack:
        model['inobs'] = output_dir + '/Ana_Countscube.fits'
    else:
        model['inobs'] = output_dir + '/Ana_ObsDef.xml'
    if inmodel_usr is None:
        model['inmodel'] = output_dir + '/Ana_Model_Output.xml'
    else:
        model['inmodel'] = inmodel_usr
    model['incube'] = 'NONE'
    model['expcube'] = 'NONE'
    model['psfcube'] = 'NONE'
    model['edispcube'] = 'NONE'
    model['bkgcube'] = 'NONE'
    if stack:
        model['incube'] = output_dir + '/Ana_Countscube.fits'
        model['expcube'] = output_dir + '/Ana_Expcube.fits'
        model['psfcube'] = output_dir + '/Ana_Psfcube.fits'
        if edisp:
            model['edispcube'] = output_dir + '/Ana_Edispcube.fits'
        model['bkgcube'] = output_dir + '/Ana_Bkgcube.fits'

    model['caldb'] = 'NONE'
    model['irf'] = 'NONE'
    model['edisp'] = edisp
    if outmap_usr is None:
        model['outcube'] = output_dir + '/Ana_Model_Cube.fits'
    else:
        model['outcube'] = outmap_usr
    model['ra'] = 'NONE'
    model['dec'] = 'NONE'
    model['rad'] = 'NONE'
    model['tmin'] = 'NONE'
    model['tmax'] = 'NONE'
    model['deadc'] = 'NONE'
    model['ebinalg'] = ebinalg
    model['emin'] = emin.to_value('TeV')
    model['emax'] = emax.to_value('TeV')
    model['enumbins'] = enumbins
    model['ebinfile'] = 'NONE'
    model['usepnt'] = False
    model['nxpix'] = npix
    model['nypix'] = npix
    model['binsz'] = map_reso.to_value('deg')
    model['coordsys'] = 'CEL'
    model['proj'] = 'TAN'
    model['xref'] = map_coord.icrs.ra.to_value('deg')
    model['yref'] = map_coord.icrs.dec.to_value('deg')
    if logfile is not None: model['logfile'] = logfile

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

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

    return model
コード例 #13
0
ファイル: observations_KSP.py プロジェクト: misabelber/LMC
binn = ctools.ctbin()
binn["inobs"] = outfile
binn["outcube"] = cntcube
binn["coordsys"] = "CEL"
binn["proj"] = "CAR"
binn["ebinalg"] = "LOG"
binn["xref"] = centerx
binn["yref"] = centery
binn["nxpix"] = nxpix
binn["nypix"] = nypix
binn["binsz"] = binsz
binn["enumbins"] = enumbins
binn["emin"] = emin
binn["emax"] = emax
binn["debug"] = True
binn.execute()

#PRODUCE MODELCUBE
mod = ctools.ctmodel()
mod["inobs"] = outfile
mod["inmodel"] = input_model
mod["outcube"] = modcube
mod["incube"] = cntcube
mod["expcube"] = "NONE"
mod["psfcube"] = "NONE"
mod["bkgcube"] = "NONE"
mod["caldb"] = caldb_
mod["irf"] = irf_
mod["debug"] = True
mod.execute()
コード例 #14
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 observation into logger
        if self._logTerse():
            self._log("\n")
            self._log.header1("Observation")
            self._log(str(self._obs))
            self._log("\n")

        # Use input file directly if given
        if self._use_maps:
            countmap = gammalib.GSkyMap(self["inobs"].filename())
            modelmap = gammalib.GSkyMap(self._modcube)

        else:

            # ...
            if self._skip_binning:
                cta_counts_cube = gammalib.GCTAEventCube(self._obs[0].events().clone())   

            # ...
            else:

                # Write header
                if self._logTerse():
                    self._log("\n")
                    self._log.header1("Generate binned map (ctbin)")

                # Create countsmap
                bin = ctools.ctbin(self._obs)
                bin["nxpix"].integer(self._nxpix)
                bin["nypix"].integer(self._nypix)
                bin["proj"].string(self._proj)
                bin["coordsys"].string(self._coordsys)
                bin["xref"].real(self._xref)
                bin["yref"].real(self._yref)
                bin["enumbins"].integer(self._enumbins)
                bin["ebinalg"].string(self._ebinalg)
                bin["emin"].real(self._emin)
                bin["emax"].real(self._emax)
                bin["binsz"].real(self._binsz)
                bin["chatter"].integer(self._chatter)
                bin["clobber"].boolean(self._clobber)
                bin["debug"].boolean(self._debug)
                bin.run()

                # Retrieve counts cube
                cta_counts_cube = bin.cube()

            # Assign GCTAEventCube to skymap
            countmap = cta_counts_cube.counts()

            # Write header
            if self._logTerse():
                self._log("\n")
                self._log.header1("Generate model map (ctmodel)")

            # Create model map
            model = ctools.ctmodel(self._obs)
            model.cube(cta_counts_cube)
            model["chatter"].integer(self._chatter)
            model["clobber"].boolean(self._clobber)
            model["debug"].boolean(self._debug)
            model["edisp"].boolean(self._edisp)
            model.run()

            # Get model map into GSkyMap object
            modelmap = model.cube().counts().copy()

        # Store counts map as residual map. Note that we need a
        # special construct here to avoid memory leaks. This seems
        # to be a SWIG feature as SWIG creates a new object when
        # calling bin.cube()
        #residualmap = bin.cube().counts()
        self._resmap = countmap.copy()
        self._resmap.stack_maps()
        modelmap.stack_maps()

        # Continue calculations depending on given algorithm
        if self._algorithm == "SUB":

            # Subtract maps 
            self._resmap -= modelmap

        elif self._algorithm == "SUBDIV":

            # Subtract and divide by model map
            self._resmap -= modelmap
            self._resmap /= modelmap
            #for pixel in modelmap:
            #    if pixel != 0.0:
            #        pixel = 1.0/pixel
            #self._resmap *= modelmap

        elif self._algorithm == "SUBDIVSQRT":

            # subtract and divide by sqrt of model map
            self._resmap -= modelmap
            self._resmap /= modelmap.sqrt()
            #for pixel in modelmap:
            #    if pixel != 0.0:
            #        pixel = 1.0/math.sqrt(pixel)
            #self._resmap *= modelmap

        else:

            # Raise error if algorithm is unkown
            raise TypeError("Algorithm \""+self._algorithm+"\" not known")

        # Optionally publish map
        if self._publish:
            self.publish()

        # Return
        return
コード例 #15
0
    def _test_python(self):
        """
        Test ctmodel from Python
        """
        # Allocate ctmodel
        model = ctools.ctmodel()

        # Check that empty ctmodel tool holds an empty model cube
        self._check_cube(model.cube(), nx=0, ny=0, nebins=0)

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

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

        # Now set ctmodel parameters
        model['incube'] = 'NONE'
        model['inmodel'] = self._model
        model['inobs'] = 'NONE'
        model['expcube'] = 'NONE'
        model['psfcube'] = 'NONE'
        model['bkgcube'] = 'NONE'
        model['caldb'] = self._caldb
        model['irf'] = self._irf
        model['rad'] = 5
        model['ra'] = 83.63
        model['dec'] = 22.01
        model['tmin'] = 0
        model['tmax'] = 1800
        model['ebinalg'] = 'LOG'
        model['emin'] = 1.0
        model['emax'] = 100.0
        model['enumbins'] = 5
        model['nxpix'] = 40
        model['nypix'] = 40
        model['binsz'] = 0.1
        model['coordsys'] = 'CEL'
        model['proj'] = 'CAR'
        model['xref'] = 83.63
        model['yref'] = 22.01
        model['outcube'] = 'ctmodel_py1.fits'
        model['logfile'] = 'ctmodel_py1.log'
        model['chatter'] = 2

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

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

        # Copy ctmodel tool
        cpy_model = model.copy()

        # Check model cube of ctmodel copy
        self._check_cube(cpy_model.cube())

        # Execute copy of ctmodel tool again, now with a higher chatter
        # level than before
        cpy_model['outcube'] = 'ctmodel_py2.fits'
        cpy_model['logfile'] = 'ctmodel_py2.log'
        cpy_model['publish'] = True
        cpy_model['chatter'] = 3
        cpy_model.logFileOpen()  # Needed to get a new log file
        cpy_model.execute()

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

        # Now clear copy of ctmodel tool
        cpy_model.clear()

        # Check that the cleared copy has also cleared the model cube
        self._check_cube(cpy_model.cube(), nx=0, ny=0, nebins=0)

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

        # Setup ctmodel tool from observation container and get model cube
        # definition from counts cube
        model = ctools.ctmodel(obs)
        model.models(gammalib.GModels(self._model))
        model['incube'] = self._cntcube
        model['expcube'] = 'NONE'
        model['psfcube'] = 'NONE'
        model['bkgcube'] = 'NONE'
        model['caldb'] = self._caldb
        model['irf'] = self._irf
        model['outcube'] = 'ctmodel_py3.fits'
        model['logfile'] = 'ctmodel_py3.log'
        model['chatter'] = 4

        # Execute ctmodel tool
        model.logFileOpen()  # Needed to get a new log file
        model.execute()

        # Check result file
        self._check_result_file('ctmodel_py3.fits', nx=20, ny=20, nebins=5)

        # Publish with name
        model.publish('My model')

        # Setup ctmodel from event list FITS file
        model = ctools.ctmodel()
        model['inobs'] = self._events
        model['incube'] = 'NONE'
        model['inmodel'] = self._model
        model['expcube'] = 'NONE'
        model['psfcube'] = 'NONE'
        model['edispcube'] = 'NONE'
        model['bkgcube'] = 'NONE'
        model['caldb'] = self._caldb
        model['irf'] = self._irf
        model['rad'] = 5
        model['ra'] = 83.63
        model['dec'] = 22.01
        model['tmin'] = 0
        model['tmax'] = 1800
        model['ebinalg'] = 'LOG'
        model['emin'] = 1.0
        model['emax'] = 100.0
        model['enumbins'] = 5
        model['nxpix'] = 40
        model['nypix'] = 40
        model['binsz'] = 0.1
        model['coordsys'] = 'CEL'
        model['proj'] = 'CAR'
        model['xref'] = 83.63
        model['yref'] = 22.01
        model['outcube'] = 'ctmodel_py4.fits'
        model['logfile'] = 'ctmodel_py4.log'
        model['chatter'] = 2

        # Run ctmodel tool
        model.logFileOpen()  # Make sure we get a log file
        model.execute()

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

        # Setup ctmodel from observation definition XML file
        model = ctools.ctmodel()
        model['inobs'] = self._obs_unbinned
        model['incube'] = 'NONE'
        model['inmodel'] = self._model
        model['expcube'] = 'NONE'
        model['psfcube'] = 'NONE'
        model['edispcube'] = 'NONE'
        model['bkgcube'] = 'NONE'
        model['caldb'] = self._caldb
        model['irf'] = self._irf
        model['rad'] = 5
        model['ra'] = 83.63
        model['dec'] = 22.01
        model['tmin'] = 0
        model['tmax'] = 1800
        model['ebinalg'] = 'LOG'
        model['emin'] = 1.0
        model['emax'] = 100.0
        model['enumbins'] = 5
        model['nxpix'] = 40
        model['nypix'] = 40
        model['binsz'] = 0.1
        model['coordsys'] = 'CEL'
        model['proj'] = 'CAR'
        model['xref'] = 83.63
        model['yref'] = 22.01
        model['outcube'] = 'ctmodel_py5.fits'
        model['logfile'] = 'ctmodel_py5.log'
        model['chatter'] = 2

        # Run ctmodel tool
        model.logFileOpen()  # Make sure we get a log file
        model.execute()

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

        # Setup ctmodel for stacked IRF
        model = ctools.ctmodel()
        model['inobs'] = 'NONE'
        model['incube'] = 'NONE'
        model['inmodel'] = self._bkgmodel
        model['expcube'] = self._expcube
        model['psfcube'] = self._psfcube
        model['edispcube'] = 'NONE'
        model['bkgcube'] = self._bkgcube
        model['edisp'] = False
        model['rad'] = 5
        model['ra'] = 83.63
        model['dec'] = 22.01
        model['tmin'] = 0
        model['tmax'] = 1800
        model['ebinalg'] = 'LOG'
        model['emin'] = 1.0
        model['emax'] = 100.0
        model['enumbins'] = 5
        model['nxpix'] = 40
        model['nypix'] = 40
        model['binsz'] = 0.1
        model['coordsys'] = 'CEL'
        model['proj'] = 'CAR'
        model['xref'] = 83.63
        model['yref'] = 22.01
        model['outcube'] = 'ctmodel_py6.fits'
        model['logfile'] = 'ctmodel_py6.log'
        model['chatter'] = 2

        # Run ctmodel tool
        model.logFileOpen()  # Make sure we get a log file
        model.execute()

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

        # Setup ctmodel for stacked IRF using energy dispersion
        model = ctools.ctmodel()
        model['inobs'] = 'NONE'
        model['incube'] = 'NONE'
        model['inmodel'] = self._bkgmodel
        model['expcube'] = self._expcube
        model['psfcube'] = self._psfcube
        model['edispcube'] = self._edispcube
        model['bkgcube'] = self._bkgcube
        model['edisp'] = True
        model['rad'] = 5
        model['ra'] = 83.63
        model['dec'] = 22.01
        model['tmin'] = 0
        model['tmax'] = 1800
        model['ebinalg'] = 'LOG'
        model['emin'] = 1.0
        model['emax'] = 100.0
        model['enumbins'] = 5
        model['nxpix'] = 40
        model['nypix'] = 40
        model['binsz'] = 0.1
        model['coordsys'] = 'CEL'
        model['proj'] = 'CAR'
        model['xref'] = 83.63
        model['yref'] = 22.01
        model['outcube'] = 'ctmodel_py7.fits'
        model['logfile'] = 'ctmodel_py7.log'
        model['chatter'] = 2

        # Run ctmodel tool
        model.logFileOpen()  # Make sure we get a log file
        model.execute()

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

        # Return
        return
コード例 #16
0
ファイル: test_ctmodel.py プロジェクト: ctools/ctools
    def _test_python(self):
        """
        Test ctmodel from Python
        """
        # Allocate ctmodel
        model = ctools.ctmodel()

        # Check that empty ctmodel tool holds an empty model cube
        self._check_cube(model.cube(), nx=0, ny=0, nebins=0)

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

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

        # Now set ctmodel parameters
        model['incube']   = 'NONE'
        model['inmodel']  = self._model
        model['inobs']    = 'NONE'
        model['expcube']  = 'NONE'
        model['psfcube']  = 'NONE'
        model['bkgcube']  = 'NONE'
        model['caldb']    = self._caldb
        model['irf']      = self._irf
        model['rad']      = 5
        model['ra']       = 83.63
        model['dec']      = 22.01
        model['tmin']     = 0
        model['tmax']     = 1800
        model['ebinalg']  = 'LOG'
        model['emin']     = 0.1
        model['emax']     = 100.0
        model['enumbins'] = 10
        model['nxpix']    = 40
        model['nypix']    = 40
        model['binsz']    = 0.1
        model['coordsys'] = 'CEL'
        model['proj']     = 'CAR'
        model['xref']     = 83.63
        model['yref']     = 22.01
        model['outcube']  = 'ctmodel_py1.fits'
        model['logfile']  = 'ctmodel_py1.log'
        model['chatter']  = 2

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

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

        # Copy ctmodel tool
        cpy_model = model.copy()

        # Check model cube of ctmodel copy
        self._check_cube(cpy_model.cube())

        # Execute copy of ctmodel tool again, now with a higher chatter
        # level than before
        cpy_model['outcube'] = 'ctmodel_py2.fits'
        cpy_model['logfile'] = 'ctmodel_py2.log'
        cpy_model['publish'] = True
        cpy_model['chatter'] = 3
        cpy_model.logFileOpen()  # Needed to get a new log file
        cpy_model.execute()

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

        # Now clear copy of ctmodel tool
        cpy_model.clear()

        # Check that the cleared copy has also cleared the model cube
        self._check_cube(cpy_model.cube(), nx=0, ny=0, nebins=0)

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

        # Setup ctmodel tool from observation container and get model cube
        # definition from counts cube
        model = ctools.ctmodel(obs)
        model.models(gammalib.GModels(self._model))
        model['incube']   = self._cntcube
        model['expcube']  = 'NONE'
        model['psfcube']  = 'NONE'
        model['bkgcube']  = 'NONE'
        model['caldb']    = self._caldb
        model['irf']      = self._irf
        model['outcube']  = 'ctmodel_py3.fits'
        model['logfile']  = 'ctmodel_py3.log'
        model['chatter']  = 4

        # Execute ctmodel tool
        model.logFileOpen()  # Needed to get a new log file
        model.execute()

        # Check result file
        self._check_result_file('ctmodel_py3.fits', nx=200, ny=200, nebins=20)

        # Publish with name
        model.publish('My model')

        # Return
        return
コード例 #17
0
    def _residuals_3D(self, obs, models, obs_id, ccube=None):
        """
        Calculate residuals for 3D observation

        Parameters
        ----------
        obs : `~gammalib.GCTAObservation`
            CTA observation
        models : `~gammalib.GModels`
            Models
        obs_id : str
            Observation ID
        ccube : `~gammalib.GCTAEventCube', optional
            Count cube with stacked events lists

        Returns
        -------
        result : dict
            Residual result dictionary
        """
        # Create observation container with observation
        obs_container = gammalib.GObservations()
        obs_container.append(obs)
        obs_container.models(models)

        # If binned data already exist set the evlist_info dictionary to have
        # attribute was_list False
        if obs.eventtype() == 'CountsCube' or ccube is not None:
            evlist_info = {'was_list': False}

        # ... otherwise bin now
        else:
            # we remember if we binned an event list so that we can
            # mask only the ROI for residual calculation
            msg = 'Setting up binned observation'
            self._log_string(gammalib.NORMAL, msg)
            obs_container, evlist_info = self._bin_evlist(obs_container)

        # Calculate Model and residuals. If model cube is provided load
        # it
        if self._use_maps:
            modcube = gammalib.GCTAEventCube(self['modcube'].filename())

        # ... otherwise calculate it now
        else:
            msg = 'Computing model cube'
            self._log_string(gammalib.NORMAL, msg)
            modelcube = ctools.ctmodel(obs_container)
            if ccube is not None:
                modelcube.cube(ccube)
            modelcube['edisp'] = self['edisp'].boolean()
            modelcube.run()
            modcube = modelcube.cube().copy()

        # Extract cntcube for residual computation
        if ccube is not None:
            cntcube = ccube
        else:
            cntcube = obs_container[0].events().copy()

        # Derive count spectra from cubes
        msg = 'Computing counts, model, and residual spectra'
        self._log_string(gammalib.NORMAL, msg)
        counts = self._cube_to_spectrum(cntcube, evlist_info)
        model = self._cube_to_spectrum(modcube, evlist_info)

        # Calculate residuals
        residuals = obsutils.residuals(self, counts, model)

        # Extract energy bounds
        ebounds = cntcube.ebounds().copy()

        # Set result dictionary
        result = {
            'obs_id': obs_id,
            'ebounds': ebounds,
            'counts_on': counts,
            'model': model,
            'residuals_on': residuals
        }

        # Calculate models of individual components if requested
        if self['components'].boolean():

            # Loop over components
            for component in models:

                # Log action
                self._log_value(gammalib.NORMAL, 'Computing model component',
                                component.name())

                # Set model cube models to individual component
                model_cont = gammalib.GModels()
                model_cont.append(component)
                modelcube.obs().models(model_cont)

                # Reset base cube that was modified internally by ctmodel
                if ccube is not None:
                    modelcube.cube(ccube)

                # Run model cube
                modelcube['edisp'] = self['edisp'].boolean()
                modelcube.run()

                # Extract spectrum of individual component
                modcube = modelcube.cube().copy()
                model = self._cube_to_spectrum(modcube, evlist_info)

                # Append to results
                result['component_%s' % component.name()] = model

        # Return result
        return result