Commit 9a1b801fc8b6fd7c0cb07bb836baa293704843be

Authored by Jürgen Knödlseder
1 parent debf6fb1

Further improvement on Python code quality

cscripts/csroot2caldb.py
... ... @@ -28,9 +28,9 @@ from cscripts import calutils
28 28  
29 29 # Optional ROOT import
30 30 try:
31   - from ROOT import TFile, TH1F, TH2F, TH3F
  31 + from ROOT import TFile
32 32 _has_root = True
33   -except:
  33 +except ImportError:
34 34 _has_root = False
35 35  
36 36  
... ... @@ -159,11 +159,11 @@ class csroot2caldb(ctools.cscript):
159 159  
160 160 Returns
161 161 -------
162   - dir : dict
  162 + ds : dict
163 163 Directory structure information
164 164 """
165 165 # Initialise directory structure dictionary
166   - dir = {}
  166 + ds = {}
167 167  
168 168 # Set base directory
169 169 base_dir = 'data'
... ... @@ -172,54 +172,54 @@ class csroot2caldb(ctools.cscript):
172 172  
173 173 # Set directory names
174 174 obs_dir = base_dir+'/bcf/'+irf['CAL_OBSID']
175   - dir['EA_DIR'] = obs_dir
176   - dir['PSF_DIR'] = obs_dir
177   - dir['EDISP_DIR'] = obs_dir
178   - dir['BGD_DIR'] = obs_dir
  175 + ds['EA_DIR'] = obs_dir
  176 + ds['PSF_DIR'] = obs_dir
  177 + ds['EDISP_DIR'] = obs_dir
  178 + ds['BGD_DIR'] = obs_dir
179 179  
180 180 # Set path to response components. If the "outdir" parameter is set
181 181 # then prefix the value to the path of the response components
182 182 outdir = self['outdir'].string()
183 183 if len(outdir) > 0:
184   - dir['BASE_PATH'] = outdir+'/'+base_dir
185   - dir['EA_PATH'] = outdir+'/'+dir['EA_DIR']
186   - dir['PSF_PATH'] = outdir+'/'+dir['PSF_DIR']
187   - dir['EDISP_PATH'] = outdir+'/'+dir['EDISP_DIR']
188   - dir['BGD_PATH'] = outdir+'/'+dir['BGD_DIR']
  184 + ds['BASE_PATH'] = outdir+'/'+base_dir
  185 + ds['EA_PATH'] = outdir+'/'+ds['EA_DIR']
  186 + ds['PSF_PATH'] = outdir+'/'+ds['PSF_DIR']
  187 + ds['EDISP_PATH'] = outdir+'/'+ds['EDISP_DIR']
  188 + ds['BGD_PATH'] = outdir+'/'+ds['BGD_DIR']
189 189 else:
190   - dir['BASE_PATH'] = base_dir
191   - dir['EA_PATH'] = dir['EA_DIR']
192   - dir['PSF_PATH'] = dir['PSF_DIR']
193   - dir['EDISP_PATH'] = dir['EDISP_DIR']
194   - dir['BGD_PATH'] = dir['BGD_DIR']
  190 + ds['BASE_PATH'] = base_dir
  191 + ds['EA_PATH'] = ds['EA_DIR']
  192 + ds['PSF_PATH'] = ds['PSF_DIR']
  193 + ds['EDISP_PATH'] = ds['EDISP_DIR']
  194 + ds['BGD_PATH'] = ds['BGD_DIR']
195 195  
196 196 # Set IRF component file names. If the "split" parameter is "yes" then
197 197 # split the IRF components over several files.
198 198 if self['split'].boolean():
199   - dir['EA_FILE'] = 'ea_'+version+'.fits'
200   - dir['PSF_FILE'] = 'psf_'+version+'.fits'
201   - dir['EDISP_FILE'] = 'edisp_'+version+'.fits'
202   - dir['BGD_FILE'] = 'bgd_'+version+'.fits'
  199 + ds['EA_FILE'] = 'ea_'+version+'.fits'
  200 + ds['PSF_FILE'] = 'psf_'+version+'.fits'
  201 + ds['EDISP_FILE'] = 'edisp_'+version+'.fits'
  202 + ds['BGD_FILE'] = 'bgd_'+version+'.fits'
203 203 else:
204   - dir['EA_FILE'] = 'irf_'+version+'.fits'
205   - dir['PSF_FILE'] = 'irf_'+version+'.fits'
206   - dir['EDISP_FILE'] = 'irf_'+version+'.fits'
207   - dir['BGD_FILE'] = 'irf_'+version+'.fits'
  204 + ds['EA_FILE'] = 'irf_'+version+'.fits'
  205 + ds['PSF_FILE'] = 'irf_'+version+'.fits'
  206 + ds['EDISP_FILE'] = 'irf_'+version+'.fits'
  207 + ds['BGD_FILE'] = 'irf_'+version+'.fits'
208 208  
209 209 # Create directory structure
210   - if not os.path.isdir(dir['EA_PATH']):
211   - os.makedirs(dir['EA_PATH'])
212   - if not os.path.isdir(dir['PSF_PATH']):
213   - os.makedirs(dir['PSF_PATH'])
214   - if not os.path.isdir(dir['EDISP_PATH']):
215   - os.makedirs(dir['EDISP_PATH'])
216   - if not os.path.isdir(dir['BGD_PATH']):
217   - os.makedirs(dir['BGD_PATH'])
218   -
219   - # Return dir
220   - return dir
221   -
222   - def _open(self, irf, dir):
  210 + if not os.path.isdir(ds['EA_PATH']):
  211 + os.makedirs(ds['EA_PATH'])
  212 + if not os.path.isdir(ds['PSF_PATH']):
  213 + os.makedirs(ds['PSF_PATH'])
  214 + if not os.path.isdir(ds['EDISP_PATH']):
  215 + os.makedirs(ds['EDISP_PATH'])
  216 + if not os.path.isdir(ds['BGD_PATH']):
  217 + os.makedirs(ds['BGD_PATH'])
  218 +
  219 + # Return ds
  220 + return ds
  221 +
  222 + def _open(self, irf, ds):
223 223 """
224 224 Open existing or create new calibration
225 225  
... ... @@ -232,55 +232,55 @@ class csroot2caldb(ctools.cscript):
232 232 ----------
233 233 irf : dict
234 234 IRF metadata dictionary
235   - dir : dict
  235 + ds : dict
236 236 Directory structure dictionary
237 237 """
238 238 # Open calibration database index
239   - dir['CIF'] = gammalib.GFits(dir['BASE_PATH']+'/caldb.indx', True)
  239 + ds['CIF'] = gammalib.GFits(ds['BASE_PATH']+'/caldb.indx', True)
240 240  
241 241 # If file has no CIF extension than create it now
242 242 try:
243   - dir['HDU_CIF'] = dir['CIF'].table('CIF')
  243 + ds['HDU_CIF'] = ds['CIF'].table('CIF')
244 244 except:
245   - dir['CIF'].append(calutils.create_cif_table())
246   - dir['HDU_CIF'] = dir['CIF'].table('CIF')
  245 + ds['CIF'].append(calutils.create_cif_table())
  246 + ds['HDU_CIF'] = ds['CIF'].table('CIF')
247 247  
248 248 # Set IRF component filenames
249   - ea_filename = dir['EA_PATH']+'/'+dir['EA_FILE']
250   - psf_filename = dir['PSF_PATH']+'/'+dir['PSF_FILE']
251   - edisp_filename = dir['EDISP_PATH']+'/'+dir['EDISP_FILE']
252   - bgd_filename = dir['BGD_PATH']+'/'+dir['BGD_FILE']
  249 + ea_filename = ds['EA_PATH']+'/'+ds['EA_FILE']
  250 + psf_filename = ds['PSF_PATH']+'/'+ds['PSF_FILE']
  251 + edisp_filename = ds['EDISP_PATH']+'/'+ds['EDISP_FILE']
  252 + bgd_filename = ds['BGD_PATH']+'/'+ds['BGD_FILE']
253 253  
254 254 # Open IRF component files
255 255 if self['split'].boolean():
256   - dir['EA_FITS'] = gammalib.GFits(ea_filename, True)
257   - dir['PSF_FITS'] = gammalib.GFits(psf_filename, True)
258   - dir['EDISP_FITS'] = gammalib.GFits(edisp_filename, True)
259   - dir['BGD_FITS'] = gammalib.GFits(bgd_filename, True)
  256 + ds['EA_FITS'] = gammalib.GFits(ea_filename, True)
  257 + ds['PSF_FITS'] = gammalib.GFits(psf_filename, True)
  258 + ds['EDISP_FITS'] = gammalib.GFits(edisp_filename, True)
  259 + ds['BGD_FITS'] = gammalib.GFits(bgd_filename, True)
260 260 else:
261   - dir['EA_FITS'] = gammalib.GFits(ea_filename, True)
262   - dir['PSF_FITS'] = dir['EA_FITS']
263   - dir['EDISP_FITS'] = dir['EA_FITS']
264   - dir['BGD_FITS'] = dir['EA_FITS']
  261 + ds['EA_FITS'] = gammalib.GFits(ea_filename, True)
  262 + ds['PSF_FITS'] = ds['EA_FITS']
  263 + ds['EDISP_FITS'] = ds['EA_FITS']
  264 + ds['BGD_FITS'] = ds['EA_FITS']
265 265  
266 266 # Open HDUs
267   - dir['HDU_EA'] = self._open_hdu(dir['EA_FITS'], "EFFECTIVE AREA",
268   - irf['EA_NAME'], irf['EA_DOC'],
269   - irf)
270   - dir['HDU_PSF'] = self._open_hdu(dir['PSF_FITS'], "POINT SPREAD FUNCTION",
271   - irf['PSF_NAME'], irf['PSF_DOC'],
272   - irf)
273   - dir['HDU_EDISP'] = self._open_hdu(dir['EDISP_FITS'], "ENERGY DISPERSION",
274   - irf['EDISP_NAME'], irf['EDISP_DOC'],
275   - irf)
276   - dir['HDU_BGD'] = self._open_hdu(dir['BGD_FITS'], "BACKGROUND",
277   - irf['BGD_NAME'], irf['BGD_DOC'],
278   - irf)
  267 + ds['HDU_EA'] = self._open_hdu(ds['EA_FITS'], "EFFECTIVE AREA",
  268 + irf['EA_NAME'], irf['EA_DOC'],
  269 + irf)
  270 + ds['HDU_PSF'] = self._open_hdu(ds['PSF_FITS'], "POINT SPREAD FUNCTION",
  271 + irf['PSF_NAME'], irf['PSF_DOC'],
  272 + irf)
  273 + ds['HDU_EDISP'] = self._open_hdu(ds['EDISP_FITS'], "ENERGY DISPERSION",
  274 + irf['EDISP_NAME'], irf['EDISP_DOC'],
  275 + irf)
  276 + ds['HDU_BGD'] = self._open_hdu(ds['BGD_FITS'], "BACKGROUND",
  277 + irf['BGD_NAME'], irf['BGD_DOC'],
  278 + irf)
279 279  
280 280 # Return
281 281 return
282 282  
283   - def _close(self, irf, dir):
  283 + def _close(self, irf, ds):
284 284 """
285 285 Close calibration FITS files
286 286  
... ... @@ -288,30 +288,30 @@ class csroot2caldb(ctools.cscript):
288 288 ----------
289 289 irf : dict
290 290 IRF metadata dictionary
291   - dir : dict
  291 + ds : dict
292 292 Directory structure dictionary
293 293 """
294 294 # Add information to CIF. We do this now as before we did not
295 295 # necessarily have all the information at hand (in particular about
296 296 # the boundaries)
297   - self._add_cif_info(irf, dir)
  297 + self._add_cif_info(irf, ds)
298 298  
299 299 # Save and close CIF
300   - dir['CIF'].save(True)
301   - dir['CIF'].close()
  300 + ds['CIF'].save(True)
  301 + ds['CIF'].close()
302 302  
303 303 # Close all IRF components. If the files have been split all components
304 304 # need to be closed, otherwise only the effective area component needs
305 305 # to be closed as representative for all components.
306   - dir['EA_FITS'].save(True)
307   - dir['EA_FITS'].close()
  306 + ds['EA_FITS'].save(True)
  307 + ds['EA_FITS'].close()
308 308 if self['split'].boolean():
309   - dir['PSF_FITS'].save(True)
310   - dir['EDISP_FITS'].save(True)
311   - dir['BGD_FITS'].save(True)
312   - dir['PSF_FITS'].close()
313   - dir['EDISP_FITS'].close()
314   - dir['BGD_FITS'].close()
  309 + ds['PSF_FITS'].save(True)
  310 + ds['EDISP_FITS'].save(True)
  311 + ds['BGD_FITS'].save(True)
  312 + ds['PSF_FITS'].close()
  313 + ds['EDISP_FITS'].close()
  314 + ds['BGD_FITS'].close()
315 315  
316 316 # Return
317 317 return
... ... @@ -393,7 +393,7 @@ class csroot2caldb(ctools.cscript):
393 393 # Return
394 394 return
395 395  
396   - def _add_cif_info(self, irf, dir):
  396 + def _add_cif_info(self, irf, ds):
397 397 """
398 398 Add information to CIF extension
399 399  
... ... @@ -401,17 +401,17 @@ class csroot2caldb(ctools.cscript):
401 401 ----------
402 402 irf : dict
403 403 IRF metadata dictionary
404   - dir : dict
  404 + ds : dict
405 405 Directory structure dictionary
406 406 """
407 407 # Set list of IRF component names
408 408 names = ['EA', 'PSF', 'EDISP', 'BGD']
409 409  
410 410 # Initialise CIF row index
411   - row = dir['HDU_CIF'].nrows()
  411 + row = ds['HDU_CIF'].nrows()
412 412  
413 413 # Append rows for all components to CIF extension
414   - dir['HDU_CIF'].append_rows(len(names))
  414 + ds['HDU_CIF'].append_rows(len(names))
415 415  
416 416 # Add information for all components
417 417 for name in names:
... ... @@ -424,30 +424,30 @@ class csroot2caldb(ctools.cscript):
424 424 key_bounds = '%s_BOUNDS' % name
425 425  
426 426 # Set generic information
427   - dir['HDU_CIF']['TELESCOP'][row] = irf['CAL_TEL']
428   - dir['HDU_CIF']['INSTRUME'][row] = irf['CAL_INST']
429   - dir['HDU_CIF']['DETNAM'][row] = irf['CAL_DET']
430   - dir['HDU_CIF']['FILTER'][row] = irf['CAL_FLT']
431   - dir['HDU_CIF']['CAL_DEV'][row] = 'ONLINE'
432   - dir['HDU_CIF']['CAL_CLAS'][row] = irf['CAL_CLASS']
433   - dir['HDU_CIF']['CAL_DTYP'][row] = irf['CAL_TYPE']
434   - dir['HDU_CIF']['CAL_VSD'][row] = irf['VAL_DATE']
435   - dir['HDU_CIF']['CAL_VST'][row] = irf['VAL_TIME']
436   - dir['HDU_CIF']['REF_TIME'][row] = irf['REF_TIME']
437   - dir['HDU_CIF']['CAL_QUAL'][row] = irf['CAL_QUAL']
438   - dir['HDU_CIF']['CAL_DATE'][row] = irf['CAL_DATE']
  427 + ds['HDU_CIF']['TELESCOP'][row] = irf['CAL_TEL']
  428 + ds['HDU_CIF']['INSTRUME'][row] = irf['CAL_INST']
  429 + ds['HDU_CIF']['DETNAM'][row] = irf['CAL_DET']
  430 + ds['HDU_CIF']['FILTER'][row] = irf['CAL_FLT']
  431 + ds['HDU_CIF']['CAL_DEV'][row] = 'ONLINE'
  432 + ds['HDU_CIF']['CAL_CLAS'][row] = irf['CAL_CLASS']
  433 + ds['HDU_CIF']['CAL_DTYP'][row] = irf['CAL_TYPE']
  434 + ds['HDU_CIF']['CAL_VSD'][row] = irf['VAL_DATE']
  435 + ds['HDU_CIF']['CAL_VST'][row] = irf['VAL_TIME']
  436 + ds['HDU_CIF']['REF_TIME'][row] = irf['REF_TIME']
  437 + ds['HDU_CIF']['CAL_QUAL'][row] = irf['CAL_QUAL']
  438 + ds['HDU_CIF']['CAL_DATE'][row] = irf['CAL_DATE']
439 439  
440 440 # Set component specific information
441   - dir['HDU_CIF']['CAL_DIR'][row] = dir[key_dir]
442   - dir['HDU_CIF']['CAL_FILE'][row] = dir[key_file]
443   - dir['HDU_CIF']['CAL_CNAM'][row] = irf[key_name]
444   - dir['HDU_CIF']['CAL_DESC'][row] = irf[key_desc]
445   - dir['HDU_CIF']['CAL_XNO'][row] = 1
  441 + ds['HDU_CIF']['CAL_DIR'][row] = ds[key_dir]
  442 + ds['HDU_CIF']['CAL_FILE'][row] = ds[key_file]
  443 + ds['HDU_CIF']['CAL_CNAM'][row] = irf[key_name]
  444 + ds['HDU_CIF']['CAL_DESC'][row] = irf[key_desc]
  445 + ds['HDU_CIF']['CAL_XNO'][row] = 1
446 446 for i in range(9):
447 447 if i >= len(irf[key_bounds]):
448   - dir['HDU_CIF']['CAL_CBD'][row,i] = 'NONE'
  448 + ds['HDU_CIF']['CAL_CBD'][row,i] = 'NONE'
449 449 else:
450   - dir['HDU_CIF']['CAL_CBD'][row,i] = irf[key_bounds][i]
  450 + ds['HDU_CIF']['CAL_CBD'][row,i] = irf[key_bounds][i]
451 451  
452 452 # Increment row index
453 453 row += 1
... ... @@ -499,7 +499,7 @@ class csroot2caldb(ctools.cscript):
499 499  
500 500  
501 501 # ROOT specific private members
502   - def _root2caldb(self, irf, dir):
  502 + def _root2caldb(self, irf, ds):
503 503 """
504 504 Translate ROOT to CALDB information
505 505  
... ... @@ -507,28 +507,28 @@ class csroot2caldb(ctools.cscript):
507 507 ----------
508 508 irf : dict
509 509 IRF metadata dictionary
510   - dir : dict
  510 + ds : dict
511 511 Directory structure dictionary
512 512 """
513 513 # Open ROOT performance file
514 514 file = TFile(self['infile'].filename().url())
515 515  
516 516 # Create effective area
517   - self._root2ea(file, irf, dir)
  517 + self._root2ea(file, irf, ds)
518 518  
519 519 # Create point spread function
520   - self._root2psf(file, irf, dir)
  520 + self._root2psf(file, irf, ds)
521 521  
522 522 # Create energy dispersion
523   - self._root2edisp(file, irf, dir)
  523 + self._root2edisp(file, irf, ds)
524 524  
525 525 # Create background
526   - self._root2bgd(file, irf, dir)
  526 + self._root2bgd(file, irf, ds)
527 527  
528 528 # Return
529 529 return
530 530  
531   - def _root2ea(self, file, irf, dir):
  531 + def _root2ea(self, file, irf, ds):
532 532 """
533 533 Translate ROOT to CALDB effective area extension
534 534  
... ... @@ -542,7 +542,7 @@ class csroot2caldb(ctools.cscript):
542 542 ROOT file
543 543 irf : dict
544 544 IRF metadata dictionary
545   - dir : dict
  545 + ds : dict
546 546 Directory structure dictionary
547 547 """
548 548 # Write header
... ... @@ -594,24 +594,24 @@ class csroot2caldb(ctools.cscript):
594 594 ereco.SetBinContent(ieng+1,ioff+1,value)
595 595  
596 596 # Set boundaries (use Ereco boundaries)
597   - bounds = self._make_2D(ereco, dir['HDU_EA'], None, 'm2')
  597 + bounds = self._make_2D(ereco, ds['HDU_EA'], None, 'm2')
598 598 for b in bounds:
599 599 irf['EA_BOUNDS'].append(b)
600 600  
601 601 # Write boundary keywords
602   - self._set_cif_keywords(dir['HDU_EA'], irf['EA_NAME'],
  602 + self._set_cif_keywords(ds['HDU_EA'], irf['EA_NAME'],
603 603 irf['EA_BOUNDS'], irf['EA_DESC'], irf)
604 604  
605 605 # Create "EFFAREA" data column
606   - self._make_2D(etrue, dir['HDU_EA'], 'EFFAREA', 'm2')
  606 + self._make_2D(etrue, ds['HDU_EA'], 'EFFAREA', 'm2')
607 607  
608 608 # Create "EFFAREA_RECO" data column
609   - self._make_2D(ereco, dir['HDU_EA'], 'EFFAREA_RECO', 'm2')
  609 + self._make_2D(ereco, ds['HDU_EA'], 'EFFAREA_RECO', 'm2')
610 610  
611 611 # Return
612 612 return
613 613  
614   - def _root2psf(self, file, irf, dir):
  614 + def _root2psf(self, file, irf, ds):
615 615 """
616 616 Translate ROOT to CALDB point spread function extension
617 617  
... ... @@ -621,7 +621,7 @@ class csroot2caldb(ctools.cscript):
621 621 ROOT file
622 622 irf : dict
623 623 IRF metadata dictionary
624   - dir : dict
  624 + ds : dict
625 625 Directory structure dictionary
626 626 """
627 627 # Write header
... ... @@ -631,16 +631,16 @@ class csroot2caldb(ctools.cscript):
631 631  
632 632 # King profile PSF
633 633 if self['psftype'].string() == 'King':
634   - self._root2psf_king(file, irf, dir)
  634 + self._root2psf_king(file, irf, ds)
635 635  
636 636 # ... otherwise use Gaussian profile PSF
637 637 else:
638   - self._root2psf_gauss(file, irf, dir)
  638 + self._root2psf_gauss(file, irf, ds)
639 639  
640 640 # Return
641 641 return
642 642  
643   - def _root2psf_gauss(self, file, irf, dir):
  643 + def _root2psf_gauss(self, file, irf, ds):
644 644 """
645 645 Translate ROOT to CALDB point spread function extension
646 646  
... ... @@ -658,7 +658,7 @@ class csroot2caldb(ctools.cscript):
658 658 ROOT file
659 659 irf : dict
660 660 IRF metadata dictionary
661   - dir : dict
  661 + ds : dict
662 662 Directory structure dictionary
663 663 """
664 664 # Get relevant ROOT histograms
... ... @@ -693,37 +693,37 @@ class csroot2caldb(ctools.cscript):
693 693 zero.SetBinContent(ieng+1,ioff+1,0.0)
694 694  
695 695 # Set boundaries
696   - bounds = self._make_2D(r68, dir['HDU_PSF'], None, 'deg')
  696 + bounds = self._make_2D(r68, ds['HDU_PSF'], None, 'deg')
697 697 for b in bounds:
698 698 irf['PSF_BOUNDS'].append(b)
699 699 irf['PSF_BOUNDS'].append('PSF(GAUSS)')
700 700  
701 701 # Write boundary keywords
702   - self._set_cif_keywords(dir['HDU_PSF'], irf['PSF_NAME'],
  702 + self._set_cif_keywords(ds['HDU_PSF'], irf['PSF_NAME'],
703 703 irf['PSF_BOUNDS'], irf['PSF_DESC'], irf)
704 704  
705 705 # Create "SCALE" data column
706   - self._make_2D(scale, dir['HDU_PSF'], 'SCALE', '')
  706 + self._make_2D(scale, ds['HDU_PSF'], 'SCALE', '')
707 707  
708 708 # Create "SIGMA_1" data column
709   - self._make_2D(r68, dir['HDU_PSF'], 'SIGMA_1', 'deg')
  709 + self._make_2D(r68, ds['HDU_PSF'], 'SIGMA_1', 'deg')
710 710  
711 711 # Create "AMPL_2" data column
712   - self._make_2D(zero, dir['HDU_PSF'], 'AMPL_2', '')
  712 + self._make_2D(zero, ds['HDU_PSF'], 'AMPL_2', '')
713 713  
714 714 # Create "SIGMA_2" data column
715   - self._make_2D(zero, dir['HDU_PSF'], 'SIGMA_2', 'deg')
  715 + self._make_2D(zero, ds['HDU_PSF'], 'SIGMA_2', 'deg')
716 716  
717 717 # Create "AMPL_3" data column
718   - self._make_2D(zero, dir['HDU_PSF'], 'AMPL_3', '')
  718 + self._make_2D(zero, ds['HDU_PSF'], 'AMPL_3', '')
719 719  
720 720 # Create "SIGMA_3" data column
721   - self._make_2D(zero, dir['HDU_PSF'], 'SIGMA_3', 'deg')
  721 + self._make_2D(zero, ds['HDU_PSF'], 'SIGMA_3', 'deg')
722 722  
723 723 # Return
724 724 return
725 725  
726   - def _root2psf_king(self, file, irf, dir):
  726 + def _root2psf_king(self, file, irf, ds):
727 727 """
728 728 Translate ROOT to CALDB point spread function extension
729 729  
... ... @@ -737,7 +737,7 @@ class csroot2caldb(ctools.cscript):
737 737 ROOT file
738 738 irf : dict
739 739 IRF metadata dictionary
740   - dir : dict
  740 + ds : dict
741 741 Directory structure dictionary
742 742 """
743 743 # Get relevant ROOT histograms
... ... @@ -784,11 +784,9 @@ class csroot2caldb(ctools.cscript):
784 784 x2 = -1.0
785 785 f1 = (math.pow(a,x1) - 1.0)/(math.pow(b,x1) - 1.0) - c
786 786 f2 = (math.pow(a,x2) - 1.0)/(math.pow(b,x2) - 1.0) - c
787   - iter = 0
788 787 while True:
789 788 x = x1 - f1 * (x1-x2)/(f1-f2)
790 789 f = (math.pow(a,x) - 1.0)/(math.pow(b,x) - 1.0) - c
791   - iter += 1
792 790 if abs(f) < 1.0e-6:
793 791 break
794 792 else:
... ... @@ -826,33 +824,30 @@ class csroot2caldb(ctools.cscript):
826 824 last_gamma = gamma
827 825 last_sigma = sigma
828 826  
829   - # Show results on console
830   - #print(ioff,ieng,gamma,sigma,x,f,iter)
831   -
832 827 # Set bin contents
833 828 gamma2D.SetBinContent(ieng+1,ioff+1,gamma)
834 829 sigma2D.SetBinContent(ieng+1,ioff+1,sigma)
835 830  
836 831 # Set boundaries
837   - bounds = self._make_2D(r68, dir['HDU_PSF'], None, 'deg')
  832 + bounds = self._make_2D(r68, ds['HDU_PSF'], None, 'deg')
838 833 for b in bounds:
839 834 irf['PSF_BOUNDS'].append(b)
840 835 irf['PSF_BOUNDS'].append('PSF(KING)')
841 836  
842 837 # Write boundary keywords
843   - self._set_cif_keywords(dir['HDU_PSF'], irf['PSF_NAME'],
  838 + self._set_cif_keywords(ds['HDU_PSF'], irf['PSF_NAME'],
844 839 irf['PSF_BOUNDS'], irf['PSF_DESC'], irf)
845 840  
846 841 # Create "GAMMA" data column
847   - self._make_2D(gamma2D, dir['HDU_PSF'], 'GAMMA', '')
  842 + self._make_2D(gamma2D, ds['HDU_PSF'], 'GAMMA', '')
848 843  
849 844 # Create "SIGMA" data column
850   - self._make_2D(sigma2D, dir['HDU_PSF'], 'SIGMA', 'deg')
  845 + self._make_2D(sigma2D, ds['HDU_PSF'], 'SIGMA', 'deg')
851 846  
852 847 # Return
853 848 return
854 849  
855   - def _root2edisp(self, file, irf, dir):
  850 + def _root2edisp(self, file, irf, ds):
856 851 """
857 852 Translate ROOT to CALDB energy dispersion extension
858 853  
... ... @@ -865,7 +860,7 @@ class csroot2caldb(ctools.cscript):
865 860 ROOT file
866 861 irf : dict
867 862 IRF metadata dictionary
868   - dir : dict
  863 + ds : dict
869 864 Directory structure dictionary
870 865 """
871 866 # Write header
... ... @@ -877,21 +872,21 @@ class csroot2caldb(ctools.cscript):
877 872 matrix = file.Get('EestOverEtrue_offaxis')
878 873  
879 874 # Set boundaries
880   - bounds = self._make_3D_migra(matrix, dir['HDU_EDISP'], None, '')
  875 + bounds = self._make_3D_migra(matrix, ds['HDU_EDISP'], None, '')
881 876 for b in bounds:
882 877 irf['EDISP_BOUNDS'].append(b)
883 878  
884 879 # Write boundary keywords
885   - self._set_cif_keywords(dir['HDU_EDISP'], irf['EDISP_NAME'],
  880 + self._set_cif_keywords(ds['HDU_EDISP'], irf['EDISP_NAME'],
886 881 irf['EDISP_BOUNDS'], irf['EDISP_DESC'], irf)
887 882  
888 883 # Create "MATRIX" data column
889   - self._make_3D_migra(matrix, dir['HDU_EDISP'], 'MATRIX', '')
  884 + self._make_3D_migra(matrix, ds['HDU_EDISP'], 'MATRIX', '')
890 885  
891 886 # Return
892 887 return
893 888  
894   - def _root2bgd(self, file, irf, dir):
  889 + def _root2bgd(self, file, irf, ds):
895 890 """
896 891 Translate ROOT to CALDB background extension.
897 892  
... ... @@ -904,7 +899,7 @@ class csroot2caldb(ctools.cscript):
904 899 ROOT file
905 900 irf : dict
906 901 IRF metadata dictionary
907   - dir : dict
  902 + ds : dict
908 903 Directory structure dictionary
909 904 """
910 905 # Write header
... ... @@ -930,23 +925,23 @@ class csroot2caldb(ctools.cscript):
930 925 self._renorm_onaxis(array, array_1D)
931 926  
932 927 # Set boundaries
933   - bounds = self._make_3D(array, dir['HDU_BGD'], None, 'deg')
  928 + bounds = self._make_3D(array, ds['HDU_BGD'], None, 'deg')
934 929 for b in bounds:
935 930 irf['BGD_BOUNDS'].append(b)
936 931  
937 932 # Write boundary keywords
938   - self._set_cif_keywords(dir['HDU_BGD'], irf['BGD_NAME'],
  933 + self._set_cif_keywords(ds['HDU_BGD'], irf['BGD_NAME'],
939 934 irf['BGD_BOUNDS'], irf['BGD_DESC'], irf)
940 935  
941 936 # Create "BGD" data column
942   - self._make_3D(array, dir['HDU_BGD'], 'BGD', '1/s/MeV/sr')
  937 + self._make_3D(array, ds['HDU_BGD'], 'BGD', '1/s/MeV/sr')
943 938  
944 939 # Return
945 940 return
946 941  
947   - def _append_column(self, hdu, name, unit, axis, log=False):
  942 + def _append_column_axis(self, hdu, name, unit, axis, log=False):
948 943 """
949   - Append column to HDU
  944 + Append column of ROOT axis values to HDU
950 945  
951 946 Parameters
952 947 ----------
... ... @@ -990,6 +985,39 @@ class csroot2caldb(ctools.cscript):
990 985 # Return
991 986 return
992 987  
  988 + def _append_column_values(self, hdu, name, unit, values):
  989 + """
  990 + Append column of values to HDU
  991 +
  992 + Parameters
  993 + ----------
  994 + hdu : `~gammalib.GFitsHDU`
  995 + FITS HDU
  996 + name : str
  997 + Column name
  998 + unit : str
  999 + Column unit
  1000 + values : list of float
  1001 + Axis values
  1002 + """
  1003 + # Continue only if columns does not yet exist
  1004 + if not hdu.contains(name):
  1005 +
  1006 + # Get number of values
  1007 + nbins = len(values)
  1008 +
  1009 + # Append column and set column unit
  1010 + hdu.append(gammalib.GFitsTableFloatCol(name, 1, nbins))
  1011 + hdu[name].unit(unit)
  1012 +
  1013 + # Fill column
  1014 + for i in range(nbins):
  1015 + hdu[name][0,i] = values[i]
  1016 +
  1017 + # Return
  1018 + return
  1019 +
  1020 +
993 1021 def _renorm_onaxis(self, hist2D, hist1D):
994 1022 """
995 1023 Renormalise 2D histogram (energy,offset) on 1D histogram (energy)
... ... @@ -1115,8 +1143,9 @@ class csroot2caldb(ctools.cscript):
1115 1143 axis.append(energy)
1116 1144 rates.append(rate)
1117 1145  
1118   - # Determine energy range
1119   - emin, emax = self._plaw_energy_range(axis, rates)
  1146 + # Determine minimum energy (ignoring the maximum energy as
  1147 + # we do not need it)
  1148 + emin = self._plaw_energy_range(axis, rates)[0]
1120 1149  
1121 1150 # Get power law coefficients
1122 1151 coeff = self._plaw_coefficients(axis, rates, emin, ethres)
... ... @@ -1318,10 +1347,10 @@ class csroot2caldb(ctools.cscript):
1318 1347 noffset = offsets.GetNbins()
1319 1348  
1320 1349 # Append axis columns to HDU
1321   - self._append_column(hdu, 'ENERG_LO', 'TeV', energies, log=True)
1322   - self._append_column(hdu, 'ENERG_HI', 'TeV', energies, log=True)
1323   - self._append_column(hdu, 'THETA_LO', 'deg', offsets)
1324   - self._append_column(hdu, 'THETA_HI', 'deg', offsets)
  1350 + self._append_column_axis(hdu, 'ENERG_LO', 'TeV', energies, log=True)
  1351 + self._append_column_axis(hdu, 'ENERG_HI', 'TeV', energies, log=True)
  1352 + self._append_column_axis(hdu, 'THETA_LO', 'deg', offsets)
  1353 + self._append_column_axis(hdu, 'THETA_HI', 'deg', offsets)
1325 1354  
1326 1355 # Append array column
1327 1356 if name != None and not hdu.contains(name):
... ... @@ -1400,37 +1429,15 @@ class csroot2caldb(ctools.cscript):
1400 1429 dets_hi.append(det_hi)
1401 1430 dets2.append(det_val*det_val)
1402 1431  
1403   - # Append DETX_LO column
1404   - if not hdu.contains('DETX_LO'):
1405   - hdu.append(gammalib.GFitsTableFloatCol('DETX_LO', 1, ndets))
1406   - hdu['DETX_LO'].unit('deg')
1407   - for i in range(ndets):
1408   - hdu['DETX_LO'][0,i] = dets_lo[i]
1409   -
1410   - # Append DETX_HI column
1411   - if not hdu.contains('DETX_HI'):
1412   - hdu.append(gammalib.GFitsTableFloatCol('DETX_HI', 1, ndets))
1413   - hdu['DETX_HI'].unit('deg')
1414   - for i in range(ndets):
1415   - hdu['DETX_HI'][0,i] = dets_hi[i]
1416   -
1417   - # Append DETY_LO column
1418   - if not hdu.contains('DETY_LO'):
1419   - hdu.append(gammalib.GFitsTableFloatCol('DETY_LO', 1, ndets))
1420   - hdu['DETY_LO'].unit('deg')
1421   - for i in range(ndets):
1422   - hdu['DETY_LO'][0,i] = dets_lo[i]
1423   -
1424   - # Append DETY_HI column
1425   - if not hdu.contains('DETY_HI'):
1426   - hdu.append(gammalib.GFitsTableFloatCol('DETY_HI', 1, ndets))
1427   - hdu['DETY_HI'].unit('deg')
1428   - for i in range(ndets):
1429   - hdu['DETY_HI'][0,i] = dets_hi[i]
  1432 + # Append DETX_LO, DETX_HI, DETY_LO and DETY_HI columns
  1433 + self._append_column_values(hdu, 'DETX_LO', 'deg', dets_lo)
  1434 + self._append_column_values(hdu, 'DETX_HI', 'deg', dets_hi)
  1435 + self._append_column_values(hdu, 'DETY_LO', 'deg', dets_lo)
  1436 + self._append_column_values(hdu, 'DETY_HI', 'deg', dets_hi)
1430 1437  
1431 1438 # Append ENERG_LO and ENERG_HI columns
1432   - self._append_column(hdu, 'ENERG_LO', 'TeV', energies, log=True)
1433   - self._append_column(hdu, 'ENERG_HI', 'TeV', energies, log=True)
  1439 + self._append_column_axis(hdu, 'ENERG_LO', 'TeV', energies, log=True)
  1440 + self._append_column_axis(hdu, 'ENERG_HI', 'TeV', energies, log=True)
1434 1441  
1435 1442 # Append array column
1436 1443 if name != None and not hdu.contains(name):
... ... @@ -1481,24 +1488,24 @@ class csroot2caldb(ctools.cscript):
1481 1488 Scaling factor for histogram values
1482 1489 """
1483 1490 # Extract Etrue, Eobs/Etrue and offset angle vectors
1484   - etrue = array.GetXaxis()
1485   - netrue = etrue.GetNbins()
1486   - migra = array.GetYaxis()
1487   - nmigra = migra.GetNbins()
1488   - offsets = array.GetZaxis()
1489   - noffset = offsets.GetNbins()
1490   - ewidth = [] # in MeV
  1491 + etrue = array.GetXaxis()
  1492 + netrue = etrue.GetNbins()
  1493 + migra = array.GetYaxis()
  1494 + nmigra = migra.GetNbins()
  1495 + offsets = array.GetZaxis()
  1496 + noffset = offsets.GetNbins()
  1497 + ewidth = [] # in MeV
1491 1498 for ieng in range(netrue):
1492 1499 ewidth.append(pow(10.0, etrue.GetBinUpEdge(ieng+1) +6.0) - \
1493 1500 pow(10.0, etrue.GetBinLowEdge(ieng+1)+6.0))
1494 1501  
1495 1502 # Append axis columns to HDU
1496   - self._append_column(hdu, 'ETRUE_LO', 'TeV', etrue, log=True)
1497   - self._append_column(hdu, 'ETRUE_HI', 'TeV', etrue, log=True)
1498   - self._append_column(hdu, 'MIGRA_LO', '', migra)
1499   - self._append_column(hdu, 'MIGRA_HI', '', migra)
1500   - self._append_column(hdu, 'THETA_LO', 'deg', offsets)
1501   - self._append_column(hdu, 'THETA_HI', 'deg', offsets)
  1503 + self._append_column_axis(hdu, 'ETRUE_LO', 'TeV', etrue, log=True)
  1504 + self._append_column_axis(hdu, 'ETRUE_HI', 'TeV', etrue, log=True)
  1505 + self._append_column_axis(hdu, 'MIGRA_LO', '', migra)
  1506 + self._append_column_axis(hdu, 'MIGRA_HI', '', migra)
  1507 + self._append_column_axis(hdu, 'THETA_LO', 'deg', offsets)
  1508 + self._append_column_axis(hdu, 'THETA_HI', 'deg', offsets)
1502 1509  
1503 1510 # Append migration matrix to HDU
1504 1511 if name != None and not hdu.contains(name):
... ... @@ -1550,17 +1557,17 @@ class csroot2caldb(ctools.cscript):
1550 1557 irf = self._init_metadata()
1551 1558  
1552 1559 # Create directory structure
1553   - dir = self._make_dirs('file', irf)
  1560 + ds = self._make_dirs('file', irf)
1554 1561  
1555 1562 # Open calibration files
1556   - self._open(irf, dir)
  1563 + self._open(irf, ds)
1557 1564  
1558 1565 # Translate ROOT to CALDB information
1559 1566 if _has_root:
1560   - self._root2caldb(irf, dir)
  1567 + self._root2caldb(irf, ds)
1561 1568  
1562 1569 # Close calibration files
1563   - self._close(irf, dir)
  1570 + self._close(irf, ds)
1564 1571  
1565 1572 # Return
1566 1573 return
... ...
examples/show_butterfly.py
... ... @@ -25,7 +25,7 @@ try:
25 25 import matplotlib.pyplot as plt
26 26 plt.figure()
27 27 plt.close()
28   -except:
  28 +except ImportError:
29 29 print('This script needs the "matplotlib" module')
30 30 sys.exit()
31 31  
... ...
examples/show_model.py
... ... @@ -25,7 +25,7 @@ try:
25 25 import matplotlib.pyplot as plt
26 26 plt.figure()
27 27 plt.close()
28   -except:
  28 +except ImportError:
29 29 print('This script needs the "matplotlib" module')
30 30 sys.exit()
31 31  
... ...
examples/show_obs.py
... ... @@ -25,7 +25,7 @@ try:
25 25 import matplotlib.pyplot as plt
26 26 plt.figure()
27 27 plt.close()
28   -except:
  28 +except ImportError:
29 29 print('This script needs the "matplotlib" module')
30 30 sys.exit()
31 31  
... ...
examples/show_pha.py
... ... @@ -26,7 +26,7 @@ try:
26 26 import matplotlib.pyplot as plt
27 27 plt.figure()
28 28 plt.close()
29   -except:
  29 +except ImportError:
30 30 print('This script needs the "matplotlib" module')
31 31 sys.exit()
32 32  
... ...
examples/show_pull_evolution.py
... ... @@ -25,12 +25,12 @@ try:
25 25 import matplotlib.pyplot as plt
26 26 plt.figure()
27 27 plt.close()
28   -except:
  28 +except ImportError:
29 29 print('This script needs the "matplotlib" module')
30 30 sys.exit()
31 31 try:
32 32 import numpy as np
33   -except:
  33 +except ImportError:
34 34 print('This script needs the "numpy" module')
35 35 sys.exit()
36 36  
... ...
examples/show_pull_histogram.py
... ... @@ -26,12 +26,12 @@ try:
26 26 import matplotlib.mlab as mlab
27 27 plt.figure()
28 28 plt.close()
29   -except:
  29 +except ImportError:
30 30 print('This script needs the "matplotlib" module')
31 31 sys.exit()
32 32 try:
33 33 import numpy as np
34   -except:
  34 +except ImportError:
35 35 print('This script needs the "numpy" module')
36 36 sys.exit()
37 37  
... ...
examples/show_response.py
... ... @@ -26,7 +26,7 @@ try:
26 26 import matplotlib.pyplot as plt
27 27 plt.figure()
28 28 plt.close()
29   -except:
  29 +except ImportError:
30 30 print('This script needs the "matplotlib" module')
31 31 sys.exit()
32 32  
... ...
examples/show_sensitivity.py
... ... @@ -26,7 +26,7 @@ try:
26 26 import matplotlib.pyplot as plt
27 27 plt.figure()
28 28 plt.close()
29   -except:
  29 +except ImportError:
30 30 print('This script needs the "matplotlib" module')
31 31 sys.exit()
32 32  
... ...
examples/show_spectrum.py
... ... @@ -25,7 +25,7 @@ try:
25 25 import matplotlib.pyplot as plt
26 26 plt.figure()
27 27 plt.close()
28   -except:
  28 +except ImportError:
29 29 print('This script needs the "matplotlib" module')
30 30 sys.exit()
31 31  
... ...
examples/show_ts_distribution.py
... ... @@ -26,12 +26,12 @@ try:
26 26 import matplotlib.pyplot as plt
27 27 plt.figure()
28 28 plt.close()
29   -except:
  29 +except ImportError:
30 30 print('This script needs the "matplotlib" module')
31 31 sys.exit()
32 32 try:
33 33 import numpy as np
34   -except:
  34 +except ImportError:
35 35 print('This script needs the "numpy" module')
36 36 sys.exit()
37 37  
... ...