def ctpsfcube(self,log=False,debug=False, **kwargs): ''' Create ctpsfcube 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 ctpsfcube to compute point spread function (PSF) cube") self.ctpsfcube = ct.ctpsfcube() self._fill_app( self.ctpsfcube,log=log,debug=debug, **kwargs) self.ctpsfcube["incube"] = self.config['file']["cntcube"] self.ctpsfcube["outcube"] = self.config['file']["psfcube"] if self.verbose: print self.ctpsfcube self.ctpsfcube.run() self.ctpsfcube.save() self.info("Saved psfcube to {0:s}".format(self.ctpsfcube["outcube"])) self.ctpsfcube
def test_functional(self): """ Test ctpsfcube functionnality. """ # Set-up ctpsfcube psfcube = ctools.ctpsfcube() psfcube["inobs"].filename(self.events_name) psfcube["incube"].filename("NONE") psfcube["outcube"].filename("psfcube.fits") psfcube["caldb"].string(self.caldb) psfcube["irf"].string(self.irf) psfcube["ebinalg"].string("LOG") psfcube["emin"].real(0.1) psfcube["emax"].real(100.0) psfcube["enumbins"].integer(20) psfcube["nxpix"].integer(10) psfcube["nypix"].integer(10) psfcube["binsz"].real(0.4) psfcube["coordsys"].string("CEL") psfcube["proj"].string("CAR") psfcube["xref"].real(83.63) psfcube["yref"].real(22.01) psfcube["amax"].real(0.3) psfcube["anumbins"].integer(10) # Run tool self.test_try("Run ctpsfcube") try: psfcube.run() self.test_try_success() except: self.test_try_failure("Exception occured in ctpsfcube.") # Save PSF cube self.test_try("Save PSF cube") try: psfcube.save() self.test_try_success() except: self.test_try_failure("Exception occured in saving PSF cube.") # Return return
def test_functional(self): """ Test ctpsfcube functionnality. """ # Set-up ctpsfcube psfcube = ctools.ctpsfcube() psfcube["inobs"] = self.events_name psfcube["incube"] = "NONE" psfcube["outcube"] = "psfcube.fits" psfcube["caldb"] = self.caldb psfcube["irf"] = self.irf psfcube["ebinalg"] = "LOG" psfcube["emin"] = 0.1 psfcube["emax"] = 100 psfcube["enumbins"] = 20 psfcube["nxpix"] = 10 psfcube["nypix"] = 10 psfcube["binsz"] = 0.4 psfcube["coordsys"] = "CEL" psfcube["proj"] = "CAR" psfcube["xref"] = 83.63 psfcube["yref"] = 22.01 psfcube["amax"] = 0.3 psfcube["anumbins"] = 10 # Run tool self.test_try("Run ctpsfcube") try: psfcube.run() self.test_try_success() except: self.test_try_failure("Exception occured in ctpsfcube.") # Save PSF cube self.test_try("Save PSF cube") try: psfcube.save() self.test_try_success() except: self.test_try_failure("Exception occured in saving PSF cube.") # Return return
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()
def _test_python(self): """ Test ctpsfcube from Python """ # Set-up ctpsfcube psfcube = ctools.ctpsfcube() psfcube['inobs'] = self._events psfcube['incube'] = 'NONE' psfcube['outcube'] = 'ctpsfcube_py1.fits' psfcube['caldb'] = self._caldb psfcube['irf'] = self._irf psfcube['ebinalg'] = 'LOG' psfcube['emin'] = 0.1 psfcube['emax'] = 100 psfcube['enumbins'] = 20 psfcube['nxpix'] = 10 psfcube['nypix'] = 10 psfcube['binsz'] = 0.4 psfcube['coordsys'] = 'CEL' psfcube['proj'] = 'CAR' psfcube['xref'] = 83.63 psfcube['yref'] = 22.01 psfcube['amax'] = 0.3 psfcube['anumbins'] = 10 psfcube['logfile'] = 'ctpsfcube_py1.log' psfcube['chatter'] = 2 # Run ctpsfcube tool psfcube.logFileOpen() # Make sure we get a log file psfcube.run() psfcube.save() # Check result file self._check_result_file('ctpsfcube_py1.fits') # Return return
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
def _test_python(self): """ Test ctpsfcube from Python """ # Allocate ctpsfcube psfcube = ctools.ctpsfcube() # Check that empty ctpsfcube tool holds a PSF cube that has no energy # bins self._check_cube(psfcube.psfcube(), nenergies=0) # Check that saving does not nothing psfcube['outcube'] = 'ctpsfcube_py0.fits' psfcube['logfile'] = 'ctpsfcube_py0.log' psfcube.logFileOpen() psfcube.save() self.test_assert(not os.path.isfile('ctpsfcube_py0.fits'), 'Check that no PSF cube has been created') # Check that clearing does not lead to an exception or segfault psfcube.clear() # Now set ctpsfcube parameters psfcube['inobs'] = self._events psfcube['incube'] = 'NONE' psfcube['caldb'] = self._caldb psfcube['irf'] = self._irf psfcube['ebinalg'] = 'LOG' psfcube['emin'] = 0.1 psfcube['emax'] = 100 psfcube['enumbins'] = 20 psfcube['nxpix'] = 10 psfcube['nypix'] = 10 psfcube['binsz'] = 0.4 psfcube['coordsys'] = 'CEL' psfcube['proj'] = 'CAR' psfcube['xref'] = 83.63 psfcube['yref'] = 22.01 psfcube['amax'] = 0.3 psfcube['anumbins'] = 10 psfcube['outcube'] = 'ctpsfcube_py1.fits' psfcube['logfile'] = 'ctpsfcube_py1.log' psfcube['chatter'] = 2 # Run ctpsfcube tool psfcube.logFileOpen() # Make sure we get a log file psfcube.run() psfcube.save() # Check result file self._check_result_file('ctpsfcube_py1.fits') # Copy ctpsfcube tool cpy_psfcube = psfcube.copy() # Check PSF cube of ctpsfcube copy self._check_cube(cpy_psfcube.psfcube()) # Execute copy of ctpsfcube tool again, now with a higher chatter # level than before cpy_psfcube['emin'] = 0.2 cpy_psfcube['emax'] = 150.0 cpy_psfcube['outcube'] = 'ctpsfcube_py2.fits' cpy_psfcube['logfile'] = 'ctpsfcube_py2.log' cpy_psfcube['addbounds'] = True cpy_psfcube['chatter'] = 3 cpy_psfcube.logFileOpen() # Needed to get a new log file cpy_psfcube.execute() # Check result file self._check_result_file('ctpsfcube_py2.fits', nenergies=23) # Now clear copy of ctpsfcube tool cpy_psfcube.clear() # Check that the cleared copy has also cleared the PSF cube self._check_cube(cpy_psfcube.psfcube(), nenergies=0) # Get mixed observation container obs = self._obs_mixed() # Set-up ctpsfcube from observation container and input counts # cube psfcube = ctools.ctpsfcube(obs) psfcube['incube'] = self._cntcube psfcube['caldb'] = self._caldb psfcube['irf'] = self._irf #psfcube['ebinalg'] = 'LOG' #psfcube['emin'] = 0.1 #psfcube['emax'] = 100 #psfcube['enumbins'] = 20 #psfcube['nxpix'] = 10 #psfcube['nypix'] = 10 #psfcube['binsz'] = 0.4 #psfcube['coordsys'] = 'CEL' #psfcube['proj'] = 'CAR' #psfcube['xref'] = 83.63 #psfcube['yref'] = 22.01 psfcube['amax'] = 0.3 psfcube['anumbins'] = 10 psfcube['addbounds'] = True psfcube['outcube'] = 'ctpsfcube_py3.fits' psfcube['logfile'] = 'ctpsfcube_py3.log' psfcube['chatter'] = 4 # Execute ctpsfcube tool psfcube.logFileOpen() # Make sure we get a log file psfcube.execute() # Check result file self._check_result_file('ctpsfcube_py3.fits') # Return return
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
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
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
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
def psf_cube(output_dir, map_reso, map_coord, map_fov, emin, emax, enumbins, ebinalg, amax=0.3, anumbins=200, logfile=None, silent=False): """ Compute a PSF cube. http://cta.irap.omp.eu/ctools/users/reference_manual/ctpsfcube.html Note that the number of point in energy corresponds to the bin poles. Parameters ---------- - output_dir (str): directory where to get input files and save outputs - map_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 - amax (float): Upper bound of angular separation between true and measued photon direction (in degrees). - anumbins (int): Number of angular separation bins. - silent (bool): use this keyword to print information Outputs -------- - Ana_Psfcube.fits: the fits PSF cube image """ npix = utilities.npix_from_fov_def(map_fov, map_reso) psfcube = ctools.ctpsfcube() psfcube['inobs'] = output_dir + '/Ana_EventsSelected.xml' psfcube['incube'] = output_dir + '/Ana_Countscube.fits' #psfcube['caldb'] = #psfcube['irf'] = psfcube['outcube'] = output_dir + '/Ana_Psfcube.fits' psfcube['ebinalg'] = ebinalg psfcube['emin'] = emin.to_value('TeV') psfcube['emax'] = emax.to_value('TeV') psfcube['enumbins'] = enumbins psfcube['ebinfile'] = 'NONE' psfcube['addbounds'] = False psfcube['usepnt'] = False psfcube['nxpix'] = npix psfcube['nypix'] = npix psfcube['binsz'] = map_reso.to_value('deg') psfcube['coordsys'] = 'CEL' psfcube['proj'] = 'TAN' psfcube['xref'] = map_coord.icrs.ra.to_value('deg') psfcube['yref'] = map_coord.icrs.dec.to_value('deg') psfcube['amax'] = amax psfcube['anumbins'] = anumbins if logfile is not None: psfcube['logfile'] = logfile if logfile is not None: psfcube.logFileOpen() psfcube.execute() if logfile is not None: psfcube.logFileClose() if not silent: print(psfcube) print('') return psfcube
def _test_python(self): """ Test ctpsfcube from Python """ # Allocate ctpsfcube psfcube = ctools.ctpsfcube() # Check that empty ctpsfcube tool holds a PSF cube that has no energy # bins self._check_cube(psfcube.psfcube(), nenergies=0) # Check that saving does not nothing psfcube['outcube'] = 'ctpsfcube_py0.fits' psfcube['logfile'] = 'ctpsfcube_py0.log' psfcube.logFileOpen() psfcube.save() self.test_assert(not os.path.isfile('ctpsfcube_py0.fits'), 'Check that no PSF cube has been created') # Check that clearing does not lead to an exception or segfault psfcube.clear() # Now set ctpsfcube parameters psfcube['inobs'] = self._events psfcube['incube'] = 'NONE' psfcube['caldb'] = self._caldb psfcube['irf'] = self._irf psfcube['ebinalg'] = 'LOG' psfcube['emin'] = 1.0 psfcube['emax'] = 100 psfcube['enumbins'] = 5 psfcube['nxpix'] = 10 psfcube['nypix'] = 10 psfcube['binsz'] = 0.4 psfcube['coordsys'] = 'CEL' psfcube['proj'] = 'CAR' psfcube['xref'] = 83.63 psfcube['yref'] = 22.01 psfcube['amax'] = 0.3 psfcube['anumbins'] = 10 psfcube['outcube'] = 'ctpsfcube_py1.fits' psfcube['logfile'] = 'ctpsfcube_py1.log' psfcube['chatter'] = 2 # Run ctpsfcube tool psfcube.logFileOpen() # Make sure we get a log file psfcube.run() psfcube.save() # Check result file self._check_result_file('ctpsfcube_py1.fits') # Copy ctpsfcube tool cpy_psfcube = psfcube.copy() # Check PSF cube of ctpsfcube copy self._check_cube(cpy_psfcube.psfcube()) # Execute copy of ctpsfcube tool again, now with a higher chatter # level than before cpy_psfcube['emin'] = 0.2 cpy_psfcube['emax'] = 150.0 cpy_psfcube['outcube'] = 'ctpsfcube_py2.fits' cpy_psfcube['logfile'] = 'ctpsfcube_py2.log' cpy_psfcube['addbounds'] = True cpy_psfcube['chatter'] = 3 cpy_psfcube.logFileOpen() # Needed to get a new log file cpy_psfcube.execute() # Check result file self._check_result_file('ctpsfcube_py2.fits', nenergies=8) # Now clear copy of ctpsfcube tool cpy_psfcube.clear() # Check that the cleared copy has also cleared the PSF cube self._check_cube(cpy_psfcube.psfcube(), nenergies=0) # Get mixed observation container obs = self._obs_mixed() # Set-up ctpsfcube from observation container and input counts # cube psfcube = ctools.ctpsfcube(obs) psfcube['incube'] = self._cntcube psfcube['caldb'] = self._caldb psfcube['irf'] = self._irf psfcube['amax'] = 0.3 psfcube['anumbins'] = 10 psfcube['addbounds'] = True psfcube['outcube'] = 'ctpsfcube_py3.fits' psfcube['logfile'] = 'ctpsfcube_py3.log' psfcube['chatter'] = 4 # Execute ctpsfcube tool psfcube.logFileOpen() # Make sure we get a log file psfcube.execute() # Check result file self._check_result_file('ctpsfcube_py3.fits') # Return return
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
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
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 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
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
binning['debug'] = debug binning.execute() expcube = ctools.ctexpcube() expcube['inobs'] = 'events_nu_' + irf + '_' + str( int(tobscta)) + 's_' + str(i + 1) + '.fits' expcube['caldb'] = caldb expcube['irf'] = irf expcube['incube'] = 'cntcube_nu_' + irf + '_' + str( int(tobscta)) + 's_' + str(i + 1) + '.fits' expcube['outcube'] = 'expcube_nu_' + irf + '_' + str( int(tobscta)) + 's_' + str(i + 1) + '.fits' expcube['debug'] = debug expcube.execute() psfcube = ctools.ctpsfcube() psfcube['inobs'] = 'events_nu_' + irf + '_' + str( int(tobscta)) + 's_' + str(i + 1) + '.fits' psfcube['caldb'] = caldb psfcube['irf'] = irf psfcube['incube'] = 'NONE' psfcube['ebinalg'] = 'LOG' 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
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
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
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 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
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