Commit cb7d7d75ed8d7b02b8e40cb6e26cfe647592175c

Authored by Jürgen Knödlseder
1 parent 4300668e

Add make_spectrum.py example script to unit tests

examples/make_spectrum.py
1 #! /usr/bin/env python 1 #! /usr/bin/env python
2 # ========================================================================== 2 # ==========================================================================
3 -# This script shows how to make a spectrum using obsutils. 3 +# Makes spectrum and optionally plot it
4 # 4 #
5 # Copyright (C) 2014-2016 Juergen Knoedlseder 5 # Copyright (C) 2014-2016 Juergen Knoedlseder
6 # 6 #
@@ -18,7 +18,7 @@ @@ -18,7 +18,7 @@
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # 19 #
20 # ========================================================================== 20 # ==========================================================================
21 -#import gammalib 21 +import sys
22 import ctools 22 import ctools
23 import cscripts 23 import cscripts
24 try: 24 try:
@@ -33,12 +33,17 @@ except: @@ -33,12 +33,17 @@ except:
33 # =============== # 33 # =============== #
34 def make_spectrum(): 34 def make_spectrum():
35 """ 35 """
36 - Make a spectrum. 36 + Simulate events and generate a source spectrum
  37 +
  38 + Returns
  39 + -------
  40 + spectrum : `~gammalib.GFits`
  41 + Spectrum FITS file
37 """ 42 """
38 # Set script parameters 43 # Set script parameters
39 - model_name = "${CTOOLS}/share/models/crab.xml"  
40 - caldb = "prod2"  
41 - irf = "South_50h" 44 + model_name = 'data/crab.xml'
  45 + caldb = 'prod2'
  46 + irf = 'South_0.5h'
42 ra = 83.63 47 ra = 83.63
43 dec = 22.01 48 dec = 22.01
44 rad_sim = 3.0 49 rad_sim = 3.0
@@ -50,36 +55,32 @@ def make_spectrum(): @@ -50,36 +55,32 @@ def make_spectrum():
50 55
51 # Simulate events 56 # Simulate events
52 sim = ctools.ctobssim() 57 sim = ctools.ctobssim()
53 - sim["inmodel"] = model_name  
54 - sim["caldb"] = caldb  
55 - sim["irf"] = irf  
56 - sim["ra"] = ra  
57 - sim["dec"] = dec  
58 - sim["rad"] = rad_sim  
59 - sim["tmin"] = tstart  
60 - sim["tmax"] = tstop  
61 - sim["emin"] = emin  
62 - sim["emax"] = emax 58 + sim['inmodel'] = model_name
  59 + sim['caldb'] = caldb
  60 + sim['irf'] = irf
  61 + sim['ra'] = ra
  62 + sim['dec'] = dec
  63 + sim['rad'] = rad_sim
  64 + sim['tmin'] = tstart
  65 + sim['tmax'] = tstop
  66 + sim['emin'] = emin
  67 + sim['emax'] = emax
63 sim.run() 68 sim.run()
64 69
65 - # Generate an energy binning  
66 - #e_min = gammalib.GEnergy(emin, "TeV")  
67 - #e_max = gammalib.GEnergy(emax, "TeV")  
68 - #ebounds = gammalib.GEbounds(10, e_min, e_max)  
69 -  
70 - # Setup csspec run 70 + # Create spectrum
71 spec = cscripts.csspec(sim.obs()) 71 spec = cscripts.csspec(sim.obs())
72 - spec["srcname"] = "Crab"  
73 - spec["outfile"] = "spectrum.fits"  
74 - spec["expcube"] = "NONE"  
75 - spec["psfcube"] = "NONE"  
76 - spec["bkgcube"] = "NONE"  
77 - spec["edisp"] = False  
78 - spec["emin"] = emin  
79 - spec["emax"] = emax  
80 - spec["enumbins"] = enumbins  
81 - spec["binned"] = False 72 + spec['srcname'] = 'Crab'
  73 + spec['outfile'] = 'example_spectrum.fits'
  74 + spec['expcube'] = 'NONE'
  75 + spec['psfcube'] = 'NONE'
  76 + spec['bkgcube'] = 'NONE'
  77 + spec['edisp'] = False
  78 + spec['emin'] = emin
  79 + spec['emax'] = emax
  80 + spec['enumbins'] = enumbins
  81 + spec['ebinalg'] = 'LOG'
82 spec.run() 82 spec.run()
  83 + spec.save()
83 84
84 # Get copy of spectrum 85 # Get copy of spectrum
85 spectrum = spec.spectrum().copy() 86 spectrum = spec.spectrum().copy()
@@ -91,19 +92,26 @@ def make_spectrum(): @@ -91,19 +92,26 @@ def make_spectrum():
91 # ============= # 92 # ============= #
92 # Plot spectrum # 93 # Plot spectrum #
93 # ============= # 94 # ============= #
94 -def plot_spectrum(spectrum): 95 +def plot_spectrum(spectrum, file=False):
95 """ 96 """
96 Plot spectrum. 97 Plot spectrum.
  98 +
  99 + Parameters
  100 + ----------
  101 + spectrum : `~gammalib.GFits`
  102 + Spectrum FITS file
  103 + type : str, optional
  104 + Plot type (blank means display on screen)
97 """ 105 """
98 - # Read spectrum file 106 + # Extract columns from spectrum file
99 table = spectrum.table(1) 107 table = spectrum.table(1)
100 - c_energy = table["Energy"]  
101 - c_ed = table["ed_Energy"]  
102 - c_eu = table["eu_Energy"]  
103 - c_flux = table["Flux"]  
104 - c_eflux = table["e_Flux"]  
105 - c_ts = table["TS"]  
106 - c_upper = table["UpperLimit"] 108 + c_energy = table['Energy']
  109 + c_ed = table['ed_Energy']
  110 + c_eu = table['eu_Energy']
  111 + c_flux = table['Flux']
  112 + c_eflux = table['e_Flux']
  113 + c_ts = table['TS']
  114 + c_upper = table['UpperLimit']
107 115
108 # Initialise arrays to be filled 116 # Initialise arrays to be filled
109 energies = [] 117 energies = []
@@ -115,7 +123,7 @@ def plot_spectrum(spectrum): @@ -115,7 +123,7 @@ def plot_spectrum(spectrum):
115 ul_ed_engs = [] 123 ul_ed_engs = []
116 ul_eu_engs = [] 124 ul_eu_engs = []
117 ul_flux = [] 125 ul_flux = []
118 - 126 +
119 # Loop over rows of the file 127 # Loop over rows of the file
120 nrows = table.nrows() 128 nrows = table.nrows()
121 for row in range(nrows): 129 for row in range(nrows):
@@ -146,31 +154,43 @@ def plot_spectrum(spectrum): @@ -146,31 +154,43 @@ def plot_spectrum(spectrum):
146 154
147 # Create figure 155 # Create figure
148 plt.figure() 156 plt.figure()
149 - plt.title("Crab spectrum") 157 + plt.title('Crab spectrum')
150 158
151 # Plot the spectrum 159 # Plot the spectrum
152 plt.loglog() 160 plt.loglog()
153 plt.grid() 161 plt.grid()
154 - plt.errorbar(energies, flux, yerr=e_flux, xerr=[ed_engs, eu_engs], fmt='ro')  
155 - plt.errorbar(ul_energies, ul_flux, xerr=[ul_ed_engs, ul_eu_engs], yerr=1.0e-11, uplims=True, fmt='ro')  
156 - plt.xlabel("Energy (TeV)")  
157 - plt.ylabel(r"E$^{2}$dN/dE (erg cm$^{-2}$ s$^{-1}$)")  
158 -  
159 - # Show spectrum  
160 - plt.show() 162 + plt.errorbar(energies, flux, yerr=e_flux, xerr=[ed_engs, eu_engs],
  163 + fmt='ro')
  164 + plt.errorbar(ul_energies, ul_flux, xerr=[ul_ed_engs, ul_eu_engs],
  165 + yerr=1.0e-11, uplims=True, fmt='ro')
  166 + plt.xlabel('Energy (TeV)')
  167 + plt.ylabel(r'E$^{2}$dN/dE (erg cm$^{-2}$ s$^{-1}$)')
  168 +
  169 + # Show spectrum or save it into file
  170 + if file:
  171 + plt.savefig('example_spectrum.eps')
  172 + else:
  173 + plt.show()
161 174
162 # Return 175 # Return
163 return 176 return
164 177
165 178
166 -#==========================# 179 +# ======================== #
167 # Main routine entry point # 180 # Main routine entry point #
168 -#==========================# 181 +# ======================== #
169 if __name__ == '__main__': 182 if __name__ == '__main__':
170 183
  184 + # Initialise option
  185 + file = False
  186 +
  187 + # Get any command line arguments
  188 + if (len(sys.argv) > 1):
  189 + file = True
  190 +
171 # Generate spectrum 191 # Generate spectrum
172 spectrum = make_spectrum() 192 spectrum = make_spectrum()
173 193
174 - # Plot spectrum 194 + # If matplotlib is installed then plot spectrum
175 if has_matplotlib: 195 if has_matplotlib:
176 - plot_spectrum(spectrum) 196 + plot_spectrum(spectrum, file=file)
test/test_examples.py
@@ -71,6 +71,7 @@ class Test(gammalib.GPythonTestSuite): @@ -71,6 +71,7 @@ class Test(gammalib.GPythonTestSuite):
71 # Execute Python script, make sure we catch any exception 71 # Execute Python script, make sure we catch any exception
72 try: 72 try:
73 rc = os.system(cmd+' > example_'+logname+'.log 2>&1') 73 rc = os.system(cmd+' > example_'+logname+'.log 2>&1')
  74 + #rc = os.system(cmd)
74 except: 75 except:
75 pass 76 pass
76 77
@@ -91,6 +92,7 @@ class Test(gammalib.GPythonTestSuite): @@ -91,6 +92,7 @@ class Test(gammalib.GPythonTestSuite):
91 # Append tests 92 # Append tests
92 self.append(self.test_generate_prod3_irfs, 'Test generate_prod3_irfs') 93 self.append(self.test_generate_prod3_irfs, 'Test generate_prod3_irfs')
93 self.append(self.test_make_pointings, 'Test make_pointings') 94 self.append(self.test_make_pointings, 'Test make_pointings')
  95 + self.append(self.test_make_spectrum, 'Test make_spectrum')
94 self.append(self.test_pipeline_binned_disk, 'Test pipeline_binned_disk') 96 self.append(self.test_pipeline_binned_disk, 'Test pipeline_binned_disk')
95 self.append(self.test_pipeline_binned_mem, 'Test pipeline_binned_mem') 97 self.append(self.test_pipeline_binned_mem, 'Test pipeline_binned_mem')
96 self.append(self.test_pipeline_stacked_disk, 'Test pipeline_stacked_disk') 98 self.append(self.test_pipeline_stacked_disk, 'Test pipeline_stacked_disk')
@@ -110,7 +112,7 @@ class Test(gammalib.GPythonTestSuite): @@ -110,7 +112,7 @@ class Test(gammalib.GPythonTestSuite):
110 script = 'make_pointings' 112 script = 'make_pointings'
111 113
112 # Execute script 114 # Execute script
113 - self._execute_python(script, args='-h', log='make_pointings_help') 115 + self._execute_python(script, args='-h', log='make_pointings_h')
114 self._execute_python(script, args='gps', log='make_pointings_gps') 116 self._execute_python(script, args='gps', log='make_pointings_gps')
115 self._execute_python(script, args='gps3', log='make_pointings_gps3') 117 self._execute_python(script, args='gps3', log='make_pointings_gps3')
116 self._execute_python(script, args='extgal', log='make_pointings_extgal') 118 self._execute_python(script, args='extgal', log='make_pointings_extgal')
@@ -122,6 +124,19 @@ class Test(gammalib.GPythonTestSuite): @@ -122,6 +124,19 @@ class Test(gammalib.GPythonTestSuite):
122 # Return 124 # Return
123 return 125 return
124 126
  127 + # Test make_spectrum
  128 + def test_make_spectrum(self):
  129 + """
  130 + Test make_spectrum
  131 + """
  132 + # Execute script
  133 + self._execute_python('make_spectrum', args='eps')
  134 +
  135 + #TODO: Do any testing
  136 +
  137 + # Return
  138 + return
  139 +
125 # Test generate_prod3_irfs 140 # Test generate_prod3_irfs
126 def test_generate_prod3_irfs(self): 141 def test_generate_prod3_irfs(self):
127 """ 142 """