Commit 9efd40b5ab270f769e4e7e315e07c9c298879488

Authored by Jürgen Knödlseder
1 parent e0891e8e

Replace print statements by calls to sys.stdout.write() functions.

As Python3 replaces the print statement by a print() function, the previous code was not compatible with Python3. We thus replaced all print statements by calls to sys.stdout.write() so that the code works  both for Python2 and Python3.
examples/make_binned_analysis.py
@@ -28,6 +28,7 @@ from gammalib import * @@ -28,6 +28,7 @@ from gammalib import *
28 from math import * 28 from math import *
29 import os 29 import os
30 import glob 30 import glob
  31 +import sys
31 32
32 33
33 # ============================= # 34 # ============================= #
@@ -82,7 +83,7 @@ def pipeline_v1(): @@ -82,7 +83,7 @@ def pipeline_v1():
82 sim["emin"].real(emin) 83 sim["emin"].real(emin)
83 sim["emax"].real(emax) 84 sim["emax"].real(emax)
84 sim.execute() 85 sim.execute()
85 - print "Simulated events ("+str(sim.celapse())+" CPU seconds)" 86 + sys.stdout.write("Simulated events ("+str(sim.celapse())+" CPU seconds)\n")
86 87
87 # Update timing 88 # Update timing
88 wall_seconds += sim.telapse() 89 wall_seconds += sim.telapse()
@@ -104,7 +105,7 @@ def pipeline_v1(): @@ -104,7 +105,7 @@ def pipeline_v1():
104 bin["yref"].real(dec) 105 bin["yref"].real(dec)
105 bin["proj"].string(proj) 106 bin["proj"].string(proj)
106 bin.execute() 107 bin.execute()
107 - print "Binned events into counts map ("+str(bin.celapse())+" CPU seconds)" 108 + sys.stdout.write("Binned events into counts map ("+str(bin.celapse())+" CPU seconds)\n")
108 109
109 # Update timing 110 # Update timing
110 wall_seconds += bin.telapse() 111 wall_seconds += bin.telapse()
@@ -119,15 +120,15 @@ def pipeline_v1(): @@ -119,15 +120,15 @@ def pipeline_v1():
119 like["caldb"].string(caldb) 120 like["caldb"].string(caldb)
120 like["irf"].string(irf) 121 like["irf"].string(irf)
121 like.execute() 122 like.execute()
122 - print "Maximum likelihood fitting ("+str(like.celapse())+" CPU seconds)" 123 + sys.stdout.write("Maximum likelihood fitting ("+str(like.celapse())+" CPU seconds)\n")
123 124
124 # Update timing 125 # Update timing
125 wall_seconds += like.telapse() 126 wall_seconds += like.telapse()
126 cpu_seconds += like.celapse() 127 cpu_seconds += like.celapse()
127 128
128 # Show total times 129 # Show total times
129 - print "Total wall time elapsed: "+str(wall_seconds)+" seconds"  
130 - print "Total CPU time used ...: "+str(cpu_seconds)+" seconds" 130 + sys.stdout.write("Total wall time elapsed: "+str(wall_seconds)+" seconds\n")
  131 + sys.stdout.write("Total CPU time used ...: "+str(cpu_seconds)+" seconds\n")
131 132
132 # Return 133 # Return
133 return 134 return
@@ -181,7 +182,7 @@ def pipeline_v2(): @@ -181,7 +182,7 @@ def pipeline_v2():
181 sim["emin"].real(emin) 182 sim["emin"].real(emin)
182 sim["emax"].real(emax) 183 sim["emax"].real(emax)
183 sim.run() 184 sim.run()
184 - print "Simulated events ("+str(sim.celapse())+" CPU seconds)" 185 + sys.stdout.write("Simulated events ("+str(sim.celapse())+" CPU seconds)\n")
185 186
186 # Update timing 187 # Update timing
187 wall_seconds += sim.telapse() 188 wall_seconds += sim.telapse()
@@ -200,7 +201,7 @@ def pipeline_v2(): @@ -200,7 +201,7 @@ def pipeline_v2():
200 bin["yref"].real(dec) 201 bin["yref"].real(dec)
201 bin["proj"].string(proj) 202 bin["proj"].string(proj)
202 bin.run() 203 bin.run()
203 - print "Binned events into counts map ("+str(bin.celapse())+" CPU seconds)" 204 + sys.stdout.write("Binned events into counts map ("+str(bin.celapse())+" CPU seconds)\n")
204 205
205 # Update timing 206 # Update timing
206 wall_seconds += bin.telapse() 207 wall_seconds += bin.telapse()
@@ -209,18 +210,18 @@ def pipeline_v2(): @@ -209,18 +210,18 @@ def pipeline_v2():
209 # Perform maximum likelihood fitting 210 # Perform maximum likelihood fitting
210 like = ctlike(bin.obs()) 211 like = ctlike(bin.obs())
211 like.run() 212 like.run()
212 - print "Maximum likelihood fitting ("+str(like.celapse())+" CPU seconds)" 213 + sys.stdout.write("Maximum likelihood fitting ("+str(like.celapse())+" CPU seconds)\n")
213 214
214 # Update timing 215 # Update timing
215 wall_seconds += like.telapse() 216 wall_seconds += like.telapse()
216 cpu_seconds += like.celapse() 217 cpu_seconds += like.celapse()
217 218
218 # Show total times 219 # Show total times
219 - print "Total wall time elapsed: "+str(wall_seconds)+" seconds"  
220 - print "Total CPU time used ...: "+str(cpu_seconds)+" seconds" 220 + sys.stdout.write("Total wall time elapsed: "+str(wall_seconds)+" seconds\n")
  221 + sys.stdout.write("Total CPU time used ...: "+str(cpu_seconds)+" seconds\n")
221 222
222 # Show model fitting results 223 # Show model fitting results
223 - #print like.obs().models() 224 + #sys.stdout.write(like.obs().models()+"\n")
224 225
225 # Plot counts 226 # Plot counts
226 plot_counts(bin.obs()) 227 plot_counts(bin.obs())
@@ -249,9 +250,9 @@ def plot_counts(observations): @@ -249,9 +250,9 @@ def plot_counts(observations):
249 styles = ['b-', 'g-', 'y-', 'n-'] 250 styles = ['b-', 'g-', 'y-', 'n-']
250 251
251 # Dump header 252 # Dump header
252 - print ""  
253 - print "Make plots (using matplotlib):"  
254 - print "==============================" 253 + sys.stdout.write("\n")
  254 + sys.stdout.write("Make plots (using matplotlib):\n")
  255 + sys.stdout.write("==============================\n")
255 256
256 # Create figure 1 257 # Create figure 1
257 plt.figure(1,figsize=(12,6)) 258 plt.figure(1,figsize=(12,6))
@@ -274,7 +275,7 @@ def plot_counts(observations): @@ -274,7 +275,7 @@ def plot_counts(observations):
274 energy.append(ebounds.elogmean(i).TeV()) 275 energy.append(ebounds.elogmean(i).TeV())
275 276
276 # Create spectrum 277 # Create spectrum
277 - print "Extract data:" 278 + sys.stdout.write("Extract data:\n")
278 counts = [0.0 for i in range(ebounds.size())] 279 counts = [0.0 for i in range(ebounds.size())]
279 for bin in cube: 280 for bin in cube:
280 index = ebounds.index(bin.energy()) 281 index = ebounds.index(bin.energy())
@@ -288,10 +289,10 @@ def plot_counts(observations): @@ -288,10 +289,10 @@ def plot_counts(observations):
288 plt.errorbar(energy, counts, error, fmt=None, ecolor='r') 289 plt.errorbar(energy, counts, error, fmt=None, ecolor='r')
289 290
290 # Extract models 291 # Extract models
291 - print "Extract models:" 292 + sys.stdout.write("Extract models:\n")
292 sum_model = [0.0 for i in range(ebounds.size())] 293 sum_model = [0.0 for i in range(ebounds.size())]
293 for k, m in enumerate(observations.models()): 294 for k, m in enumerate(observations.models()):
294 - print "- "+m.name() 295 + sys.stdout.write("- "+m.name()+"\n")
295 model = [0.0 for i in range(ebounds.size())] 296 model = [0.0 for i in range(ebounds.size())]
296 for bin in cube: 297 for bin in cube:
297 index = ebounds.index(bin.energy()) 298 index = ebounds.index(bin.energy())
@@ -322,7 +323,7 @@ def plot_counts(observations): @@ -322,7 +323,7 @@ def plot_counts(observations):
322 cube = cast_GCTAEventCube(obs.events()) 323 cube = cast_GCTAEventCube(obs.events())
323 324
324 # Create offset histogram 325 # Create offset histogram
325 - print "Extract data:" 326 + sys.stdout.write("Extract data:\n")
326 nx = 30 327 nx = 30
327 doffset2 = 0.01 328 doffset2 = 0.01
328 offset2 = [(i+0.5)*doffset2 for i in range(nx)] 329 offset2 = [(i+0.5)*doffset2 for i in range(nx)]
@@ -341,10 +342,10 @@ def plot_counts(observations): @@ -341,10 +342,10 @@ def plot_counts(observations):
341 plt.semilogy(offset2, counts, 'ro', label='data') 342 plt.semilogy(offset2, counts, 'ro', label='data')
342 343
343 # Extract models 344 # Extract models
344 - print "Extract models:" 345 + sys.stdout.write("Extract models:\n")
345 sum_model = [0.0 for i in range(nx)] 346 sum_model = [0.0 for i in range(nx)]
346 for k, m in enumerate(observations.models()): 347 for k, m in enumerate(observations.models()):
347 - print "- "+m.name() 348 + sys.stdout.write("- "+m.name()+"\n")
348 model = [0.0 for i in range(nx)] 349 model = [0.0 for i in range(nx)]
349 for bin in cube: 350 for bin in cube:
350 off = bin.dir().dist_deg(crab) 351 off = bin.dir().dist_deg(crab)
@@ -368,7 +369,7 @@ def plot_counts(observations): @@ -368,7 +369,7 @@ def plot_counts(observations):
368 plt.show() 369 plt.show()
369 370
370 except: 371 except:
371 - print "Matplotlib is not (correctly) installed on your system. No counts spectra are shown." 372 + sys.stdout.write("Matplotlib is not (correctly) installed on your system. No counts spectra are shown.\n")
372 373
373 # Return 374 # Return
374 return 375 return
@@ -398,10 +399,10 @@ if __name__ == '__main__': @@ -398,10 +399,10 @@ if __name__ == '__main__':
398 around the Crab has been performed. 399 around the Crab has been performed.
399 """ 400 """
400 # Dump header 401 # Dump header
401 - print "*************************************"  
402 - print "* CTA binned analysis scripts *"  
403 - print "*************************************"  
404 - print "... this script will take 1-2 minutes" 402 + sys.stdout.write("*************************************\n")
  403 + sys.stdout.write("* CTA binned analysis scripts *\n")
  404 + sys.stdout.write("*************************************\n")
  405 + sys.stdout.write("... this script will take 1-2 minutes\n")
405 406
406 # Remove any existing result files 407 # Remove any existing result files
407 list = [glob.glob("*.fits"), glob.glob("*.log"), glob.glob("*.xml")] 408 list = [glob.glob("*.fits"), glob.glob("*.log"), glob.glob("*.xml")]
@@ -410,14 +411,14 @@ if __name__ == '__main__': @@ -410,14 +411,14 @@ if __name__ == '__main__':
410 os.remove(file) 411 os.remove(file)
411 412
412 # Save intermediate results on disk 413 # Save intermediate results on disk
413 - print ""  
414 - print "Executable analysis pipeline:"  
415 - print "=============================" 414 + sys.stdout.write("\n")
  415 + sys.stdout.write("Executable analysis pipeline:\n")
  416 + sys.stdout.write("=============================\n")
416 pipeline_v1() 417 pipeline_v1()
417 418
418 # Do analysis in memory 419 # Do analysis in memory
419 - print ""  
420 - print "In memory analysis pipeline:"  
421 - print "============================" 420 + sys.stdout.write("\n")
  421 + sys.stdout.write("In memory analysis pipeline:\n")
  422 + sys.stdout.write("============================\n")
422 pipeline_v2() 423 pipeline_v2()
423 - print "" 424 + sys.stdout.write("\n")
examples/show_pull_histogram.py
@@ -58,11 +58,10 @@ def read_pull(filename, parname): @@ -58,11 +58,10 @@ def read_pull(filename, parname):
58 try: 58 try:
59 index = row.index(parname) 59 index = row.index(parname)
60 except: 60 except:
61 - print 'ERROR: Parameter "'+parname+'" not found in list:' 61 + sys.stdout.write('ERROR: Parameter "'+parname+'" not found in list:\n')
62 for p in row: 62 for p in row:
63 - print ' "'+p+'"' 63 + sys.stdout.write(' "'+p+'"\n')
64 raise NameError(parname) 64 raise NameError(parname)
65 - #print index  
66 65
67 # Handle data rows 66 # Handle data rows
68 else: 67 else:
@@ -73,7 +72,6 @@ def read_pull(filename, parname): @@ -73,7 +72,6 @@ def read_pull(filename, parname):
73 72
74 # Create numpy array 73 # Create numpy array
75 a = np.array(values) 74 a = np.array(values)
76 - #print a  
77 75
78 # Return array 76 # Return array
79 return a 77 return a
@@ -89,7 +87,7 @@ if __name__ == '__main__': @@ -89,7 +87,7 @@ if __name__ == '__main__':
89 # Print usage information 87 # Print usage information
90 usage = "Usage: show_pull_histogram filename parname [bins]" 88 usage = "Usage: show_pull_histogram filename parname [bins]"
91 if len(sys.argv) < 3: 89 if len(sys.argv) < 3:
92 - print usage 90 + sys.stdout.write(usage+"\n")
93 sys.exit() 91 sys.exit()
94 92
95 # Extract parameters 93 # Extract parameters
examples/show_ts_distribution.py
@@ -53,10 +53,9 @@ def read_ts(filename, tsname=&quot;TS&quot;): @@ -53,10 +53,9 @@ def read_ts(filename, tsname=&quot;TS&quot;):
53 try: 53 try:
54 index = row.index(tsname) 54 index = row.index(tsname)
55 except: 55 except:
56 - print 'ERROR: Column "TS" not found in file'  
57 - print row 56 + sys.stdout.write('ERROR: Column "TS" not found in file\n')
  57 + sys.stdout.write(row+"\n")
58 raise NameError("TS") 58 raise NameError("TS")
59 - #print index  
60 59
61 # Handle data rows 60 # Handle data rows
62 else: 61 else:
@@ -227,7 +226,7 @@ if __name__ == &#39;__main__&#39;: @@ -227,7 +226,7 @@ if __name__ == &#39;__main__&#39;:
227 usage = "Usage: show_ts_distribution filename" \ 226 usage = "Usage: show_ts_distribution filename" \
228 " [-n bins] [-c column] [-t title] [-p plot]" 227 " [-n bins] [-c column] [-t title] [-p plot]"
229 if len(sys.argv) < 2: 228 if len(sys.argv) < 2:
230 - print usage 229 + sys.stdout.write(usage+"\n")
231 sys.exit() 230 sys.exit()
232 231
233 # Extract parameters 232 # Extract parameters
@@ -257,10 +256,10 @@ if __name__ == &#39;__main__&#39;: @@ -257,10 +256,10 @@ if __name__ == &#39;__main__&#39;:
257 try: 256 try:
258 par['value'] = sys.argv[i] 257 par['value'] = sys.argv[i]
259 except: 258 except:
260 - print usage 259 + sys.stdout.write(usage+"\n")
261 sys.exit() 260 sys.exit()
262 else: 261 else:
263 - print usage 262 + sys.stdout.write(usage+"\n")
264 sys.exit() 263 sys.exit()
265 264
266 # Next item 265 # Next item
@@ -274,7 +273,7 @@ if __name__ == &#39;__main__&#39;: @@ -274,7 +273,7 @@ if __name__ == &#39;__main__&#39;:
274 273
275 # Read values from CSV file 274 # Read values from CSV file
276 values = read_ts(filename, tsname=tsname) 275 values = read_ts(filename, tsname=tsname)
277 - print len(values), "values read." 276 + sys.stdout.write(len(values), "values read.\n")
278 277
279 # Show histogram 278 # Show histogram
280 if plot == "pdf": 279 if plot == "pdf":
scripts/cspull.py
@@ -90,7 +90,7 @@ class cspull(GApplication): @@ -90,7 +90,7 @@ class cspull(GApplication):
90 pars = GPars(parfile) 90 pars = GPars(parfile)
91 except: 91 except:
92 # Signal if parfile was not found 92 # Signal if parfile was not found
93 - print "Parfile "+parfile+" not found. Create default parfile." 93 + sys.stdout.write("Parfile "+parfile+" not found. Create default parfile.\n")
94 94
95 # Create default parfile 95 # Create default parfile
96 pars = GPars() 96 pars = GPars()
scripts/cssens.py
@@ -101,7 +101,7 @@ class cssens(GApplication): @@ -101,7 +101,7 @@ class cssens(GApplication):
101 pars = GPars(parfile) 101 pars = GPars(parfile)
102 except: 102 except:
103 # Signal if parfile was not found 103 # Signal if parfile was not found
104 - print "Parfile "+parfile+" not found. Create default parfile." 104 + sys.stdout.write("Parfile "+parfile+" not found. Create default parfile.\n")
105 105
106 # Create default parfile 106 # Create default parfile
107 pars = GPars() 107 pars = GPars()
scripts/cstsdist.py
@@ -91,7 +91,7 @@ class cstsdist(GApplication): @@ -91,7 +91,7 @@ class cstsdist(GApplication):
91 pars = GPars(parfile) 91 pars = GPars(parfile)
92 except: 92 except:
93 # Signal if parfile was not found 93 # Signal if parfile was not found
94 - print "Parfile "+parfile+" not found. Create default parfile." 94 + sys.stdout.write("Parfile "+parfile+" not found. Create default parfile.\n")
95 95
96 # Create default parfile 96 # Create default parfile
97 pars = GPars() 97 pars = GPars()
scripts/cta_make_nodes.py
@@ -86,7 +86,8 @@ def create_nodes(emin, emax, enumbins): @@ -86,7 +86,8 @@ def create_nodes(emin, emax, enumbins):
86 write_node(file, energy, scale) 86 write_node(file, energy, scale)
87 87
88 # Debug 88 # Debug
89 - #print energy, math.pow(10.0, int(math.log10(scale))-1.0) 89 + #sys.stdout.write(energy)
  90 + #sys.stdout.write(math.pow(10.0, int(math.log10(scale))-1.0)±"\n")
90 91
91 # Close file 92 # Close file
92 file.close() 93 file.close()
@@ -105,7 +106,7 @@ if __name__ == &#39;__main__&#39;: @@ -105,7 +106,7 @@ if __name__ == &#39;__main__&#39;:
105 # Check command line 106 # Check command line
106 usage = "Usage: cta_make_nodes emin emax enumbins" 107 usage = "Usage: cta_make_nodes emin emax enumbins"
107 if len(sys.argv) < 3: 108 if len(sys.argv) < 3:
108 - print usage 109 + sys.stdout.write(usage+"\n")
109 sys.exit() 110 sys.exit()
110 111
111 # Extract parameters 112 # Extract parameters
scripts/cta_root2irf.py
@@ -149,7 +149,7 @@ def make_files(filename, prfname, bkgname): @@ -149,7 +149,7 @@ def make_files(filename, prfname, bkgname):
149 149
150 # Write header 150 # Write header
151 fprf.write("log(E) Area r68 r80 ERes. BG Rate Diff Sens\n") 151 fprf.write("log(E) Area r68 r80 ERes. BG Rate Diff Sens\n")
152 - print "log(E) Area Area80 r68 r80 ERes. BG Rate Diff Sens BGRateSqDeg BGInt (BGIntControl)" 152 + #sys.stdout.write("log(E) Area Area80 r68 r80 ERes. BG Rate Diff Sens BGRateSqDeg BGInt (BGIntControl)\n")
153 153
154 # Get histograms. Konrad's root files do not have an EffectiveArea80 154 # Get histograms. Konrad's root files do not have an EffectiveArea80
155 # histogram, but his effective area is for 80% containment radius 155 # histogram, but his effective area is for 80% containment radius
@@ -222,8 +222,8 @@ def make_files(filename, prfname, bkgname): @@ -222,8 +222,8 @@ def make_files(filename, prfname, bkgname):
222 fbkg.write(str(energy)+" "+str(bkg_rate)+"\n") 222 fbkg.write(str(energy)+" "+str(bkg_rate)+"\n")
223 223
224 # Show performance file 224 # Show performance file
225 - print "%.1f %.1f %.1f %.4f %.4f %.4f %.7f %.5e %.5e %.5e (%.5e)" % \  
226 - (logE, area, area80, r68, r80, dE, bgd, diffs, bgdsq, bkg_rate, bkg_rate2) 225 + #print "%.1f %.1f %.1f %.4f %.4f %.4f %.7f %.5e %.5e %.5e (%.5e)" % \
  226 + # (logE, area, area80, r68, r80, dE, bgd, diffs, bgdsq, bkg_rate, bkg_rate2)
227 227
228 # Write trailer 228 # Write trailer
229 fprf.write("---------------------------------------------\n") 229 fprf.write("---------------------------------------------\n")
@@ -285,7 +285,7 @@ if __name__ == &#39;__main__&#39;: @@ -285,7 +285,7 @@ if __name__ == &#39;__main__&#39;:
285 # Build output filenames 285 # Build output filenames
286 prfname = name + ".dat" 286 prfname = name + ".dat"
287 bkgname = "bkg_"+name+".txt" 287 bkgname = "bkg_"+name+".txt"
288 - print prfname, bkgname 288 + #print prfname, bkgname
289 289
290 # Create files 290 # Create files
291 make_files(file, prfname, bkgname) 291 make_files(file, prfname, bkgname)
test/test_python.py
@@ -177,10 +177,10 @@ if __name__ == &#39;__main__&#39;: @@ -177,10 +177,10 @@ if __name__ == &#39;__main__&#39;:
177 Test ctools Python modules. 177 Test ctools Python modules.
178 """ 178 """
179 # Dump header 179 # Dump header
180 - print ""  
181 - print "*************************************"  
182 - print "* ctools Python interface testing *"  
183 - print "************************************" 180 + sys.stdout.write("\n")
  181 + sys.stdout.write("***********************************\n")
  182 + sys.stdout.write("* ctools Python interface testing *\n")
  183 + sys.stdout.write("***********************************\n")
184 184
185 # Set PFILES environment variable 185 # Set PFILES environment variable
186 try: 186 try:
@@ -197,11 +197,11 @@ if __name__ == &#39;__main__&#39;: @@ -197,11 +197,11 @@ if __name__ == &#39;__main__&#39;:
197 os.remove(file) 197 os.remove(file)
198 198
199 # Save intermediate results on disk 199 # Save intermediate results on disk
200 - print "Test executable analysis: ", 200 + sys.stdout.write("Test executable analysis: ")
201 pipeline_v1() 201 pipeline_v1()
202 - print " ok" 202 + sys.stdout.write(" ok\n")
203 203
204 # Keep results in memory 204 # Keep results in memory
205 - print "Test in-memory analysis: ", 205 + sys.stdout.write("Test in-memory analysis: ")
206 pipeline_v2() 206 pipeline_v2()
207 - print " ok" 207 + sys.stdout.write(" ok\n")