diff --git a/cscripts/csfindobs.py b/cscripts/csfindobs.py index e5090a0..da8d8aa 100755 --- a/cscripts/csfindobs.py +++ b/cscripts/csfindobs.py @@ -18,11 +18,11 @@ # along with this program. If not, see . # # ========================================================================== -import gammalib -import ctools import sys import os import json +import gammalib +import ctools # =============== # @@ -145,7 +145,7 @@ class csfindobs(ctools.cscript): if not filename.is_fits(): raise RuntimeError('Observation index file "'+ self._obs_index+ - '"[OBS_INDEX]" for FITS data store "'+ + '[OBS_INDEX]" for FITS data store "'+ self._prodname+ '" not available. Check your master index '+ 'file or run csiactdata to get a list of '+ diff --git a/cscripts/csiactcopy.py b/cscripts/csiactcopy.py index bd7b859..e4da88f 100755 --- a/cscripts/csiactcopy.py +++ b/cscripts/csiactcopy.py @@ -18,19 +18,19 @@ # along with this program. If not, see . # # ========================================================================== -import gammalib -import ctools import sys import os import json import shutil +import gammalib +import ctools # ================ # # csiactdata class # # ================ # class csiactcopy(ctools.cscript): """ - Copies IACT data from remote machine. + Copies IACT data from remote machine This script copies IACT data from one location to another. It can take a list of observation IDs to allow the download specific @@ -64,7 +64,7 @@ class csiactcopy(ctools.cscript): # Private methods def _get_parameters(self): """ - Get parameters from parfile and setup the observation. + Get parameters from parfile and setup the observation """ # Get Parameters @@ -134,7 +134,7 @@ class csiactcopy(ctools.cscript): else: # Create directory if not existent - dest_dir = os.path.dirname(destination) + dest_dir = os.path.dirname(destination) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) @@ -154,8 +154,9 @@ class csiactcopy(ctools.cscript): def _merge(self, localfits, remotefits, hduname, clobber): """ - merge remote and local fits file - If local fits file not present, a new one is created + Merge remote and local fits files + + If the local fits file is not present, a new one is created. """ if self._logTerse(): @@ -216,8 +217,8 @@ class csiactcopy(ctools.cscript): # Create file name remotefile = remotefits + selection - # open remote fits file - remote = gammalib.GFits(str(remotefile)) + # Open remote fits file + remote = gammalib.GFits(str(remotefile)) # If first iteration, create clone of FITS column for later use if i == 0: @@ -236,7 +237,7 @@ class csiactcopy(ctools.cscript): # Loop over rows and columns to copy over values exteding remote HDU for col in tmp_hdu: for row in range(col.length()): - remote_hdu[col.name()][size + row] = col[row] + remote_hdu[col.name()][size + row] = col[row] # Get remote obs_id remote_obs = [] @@ -472,14 +473,14 @@ class csiactcopy(ctools.cscript): for row in range(table.nrows()): # Get observation ID - obs_id = table['OBS_ID'][row] - file_dir = table['FILE_DIR'][row] - file_name = table['FILE_NAME'][row] + obs_id = table['OBS_ID'][row] + file_dir = table['FILE_DIR'][row] + file_name = table['FILE_NAME'][row] # Skip if filename is empty if file_name == '': continue - + # Check if we need to consider an input runlist if len(self._runs): @@ -499,7 +500,7 @@ class csiactcopy(ctools.cscript): if has_size and newlen > oldlen: cp_size += table['SIZE'][row] - # Otherwise add every file + # Otherwise add every file else: # Get filename fname = os.path.join(os.path.dirname(remote_hdu), @@ -531,7 +532,7 @@ class csiactcopy(ctools.cscript): for filename in files: self._log(str(filename)+'\n') - # Close HDU index file + # Close HDU index file fits.close() # If prodname is not found just log that we skip the config @@ -541,15 +542,15 @@ class csiactcopy(ctools.cscript): self._log.header3('Skipping config "'+ str(config['name'])+'"') self._log('\n') - - # Raise Exception if prodname was not found + + # Raise Exception if prodname was not found if not has_prod: msg = '*** ERROR: FITS production "'+self._prodname+'" not ' msg += 'available. Available productions are:\n' for config in configs: msg += ' - '+config['name']+'\n' raise RuntimeError(msg) - + # Logging if self._logNormal(): self._log('\n') @@ -624,7 +625,7 @@ class csiactcopy(ctools.cscript): if self._logTerse(): self._log('\n') - self._log.header3('OBS index') + self._log.header3('OBS index') # Merge remote index files with local files self._merge(local_obs, remote_obs, 'OBS_INDEX', self._clobber()) @@ -678,7 +679,7 @@ class csiactcopy(ctools.cscript): self._log('Keeping "'+str(config['name'])+'"') self._log('\n') - # Signals that downloaded config is available + # Signals that downloaded config is available if config['name'] == self._prodname: has_config = True @@ -697,7 +698,7 @@ class csiactcopy(ctools.cscript): f = open(localmaster, 'w') data['datasets'] = newconfigs json.dump(data, f, indent=2) - f.close() + f.close() # Log summary if self._logNormal(): diff --git a/cscripts/csiactdata.py b/cscripts/csiactdata.py index 81d05ca..266ca6e 100755 --- a/cscripts/csiactdata.py +++ b/cscripts/csiactdata.py @@ -18,11 +18,11 @@ # along with this program. If not, see . # # ========================================================================== -import gammalib -import ctools import sys import os import json +import gammalib +import ctools # ================ # @@ -30,7 +30,7 @@ import json # ================ # class csiactdata(ctools.cscript): """ - Inspect an IACT data storage. + Inspect an IACT data storage This script inspects the available FITS data storage on the user machine and writes information about the available FITS configurations into a log @@ -44,12 +44,12 @@ class csiactdata(ctools.cscript): Constructor. """ # Set name - self._name = "csiactdata" - self._version = "1.1.0" - self._datapath = os.getenv("VHEFITS","") + self._name = 'csiactdata' + self._version = '1.1.0' + self._datapath = os.getenv('VHEFITS','') self._prodnames = [] - self._master_indx = "" - self._master_file = "" + self._master_indx = '' + self._master_file = '' # Initialise application by calling the appropriate class # constructor. @@ -62,18 +62,18 @@ class csiactdata(ctools.cscript): # Private methods def _get_parameters(self): """ - Get parameters from parfile and setup the observation. + Get parameters from parfile and setup the observation """ # Get datapath if not already set - if self._datapath == "": - self._datapath = self["datapath"].string() + if self._datapath == '': + self._datapath = self['datapath'].string() # Expand environment self._datapath = gammalib.expand_env(self._datapath) # Get filename of master index file - self._master_indx = self["master_indx"].string() + self._master_indx = self['master_indx'].string() self._master_file = os.path.join(self._datapath, self._master_indx) # Check for presence of master index file @@ -86,7 +86,7 @@ class csiactdata(ctools.cscript): # Write input parameters into logger if self._logTerse(): self._log_parameters() - self._log("\n") + self._log('\n') # Return return @@ -94,28 +94,28 @@ class csiactdata(ctools.cscript): # Log configuration def _log_configuration(self, config): """ - Log configuration. + Log configuration """ # Log information if self._logTerse(): - self._log.header3(str(config["name"])) - self._log.parformat("Name") - self._log(str(config["name"])) - self._log("\n") - self._log.parformat("Observation index") - self._log(str(config["obsindx"])) - self._log("\n") - self._log.parformat("HDU index") - self._log(str(config["hduindx"])) - self._log("\n") + self._log.header3(str(config['name'])) + self._log.parformat('Name') + self._log(str(config['name'])) + self._log('\n') + self._log.parformat('Observation index') + self._log(str(config['obsindx'])) + self._log('\n') + self._log.parformat('HDU index') + self._log(str(config['hduindx'])) + self._log('\n') # Print additional information for key in config: - if key in ["name","hduindx","obsindx"]: + if key in ['name','hduindx','obsindx']: continue self._log.parformat(str(key)) self._log(str(config[key])) - self._log("\n") + self._log('\n') # Return return @@ -124,7 +124,7 @@ class csiactdata(ctools.cscript): # Public methods def run(self): """ - Run the script. + Run the script """ # Switch screen logging on in debug mode if self._logDebug(): @@ -135,39 +135,39 @@ class csiactdata(ctools.cscript): # Write header into logger if self._logTerse(): - self._log("\n") - self._log.header1("Data storage entries") - self._log.parformat("Master index file") + self._log('\n') + self._log.header1('Data storage entries') + self._log.parformat('Master index file') self._log(self._master_file) - self._log("\n") + self._log('\n') # Open and load JSON file json_data = open(self._master_file).read() data = json.loads(json_data) - configs = data["datasets"] + configs = data['datasets'] # Initialise array for available names self._prodnames = [] # Write header into logger - self._log("\n") - self._log.header2("Available data configs") + self._log('\n') + self._log.header2('Available data configs') # Loop over configs and log available configs for config in configs: # Create hdu and obs index files - hdu = os.path.join(self._datapath, config["hduindx"]) - obs = os.path.join(self._datapath, config["obsindx"]) - filename_hdu = gammalib.GFilename(str(hdu)+"[HDU_INDEX]") - filename_obs = gammalib.GFilename(str(obs)+"[OBS_INDEX]") + hdu = os.path.join(self._datapath, config['hduindx']) + obs = os.path.join(self._datapath, config['obsindx']) + filename_hdu = gammalib.GFilename(str(hdu)+'[HDU_INDEX]') + filename_obs = gammalib.GFilename(str(obs)+'[OBS_INDEX]') # If index files are available then log configuration # information ... if (filename_hdu.is_fits() and filename_obs.is_fits()): # Append to available names - self._prodnames.append(str(config["name"])) + self._prodnames.append(str(config['name'])) # Log information self._log_configuration(config) @@ -175,15 +175,15 @@ class csiactdata(ctools.cscript): # ... otherwise log that the configuration is not available else: if self._logTerse(): - self._log.header3(str(config["name"])) - self._log(" Not available\n") + self._log.header3(str(config['name'])) + self._log(' Not available\n') # Return return def execute(self): """ - Execute the script. + Execute the script """ # Open logfile self.logFileOpen() @@ -198,11 +198,12 @@ class csiactdata(ctools.cscript): """ Return available FITS production names - Returns: + Returns + ------- + names : list of str List of available FITS production names. """ - - # Return + # Return return self._prodnames diff --git a/cscripts/csiactobs.py b/cscripts/csiactobs.py index c508768..27d9e89 100755 --- a/cscripts/csiactobs.py +++ b/cscripts/csiactobs.py @@ -18,11 +18,11 @@ # along with this program. If not, see . # # ========================================================================== -import gammalib -import ctools import sys import os import json +import gammalib +import ctools # =============== # @@ -30,7 +30,7 @@ import json # =============== # class csiactobs(ctools.cscript): """ - Generates an IACT observation definition XML file. + Generates an IACT observation definition XML file This class implements the creation of a observation xml file for IACT data analysis. This class is dedicated for use inside a IACT @@ -143,8 +143,8 @@ class csiactobs(ctools.cscript): self._ev_hiera = self['ev_hiera'].string().split('|') self._aeff_hiera = self['aeff_hiera'].string().split('|') self._psf_hiera = self['psf_hiera'].string().split('|') - self._bkg_hiera = self['bkg_hiera'].string().split('|') - self._edisp_hiera = self['edisp_hiera'].string().split('|') + self._bkg_hiera = self['bkg_hiera'].string().split('|') + self._edisp_hiera = self['edisp_hiera'].string().split('|') self._bkg_mod_hiera = self['bkg_mod_hiera'].string().split('|') # Read hidden background parameters @@ -264,7 +264,7 @@ class csiactobs(ctools.cscript): spec[1].fix() else: spec[0].free() - spec[1].free() + spec[1].free() else: @@ -319,7 +319,8 @@ class csiactobs(ctools.cscript): bck = gammalib.GCTAModelRadialAcceptance(radial, spec) else: - sys.exit('Background type "'+self._bkgtype+'" unsupported') + msg = 'Background type "'+self._bkgtype+'" unsupported' + raise RuntimeError(msg) # Copy model model = bck.clone() @@ -366,7 +367,7 @@ class csiactobs(ctools.cscript): self._log.header1('Looping over '+str(len(self._runlist))+' runs') # Initialise energy range values for logging - self._ebounds.clear() + self._ebounds.clear() # Loop over runs for obs_id in self._runlist: @@ -396,12 +397,15 @@ class csiactobs(ctools.cscript): index = formats.index(version) break if index >= 0: - eventfile = os.path.join(self._subdir, hduindx_hdu['FILE_DIR'][index], hduindx_hdu['FILE_NAME'][index]) + eventfile = os.path.join(self._subdir, + hduindx_hdu['FILE_DIR'][index], + hduindx_hdu['FILE_NAME'][index]) eventhdu = hduindx_hdu['HDU_NAME'][index] eventfile += '['+eventhdu+']' if not gammalib.GFilename(eventfile).is_fits(): if self._logTerse(): - self._log('Skipping observation '+str(obs_id)+': eventfile "'+eventfile+'" not found\n') + self._log('Skipping observation '+str(obs_id)+ + ': eventfile "'+eventfile+'" not found\n') continue # Handle Aeff @@ -412,12 +416,15 @@ class csiactobs(ctools.cscript): index = formats.index(version) break if index >= 0: - aefffile = os.path.join(self._subdir, hduindx_hdu['FILE_DIR'][index], hduindx_hdu['FILE_NAME'][index]) + aefffile = os.path.join(self._subdir, + hduindx_hdu['FILE_DIR'][index], + hduindx_hdu['FILE_NAME'][index]) aeffhdu = hduindx_hdu['HDU_NAME'][index] aefffile += '['+aeffhdu+']' if not gammalib.GFilename(aefffile).is_fits(): if self._logTerse(): - self._log('Skipping observation '+str(obs_id)+': effective area "'+aefffile+'" not found\n') + self._log('Skipping observation '+str(obs_id)+ + ': effective area "'+aefffile+'" not found\n') continue # Handle psf @@ -428,11 +435,15 @@ class csiactobs(ctools.cscript): index = formats.index(version) break if index >= 0: - psffile = os.path.join(self._subdir, hduindx_hdu['FILE_DIR'][index], hduindx_hdu['FILE_NAME'][index]) + psffile = os.path.join(self._subdir, + hduindx_hdu['FILE_DIR'][index], + hduindx_hdu['FILE_NAME'][index]) psffile += '['+hduindx_hdu['HDU_NAME'][index]+']' if not gammalib.GFilename(psffile).is_fits(): if self._logTerse(): - self._log('Skipping observation '+str(obs_id)+': point spread function "'+psffile+'" not found\n') + self._log('Skipping observation '+str(obs_id)+ + ': point spread function "'+psffile+ + '" not found\n') continue # Handle edisp @@ -443,11 +454,15 @@ class csiactobs(ctools.cscript): index = formats.index(version) break if index >= 0: - edispfile = os.path.join(self._subdir, hduindx_hdu['FILE_DIR'][index], hduindx_hdu['FILE_NAME'][index]) + edispfile = os.path.join(self._subdir, + hduindx_hdu['FILE_DIR'][index], + hduindx_hdu['FILE_NAME'][index]) edispfile += '['+hduindx_hdu['HDU_NAME'][index]+']' if not gammalib.GFilename(edispfile).is_fits(): if self._logTerse(): - self._log('Warning: observation '+str(obs_id)+' has no energy dispersion "'+edispfile+'" information\n') + self._log('Warning: observation '+str(obs_id)+ + ' has no energy dispersion "'+edispfile+ + '" information\n') edispfile = '' # Handle background @@ -459,20 +474,27 @@ class csiactobs(ctools.cscript): index = formats.index(version) break if index >= 0: - bkgfile = os.path.join(self._subdir, hduindx_hdu['FILE_DIR'][index], hduindx_hdu['FILE_NAME'][index]) + bkgfile = os.path.join(self._subdir, + hduindx_hdu['FILE_DIR'][index], + hduindx_hdu['FILE_NAME'][index]) bkgfile += '['+hduindx_hdu['HDU_NAME'][index]+']' if 'irf' in bkg_mod_hierarchy and not gammalib.GFilename(bkgfile).is_fits(): bkg_mod_hierarchy.remove('irf') if self._logTerse(): - self._log('Warning: observation '+str(obs_id)+' has no background information (file="'+bkgfile+'"). IRF background cannot be used\n') + self._log('Warning: observation '+str(obs_id)+ + ' has no background information (file="'+ + bkgfile+'"). IRF background cannot be used\n') bkgfile = '' if len(bkg_mod_hierarchy) == 0: if self._logTerse(): - self._log('Skipping observation '+str(obs_id)+': No background can be used\n') + self._log('Skipping observation '+str(obs_id)+ + ': No background can be used\n') continue else: if self._logTerse(): - self._log('Observation '+str(obs_id)+': Falling back to background "'+bkg_mod_hierarchy[0]+'"\n') + self._log('Observation '+str(obs_id)+ + ': Falling back to background "'+ + bkg_mod_hierarchy[0]+'"\n') # Close hdu index file hduindx.close() @@ -480,15 +502,15 @@ class csiactobs(ctools.cscript): # Handle background scale information if available bkg_scale = 1.0 if self._use_bkg_scale: - obsindx = gammalib.GFits(self._obs_index+'[OBS_INDEX]'+obs_selection) + obsindx = gammalib.GFits(self._obs_index+'[OBS_INDEX]'+obs_selection) bkg_scale = obsindx['OBS_INDEX']['BKG_SCALE'][0] obsindx.close() # Open fits file to determine the observation name - fits = gammalib.GFits(eventfile) - events = fits[eventhdu] + fits = gammalib.GFits(eventfile) + events = fits[eventhdu] object_name = events.string('OBJECT') - telescope = events.string('TELESCOP') + telescope = events.string('TELESCOP') # Close FITS file fits.close() @@ -516,11 +538,17 @@ class csiactobs(ctools.cscript): aeff_fits.close() # Append instrumental background model - self._models.append(self._iact_background(telescope, obs_id, bkg_scale, bkg_mod_hierarchy[0], run_emin.TeV(), run_emax.TeV())) + self._models.append(self._iact_background(telescope, + obs_id, + bkg_scale, + bkg_mod_hierarchy[0], + run_emin.TeV(), + run_emax.TeV())) # Logging if self._logTerse(): - self._log('Adding observation '+str(obs_id)+' ("'+object_name+'")\n') + self._log('Adding observation '+str(obs_id)+ + ' ("'+object_name+'")\n') if self._logExplicit(): self._log(' Event file: '+eventfile+'\n') @@ -606,7 +634,7 @@ class csiactobs(ctools.cscript): def execute(self): """ - Execute the script. + Execute the script """ # Open logfile self.logFileOpen() @@ -621,7 +649,9 @@ class csiactobs(ctools.cscript): return def save(self): - + """ + Save model definition XML file + """ # Save observation XML file self._xml.save(self._outobs) @@ -633,8 +663,9 @@ class csiactobs(ctools.cscript): def ebounds(self): """ - Returns runlist energy range + Return runlist energy boundaries """ + # Return energy boundaries return self._ebounds def obs(self): diff --git a/cscripts/csmodelinfo.py b/cscripts/csmodelinfo.py index a431aaf..fd913fa 100755 --- a/cscripts/csmodelinfo.py +++ b/cscripts/csmodelinfo.py @@ -18,9 +18,9 @@ # along with this program. If not, see . # # ========================================================================== +import sys import gammalib import ctools -import sys # ================= # diff --git a/cscripts/csmodelmerge.py b/cscripts/csmodelmerge.py index f2e8ef5..558e428 100755 --- a/cscripts/csmodelmerge.py +++ b/cscripts/csmodelmerge.py @@ -18,10 +18,10 @@ # along with this program. If not, see . # # ========================================================================== -import gammalib -import ctools import sys import glob +import gammalib +import ctools # ================== # @@ -29,7 +29,7 @@ import glob # ================== # class csmodelmerge(ctools.cscript): """ - Merge model definition XML files. + Merge model definition XML files An arbitrary number of model definition XML files will be merged into a single model definition XML file. @@ -41,8 +41,8 @@ class csmodelmerge(ctools.cscript): Constructor. """ # Set name - self._name = "csmodelmerge" - self._version = "1.1.0" + self._name = 'csmodelmerge' + self._version = '1.1.0' # Initialise class members self._files = None @@ -59,45 +59,45 @@ class csmodelmerge(ctools.cscript): # Private methods def _get_parameters(self): """ - Get parameters from parfile. + Get parameters from parfile """ # Get input models string - inmodels = self["inmodels"].string() + inmodels = self['inmodels'].string() # Handle ascii files - if "@" == inmodels[0]: - self._files = open(inmodels.replace("@","")).read().splitlines() + if '@' == inmodels[0]: + self._files = open(inmodels.replace('@','')).read().splitlines() # Handle wild card strings - elif "*" in inmodels: + elif '*' in inmodels: self._files = glob.glob(inmodels) # Handle space separated list - elif " " in inmodels: - self._files = inmodels.split(" ") + elif ' ' in inmodels: + self._files = inmodels.split(' ') # Handle semi-colon separated list - elif ";" in inmodels: - self._files = inmodels.split(";") + elif ';' in inmodels: + self._files = inmodels.split(';') # Throw exception if input models cannot be decoded else: - msg = "Parameter \"inmodels\" must contain either an @ASCII "\ - "file, a semi-colon-separated or whitespace-separated "\ - "list of files or a wildcard string." - raise RuntimeError(msg) + msg = 'Parameter "inmodels" must contain either an @ASCII '\ + 'file, a semi-colon-separated or whitespace-separated '\ + 'list of files or a wildcard string.' + raise RuntimeError(msg) # Read ahead output filename if self._read_ahead(): - self["outmodel"].filename() + self['outmodel'].filename() # Get clobber parameter - self._clobber = self["clobber"].boolean() + self._clobber = self['clobber'].boolean() # Write input parameters into logger if self._logTerse(): self._log_parameters() - self._log("\n") + self._log('\n') # Return return @@ -106,7 +106,7 @@ class csmodelmerge(ctools.cscript): # Public methods def run(self): """ - Run the script. + Run the script """ # Switch screen logging on in debug mode if self._logDebug(): @@ -117,8 +117,8 @@ class csmodelmerge(ctools.cscript): # Write header if self._logTerse(): - self._log("\n") - self._log.header1("Merge models") + self._log('\n') + self._log.header1('Merge models') # Initialise model container self._models = gammalib.GModels() @@ -133,23 +133,23 @@ class csmodelmerge(ctools.cscript): if self._logTerse(): nmodels = models.size() if nmodels == 0: - self._log(gammalib.parformat("Add no model from file")) + self._log(gammalib.parformat('Add no model from file')) elif nmodels == 1: - self._log(gammalib.parformat("Add 1 model from file")) + self._log(gammalib.parformat('Add 1 model from file')) else: - self._log(gammalib.parformat("Add %d models from file" % + self._log(gammalib.parformat('Add %d models from file' % nmodels)) self._log(file_) - self._log("\n") + self._log('\n') # Extend model container by adding all models in the model file self._models.extend(models) # Log total number of models if self._logTerse(): - self._log(gammalib.parformat("Models after merging")) + self._log(gammalib.parformat('Models after merging')) self._log(self._models.size()) - self._log("\n") + self._log('\n') # Return return @@ -160,29 +160,25 @@ class csmodelmerge(ctools.cscript): """ # Write header if self._logTerse(): - self._log("\n") - self._log.header1("Save models") + self._log('\n') + self._log.header1('Save models') # Get output filename in case it was not read ahead - outmodel = self["outmodel"].filename() + outmodel = self['outmodel'].filename() - # Check if file exists and apply clobber if false + # If file exists and clobber flag is false then raise an exception if outmodel.exists() and not self._clobber: - - # Set error message - msg = "Cannot save \""+outmodel.url()+"\": File already exists " - msg += "Use parameter clobber=yes to allow overwriting of files." - - # Throw exception since file cannnot be overwritten + msg = 'Cannot save ""+outmodel.url()+"": File already exists. '\ + 'Use parameter clobber=yes to allow overwriting of files.' raise RuntimeError(msg) else: # Log filename if self._logTerse(): - self._log(gammalib.parformat("Model definition XML file")) + self._log(gammalib.parformat('Model definition XML file')) self._log(outmodel.url()) - self._log("\n") + self._log('\n') # Save models self._models.save(outmodel) @@ -192,7 +188,7 @@ class csmodelmerge(ctools.cscript): def execute(self): """ - Execute the script. + Execute the script """ # Open logfile self.logFileOpen() diff --git a/cscripts/csobsinfo.py b/cscripts/csobsinfo.py index 45e9f24..2ba529f 100755 --- a/cscripts/csobsinfo.py +++ b/cscripts/csobsinfo.py @@ -18,9 +18,9 @@ # along with this program. If not, see . # # ========================================================================== +import sys import gammalib import ctools -import sys # =============== # @@ -28,7 +28,7 @@ import sys # =============== # class csobsinfo(ctools.cscript): """ - Shows the content of an observation container. + Shows the content of an observation container """ # Constructor @@ -37,8 +37,8 @@ class csobsinfo(ctools.cscript): Constructor. """ # Set name - self._name = "csobsinfo" - self._version = "1.1.0" + self._name = 'csobsinfo' + self._version = '1.1.0' # Initialise class members self._obj_dir = None @@ -65,31 +65,31 @@ class csobsinfo(ctools.cscript): # Private methods def _get_parameters(self): """ - Get parameters from parfile and setup the observation. + Get parameters from parfile and setup the observation """ # Get parameters if self._obs.size() == 0: - self._require_inobs("csobsinfo::get_parameters") + self._require_inobs('csobsinfo::get_parameters') self._obs = self._get_observations(False) # Initialise object position self._obj_dir = gammalib.GSkyDir() # Get (optional) offset parameters - self._compute_offset = self["offset"].boolean() + self._compute_offset = self['offset'].boolean() if self._compute_offset: - ra = self["ra"].real() - dec = self["dec"].real() + ra = self['ra'].real() + dec = self['dec'].real() self._obj_dir.radec_deg(ra,dec) # Read ahead DS9 filename if self._read_ahead(): - self["ds9file"].filename() + self['ds9file'].filename() # Write input parameters into logger if self._logTerse(): self._log_parameters() - self._log("\n") + self._log('\n') # Return return @@ -98,7 +98,7 @@ class csobsinfo(ctools.cscript): # Public methods def run(self): """ - Run the script. + Run the script """ # Switch screen logging on in debug mode if self._logDebug(): @@ -128,23 +128,20 @@ class csobsinfo(ctools.cscript): # Write header if self._logTerse(): - self._log("\n") - if self._obs.size() > 1: - self._log.header1("Observations") - else: - self._log.header1("Observation") + self._log('\n') + self._log.header1(gammalib.number('Observation', self._obs.size())) # Loop over observations for obs in self._obs: # Skip non-CTA observations - if not obs.classname() == "GCTAObservation": - self._log("Skipping "+obs.instrument()+" observation\n") + if not obs.classname() == 'GCTAObservation': + self._log('Skipping '+obs.instrument()+' observation\n') continue # Use observed object as observation name if name is not given obs_name = obs.name() - if obs_name == "": + if obs_name == '': obs_name = obs.object() # Logging @@ -180,24 +177,24 @@ class csobsinfo(ctools.cscript): livetime += obs.livetime() # Bookkeeping - if obs.eventtype() == "CountsCube": + if obs.eventtype() == 'CountsCube': n_eventbins += obs.events().size() n_obs_binned += 1 if self._logTerse(): - self._log.parformat("Binned") - self._log("yes\n") - self._log.parformat("Number of bins") + self._log.parformat('Binned') + self._log('yes\n') + self._log.parformat('Number of bins') self._log(str(obs.events().size())) - self._log("\n") + self._log('\n') else: n_events += obs.events().size() n_obs_unbinned += 1 if self._logTerse(): - self._log.parformat("Binned") - self._log("no\n") - self._log.parformat("Number of events") + self._log.parformat('Binned') + self._log('no\n') + self._log.parformat('Number of events') self._log(str(obs.events().size())) - self._log("\n") + self._log('\n') # Retrieve zenith and azimuth and store for later use zenith = obs.pointing().zenith() @@ -216,98 +213,98 @@ class csobsinfo(ctools.cscript): if self._logTerse(): # Log the observation energy range (if available) - self._log.parformat("Energy range") + self._log.parformat('Energy range') if obs_bounds.size() == 0: - self._log("undefined") + self._log('undefined') else: self._log(str(obs_bounds.emin())) - self._log(" - ") + self._log(' - ') self._log(str(obs_bounds.emax())) - self._log("\n") + self._log('\n') # Log observation time interval - self._log.parformat("Time range (MJD)") + self._log.parformat('Time range (MJD)') if obs_gti.size() == 0: - self._log("undefined") + self._log('undefined') else: self._log(str(obs_gti.tstart().mjd())) - self._log(" - ") + self._log(' - ') self._log(str(obs_gti.tstop().mjd())) - self._log("\n") + self._log('\n') # Log ontime - self._log.parformat("Ontime") + self._log.parformat('Ontime') self._log(str(obs.ontime())) - self._log(" s\n") + self._log(' s\n') # Log livetime - self._log.parformat("Livetime") + self._log.parformat('Livetime') self._log(str(obs.livetime())) - self._log(" s\n") + self._log(' s\n') # Log dead time fraction - self._log.parformat("Deadtime fraction (%)") - self._log("%.3f" % (deadfrac)) - self._log("\n") + self._log.parformat('Deadtime fraction (%)') + self._log('%.3f' % (deadfrac)) + self._log('\n') # Log pointing direction - self._log.parformat("Pointing") + self._log.parformat('Pointing') self._log(str(pnt_dir)) - self._log("\n") + self._log('\n') # Optionally log offset with respect to target direction if self._compute_offset: - self._log.parformat("Offset from target") - self._log("%.2f" % (offset)) - self._log(" deg\n") + self._log.parformat('Offset from target') + self._log('%.2f' % (offset)) + self._log(' deg\n') # Log Zenith and Azimuth if required - self._log.parformat("Zenith angle") - self._log("%.2f" % (zenith)) - self._log(" deg\n") - self._log.parformat("Azimuth angle") - self._log("%.2f" % (azimuth)) - self._log(" deg\n") + self._log.parformat('Zenith angle') + self._log('%.2f' % (zenith)) + self._log(' deg\n') + self._log.parformat('Azimuth angle') + self._log('%.2f' % (azimuth)) + self._log(' deg\n') # Log summary if self._logTerse(): # Write header - self._log("\n") - self._log.header1("Summary") + self._log('\n') + self._log.header1('Summary') # Log general summary - self._log.header3("Observations") - self._log.parformat("Unbinned observations") + self._log.header3('Observations') + self._log.parformat('Unbinned observations') self._log(str(n_obs_unbinned)) - self._log("\n") - self._log.parformat("Binned observations") + self._log('\n') + self._log.parformat('Binned observations') self._log(str(n_obs_binned)) - self._log("\n") - self._log.header3("Events") - self._log.parformat("Number of events") + self._log('\n') + self._log.header3('Events') + self._log.parformat('Number of events') self._log(str(n_events)) - self._log("\n") - self._log.parformat("Number of bins") + self._log('\n') + self._log.parformat('Number of bins') self._log(str(n_eventbins)) - self._log("\n") + self._log('\n') # Log pointing summary - self._log.header3("Pointings") + self._log.header3('Pointings') # Log mean offset if possible if self._compute_offset: - self._log.parformat("Mean offset angle") - self._log("%.2f" % (sum(self._offsets)/len(self._offsets))) - self._log(" deg\n") + self._log.parformat('Mean offset angle') + self._log('%.2f' % (sum(self._offsets)/len(self._offsets))) + self._log(' deg\n') # Log mean azimuth and zenith angle - self._log.parformat("Mean zenith angle") - self._log("%.2f" % (sum(self._zeniths)/len(self._zeniths))) - self._log(" deg\n") - self._log.parformat("Mean azimuth angle") - self._log("%.2f" % (sum(self._azimuths)/len(self._azimuths))) - self._log(" deg\n") + self._log.parformat('Mean zenith angle') + self._log('%.2f' % (sum(self._zeniths)/len(self._zeniths))) + self._log(' deg\n') + self._log.parformat('Mean azimuth angle') + self._log('%.2f' % (sum(self._azimuths)/len(self._azimuths))) + self._log(' deg\n') # Optionally log names of observations. Note that the set class # is used to extract all different observation names from the @@ -316,49 +313,51 @@ class csobsinfo(ctools.cscript): if self._logExplicit() and sys.version_info >= (2,4): obs_set = set(obs_names) for name in obs_set: - self._log.parformat("\""+name+"\"") + self._log.parformat('"'+name+'"') self._log(str(obs_names.count(name))) - self._log("\n") - self._log("\n") + self._log('\n') + self._log('\n') # Log energy range - self._log.header3("Energy range") - self._log.parformat("Minimum energy") + self._log.header3('Energy range') + self._log.parformat('Minimum energy') if self._ebounds.size() == 0: - self._log("undefined") + self._log('undefined') else: self._log(str(self._ebounds.emin())) - self._log("\n") - self._log.parformat("Maximum energy") + self._log('\n') + self._log.parformat('Maximum energy') if self._ebounds.size() == 0: - self._log("undefined") + self._log('undefined') else: self._log(str(self._ebounds.emax())) - self._log("\n") + self._log('\n') # Log time range - self._log.header3("Time range") - self._log.parformat("Start (MJD)") + self._log.header3('Time range') + self._log.parformat('Start (MJD)') self._log(str(self._gti.tstart().mjd())) - self._log("\n") - self._log.parformat("Stop (MJD)") + self._log('\n') + self._log.parformat('Stop (MJD)') self._log(str(self._gti.tstop().mjd())) - self._log("\n") + self._log('\n') # Log ontime and livetime in different units - self._log.parformat("Total ontime") - self._log("%.2f s = %.2f min = %.2f h" % (ontime, ontime/60., ontime/3600.)) - self._log("\n") - self._log.parformat("Total livetime") - self._log("%.2f s = %.2f min = %.2f h" % (livetime, livetime/60.0, livetime/3600.)) - self._log("\n") + self._log.parformat('Total ontime') + self._log('%.2f s = %.2f min = %.2f h' % + (ontime, ontime/60., ontime/3600.)) + self._log('\n') + self._log.parformat('Total livetime') + self._log('%.2f s = %.2f min = %.2f h' % + (livetime, livetime/60.0, livetime/3600.)) + self._log('\n') # Return return def save(self): """ - Save pointings into DS9 region file. + Save pointings into DS9 region file This method saves all pointing directions that are found in the observation container into a DS9 region file. If "NONE" is @@ -366,35 +365,35 @@ class csobsinfo(ctools.cscript): """ # Get output filename in case it was not read ahead - ds9file = self["ds9file"].filename() + ds9file = self['ds9file'].filename() # Check if DS9 file is valid - if ds9file.url() != "NONE": + if ds9file.url() != 'NONE': # Write header if self._logTerse(): - self._log("\n") - self._log.header1("Save pointings in DS9 file") + self._log('\n') + self._log.header1('Save pointings in DS9 file') # Log filename if self._logTerse(): - self._log(gammalib.parformat("DS9 filename")) + self._log(gammalib.parformat('DS9 filename')) self._log(ds9file.url()) - self._log("\n") + self._log('\n') # Open file - f = open(ds9file.url(),"w") + f = open(ds9file.url(),'w') # Write coordinate system - f.write("fk5\n") + f.write('fk5\n') # Loop over pointings for i in range(len(self._pnt_ra)): # Create string - line = "point(" - line+=str(self._pnt_ra[i])+","+str(self._pnt_dec[i])+")" - line+=" # point=cross 20 width=3 \n" + line = 'point(' + line += str(self._pnt_ra[i])+','+str(self._pnt_dec[i])+')' + line += ' # point=cross 20 width=3\n' # Write to file f.write(line)