Commit bdcd55cce0d77483e56329b88dd206f22ef1464e

Authored by Jürgen Knödlseder
1 parent 15aa103b

Unify interface of example scripts (#1828)

All example scripts now use the cscripts.ioutils.get_args_options() function to get arguments and options.
cscripts/ioutils.py
... ... @@ -90,7 +90,7 @@ def get_args_options(options, usage):
90 90 # If there are no command line arguments then show usage string and
91 91 # exit
92 92 if len(sys.argv) < 1:
93   - print(usage)
  93 + print('Usage: %s' % usage)
94 94 sys.exit()
95 95  
96 96 # First possible option is element 1
... ... @@ -116,13 +116,13 @@ def get_args_options(options, usage):
116 116 try:
117 117 option['value'] = str(sys.argv[i])
118 118 except:
119   - print(usage)
  119 + print('Usage: %s' % usage)
120 120 sys.exit()
121 121  
122 122 # ... there is no following parameter, hence write out usage
123 123 # and quite
124 124 else:
125   - print(usage)
  125 + print('Usage: %s' % usage)
126 126 sys.exit()
127 127  
128 128 # We can break now as every option should only occur once
... ...
examples/make_spectrum.py
... ... @@ -25,9 +25,9 @@ try:
25 25 import matplotlib.pyplot as plt
26 26 plt.figure()
27 27 plt.close()
28   - has_matplotlib = True
29 28 except:
30   - has_matplotlib = False
  29 + print('This script needs the "matplotlib" module')
  30 + sys.exit()
31 31  
32 32  
33 33 # =============== #
... ... @@ -94,7 +94,7 @@ def make_spectrum(datadir):
94 94 # ============= #
95 95 # Plot spectrum #
96 96 # ============= #
97   -def plot_spectrum(spectrum, file=False):
  97 +def plot_spectrum(spectrum, plotfile):
98 98 """
99 99 Plot spectrum
100 100  
... ... @@ -102,8 +102,8 @@ def plot_spectrum(spectrum, file=False):
102 102 ----------
103 103 spectrum : `~gammalib.GFits`
104 104 Spectrum FITS file
105   - file : bool, optional
106   - Plot into a file
  105 + plotfile : str
  106 + Plot filename
107 107 """
108 108 # Extract columns from spectrum file
109 109 table = spectrum.table(1)
... ... @@ -169,8 +169,8 @@ def plot_spectrum(spectrum, file=False):
169 169 plt.ylabel(r'E$^{2}$dN/dE (erg cm$^{-2}$ s$^{-1}$)')
170 170  
171 171 # Show spectrum or save it into file
172   - if file:
173   - plt.savefig('example_spectrum.eps')
  172 + if len(plotfile) > 0:
  173 + plt.savefig(plotfile)
174 174 else:
175 175 plt.show()
176 176  
... ... @@ -183,19 +183,22 @@ def plot_spectrum(spectrum, file=False):
183 183 # ======================== #
184 184 if __name__ == '__main__':
185 185  
186   - # Get optional arguments
187   - if len(sys.argv) >= 2:
188   - datadir = sys.argv[1]
189   - else:
190   - datadir = 'data'
191   - if len(sys.argv) >= 3:
192   - file = True
193   - else:
194   - file = False
  186 + # Set usage string
  187 + usage = 'make_spectrum.py [-d datadir] [-p plotfile]'
  188 +
  189 + # Set default options
  190 + options = [{'option': '-d', 'value': 'data'},
  191 + {'option': '-p', 'value': ''}]
  192 +
  193 + # Get arguments and options from command line arguments
  194 + args, options = cscripts.ioutils.get_args_options(options, usage)
  195 +
  196 + # Extract script parameters from options
  197 + datadir = options[0]['value']
  198 + plotfile = options[1]['value']
195 199  
196 200 # Generate spectrum
197 201 spectrum = make_spectrum(datadir)
198 202  
199   - # If matplotlib is installed then plot spectrum
200   - if has_matplotlib:
201   - plot_spectrum(spectrum, file=file)
  203 + # Plot spectrum
  204 + plot_spectrum(spectrum, plotfile)
... ...
examples/show_butterfly.py
... ... @@ -20,6 +20,7 @@
20 20 # ==========================================================================
21 21 import sys
22 22 import gammalib
  23 +import cscripts
23 24 try:
24 25 import matplotlib.pyplot as plt
25 26 plt.figure()
... ... @@ -29,23 +30,22 @@ except:
29 30 sys.exit()
30 31  
31 32  
32   -# ============ #
33   -# Script entry #
34   -# ============ #
35   -if __name__ == '__main__':
36   -
37   - # Check for given butterfly file
38   - if len(sys.argv) < 2:
39   - sys.exit('Usage: show_butterfly.py butterfly.txt [file]')
40   -
41   - # Check if plotting in file is requested
42   - plotfile = ''
43   - if len(sys.argv) == 3:
44   - plotfile = sys.argv[2]
  33 +# ============== #
  34 +# Plot butterfly #
  35 +# ============== #
  36 +def plot_butterfly(filename, plotfile):
  37 + """
  38 + Plot butterfly diagram
45 39  
46   - # Read given butterfly file
47   - filename = sys.argv[1]
48   - csv = gammalib.GCsv(filename)
  40 + Parameters
  41 + ----------
  42 + filename : str
  43 + Butterfly CSV file
  44 + plotfile : str
  45 + Plot filename
  46 + """
  47 + # Read butterfly file
  48 + csv = gammalib.GCsv(filename)
49 49  
50 50 # Initialise arrays to be filled
51 51 butterfly_x = []
... ... @@ -65,15 +65,13 @@ if __name__ == &#39;__main__&#39;:
65 65 line_x.append(csv.real(row,0))
66 66 line_y.append(csv.real(row,1))
67 67  
68   - # Loop over the rows backwards to compute the lower edge
69   - # of the confidence band
  68 + # Loop over the rows backwards to compute the lower edge of the
  69 + # confidence band
70 70 for row in range(nrows):
71 71 index = nrows - 1 - row
72 72 butterfly_x.append(csv.real(index,0))
73   - low_error = csv.real(index,3)
74   - if low_error < 1e-26:
75   - low_error = 1e-26
76   - butterfly_y.append(low_error)
  73 + low_error = max(csv.real(index,3), 1e-26)
  74 + butterfly_y.append(low_error)
77 75  
78 76 # Plot the butterfly and spectral line
79 77 plt.figure()
... ... @@ -90,3 +88,27 @@ if __name__ == &#39;__main__&#39;:
90 88 plt.savefig(plotfile)
91 89 else:
92 90 plt.show()
  91 +
  92 + # Return
  93 + return
  94 +
  95 +
  96 +# ======================== #
  97 +# Main routine entry point #
  98 +# ======================== #
  99 +if __name__ == '__main__':
  100 +
  101 + # Set usage string
  102 + usage = 'show_butterfly.py [-p plotfile] file'
  103 +
  104 + # Set default options
  105 + options = [{'option': '-p', 'value': ''}]
  106 +
  107 + # Get arguments and options from command line arguments
  108 + args, options = cscripts.ioutils.get_args_options(options, usage)
  109 +
  110 + # Extract script parameters from options
  111 + plotfile = options[0]['value']
  112 +
  113 + # Plot butterfly diagram
  114 + plot_butterfly(args[0], plotfile)
... ...
examples/show_model.py
... ... @@ -20,6 +20,7 @@
20 20 # ==========================================================================
21 21 import sys
22 22 import gammalib
  23 +import cscripts
23 24 try:
24 25 import matplotlib.pyplot as plt
25 26 plt.figure()
... ... @@ -32,7 +33,7 @@ except:
32 33 # ======================= #
33 34 # Plot spectral component #
34 35 # ======================= #
35   -def plot_spectrum(model, emin=0.01, emax=100.0, enumbins=100, plotfile=''):
  36 +def plot_spectrum(model, plotfile, emin=0.01, emax=100.0, enumbins=100):
36 37 """
37 38 Plot spectral model component
38 39  
... ... @@ -40,14 +41,14 @@ def plot_spectrum(model, emin=0.01, emax=100.0, enumbins=100, plotfile=&#39;&#39;):
40 41 ----------
41 42 model : `~gammalib.GModel`
42 43 Model
  44 + plotfile : str
  45 + Name of plot file
43 46 emin : float, optional
44 47 Minimum energy (TeV)
45 48 emax : float, optional
46 49 Maximum energy (TeV)
47 50 enumbins : integer, optional
48 51 Number of energy bins
49   - plotfile : str, optional
50   - Name of plot file
51 52 """
52 53 # Get spectral component
53 54 spectrum = model.spectral()
... ... @@ -57,18 +58,12 @@ def plot_spectrum(model, emin=0.01, emax=100.0, enumbins=100, plotfile=&#39;&#39;):
57 58 e_max = gammalib.GEnergy(emax, 'TeV')
58 59 ebounds = gammalib.GEbounds(enumbins, e_min, e_max)
59 60  
60   - # Setup model plot
  61 + # Setup lists of x and y values
61 62 x = []
62 63 y = []
63   - min = 1.0e30
64   - max = 0.0
65 64 for i in range(enumbins):
66 65 energy = ebounds.elogmean(i)
67 66 value = spectrum.eval(energy)
68   - if value > max:
69   - max = value
70   - if value < min:
71   - min = value
72 67 x.append(energy.TeV())
73 68 y.append(value)
74 69  
... ... @@ -80,7 +75,6 @@ def plot_spectrum(model, emin=0.01, emax=100.0, enumbins=100, plotfile=&#39;&#39;):
80 75 plt.loglog(x, y, color='red')
81 76 plt.xlabel('Energy (TeV)')
82 77 plt.ylabel(r'dN/dE (ph s$^{-1}$ cm$^{-2}$ MeV$^{-1}$)')
83   - #plt.ylim([min,max])
84 78  
85 79 # Show spectrum or save it into file
86 80 if len(plotfile) > 0:
... ... @@ -92,31 +86,32 @@ def plot_spectrum(model, emin=0.01, emax=100.0, enumbins=100, plotfile=&#39;&#39;):
92 86 return
93 87  
94 88  
95   -# ============= #
96   -# Script entry #
97   -# ============= #
  89 +# ======================== #
  90 +# Main routine entry point #
  91 +# ======================== #
98 92 if __name__ == '__main__':
99 93  
100   - # Check for model filename
101   - if len(sys.argv) < 2:
102   - sys.exit('Usage: show_model.py model.xml [name] [file]')
  94 + # Set usage string
  95 + usage = 'show_model.py [-n name] [-p plotfile] file'
103 96  
104   - # Get optional model index
105   - if len(sys.argv) >= 3:
106   - name = sys.argv[2]
107   - else:
  97 + # Set default options
  98 + options = [{'option': '-n', 'value': ''},
  99 + {'option': '-p', 'value': ''}]
  100 +
  101 + # Get arguments and options from command line arguments
  102 + args, options = cscripts.ioutils.get_args_options(options, usage)
  103 +
  104 + # Extract script parameters from options
  105 + name = options[0]['value']
  106 + plotfile = options[1]['value']
  107 + if len(name) == 0:
108 108 name = 0
109   - if len(sys.argv) == 4:
110   - plotfile = sys.argv[3]
111   - else:
112   - plotfile = ''
113 109  
114 110 # Read models XML file
115   - filename = sys.argv[1]
116   - models = gammalib.GModels(filename)
  111 + models = gammalib.GModels(args[0])
117 112  
118 113 # Extract relevant model
119 114 model = models[name]
120 115  
121 116 # Plot spectrum
122   - plot_spectrum(model, plotfile=plotfile)
  117 + plot_spectrum(model, plotfile)
... ...
examples/show_obs.py
... ... @@ -33,7 +33,7 @@ except:
33 33 # ==================== #
34 34 # Run csobsinfo script #
35 35 # ==================== #
36   -def run_csobsinfo(filename, ra=None, dec=None, debug=True):
  36 +def run_csobsinfo(filename, ra, dec, debug=True):
37 37 """
38 38 Run csobsinfo script
39 39  
... ... @@ -41,9 +41,9 @@ def run_csobsinfo(filename, ra=None, dec=None, debug=True):
41 41 ----------
42 42 filename : str
43 43 File name of observation definition XML file
44   - ra : float, optional
  44 + ra : str
45 45 Target Right Ascension (deg)
46   - dec : float, optional
  46 + dec : str
47 47 Target declination of pointing (deg)
48 48 debug : bool, optional
49 49 Switch on debugging in csobsinfo run
... ... @@ -62,9 +62,9 @@ def run_csobsinfo(filename, ra=None, dec=None, debug=True):
62 62 info['debug'] = debug
63 63  
64 64 # Set offset
65   - if ra != None and dec != None:
66   - info['ra'] = ra
67   - info['dec'] = dec
  65 + if ra != '' and dec != '':
  66 + info['ra'] = float(ra)
  67 + info['dec'] = float(dec)
68 68 info['offset'] = True
69 69 else:
70 70 info['offset'] = False
... ... @@ -79,7 +79,7 @@ def run_csobsinfo(filename, ra=None, dec=None, debug=True):
79 79 # ================ #
80 80 # Plot information #
81 81 # ================ #
82   -def plot_information(info, plotfile=''):
  82 +def plot_information(info, plotfile):
83 83 """
84 84 Plot information
85 85  
... ... @@ -87,7 +87,7 @@ def plot_information(info, plotfile=&#39;&#39;):
87 87 ----------
88 88 info : `~cscripts.csobsinfo`
89 89 csobsinfo instance
90   - plotfile : str, optional
  90 + plotfile : str
91 91 Plot filename
92 92 """
93 93 # Retrieve observation info
... ... @@ -178,22 +178,24 @@ def plot_information(info, plotfile=&#39;&#39;):
178 178 # ======================== #
179 179 if __name__ == '__main__':
180 180  
181   - # Print usage message if wrong number of arguments is provided
182   - if len(sys.argv) < 2:
183   - sys.exit('Usage: inspect_obs.py inobs.xml [ra] [dec] [file]')
  181 + # Set usage string
  182 + usage = 'show_model.py [-ra ra] [-dec dec] [-p plotfile] file'
184 183  
185   - # Extract optional parameters
186   - plotfile = ''
187   - ra = None
188   - dec = None
189   - if len(sys.argv) == 3:
190   - plotfile = sys.argv[2]
191   - elif len(sys.argv) == 4:
192   - ra = float(sys.argv[2])
193   - dec = float(sys.argv[3])
  184 + # Set default options
  185 + options = [{'option': '-ra', 'value': ''},
  186 + {'option': '-dec', 'value': ''},
  187 + {'option': '-p', 'value': ''}]
  188 +
  189 + # Get arguments and options from command line arguments
  190 + args, options = cscripts.ioutils.get_args_options(options, usage)
  191 +
  192 + # Extract script parameters from options
  193 + ra = options[0]['value']
  194 + dec = options[1]['value']
  195 + plotfile = options[2]['value']
194 196  
195 197 # Run csobsinfo
196   - info = run_csobsinfo(sys.argv[1], ra=ra, dec=dec)
  198 + info = run_csobsinfo(args[0], ra, dec)
197 199  
198 200 # Plot information
199   - plot_information(info, plotfile=plotfile)
  201 + plot_information(info, plotfile)
... ...
examples/show_pha.py
1 1 #! /usr/bin/env python
2 2 # ==========================================================================
3   -# Show a spectrum in PHA format.
  3 +# Show a spectrum in PHA format
4 4 #
5 5 # Copyright (C) 2013-2016 Juergen Knoedlseder
6 6 #
... ... @@ -21,6 +21,7 @@
21 21 import sys
22 22 import math
23 23 import gammalib
  24 +import cscripts
24 25 try:
25 26 import matplotlib.pyplot as plt
26 27 plt.figure()
... ... @@ -33,7 +34,7 @@ except:
33 34 # ================= #
34 35 # Show PHA spectrum #
35 36 # ================= #
36   -def show_pha(pha, plotfile=''):
  37 +def show_pha(pha, plotfile):
37 38 """
38 39 Show PHA spectrum
39 40  
... ... @@ -41,7 +42,7 @@ def show_pha(pha, plotfile=&#39;&#39;):
41 42 ----------
42 43 spectrum : `~gammalib.GPha`
43 44 PHA file
44   - plotfile : str, optional
  45 + plotfile : str
45 46 Plot file name
46 47 """
47 48 # Create figure
... ... @@ -94,22 +95,20 @@ def show_pha(pha, plotfile=&#39;&#39;):
94 95 # ======================== #
95 96 if __name__ == '__main__':
96 97  
97   - # Print usage information
98   - usage = 'Usage: show_pha.py filename [file]'
99   - if len(sys.argv) < 2:
100   - print(usage)
101   - sys.exit()
  98 + # Set usage string
  99 + usage = 'show_pha.py [-p plotfile] file'
102 100  
103   - # Check if plotting in file is requested
104   - plotfile = ''
105   - if len(sys.argv) == 3:
106   - plotfile = sys.argv[2]
  101 + # Set default options
  102 + options = [{'option': '-p', 'value': ''}]
107 103  
108   - # Extract parameters
109   - filename = sys.argv[1]
  104 + # Get arguments and options from command line arguments
  105 + args, options = cscripts.ioutils.get_args_options(options, usage)
  106 +
  107 + # Extract script parameters from options
  108 + plotfile = options[0]['value']
110 109  
111 110 # Load PHA spectrum
112   - pha = gammalib.GPha(filename)
  111 + pha = gammalib.GPha(args[0])
113 112  
114 113 # Show PHA spectrum
115   - show_pha(pha, plotfile=plotfile)
  114 + show_pha(pha, plotfile)
... ...
examples/show_pull_evolution.py
... ... @@ -20,6 +20,7 @@
20 20 # ==========================================================================
21 21 import sys
22 22 import csv
  23 +import cscripts
23 24 try:
24 25 import matplotlib.pyplot as plt
25 26 plt.figure()
... ... @@ -83,26 +84,22 @@ def read_pull(filename, parname):
83 84 return a
84 85  
85 86  
86   -# ======================== #
87   -# Main routine entry point #
88   -# ======================== #
89   -if __name__ == '__main__':
90   -
91   - # Print usage information
92   - usage = 'Usage: show_pull_evolution.py filename parname [file]'
93   - if len(sys.argv) < 3:
94   - print(usage)
95   - sys.exit()
96   -
97   - # Check if plotting in file is requested
98   - plotfile = ''
99   - if len(sys.argv) == 4:
100   - plotfile = sys.argv[3]
101   -
102   - # Extract parameters
103   - filename = sys.argv[1]
104   - parname = sys.argv[2]
  87 +# =================== #
  88 +# Plot pull evolution #
  89 +# =================== #
  90 +def plot_pull_evolution(filename, parname, plotfile):
  91 + """
  92 + Plot pull evolution
105 93  
  94 + Parameters
  95 + ----------
  96 + filename : str
  97 + Pull filename
  98 + parname : str
  99 + Parameter name
  100 + plotfile : str
  101 + Plot filename
  102 + """
106 103 # Read values from CSV file
107 104 values = read_pull(filename, parname)
108 105  
... ... @@ -134,3 +131,27 @@ if __name__ == &#39;__main__&#39;:
134 131 plt.savefig(plotfile)
135 132 else:
136 133 plt.show()
  134 +
  135 + # Return
  136 + return
  137 +
  138 +
  139 +# ======================== #
  140 +# Main routine entry point #
  141 +# ======================== #
  142 +if __name__ == '__main__':
  143 +
  144 + # Set usage string
  145 + usage = 'show_pull_evolution.py [-p plotfile] file parameter'
  146 +
  147 + # Set default options
  148 + options = [{'option': '-p', 'value': ''}]
  149 +
  150 + # Get arguments and options from command line arguments
  151 + args, options = cscripts.ioutils.get_args_options(options, usage)
  152 +
  153 + # Extract script parameters from options
  154 + plotfile = options[0]['value']
  155 +
  156 + # Plot pull evolution
  157 + plot_pull_evolution(args[0], args[1], plotfile)
... ...
examples/show_pull_histogram.py
... ... @@ -20,6 +20,7 @@
20 20 # ==========================================================================
21 21 import sys
22 22 import csv
  23 +import cscripts
23 24 try:
24 25 import matplotlib.pyplot as plt
25 26 import matplotlib.mlab as mlab
... ... @@ -84,29 +85,24 @@ def read_pull(filename, parname):
84 85 return a
85 86  
86 87  
87   -# ======================== #
88   -# Main routine entry point #
89   -# ======================== #
90   -if __name__ == '__main__':
91   -
92   - # Print usage information
93   - usage = 'Usage: show_pull_histogram.py filename parname [bins] [file]'
94   - if len(sys.argv) < 3:
95   - print(usage)
96   - sys.exit()
97   -
98   - # Extract parameters
99   - filename = sys.argv[1]
100   - parname = sys.argv[2]
101   - if len(sys.argv) > 3:
102   - nbins = int(sys.argv[3])
103   - else:
104   - nbins = 50
105   - if len(sys.argv) == 5:
106   - plotfile = sys.argv[4]
107   - else:
108   - plotfile = ''
  88 +# =================== #
  89 +# Plot pull histogram #
  90 +# =================== #
  91 +def plot_pull_histogram(filename, parname, nbins, plotfile):
  92 + """
  93 + Plot pull histogram
109 94  
  95 + Parameters
  96 + ----------
  97 + filename : str
  98 + Pull filename
  99 + parname : str
  100 + Parameter name
  101 + nbins : int
  102 + Number of hisogram bins
  103 + plotfile : str
  104 + Plot filename
  105 + """
110 106 # Read values from CSV file
111 107 values = read_pull(filename, parname)
112 108  
... ... @@ -132,3 +128,29 @@ if __name__ == &#39;__main__&#39;:
132 128 plt.savefig(plotfile)
133 129 else:
134 130 plt.show()
  131 +
  132 + # Return
  133 + return
  134 +
  135 +
  136 +# ======================== #
  137 +# Main routine entry point #
  138 +# ======================== #
  139 +if __name__ == '__main__':
  140 +
  141 + # Set usage string
  142 + usage = 'show_pull_histogram.py [-n bins] [-p plotfile] file parameter'
  143 +
  144 + # Set default options
  145 + options = [{'option': '-n', 'value': '50'},
  146 + {'option': '-p', 'value': ''}]
  147 +
  148 + # Get arguments and options from command line arguments
  149 + args, options = cscripts.ioutils.get_args_options(options, usage)
  150 +
  151 + # Extract script parameters from options
  152 + nbins = int(options[0]['value'])
  153 + plotfile = options[1]['value']
  154 +
  155 + # Plot pull histogram
  156 + plot_pull_histogram(args[0], args[1], nbins, plotfile)
... ...
examples/show_response.py
... ... @@ -21,6 +21,7 @@
21 21 import sys
22 22 import math
23 23 import gammalib
  24 +import cscripts
24 25 try:
25 26 import matplotlib.pyplot as plt
26 27 plt.figure()
... ... @@ -313,22 +314,18 @@ def show_one_response(rspname, dbname, name, rootdir=None, color=&#39;r&#39;):
313 314 return
314 315  
315 316  
316   -# ======================== #
317   -# Main routine entry point #
318   -# ======================== #
319   -if __name__ == '__main__':
320   -
321   - # Print usage information
322   - usage = 'Usage: show_response.py [file]'
323   - if len(sys.argv) < 1:
324   - print(usage)
325   - sys.exit()
326   -
327   - # Check if plotting in file is requested
328   - plotfile = ''
329   - if len(sys.argv) == 2:
330   - plotfile = sys.argv[1]
  317 +# ==================== #
  318 +# Show one sensitivity #
  319 +# ==================== #
  320 +def show_response(plotfile):
  321 + """
  322 + Show response
331 323  
  324 + Parameters
  325 + ----------
  326 + plotfile : str
  327 + Plot filename
  328 + """
332 329 # Create figures
333 330 plt.figure(1)
334 331 plt.title('Effective area')
... ... @@ -338,16 +335,14 @@ if __name__ == &#39;__main__&#39;:
338 335 plt.title('Sensitivity')
339 336  
340 337 # Set response dictionary
341   - rsps = [
342   - {'dbname': 'prod2',
  338 + rsps = [{'dbname': 'prod2',
343 339 'rspname': 'South_0.5h',
344 340 'name': 'Prod2 (30 min)',
345 341 'color': 'b'},
346 342 {'dbname': 'prod2',
347 343 'rspname': 'South_50h',
348 344 'name': 'Prod2 (50 h)',
349   - 'color': 'r'}
350   - ]
  345 + 'color': 'r'}]
351 346  
352 347 # Loop over all responses
353 348 for rsp in rsps:
... ... @@ -357,10 +352,7 @@ if __name__ == &#39;__main__&#39;:
357 352 rspname = rsp['rspname']
358 353 color = rsp['color']
359 354 name = rsp['name']
360   - if rsp.has_key('rootdir'):
361   - rootdir = rsp['rootdir']
362   - else:
363   - rootdir = None
  355 + rootdir = rsp.setdefault('rootdir', None)
364 356  
365 357 # Show response
366 358 show_one_response(rspname, dbname, name, rootdir=rootdir, color=color)
... ... @@ -370,3 +362,27 @@ if __name__ == &#39;__main__&#39;:
370 362 plt.savefig(plotfile)
371 363 else:
372 364 plt.show()
  365 +
  366 + # Return
  367 + return
  368 +
  369 +
  370 +# ======================== #
  371 +# Main routine entry point #
  372 +# ======================== #
  373 +if __name__ == '__main__':
  374 +
  375 + # Set usage string
  376 + usage = 'show_response.py [-p plotfile]'
  377 +
  378 + # Set default options
  379 + options = [{'option': '-p', 'value': ''}]
  380 +
  381 + # Get arguments and options from command line arguments
  382 + args, options = cscripts.ioutils.get_args_options(options, usage)
  383 +
  384 + # Extract script parameters from options
  385 + plotfile = options[0]['value']
  386 +
  387 + # Show response
  388 + show_response(plotfile)
... ...
examples/show_sensitivity.py
... ... @@ -21,6 +21,7 @@
21 21 import sys
22 22 import math
23 23 import gammalib
  24 +import cscripts
24 25 try:
25 26 import matplotlib.pyplot as plt
26 27 plt.figure()
... ... @@ -96,7 +97,7 @@ def read_sensitivity(filename):
96 97 # ===================== #
97 98 # Show sensitivity data #
98 99 # ===================== #
99   -def show_sensitivity(sensitivity, filename, plotfile=''):
  100 +def show_sensitivity(sensitivity, filename, plotfile):
100 101 """
101 102 Plot sensitivity data
102 103  
... ... @@ -106,7 +107,7 @@ def show_sensitivity(sensitivity, filename, plotfile=&#39;&#39;):
106 107 Dictionary with sensitivity information
107 108 filename : str
108 109 Name of CSV file
109   - plotfile : str, optional
  110 + plotfile : str
110 111 Plot file name
111 112 """
112 113 # Build title
... ... @@ -145,23 +146,24 @@ def show_sensitivity(sensitivity, filename, plotfile=&#39;&#39;):
145 146 # ======================== #
146 147 if __name__ == '__main__':
147 148  
148   - # Print usage information
149   - usage = 'Usage: show_sensitivity.py [filename] [file]'
150   - if len(sys.argv) < 1:
151   - print(usage)
152   - sys.exit()
  149 + # Set usage string
  150 + usage = 'show_sensitivity.py [-p plotfile] [file]'
153 151  
154   - # Extract parameters
155   - if len(sys.argv) == 1:
156   - filename = 'sensitivity.dat'
  152 + # Set default options
  153 + options = [{'option': '-p', 'value': ''}]
  154 +
  155 + # Get arguments and options from command line arguments
  156 + args, options = cscripts.ioutils.get_args_options(options, usage)
  157 +
  158 + # Extract script parameters from options
  159 + plotfile = options[0]['value']
  160 + if len(args) > 0:
  161 + filename = args[0]
157 162 else:
158   - filename = sys.argv[1]
159   - plotfile = ''
160   - if len(sys.argv) == 3:
161   - plotfile = sys.argv[2]
  163 + filename = 'sensitivity.dat'
162 164  
163 165 # Read sensitivity data
164 166 sensitivity = read_sensitivity(filename)
165 167  
166 168 # Show sensitivity data
167   - show_sensitivity(sensitivity, filename, plotfile=plotfile)
  169 + show_sensitivity(sensitivity, filename, plotfile)
... ...
examples/show_spectrum.py
... ... @@ -20,6 +20,7 @@
20 20 # ==========================================================================
21 21 import sys
22 22 import gammalib
  23 +import cscripts
23 24 try:
24 25 import matplotlib.pyplot as plt
25 26 plt.figure()
... ... @@ -32,7 +33,7 @@ except:
32 33 # ============= #
33 34 # Show spectrum #
34 35 # ============= #
35   -def show_spectrum(filename, plotfile=''):
  36 +def show_spectrum(filename, plotfile):
36 37 """
37 38 Plot sensitivity data
38 39  
... ... @@ -40,7 +41,7 @@ def show_spectrum(filename, plotfile=&#39;&#39;):
40 41 ----------
41 42 filename : str
42 43 Name of spectrum FITS file
43   - plotfile : str, optional
  44 + plotfile : str
44 45 Plot file name
45 46 """
46 47 # Read spectrum file
... ... @@ -116,17 +117,17 @@ def show_spectrum(filename, plotfile=&#39;&#39;):
116 117 # ======================== #
117 118 if __name__ == '__main__':
118 119  
119   - # Print usage information
120   - usage = 'Usage: show_spectrum.py filename [file]'
121   - if len(sys.argv) < 2:
122   - print(usage)
123   - sys.exit()
  120 + # Set usage string
  121 + usage = 'show_spectrum.py [-p plotfile] [file]'
124 122  
125   - # Extract parameters
126   - filename = sys.argv[1]
127   - plotfile = ''
128   - if len(sys.argv) == 3:
129   - plotfile = sys.argv[2]
  123 + # Set default options
  124 + options = [{'option': '-p', 'value': ''}]
  125 +
  126 + # Get arguments and options from command line arguments
  127 + args, options = cscripts.ioutils.get_args_options(options, usage)
  128 +
  129 + # Extract script parameters from options
  130 + plotfile = options[0]['value']
130 131  
131 132 # Show spectrum
132   - show_spectrum(filename, plotfile=plotfile)
  133 + show_spectrum(args[0], plotfile)
... ...
examples/show_ts_distribution.py
... ... @@ -21,6 +21,7 @@
21 21 import sys
22 22 import csv
23 23 import math
  24 +import cscripts
24 25 try:
25 26 import matplotlib.pyplot as plt
26 27 plt.figure()
... ... @@ -130,7 +131,7 @@ def erf(x):
130 131 # =============================== #
131 132 # Display cumulative distribution #
132 133 # =============================== #
133   -def dist_cdf(values, nbins, title, expect='', plotfile=''):
  134 +def dist_cdf(values, nbins, title, plotfile, expect=''):
134 135 """
135 136 Display cumulative TS distribution and overplots expectation
136 137  
... ... @@ -142,8 +143,10 @@ def dist_cdf(values, nbins, title, expect=&#39;&#39;, plotfile=&#39;&#39;):
142 143 Number of bins
143 144 title : str
144 145 Plot title
145   - plotfile : str, optional
  146 + plotfile : str
146 147 Plot file name
  148 + expect : str, optional
  149 + If 'show', show expectation
147 150 """
148 151 # Set range and adapt number of bins. We make sure that we have a
149 152 # histogram bin centred on 0 that will capture the TS=0 part.
... ... @@ -205,7 +208,7 @@ def dist_cdf(values, nbins, title, expect=&#39;&#39;, plotfile=&#39;&#39;):
205 208 # ======================================== #
206 209 # Display probability density distribution #
207 210 # ======================================== #
208   -def dist_pdf(values, nbins, title, expect='', plotfile=''):
  211 +def dist_pdf(values, nbins, title, plotfile, expect=''):
209 212 """
210 213 Display probability density TS distribution and overplots expectation
211 214  
... ... @@ -217,8 +220,10 @@ def dist_pdf(values, nbins, title, expect=&#39;&#39;, plotfile=&#39;&#39;):
217 220 Number of bins
218 221 title : str
219 222 Plot title
220   - plotfile : str, optional
  223 + plotfile : str
221 224 Plot file name
  225 + expect : str, optional
  226 + If 'show', show expectation
222 227 """
223 228 # Set range and adapt number of bins. We make sure that we have a
224 229 # histogram bin centred on 0 that will capture the TS=0 part.
... ... @@ -279,59 +284,35 @@ def dist_pdf(values, nbins, title, expect=&#39;&#39;, plotfile=&#39;&#39;):
279 284 # ======================== #
280 285 if __name__ == '__main__':
281 286  
282   - # Print usage information
283   - usage = 'Usage: show_ts_distribution.py filename' \
284   - ' [-n bins] [-c column] [-t title] [-p plot] [-f file]'
285   - if len(sys.argv) < 2:
286   - print(usage)
287   - sys.exit()
288   -
289   - # Extract parameters
290   - filename = sys.argv[1]
291   -
292   - # Parameter dictionnary
293   - pars = [{'option': '-n', 'value': 30},
294   - {'option': '-c', 'value': 'TS'},
295   - {'option': '-t', 'value': 'TS distribution'},
296   - {'option': '-p', 'value': 'pdf'},
297   - {'option': '-e', 'value': ''},
298   - {'option': '-f', 'value': ''}]
299   -
300   - # Gather parameters from command line
301   - i = 2
302   - while i < len(sys.argv):
303   -
304   - # Search for options
305   - for par in pars:
306   - if sys.argv[i] == par['option']:
307   - if len(sys.argv) > i+1:
308   - i += 1
309   - try:
310   - par['value'] = sys.argv[i]
311   - except:
312   - print(usage)
313   - sys.exit()
314   - else:
315   - print(usage)
316   - sys.exit()
317   -
318   - # Next item
319   - i += 1
320   -
321   - # Recover parameters
322   - nbins = int(pars[0]['value'])
323   - tsname = pars[1]['value']
324   - title = pars[2]['value']
325   - plot = pars[3]['value']
326   - expect = pars[4]['value']
327   - plotfile = pars[5]['value']
  287 + # Set usage string
  288 + usage = ('show_ts_distribution.py [-n bins] [-c column] [-title title] '
  289 + '[-e expect] [-t type] [-p plotfile] file')
  290 +
  291 + # Set default options
  292 + options = [{'option': '-n', 'value': 30},
  293 + {'option': '-c', 'value': 'TS'},
  294 + {'option': '-title', 'value': 'TS distribution'},
  295 + {'option': '-e', 'value': ''},
  296 + {'option': '-t', 'value': 'pdf'},
  297 + {'option': '-p', 'value': ''}]
  298 +
  299 + # Get arguments and options from command line arguments
  300 + args, options = cscripts.ioutils.get_args_options(options, usage)
  301 +
  302 + # Extract script parameters from options
  303 + nbins = int(options[0]['value'])
  304 + tsname = options[1]['value']
  305 + title = options[2]['value']
  306 + expect = options[3]['value']
  307 + disttype = options[4]['value']
  308 + plotfile = options[5]['value']
328 309  
329 310 # Read values from CSV file
330   - values = read_ts(filename, tsname=tsname)
  311 + values = read_ts(args[0], tsname=tsname)
331 312 print('%d values read.' % len(values))
332 313  
333 314 # Show histogram
334   - if plot == 'pdf':
335   - dist_pdf(values, nbins, title, expect=expect, plotfile=plotfile)
  315 + if disttype == 'pdf':
  316 + dist_pdf(values, nbins, title, plotfile, expect=expect)
336 317 else:
337   - dist_cdf(values, nbins, title, expect=expect, plotfile=plotfile)
  318 + dist_cdf(values, nbins, title, plotfile, expect=expect)
... ...
test/test_examples.py.in
... ... @@ -161,8 +161,7 @@ class Test(gammalib.GPythonTestSuite):
161 161 Test generate_prod3_irfs
162 162 """
163 163 # Execute script
164   - self._execute_python('generate_prod3_irfs',
165   - args=self._datadir)
  164 + self._execute_python('generate_prod3_irfs', args=self._datadir)
166 165  
167 166 # Return
168 167 return
... ... @@ -172,9 +171,11 @@ class Test(gammalib.GPythonTestSuite):
172 171 """
173 172 Test make_spectrum
174 173 """
  174 + # Set arguments
  175 + args = '-d %s -p example_spectrum.eps' % self._datadir
  176 +
175 177 # Execute script
176   - self._execute_python('make_spectrum',
177   - args=self._datadir+' eps')
  178 + self._execute_python('make_spectrum', args=args)
178 179  
179 180 # Return
180 181 return
... ... @@ -184,9 +185,11 @@ class Test(gammalib.GPythonTestSuite):
184 185 """
185 186 Test make_ts_distributions
186 187 """
  188 + # Set arguments
  189 + args = '-n 2 -e 0 -t 1800 -d %s' % self._datadir
  190 +
187 191 # Execute script
188   - self._execute_python('make_ts_distributions',
189   - args='-n 2 -e 0 -t 1800 -d '+self._datadir)
  192 + self._execute_python('make_ts_distributions', args=args)
190 193  
191 194 # Return
192 195 return
... ... @@ -262,10 +265,11 @@ class Test(gammalib.GPythonTestSuite):
262 265 """
263 266 Test show_butterfly
264 267 """
  268 + # Set arguments
  269 + args = '-p example_show_butterfly.eps %s/butterfly.txt' % self._datadir
  270 +
265 271 # Execute script
266   - self._execute_python('show_butterfly',
267   - args=self._datadir+'/butterfly.txt '
268   - 'example_show_butterfly.eps')
  272 + self._execute_python('show_butterfly', args=args)
269 273  
270 274 # Return
271 275 return
... ... @@ -275,10 +279,17 @@ class Test(gammalib.GPythonTestSuite):
275 279 """
276 280 Test show_model
277 281 """
  282 + # Set arguments
  283 + args = '-n Crab -p example_show_model1.eps %s/crab.xml' % self._datadir
  284 +
  285 + # Execute script
  286 + self._execute_python('show_model', args=args)
  287 +
  288 + # Set new arguments
  289 + args = '-p example_show_model2.eps %s/crab.xml' % self._datadir
  290 +
278 291 # Execute script
279   - self._execute_python('show_model',
280   - args=self._datadir+'/crab.xml '
281   - 'Crab example_show_model.eps')
  292 + self._execute_python('show_model', args=args)
282 293  
283 294 # Return
284 295 return
... ... @@ -288,10 +299,11 @@ class Test(gammalib.GPythonTestSuite):
288 299 """
289 300 Test show_pha
290 301 """
  302 + # Set arguments
  303 + args = '-p example_show_pha.eps %s/pha.fits' % self._datadir
  304 +
291 305 # Execute script
292   - self._execute_python('show_pha',
293   - args=self._datadir+'/pha.fits '
294   - 'example_show_pha.eps')
  306 + self._execute_python('show_pha', args=args)
295 307  
296 308 # Return
297 309 return
... ... @@ -301,11 +313,12 @@ class Test(gammalib.GPythonTestSuite):
301 313 """
302 314 Test show_pull_evolution
303 315 """
  316 + # Set arguments
  317 + args = ('-p example_show_pull_evolution.eps %s/pull.dat '
  318 + 'Pull_Crab_Prefactor' % self._datadir)
  319 +
304 320 # Execute script
305   - self._execute_python('show_pull_evolution',
306   - args=self._datadir+'/pull.dat '
307   - 'Pull_Crab_Prefactor '
308   - 'example_show_pull_evolution.eps')
  321 + self._execute_python('show_pull_evolution', args=args)
309 322  
310 323 # Return
311 324 return
... ... @@ -315,11 +328,19 @@ class Test(gammalib.GPythonTestSuite):
315 328 """
316 329 Test show_pull_histogram
317 330 """
  331 + # Set arguments
  332 + args = ('-p example_show_pull_histogram1.eps %s/pull.dat '
  333 + 'Pull_Crab_Prefactor' % self._datadir)
  334 +
  335 + # Execute script
  336 + self._execute_python('show_pull_histogram', args=args)
  337 +
  338 + # Set arguments
  339 + args = ('-n 20 -p example_show_pull_histogram2.eps %s/pull.dat '
  340 + 'Pull_Crab_Prefactor' % self._datadir)
  341 +
318 342 # Execute script
319   - self._execute_python('show_pull_histogram',
320   - args=self._datadir+'/pull.dat '
321   - 'Pull_Crab_Prefactor 50 '
322   - 'example_show_pull_histogram.eps')
  343 + self._execute_python('show_pull_histogram', args=args)
323 344  
324 345 # Return
325 346 return
... ... @@ -329,8 +350,11 @@ class Test(gammalib.GPythonTestSuite):
329 350 """
330 351 Test show_response
331 352 """
  353 + # Set arguments
  354 + args = '-p example_show_response.eps'
  355 +
332 356 # Execute script
333   - self._execute_python('show_response', args='example_show_response.eps')
  357 + self._execute_python('show_response', args=args)
334 358  
335 359 # Return
336 360 return
... ... @@ -340,10 +364,12 @@ class Test(gammalib.GPythonTestSuite):
340 364 """
341 365 Test show_sensitivity
342 366 """
  367 + # Set arguments
  368 + args = ('-p example_show_sensitivity.eps %s/sensitivity.dat' %
  369 + self._datadir)
  370 +
343 371 # Execute script
344   - self._execute_python('show_sensitivity',
345   - args=self._datadir+'/sensitivity.dat '
346   - 'example_show_sensitivity.eps')
  372 + self._execute_python('show_sensitivity', args=args)
347 373  
348 374 # Return
349 375 return
... ... @@ -353,10 +379,11 @@ class Test(gammalib.GPythonTestSuite):
353 379 """
354 380 Test show_spectrum
355 381 """
  382 + # Set arguments
  383 + args = '-p example_show_spectrum.eps %s/spectrum.fits' % self._datadir
  384 +
356 385 # Execute script
357   - self._execute_python('show_spectrum',
358   - args=self._datadir+'/spectrum.fits '
359   - 'example_show_spectrum.eps')
  386 + self._execute_python('show_spectrum', args=args)
360 387  
361 388 # Return
362 389 return
... ... @@ -366,10 +393,19 @@ class Test(gammalib.GPythonTestSuite):
366 393 """
367 394 Test show_ts_distribution
368 395 """
  396 + # Set arguments
  397 + args = ('-n 100 -p example_show_ts_distribution1.eps %s/ts.dat' %
  398 + self._datadir)
  399 +
  400 + # Execute script
  401 + self._execute_python('show_ts_distribution', args=args)
  402 +
  403 + # Set arguments
  404 + args = ('-n 100 -t cdf -p example_show_ts_distribution2.eps %s/ts.dat' %
  405 + self._datadir)
  406 +
369 407 # Execute script
370   - self._execute_python('show_ts_distribution',
371   - args=self._datadir+'/ts.dat -n 100 '
372   - '-f example_show_ts_distribution.eps')
  408 + self._execute_python('show_ts_distribution', args=args)
373 409  
374 410 # Return
375 411 return
... ... @@ -379,10 +415,18 @@ class Test(gammalib.GPythonTestSuite):
379 415 """
380 416 Test show_obs
381 417 """
  418 + # Set arguments
  419 + args = '-p example_show_obs1.eps %s/obs_unbinned.xml' % self._datadir
  420 +
  421 + # Execute script
  422 + self._execute_python('show_obs', args=args)
  423 +
  424 + # Set arguments
  425 + args = ('-ra 83.63 -dec 22.01 -p example_show_obs2.eps '
  426 + '%s/obs_unbinned.xml' % self._datadir)
  427 +
382 428 # Execute script
383   - self._execute_python('show_obs',
384   - args=self._datadir+'/obs_unbinned.xml '
385   - 'example_show_obs.eps')
  429 + self._execute_python('show_obs', args=args)
386 430  
387 431 # Return
388 432 return
... ...