Commit 7e4a03953ddb55949884cf30fcf8bf5d81058a6e

Authored by Jürgen Knödlseder
1 parent 9c93dcc7

Remove cast.

Showing 1 changed file with 126 additions and 129 deletions
examples/make_binned_analysis.py
@@ -4,10 +4,7 @@ @@ -4,10 +4,7 @@
4 # ctools. If matplotlib is installed, a counts spectrum and an offset 4 # ctools. If matplotlib is installed, a counts spectrum and an offset
5 # histogram will be displayed. 5 # histogram will be displayed.
6 # 6 #
7 -# Required 3rd party modules:  
8 -# None  
9 -#  
10 -# Copyright (C) 2011 Jurgen Knodlseder 7 +# Copyright (C) 2011-2012 Jurgen Knodlseder
11 # 8 #
12 # This program is free software: you can redistribute it and/or modify 9 # This program is free software: you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by 10 # it under the terms of the GNU General Public License as published by
@@ -29,6 +26,11 @@ from math import * @@ -29,6 +26,11 @@ from math import *
29 import os 26 import os
30 import glob 27 import glob
31 import sys 28 import sys
  29 +try:
  30 + import matplotlib.pyplot as plt
  31 + has_matplotlib = True
  32 +except:
  33 + has_matplotlib = False
32 34
33 35
34 # ============================= # 36 # ============================= #
@@ -224,7 +226,10 @@ def pipeline_v2(): @@ -224,7 +226,10 @@ def pipeline_v2():
224 #sys.stdout.write(like.obs().models()+"\n") 226 #sys.stdout.write(like.obs().models()+"\n")
225 227
226 # Plot counts 228 # Plot counts
227 - plot_counts(bin.obs()) 229 + if has_matplotlib:
  230 + plot_counts(bin.obs())
  231 + else:
  232 + sys.stdout.write("Matplotlib is not (correctly) installed on your system. No counts spectra are shown.\n")
228 233
229 # Return 234 # Return
230 return 235 return
@@ -237,139 +242,131 @@ def plot_counts(observations): @@ -237,139 +242,131 @@ def plot_counts(observations):
237 """ 242 """
238 Plot counts. 243 Plot counts.
239 """ 244 """
240 - # Only proceed if matplotlib is available  
241 - try:  
242 - # Import matplotlib  
243 - import matplotlib.pyplot as plt  
244 -  
245 - # Set legend fontsize  
246 - params = {'legend.fontsize': 10}  
247 - plt.rcParams.update(params)  
248 -  
249 - # Set plot styles  
250 - styles = ['b-', 'g-', 'y-', 'n-']  
251 -  
252 - # Dump header  
253 - sys.stdout.write("\n")  
254 - sys.stdout.write("Make plots (using matplotlib):\n")  
255 - sys.stdout.write("==============================\n")  
256 -  
257 - # Create figure 1  
258 - plt.figure(1,figsize=(12,6))  
259 - plt.subplots_adjust(hspace=.7) 245 + # Set legend fontsize
  246 + params = {'legend.fontsize': 10}
  247 + plt.rcParams.update(params)
260 248
261 - # Create subplot 1  
262 - plt.subplot(121)  
263 - plt.title("Spectrum (summed over all pixels)")  
264 -  
265 - # Loop over observations  
266 - for obs in observations:  
267 -  
268 - # Get event cube  
269 - cube = cast_GCTAEventCube(obs.events())  
270 -  
271 - # Create energy axis  
272 - energy = []  
273 - ebounds = cube.ebounds()  
274 - for i in range(ebounds.size()):  
275 - energy.append(ebounds.elogmean(i).TeV()) 249 + # Set plot styles
  250 + styles = ['b-', 'g-', 'y-', 'n-']
276 251
277 - # Create spectrum  
278 - sys.stdout.write("Extract data:\n")  
279 - counts = [0.0 for i in range(ebounds.size())]  
280 - for bin in cube:  
281 - index = ebounds.index(bin.energy())  
282 - counts[index] = counts[index] + bin.counts() 252 + # Dump header
  253 + sys.stdout.write("\n")
  254 + sys.stdout.write("Make plots (using matplotlib):\n")
  255 + sys.stdout.write("==============================\n")
  256 +
  257 + # Create figure 1
  258 + plt.figure(1,figsize=(12,6))
  259 + plt.subplots_adjust(hspace=.7)
283 260
284 - # Create error bars  
285 - error = [sqrt(c) for c in counts]  
286 -  
287 - # Plot spectrum  
288 - plt.loglog(energy, counts, 'ro', label='data')  
289 - plt.errorbar(energy, counts, error, fmt=None, ecolor='r')  
290 -  
291 - # Extract models  
292 - sys.stdout.write("Extract models:\n")  
293 - sum_model = [0.0 for i in range(ebounds.size())]  
294 - for k, m in enumerate(observations.models()):  
295 - sys.stdout.write("- "+m.name()+"\n")  
296 - model = [0.0 for i in range(ebounds.size())]  
297 - for bin in cube:  
298 - index = ebounds.index(bin.energy())  
299 - prob = m.eval(bin, obs)  
300 - model[index] = model[index] + prob * bin.size()  
301 - for i in range(ebounds.size()):  
302 - sum_model[i] = sum_model[i] + model[i]  
303 - plt.loglog(energy, model, styles[k], label=m.name())  
304 - plt.loglog(energy, sum_model, 'r-', label='total')  
305 -  
306 - # Put labels  
307 - plt.xlabel("Energy (TeV)")  
308 - plt.ylabel("Counts")  
309 - plt.legend(loc="lower left")  
310 -  
311 - # Create subplot 2  
312 - plt.subplot(122)  
313 - plt.title("Offset (summed over all energies)")  
314 -  
315 - # Set Crab direction  
316 - crab = GSkyDir()  
317 - crab.radec_deg(83.63, 22.01) 261 + # Create subplot 1
  262 + plt.subplot(121)
  263 + plt.title("Spectrum (summed over all pixels)")
  264 +
  265 + # Loop over observations
  266 + for obs in observations:
  267 +
  268 + # Get event cube
  269 + cube = obs.events()
318 270
319 - # Loop over observations  
320 - for obs in observations: 271 + # Create energy axis
  272 + energy = []
  273 + ebounds = cube.ebounds()
  274 + for i in range(ebounds.size()):
  275 + energy.append(ebounds.elogmean(i).TeV())
  276 +
  277 + # Create spectrum
  278 + sys.stdout.write("Extract data:\n")
  279 + counts = [0.0 for i in range(ebounds.size())]
  280 + for bin in cube:
  281 + index = ebounds.index(bin.energy())
  282 + counts[index] = counts[index] + bin.counts()
  283 +
  284 + # Create error bars
  285 + error = [sqrt(c) for c in counts]
  286 +
  287 + # Plot spectrum
  288 + plt.loglog(energy, counts, 'ro', label='data')
  289 + plt.errorbar(energy, counts, error, fmt=None, ecolor='r')
  290 +
  291 + # Extract models
  292 + sys.stdout.write("Extract models:\n")
  293 + sum_model = [0.0 for i in range(ebounds.size())]
  294 + for k, m in enumerate(observations.models()):
  295 + sys.stdout.write("- "+m.name()+"\n")
  296 + model = [0.0 for i in range(ebounds.size())]
  297 + for bin in cube:
  298 + index = ebounds.index(bin.energy())
  299 + prob = m.eval(bin, obs)
  300 + model[index] = model[index] + prob * bin.size()
  301 + for i in range(ebounds.size()):
  302 + sum_model[i] = sum_model[i] + model[i]
  303 + plt.loglog(energy, model, styles[k], label=m.name())
  304 + plt.loglog(energy, sum_model, 'r-', label='total')
  305 +
  306 + # Put labels
  307 + plt.xlabel("Energy (TeV)")
  308 + plt.ylabel("Counts")
  309 + plt.legend(loc="lower left")
  310 +
  311 + # Create subplot 2
  312 + plt.subplot(122)
  313 + plt.title("Offset (summed over all energies)")
  314 +
  315 + # Set Crab direction
  316 + crab = GSkyDir()
  317 + crab.radec_deg(83.63, 22.01)
  318 +
  319 + # Loop over observations
  320 + for obs in observations:
  321 +
  322 + # Get event cube
  323 + cube = obs.events()
321 324
322 - # Get event cube  
323 - cube = cast_GCTAEventCube(obs.events())  
324 -  
325 - # Create offset histogram  
326 - sys.stdout.write("Extract data:\n")  
327 - nx = 30  
328 - doffset2 = 0.01  
329 - offset2 = [(i+0.5)*doffset2 for i in range(nx)]  
330 - counts = [0.0 for i in range(nx)] 325 + # Create offset histogram
  326 + sys.stdout.write("Extract data:\n")
  327 + nx = 30
  328 + doffset2 = 0.01
  329 + offset2 = [(i+0.5)*doffset2 for i in range(nx)]
  330 + counts = [0.0 for i in range(nx)]
  331 + for bin in cube:
  332 + off = GCTAInstDir(bin.dir()).dist_deg(crab)
  333 + off2 = off*off
  334 + index = int(off2/doffset2)
  335 + if index < nx:
  336 + counts[index] = counts[index] + bin.counts()
  337 +
  338 + # Create error bars
  339 + error = [sqrt(c) for c in counts]
  340 +
  341 + # Plot distribution
  342 + plt.semilogy(offset2, counts, 'ro', label='data')
  343 +
  344 + # Extract models
  345 + sys.stdout.write("Extract models:\n")
  346 + sum_model = [0.0 for i in range(nx)]
  347 + for k, m in enumerate(observations.models()):
  348 + sys.stdout.write("- "+m.name()+"\n")
  349 + model = [0.0 for i in range(nx)]
331 for bin in cube: 350 for bin in cube:
332 - off = bin.dir().dist_deg(crab) 351 + off = GCTAInstDir(bin.dir()).dist_deg(crab)
333 off2 = off*off 352 off2 = off*off
334 index = int(off2/doffset2) 353 index = int(off2/doffset2)
335 if index < nx: 354 if index < nx:
336 - counts[index] = counts[index] + bin.counts()  
337 -  
338 - # Create error bars  
339 - error = [sqrt(c) for c in counts]  
340 -  
341 - # Plot distribution  
342 - plt.semilogy(offset2, counts, 'ro', label='data')  
343 -  
344 - # Extract models  
345 - sys.stdout.write("Extract models:\n")  
346 - sum_model = [0.0 for i in range(nx)]  
347 - for k, m in enumerate(observations.models()):  
348 - sys.stdout.write("- "+m.name()+"\n")  
349 - model = [0.0 for i in range(nx)]  
350 - for bin in cube:  
351 - off = bin.dir().dist_deg(crab)  
352 - off2 = off*off  
353 - index = int(off2/doffset2)  
354 - if index < nx:  
355 - prob = m.eval(bin, obs)  
356 - model[index] = model[index] + prob * bin.size()  
357 - for i in range(nx):  
358 - sum_model[i] = sum_model[i] + model[i]  
359 - plt.plot(offset2, model, styles[k], label=m.name())  
360 - plt.plot(offset2, sum_model, 'r-', label='total')  
361 - plt.ylim(ymin=0.1)  
362 -  
363 - # Put labels  
364 - plt.xlabel("Offset (deg^2)")  
365 - plt.ylabel("Counts")  
366 - plt.legend(loc="upper right")  
367 -  
368 - # Show counts spectra  
369 - plt.show()  
370 -  
371 - except:  
372 - sys.stdout.write("Matplotlib is not (correctly) installed on your system. No counts spectra are shown.\n") 355 + prob = m.eval(bin, obs)
  356 + model[index] = model[index] + prob * bin.size()
  357 + for i in range(nx):
  358 + sum_model[i] = sum_model[i] + model[i]
  359 + plt.plot(offset2, model, styles[k], label=m.name())
  360 + plt.plot(offset2, sum_model, 'r-', label='total')
  361 + plt.ylim(ymin=0.1)
  362 +
  363 + # Put labels
  364 + plt.xlabel("Offset (deg^2)")
  365 + plt.ylabel("Counts")
  366 + plt.legend(loc="upper right")
  367 +
  368 + # Show counts spectra
  369 + plt.show()
373 370
374 # Return 371 # Return
375 return 372 return