Loading [MathJax]/extensions/tex2jax.js
The Gaudi Framework  v36r7 (7f57a304)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
HistoUtils.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
18 """
19 This module contains set of simple and useful utilities for booking and
20 manipulations with Gaudi-AIDA histograms, inspired by Thomas' request
21 
22 The module contains following public symbols:
23 
24  - book for booking of various 1D,2D&3D-histograms
25  - bookProf for booking of various 1D&2D-profiles
26  - getAsAIDA for retrieval of histograms/profiles from HTS in AIDA format
27  - getAsROOT for retrieval of histograms/profiles from HTS in ROOT format
28  - fill for smart filling of 1D-histogram (AIDA or ROOT)
29  - aida2root for conversion of AIDA histogram to ROOT
30  - HistoStats for many statistical information
31  - HistoFile class for storing histograms to a file
32  - histoDump for dumping of the histogram in text format (a'la HBOOK)
33  - dumpHisto for dumping of the histogram in text format (a'la HBOOK)
34 
35 """
36 from __future__ import print_function
37 
38 # =============================================================================
39 __author__ = "Vanya BELYAEV ibelyaev@physics.syr.edu"
40 # =============================================================================
41 __all__ = (
42  "book", # book AIDA histogram using Histogram Service
43  "bookProf", # book AIDA profile histogram using Histogram Service
44  "getAsAIDA", # get the histogram form Histogram Service as AIDA histogram
45  "getAsROOT", # get the histogram form Histogram Service as AIDA histogram
46  "fill", # "power-fill" method for filling of histograms
47  "aida2root", # AIDA -> ROOT converter
48  "HistoStats", # statistical information for 1D-histograms
49  "HistoFile", # class for storing histograms to a file
50  "histoDump", # dump histogramintext format a'la HBOOK
51  "dumpHisto", # dump histogramintext format a'la HBOOK
52 )
53 # =============================================================================
54 # import core of Gaudi
55 import ROOT
56 from GaudiPython.Bindings import AppMgr
57 from GaudiPython.Bindings import gbl as cpp
58 from GaudiPython.Bindings import iHistogramSvc
59 
60 HID = cpp.GaudiAlg.ID
61 
62 
63 useROOT = False
64 
65 # =============================================================================
66 # Helper private auxiliary function to get Application Manager
67 
68 
69 def _getAppMgr(**kwargs):
70  """
71  Helper private auxiliary function to get Application Manager
72  """
73  gaudi = kwargs.get("gaudi", None)
74  if not gaudi:
75  gaudi = AppMgr()
76  if not gaudi:
77  raise RuntimeError("Unable to get valid ApplicationMgr")
78 
79  state = gaudi._isvc.FSMState()
80  if state < cpp.Gaudi.StateMachine.CONFIGURED:
81  gaudi.config()
82  state = gaudi._isvc.FSMState()
83  if state < cpp.Gaudi.StateMachine.INITIALIZED:
84  gaudi.initialize()
85 
86  return gaudi # RETURN
87 
88 
89 # =============================================================================
90 # Helper private auxiliary function to get iHistogramSvs
91 
92 
93 def _getHistoSvc(**kwargs):
94  """
95  Helper private auxiliary function to get iHistogramSvs
96  """
97  svc = kwargs.get("service", None)
98  if not svc:
99  svc = kwargs.get("svc", None)
100  else:
101  return svc # RETURN
102  gaudi = _getAppMgr(**kwargs)
103  return gaudi.histsvc() # RETURN
104 
105 
106 # =============================================================================
107 # Helper private auxiliary function to get iDataSvs
108 
109 
110 def _getEvtSvc(**kwargs):
111  """
112  Helper private auxiliary function to get iDataSvs
113  """
114  svc = kwargs.get("service", None)
115  if not svc:
116  svc = kwargs.get("svc", None)
117  else:
118  return svc # RETURN
119  gaudi = _getAppMgr(**kwargs)
120  return gaudi.evtsvc() # RETURN
121 
122 
123 # =============================================================================
124 # The trivial function to book the various 1D,2D&3D-histograms
125 
126 
127 def book(*args, **kwargs):
128  """
129  The trivial function to book the various 1D,2D&3D-histograms
130 
131  (1) book the trivial 1D histogram with full path
132 
133  >>> h1D = book ( 'path/to/my/histo' , ## path in Histogram Transient Store
134  'cosine of decay angle ' , ## histogram title
135  100 , ## number of bins
136  -1 , ## low edge
137  100 ) ## high edge
138 
139  (2) book the trivial 1D histogram with directory path and string ID :
140 
141  >>> h1D = book ( 'path/to/directory' , ## the path to directory in HTS
142  'H1' , ## string histogram identifier
143  'cosine of decay angle ' , ## histogram title
144  100 , ## number of bins
145  -1 , ## low edge
146  100 ) ## high edge
147 
148  (3) book the trivial 1D histogram with directory path and integer ID :
149 
150  >>> h1D = book ( 'path/to/directory' , ## the path to directory in HTS
151  124 , ## integer histogram identifier
152  'cosine of decay angle ' , ## histogram title
153  100 , ## number of bins
154  -1 , ## low edge
155  100 ) ## high edge
156 
157  (4) book the trivial 2D histogram with full path
158 
159  >>> h1D = book ( 'path/to/my/histo' , ## path in Histogram Transient Store
160  'm12**2 versus m13**2' , ## histogram title
161  50 , ## number of X-bins
162  1.0 , ## low X-edge
163  4.0 , ## high X-edge
164  50 , ## number of Y-bins
165  1 , ## low Y-edge
166  2 ) ## high Y-edge
167 
168  (5) book the trivial 2D histogram with directory path and literal ID
169 
170  >>> h1D = book ( 'path/to/directory' , ## path in Histogram Transient Store
171  'Dalitz1' , ## literal histogram identifier
172  'm12**2 versus m13**2' , ## histogram title
173  50 , ## number of X-bins
174  1.0 , ## low X-edge
175  4.0 , ## high X-edge
176  50 , ## number of Y-bins
177  1 , ## low Y-edge
178  2 ) ## high Y-edge
179 
180  (6) book the trivial 2D histogram with directory path and integer ID
181 
182  >>> h1D = book ( 'path/to/directory' , ## path in Histogram Transient Store
183  854 , ## integer histogram identifier
184  'm12**2 versus m13**2' , ## histogram title
185  50 , ## number of X-bins
186  1.0 , ## low X-edge
187  4.0 , ## high X-edge
188  50 , ## number of Y-bins
189  1.0 , ## low Y-edge
190  4.0 ) ## high Y-edge
191 
192  (7) book the trivial 3D histogram with full path
193 
194  >>> h1D = book ( 'path/to/my/histo' , ## path in Histogram Transient Store
195  'x vs y vs z ' , ## histogram title
196  10 , ## number of X-bins
197  -1.0 , ## low X-edge
198  1.0 , ## high X-edge
199  10 , ## number of Y-bins
200  -1.0 , ## low Y-edge
201  1.0 , ## high Y-edge
202  10 , ## number of Z-bins
203  -1.0 , ## low Z-edge
204  1.0 ) ## high Z-edge
205 
206  (8) book the trivial 3D histogram with directory path and literal ID
207 
208  >>> h1D = book ( 'path/to/directory' , ## path in Histogram Transient Store
209  'xyz' , ## literal histogram identifier
210  'x vs y vs z' , ## histogram title
211  10 , ## number of X-bins
212  -1.0 , ## low X-edge
213  1.0 , ## high X-edge
214  10 , ## number of Y-bins
215  -1.0 , ## low Y-edge
216  1.0 , ## high Y-edge
217  10 , ## number of Z-bins
218  -1.0 , ## low Z-edge
219  1.0 ) ## high Z-edge
220 
221  (9) book the trivial 3D histogram with directory path and integer ID
222 
223  >>> h1D = book ( 'path/to/directory' , ## path in Histogram Transient Store
224  888 , ## integer histogram identifier
225  'x vs y vs z' , ## histogram title
226  10 , ## number of X-bins
227  -1.0 , ## low X-edge
228  1.0 , ## high X-edge
229  10 , ## number of Y-bins
230  -1.0 , ## low Y-edge
231  1.0 , ## high Y-edge
232  10 , ## number of Z-bins
233  -1.0 , ## low Z-edge
234  1.0 ) ## high Z-edge
235 
236  Many other booking methods are available,
237  e.g. for the histograms with non-equidistant bins, see IHistogamSvc::book
238 
239  """
240  if useROOT or kwargs.get("useROOT", False) or not kwargs.get("useAIDA", True):
241  from ROOT import TH1D
242 
243  a0 = args[0]
244  a1 = args[1]
245  a2 = args[2]
246  if not str is type(a1):
247  a1 = "h" + str(a1)
248  if str is type(a2):
249  return TH1D(a0 + a1, a2, *args[3:])
250  else:
251  return TH1D(a0, a1, *args[2:])
252 
253  svc = _getHistoSvc(**kwargs)
254  if not svc:
255  raise RuntimeError("Unable to get valid HistogramService ")
256  # book the histogram using the service
257  return svc.book(*args) # RETURN
258 
259 
260 book.__doc__ += (
261  "\n\n" + "\thelp(iHistogramSvc.book) : \n\n" + iHistogramSvc.book.__doc__
262 )
263 book.__doc__ += (
264  "\n\n" + "\thelp(IHistogramSvc::book) : \n\n" + cpp.IHistogramSvc.book.__doc__
265 )
266 
267 # =============================================================================
268 # The trivial function to book 1D&2D profile histograms:
269 
270 
271 def bookProf(*args, **kwargs):
272  """
273 
274  The trivial function to book 1D&2D profile histograms:
275 
276  (1) book 1D-profile histogram with full path in Histogram Transient Store:
277  >>> histo = bookProf ( 'path/to/my/profile' , ## path in Histogram Transient Store
278  'Energy Correction' , ## the histogram title
279  100 , ## number of X-bins
280  0.0 , ## low X-edge
281  100 ) ## high X-edge
282 
283  (2) book 1D-profile histogram with directory path and literal ID
284  >>> histo = bookProf ( 'path/to/my/profile' , ## path in Histogram Transient Store
285  'Calibration' , ## the histogram literal identifier
286  'Energy Correction' , ## the histogram title
287  100 , ## number of X-bins
288  0.0 , ## low X-edge
289  100 ) ## high X-edge
290 
291  (3) book 1D-profile histogram with directory path and integer ID
292  >>> histo = bookProf ( 'path/to/my/profile' , ## path in Histogram Transient Store
293  418 , ## the histogram integer identifier
294  'Energy Correction' , ## the histogram title
295  100 , ## number of X-bins
296  0.0 , ## low X-edge
297  100 ) ## high X-edge
298 
299  (4) book 2D-profile histogram with full path in Histogram Transient Store:
300  >>> histo = bookProf ( 'path/to/my/profile' , ## path in Histogram Transient Store
301  'Energy Correction' , ## the histogram title
302  50 , ## number of X-bins
303  0.0 , ## low X-edge
304  100 , ## high X-edge
305  50 , ## number of Y-bins
306  0.0 , ## low Y-edge
307  100 ) ## high Y-edge
308 
309  (5) book 2D-profile histogram with directory path and literal ID
310  >>> histo = bookProf ( 'path/to/my/profile' , ## path in Histogram Transient Store
311  'Calibration' , ## the histogram literal identifier
312  'Energy Correction' , ## the histogram title
313  50 , ## number of X-bins
314  0.0 , ## low X-edge
315  100 , ## high X-edge
316  50 , ## number of Y-bins
317  0.0 , ## low Y-edge
318  100 ) ## high Y-edge
319 
320  (6) book 2D-profile histogram with directory path and integer ID
321  >>> histo = bookProf ( 'path/to/my/profile' , ## path in Histogram Transient Store
322  418 , ## the histogram integer identifier
323  'Energy Correction' , ## the histogram title
324  50 , ## number of X-bins
325  0.0 , ## low X-edge
326  100 , ## high X-edge
327  50 , ## number of Y-bins
328  0.0 , ## low Y-edge
329  100 ) ## high Y-edge
330 
331  Many other booking methods are available,
332  e.g. for the histograms with non-equidistant bins, see IHistogamSvc::book
333 
334  """
335  svc = _getHistoSvc(**kwargs)
336  if not svc:
337  raise RuntimeError("Unable to get valid HistogramService ")
338  # book the histogram using the service
339  return svc.bookProf(*args) # RETURN
340 
341 
342 bookProf.__doc__ += (
343  "\n\n" + "\thelp(iHistogramSvc.bookProf) : \n\n" + iHistogramSvc.bookProf.__doc__
344 )
345 bookProf.__doc__ += (
346  "\n\n"
347  + "\thelp(IHistogramSvc::bookProf) : \n\n"
348  + cpp.IHistogramSvc.bookProf.__doc__
349 )
350 
351 # =============================================================================
352 # The most trivial function to retrieve the histogram from Histogram Transient Store
353 
354 
355 def getAsAIDA(path, **kwargs):
356  """
357 
358  The most trivial function to retrieve the histogram from Histogram Transient Store
359  The histogram is returned by reference to its AIDA-representation (if possible)
360 
361  >>> h = getAsAIDA ( 'some/path/to/my/histogram' )
362 
363  """
364  svc = _getHistoSvc(**kwargs)
365  if not svc:
366  raise RuntimeError("Unable to get valid HistogramService ")
367  # return the histogram
368  return svc.getAsAIDA(path) # RETURN
369 
370 
371 getAsAIDA.__doc__ += (
372  "\n\n" + "\thelp(iHistogramSvc.getAsAIDA) : \n\n" + iHistogramSvc.getAsAIDA.__doc__
373 )
374 getAsAIDA.__doc__ += (
375  "\n\n" + "\thelp(iHistogramSvc.retrieve) : \n\n" + iHistogramSvc.retrieve.__doc__
376 )
377 
378 # =============================================================================
379 # The most trivial function to retrieve the histogram from Histogram Transient Store
380 
381 
382 def getAsROOT(path, **kwargs):
383  """
384 
385  The most trivial function to retrieve the histogram from Histogram Transient Store
386  The histogram is returned by reference to its underlying native ROOT-representation (if possible)
387 
388  >>> h = getAsROOT ( 'some/path/to/my/histogram' )
389 
390  """
391  svc = _getHistoSvc(**kwargs)
392  if not svc:
393  raise RuntimeError("Unable to get valid HistogramService ")
394  # return the histogram
395  return svc.getAsROOT(path) # RETURN
396 
397 
398 getAsROOT.__doc__ += (
399  "\n\n" + "\thelp(iHistogramSvc.getAsROOT) : \n\n" + iHistogramSvc.getAsROOT.__doc__
400 )
401 
402 
403 # =============================================================================
404 # The function which allows 'the smart fill' of 1D-histogram
405 def fill(
406  histo, # histogram
407  data, # input data
408  fun=lambda x: x, # function to be used
409  cut=lambda x: True, # cut to be applied
410  **kwargs
411 ): # optional extra arguments
412  """
413 
414  The function which allows 'the smart fill' of 1D-histogram
415 
416  >>> histo = ...
417 
418  The most trivial case, fill with the value
419  >>> fill ( histo , 1.0 )
420 
421  Fill from any iterable object (sequence)
422  >>> fill ( histo , [1,,2,3,4,5,10] )
423 
424  Fill from iterable object and apply the function:
425  >>> fill ( histo , [1,2,3,4,5] , math.sin )
426 
427  Use lambda form:
428  >>> fill ( histo , [1,2,3,4,5] , lambda x : x*x )
429 
430  The same
431  >>> fill ( histo , [1,2,3,4,5] , fun = lambda x : x*x )
432 
433  Use internal attributes:
434  >>> tracks = evtSvc['Rec/Track/Best'] ## iterable container of tracks
435  >>> fill ( histo , tracks , lambda t : t.pt() )
436 
437  Apply the predicate: fill only even numbers:
438  >>> fill ( histo , [1,2,3,4,5,6,7] , lambda x : x , lambda y : y%2 )
439 
440  The same (omit the trivial function) :
441  >>> fill ( histo , [1,2,3,4,5,6,7] , cut = lambda y : y%2 )
442 
443  Apply the predicate: fill only pt for positively charged tracks:
444  >>> tracks = evtSvc['Rec/Track/Best']
445  >>> fill ( histo , tracks , lambda t : t.pt() , lambda t : 0<t.charge() )
446 
447  The same:
448  >>> fill ( histo , tracks ,
449  fun = lambda t : t.pt() ,
450  cut = lambda t : 0<t.charge() )
451 
452  Ordinary functions are also fine:
453  >>> def myfun ( track ) : return sin( track.pt() + track.p() )
454  >>> def mycut ( track ) : return track.p() > 100 * GeV
455  >>> fill ( histo , tracks , myfun , mycut )
456 
457  The 'data' could be the address in TES, in this case the object
458  is retrieved from TES and the method is applied to the objects,
459  retrieved from TES:
460  >>> fill ( histo , ## the reference to the histogram
461  'Rec/Track/Best' , ## the location of objects in TES
462  lambda t : t.pt() ) ## function to be used for histogram fill
463  >>> fill ( histo , ## the reference to the histogram
464  'Rec/Track/Best' , ## the address of objects in TES
465  lambda t : t.pt() , ## the function to be used for histogram fill
466  lambda t : t.charge()>0 ) ## the criteria to select tracks
467 
468  The arguments 'fun' and 'cut' could be strings, in this case
469  they are evaluated by python before usage.
470  This option could be often very useful.
471 
472  """
473 
474  # if value is a string, try to get the objects from TES
475  if type(data) == str:
476  svc = _getEvtSvc(**kwargs)
477  data = svc[data]
478  return fill(histo, data, fun, cut, **kwargs)
479 
480  # if the function is a string: evaluate it!
481  if type(fun) == str:
482  fun = eval(fun, globals())
483 
484  # if the criterion is a string: evaluate it!
485  if type(cut) == str:
486  cut = eval(cut, globals())
487 
488  if not hasattr(data, "__iter__"):
489  data = [data]
490 
491  if not hasattr(histo, "fill") and hasattr(histo, "Fill"):
492  setattr(histo, "fill", getattr(histo, "Fill"))
493 
494  for item in data:
495  if not cut(item):
496  continue # CONTINUE
497  histo.fill(fun(item))
498 
499  return histo # RETURN
500 
501 
502 # =============================================================================
503 # AIDA -> ROOT converter
504 aida2root = cpp.Gaudi.Utils.Aida2ROOT.aida2root
505 
506 # =============================================================================
507 # Convert AIDA to ROOT
508 
509 
510 def _to_root_(self):
511  """
512  Convert AIDA to ROOT
513 
514  >>> aida = ... ## get AIDA histogram
515  >>> root = aida.toROOT() ## convert it to ROOT
516 
517  """
518  return aida2root(self)
519 
520 
521 _to_root_.__doc__ += aida2root.__doc__
522 
523 for t in (
524  cpp.AIDA.IHistogram3D,
525  cpp.AIDA.IHistogram2D,
526  cpp.AIDA.IHistogram1D,
527  cpp.AIDA.IProfile2D,
528  cpp.AIDA.IProfile1D,
529 ):
530  if not hasattr(t, "Fill") and hasattr(t, "fill"):
531  setattr(t, "Fill", getattr(t, "fill"))
532  for attr in ("toROOT", "toRoot", "asROOT", "asRoot", "AsROOT", "AsRoot"):
533  if not hasattr(t, attr):
534  setattr(t, attr, _to_root_)
535 
536 cpp.AIDA.IHistogram3D.__repr__ = lambda s: cpp.GaudiAlg.Print3D.toString(
537  s, HID(s.title())
538 )
539 cpp.AIDA.IHistogram3D.__str__ = cpp.AIDA.IHistogram3D.__repr__
540 
541 HistoStats = cpp.Gaudi.Utils.HistoStats
542 
543 # =============================================================================
544 # Evaluate 'bin-by-bin' momentum of certain order around the value
545 
546 
547 def _moment_(self, order, value=0):
548  """
549  Evaluate 'bin-by-bin' momentum of order 'order' around the value 'value'
550  for 1D histogram
551 
552  >>> h1 = ...
553  >>> print(h1.moment ( 5 ))
554 
555  """
556  return HistoStats.moment(self, order, value)
557 
558 
559 # =============================================================================
560 # Evaluate error in 'bin-by-bin' momentum of certain order around the value
561 
562 
563 def _momentErr_(self, order):
564  """
565  Evaluate error for 'bin-by-bin' momentum of order 'order' around the value 'value'
566  for 1D histogram
567 
568  >>> h1 = ...
569  >>> print(h1.momentErr ( 5 ))
570 
571  """
572  return HistoStats.momentErr(self, order)
573 
574 
575 # =============================================================================
576 # Evaluate 'bin-by-bin' central momentum (around mean value)
577 
578 
579 def _centralMoment_(self, order):
580  """
581  Evaluate 'bin-by-bin' central momentum (around mean value)
582  for 1D histogram
583 
584  >>> h1 = ...
585  >>> print(h1.centralMoment ( 5 ))
586 
587  """
588  return HistoStats.centralMoment(self, order)
589 
590 
591 # =============================================================================
592 # Evaluate error in 'bin-by-bin' momentum of certain order around the value
593 
594 
595 def _centralMomentErr_(self, order):
596  """
597  Evaluate error for 'bin-by-bin' central momentum (around mean value)
598  for 1D histogram
599 
600  >>> h1 = ...
601  >>> print(h1.centralMomentErr ( 5 ))
602 
603  """
604  return HistoStats.centralMomentErr(self, order)
605 
606 
607 # =============================================================================
608 # Evaluate 'bin-by-bin' skewness for 1D histogram
609 
610 
611 def _skewness_(self):
612  """
613  Evaluate 'bin-by-bin' skewness for 1D AIDA histogram
614 
615  >>> h1 = ...
616  >>> print(h1.skewness())
617 
618  """
619  return HistoStats.skewness(self)
620 
621 
622 # =============================================================================
623 # Evaluate error for 'bin-by-bin' skewness for 1D histogram
624 
625 
626 def _skewnessErr_(self):
627  """
628  Evaluate error for 'bin-by-bin' skewness
629 
630  >>> h1 = ...
631  >>> print(h1.skewnessErr())
632 
633  """
634  return HistoStats.skewnessErr(self)
635 
636 
637 # =============================================================================
638 # Evaluate 'bin-by-bin' kurtosis for 1D histogram
639 
640 
641 def _kurtosis_(self):
642  """
643  Evaluate 'bin-by-bin' kurtosis
644 
645  >>> h1 = ...
646  >>> print(h1.kurtosis ())
647 
648  """
649  return HistoStats.kurtosis(self)
650 
651 
652 # =============================================================================
653 # Evaluate error for 'bin-by-bin' kurtosis for 1D histogram
654 
655 
656 def _kurtosisErr_(self):
657  """
658  Evaluate error for 'bin-by-bin' kurtotis for 1D AIDA histogram
659 
660  >>> h1 = ...
661  >>> print(h1.kurtotisErr())
662 
663  """
664  return HistoStats.kurtosisErr(self)
665 
666 
667 # =============================================================================
668 
669 
670 def _nEff_(self):
671  """
672  Number of equivalent entries
673  """
674  return HistoStats.nEff(self)
675 
676 
677 # =============================================================================
678 
679 
680 def _mean_(self):
681  """
682  Evaluate the MEAN value
683  """
684  return HistoStats.mean(self)
685 
686 
687 # =============================================================================
688 
689 
690 def _meanErr_(self):
691  """
692  Evaluate the error for MEAN estimate
693  """
694  return HistoStats.meanErr(self)
695 
696 
697 # =============================================================================
698 
699 
700 def _rms_(self):
701  """
702  Evaluate the RMS for AIDA histogram
703  """
704  return HistoStats.rms(self)
705 
706 
707 # =============================================================================
708 
709 
710 def _rmsErr_(self):
711  """
712  Evaluate the error for RMS estimate
713  """
714  return HistoStats.rmsErr(self)
715 
716 
717 # =============================================================================
718 
719 
721  """
722  Get an error in the sum bin height ('in-range integral')
723  """
724  return HistoStats.sumBinHeightErr(self)
725 
726 
727 # =============================================================================
728 
729 
731  """Get an error in the sum bin height ('in-range integral')"""
732  return HistoStats.sumAllBinHeightErr(self)
733 
734 
735 # =============================================================================
736 
737 
739  """
740  The fraction of overflow entries (useful for shape comparison)
741  """
742  return HistoStats.overflowEntriesFrac(self)
743 
744 
745 # =============================================================================
746 
747 
749  """
750  The error for fraction of overflow entries (useful for shape comparison)
751  """
752  return HistoStats.overflowEntriesFracErr(self)
753 
754 
755 # =============================================================================
756 
757 
759  """
760  The fraction of underflow entries (useful for shape comparison)
761  """
762  return HistoStats.underflowEntriesFrac(self)
763 
764 
765 # =============================================================================
766 
767 
769  """
770  The error for fraction of underflow entries (useful for shape comparison)
771  """
772  return HistoStats.underflowEntriesFracErr(self)
773 
774 
775 # =============================================================================
776 
777 
779  """
780  The fraction of overflow integral (useful for shape comparison)
781  """
782  return HistoStats.overflowIntegralFrac(self)
783 
784 
785 # =============================================================================
786 
787 
789  """
790  The error for fraction of overflow integral (useful for shape comparison)
791  """
792  return HistoStats.overflowIntegralFracErr(self)
793 
794 
795 # =============================================================================
796 
797 
799  """
800  The fraction of underflow integral (useful for shape comparison)
801  """
802  return HistoStats.underflowIntegralFrac(self)
803 
804 
805 # =============================================================================
806 
807 
809  """
810  The error for fraction of underflow integral (useful for shape comparison)
811  """
812  return HistoStats.underflowIntegralFracErr(self)
813 
814 
815 # =============================================================================
816 # get number of entries in histogram up to the certain bin (not-included)
817 # get number of entries in histogram form the certain
818 # minimal bin up to the certain maximal bin (not-included)
819 
820 
821 def _nEntries_(self, i1, i2=-10000000):
822  """
823  Get number of entries in histogram up to the certain bin (not-included)
824 
825  attention: underflow bin is included!
826 
827  >>> h1
828  >>> print(h1.nEntries ( 10 ))
829 
830  Get number of entries in histogram form the certain
831  minimal bin up to the certain maximal bin (not-included)
832 
833  >>> h1
834  >>> print(h1.nEntries ( 10 , 15 ))
835 
836  """
837  if i2 < i1 or i2 < 0:
838  return HistoStats.nEntries(self, i1)
839  return HistoStats.nEntries(self, i1, i2)
840 
841 
842 # =============================================================================
843 
844 
845 def _nEntriesFrac_(self, i1, i2=-10000000):
846  """
847  Get the fraction of entries in histogram up to the certain bin (not-included)
848 
849  attention: underflow bin is included!
850 
851  >>> h1
852  >>> print(h1.nEntriesFrac ( 10 ))
853 
854  Get the fraction of entries in histogram form the certain
855  minimal bin up to the certain maximal bin (not-included)
856 
857  >>> h1
858  >>> print(h1.nEntriesFrac ( 10 , 15 ))
859 
860  """
861  if i2 < i1 or i2 < 0:
862  return HistoStats.nEntriesFrac(self, i1)
863  return HistoStats.nEntriesFrac(self, i1, i2)
864 
865 
866 # =============================================================================
867 
868 
869 def _nEntriesFracErr_(self, i1, i2=-10000000):
870  """
871  Get error for fraction of entries in histogram up to the certain bin (not-included)
872 
873  attention: underflow bin is included!
874 
875  >>> h1
876  >>> print(h1.nEntriesFracErr( 10 ))
877 
878  Get error fraction of entries in histogram form the certain
879  minimal bin up to the certain maximal bin (not-included)
880 
881  >>> h1
882  >>> print(h1.nEntriesFracErr ( 10 , 15 ))
883 
884  """
885  if i2 < i1 or i2 < 0:
886  return HistoStats.nEntriesFracErr(self, i1)
887  return HistoStats.nEntriesFracErr(self, i1, i2)
888 
889 
890 # =============================================================================
891 i1DH = cpp.AIDA.IHistogram1D
892 
893 if not hasattr(i1DH, "moment"):
894  i1DH.moment = _moment_
895 if not hasattr(i1DH, "momentErr"):
896  i1DH.momentErr = _momentErr_
897 if not hasattr(i1DH, "centralMoment"):
898  i1DH.centralMoment = _centralMoment_
899 if not hasattr(i1DH, "momentMomentErr"):
900  i1DH.centralMomentErr = _centralMomentErr_
901 if not hasattr(i1DH, "nEff"):
902  i1DH.nEff = _nEff_
903 if not hasattr(i1DH, "mean"):
904  i1DH.mean = _mean_
905 if not hasattr(i1DH, "meanErr"):
906  i1DH.meanErr = _meanErr_
907 if not hasattr(i1DH, "rms"):
908  i1DH.rms = _rms_
909 if not hasattr(i1DH, "rmsErr"):
910  i1DH.rmsErr = _rmsErr_
911 if not hasattr(i1DH, "skewness"):
912  i1DH.skewness = _skewness_
913 if not hasattr(i1DH, "skewnessErr"):
914  i1DH.skewnessErr = _skewnessErr_
915 if not hasattr(i1DH, "kurtosis"):
916  i1DH.kurtosis = _kurtosis_
917 if not hasattr(i1DH, "kurtosisErr"):
918  i1DH.kurtosisErr = _kurtosisErr_
919 
920 if not hasattr(i1DH, "overflowEntriesFrac"):
921  i1DH.overflowEntriesFrac = _overflowEntriesFrac_
922 if not hasattr(i1DH, "overflowEntriesFracErr"):
923  i1DH.overflowEntriesFracErr = _overflowEntriesFracErr_
924 if not hasattr(i1DH, "underflowEntriesFrac"):
925  i1DH.underflowEntriesFrac = _underflowEntriesFrac_
926 if not hasattr(i1DH, "underflowEntriesFracErr"):
927  i1DH.underflowEntriesFracErr = _underflowEntriesFracErr_
928 
929 if not hasattr(i1DH, "overflowIntegralFrac"):
930  i1DH.overflowIntegralFrac = _overflowIntegralFrac_
931 if not hasattr(i1DH, "overflowIntegralFracErr"):
932  i1DH.overflowIntegralFracErr = _overflowIntegralFracErr_
933 if not hasattr(i1DH, "underflowIntegralFrac"):
934  i1DH.underflowIntegralFrac = _underflowIntegralFrac_
935 if not hasattr(i1DH, "underflowIntegralFracErr"):
936  i1DH.underflowIntegralFracErr = _underflowIntegralFracErr_
937 
938 if not hasattr(i1DH, "nEntries"):
939  i1DH.nEntries = _nEntries_
940 if not hasattr(i1DH, "nEntriesFrac"):
941  i1DH.nEntriesFrac = _nEntriesFrac_
942 if not hasattr(i1DH, "nEntriesFracErr"):
943  i1DH.nEntriesFracErr = _nEntriesFracErr_
944 
945 # ============================================================================
946 
947 
948 def _path_(self):
949  """
950  Get the path in THS for the given AIDA object:
951 
952  >>> aida =
953  >>> print(aida.path())
954 
955  """
956  return cpp.Gaudi.Utils.Histos.path(self)
957 
958 
959 iBH = cpp.AIDA.IBaseHistogram
960 if not hasattr(iBH, "path"):
961  iBH.path = _path_
962 if not hasattr(iBH, "TESpath"):
963  iBH.TESpath = _path_
964 if not hasattr(iBH, "location"):
965  iBH.location = _path_
966 
967 
968 # =============================================================================
969 def __dumpHisto__(histo, *args):
970  """
971 
972  Dump the histogram/profile in text format (a'la HBOOK)
973 
974  >>> histo
975  >>> print(dumpHisto ( histo ))
976 
977  >>> print(histo.dump())
978  >>> print(histo.dump( 20 , 20 ))
979  >>> print(histo.dump( 20 , 20 , True ))
980 
981  Uses:
982 
983  """
984  return cpp.Gaudi.Utils.Histos.histoDump(histo, *args)
985 
986 
987 __dumpHisto__.__doc__ = "\n" + cpp.Gaudi.Utils.Histos.histoDump.__doc__
988 
989 # =============================================================================
990 # the actual function for text dump of the histogram
991 histoDump = __dumpHisto__
992 dumpHisto = __dumpHisto__
993 
994 for t in (
995  cpp.AIDA.IHistogram1D,
996  cpp.AIDA.IProfile1D,
997  ROOT.TH1D,
998  ROOT.TH1F,
999  ROOT.TH1,
1000  ROOT.TProfile,
1001 ):
1002  for method in ("dump", "dumpHisto", "dumpAsText"):
1003  if not hasattr(t, method):
1004  setattr(t, method, __dumpHisto__)
1005 
1006 # ==============================================================================
1007 
1008 
1010  """
1011  Class to write histograms to a ROOT file.
1012  hFile = HistoFile("myFile.root")
1013  myHisto = ...
1014  hFile.save(myHisto)
1015  myHisto0 = ...
1016  myHisto1 = ...
1017  myHisto2 = ...
1018  hFile.save(myHisto0, myHisto1, myHisto2)
1019  histoList = [h0, h1, h2, h3]
1020  hFile.save(histoList)
1021  ...
1022  hWriter.close()
1023  """
1024 
1025  __author__ = "Juan Palacios juan.palacios@nikhef.nl"
1026 
1027  def __init__(self, fileName):
1028  self.file = ROOT.TFile(fileName, "RECREATE")
1029  from GaudiPython import gbl
1030 
1031  self.aida2root = gbl.Gaudi.Utils.Aida2ROOT.aida2root
1032  self.aidaTypes = [
1033  gbl.AIDA.IHistogram1D,
1034  gbl.AIDA.IHistogram2D,
1035  gbl.AIDA.IHistogram3D,
1036  gbl.AIDA.IProfile1D,
1037  gbl.AIDA.IProfile2D,
1038  gbl.AIDA.IHistogram,
1039  ]
1040 
1041  def __convertibleType(self, histo):
1042  histoType = type(histo)
1043  for t in self.aidaTypes:
1044  if histoType == t:
1045  return True
1046  return False
1047 
1048  def save(self, *args):
1049  """
1050  This function stores histograms on the file for future saving.
1051  It takes an arbitrary number of AIDA or ROOT histograms or
1052  a list of them.
1053  """
1054  if args:
1055  if type(args[0]) == list:
1056  histoList = args[0]
1057  else:
1058  histoList = args
1059  for h in histoList:
1060  if self.__convertibleType(h):
1061  h = self.aida2root(h)
1062  h.Write()
1063 
1064  def close(self):
1065  self.file.Write()
1066  self.file.Close()
1067 
1068 
1069 # =============================================================================
1070 if "__main__" == __name__:
1071  import sys
1072 
1073  print(__doc__)
1074  for o in __all__:
1075  print(o)
1076  print(sys.modules[__name__].__dict__[o].__doc__)
1077 
1078 # =============================================================================
1079 # The END
1080 # =============================================================================
GaudiPython.HistoUtils._rmsErr_
def _rmsErr_(self)
Definition: HistoUtils.py:710
GaudiPython.HistoUtils.bookProf
def bookProf(*args, **kwargs)
Definition: HistoUtils.py:271
GaudiPython.HistoUtils.HistoFile
Definition: HistoUtils.py:1009
GaudiPython.HistoUtils.HID
HID
Definition: HistoUtils.py:60
GaudiPython.HistoUtils.HistoFile.__convertibleType
def __convertibleType(self, histo)
Definition: HistoUtils.py:1041
GaudiPython.HistoUtils.getAsAIDA
def getAsAIDA(path, **kwargs)
Definition: HistoUtils.py:355
GaudiPython.HistoUtils.HistoFile.close
def close(self)
Definition: HistoUtils.py:1064
GaudiPython.HistoUtils._nEntriesFrac_
def _nEntriesFrac_(self, i1, i2=-10000000)
Definition: HistoUtils.py:845
GaudiPython.HistoUtils._meanErr_
def _meanErr_(self)
Definition: HistoUtils.py:690
GaudiPython.HistoUtils.HistoFile.__init__
def __init__(self, fileName)
Definition: HistoUtils.py:1027
GaudiPython.HistoUtils._skewnessErr_
def _skewnessErr_(self)
Definition: HistoUtils.py:626
GaudiPython.HistoUtils._overflowEntriesFrac_
def _overflowEntriesFrac_(self)
Definition: HistoUtils.py:738
GaudiPython.HistoUtils.book
def book(*args, **kwargs)
Definition: HistoUtils.py:127
GaudiPython.HistoUtils._underflowEntriesFrac_
def _underflowEntriesFrac_(self)
Definition: HistoUtils.py:758
GaudiPython.Bindings.AppMgr
Definition: Bindings.py:873
GaudiPython.HistoUtils._overflowIntegralFrac_
def _overflowIntegralFrac_(self)
Definition: HistoUtils.py:778
GaudiPython.HistoUtils.HistoFile.save
def save(self, *args)
Definition: HistoUtils.py:1048
GaudiPython.HistoUtils.aida2root
aida2root
Definition: HistoUtils.py:504
GaudiPython.HistoUtils._sumAllBinHeightErr_
def _sumAllBinHeightErr_(self)
Definition: HistoUtils.py:730
GaudiPython.HistoUtils._kurtosis_
def _kurtosis_(self)
Definition: HistoUtils.py:641
GaudiPython.Bindings
Definition: Bindings.py:1
GaudiPython.HistoUtils._nEntries_
def _nEntries_(self, i1, i2=-10000000)
Definition: HistoUtils.py:821
GaudiPython.HistoUtils._getAppMgr
def _getAppMgr(**kwargs)
Definition: HistoUtils.py:69
GaudiPython.HistoUtils._momentErr_
def _momentErr_(self, order)
Definition: HistoUtils.py:563
GaudiPython.HistoUtils._overflowEntriesFracErr_
def _overflowEntriesFracErr_(self)
Definition: HistoUtils.py:748
GaudiPython.HistoUtils._underflowIntegralFracErr_
def _underflowIntegralFracErr_(self)
Definition: HistoUtils.py:808
GaudiPython.HistoUtils._path_
def _path_(self)
Definition: HistoUtils.py:948
GaudiPython.HistoUtils._getEvtSvc
def _getEvtSvc(**kwargs)
Definition: HistoUtils.py:110
GaudiPython.HistoUtils._underflowEntriesFracErr_
def _underflowEntriesFracErr_(self)
Definition: HistoUtils.py:768
GaudiPython.HistoUtils._centralMoment_
def _centralMoment_(self, order)
Definition: HistoUtils.py:579
GaudiPython.HistoUtils._rms_
def _rms_(self)
Definition: HistoUtils.py:700
GaudiPython.HistoUtils._to_root_
def _to_root_(self)
Definition: HistoUtils.py:510
GaudiPython.HistoUtils._kurtosisErr_
def _kurtosisErr_(self)
Definition: HistoUtils.py:656
GaudiPython.HistoUtils._getHistoSvc
def _getHistoSvc(**kwargs)
Definition: HistoUtils.py:93
GaudiPython.HistoUtils._nEntriesFracErr_
def _nEntriesFracErr_(self, i1, i2=-10000000)
Definition: HistoUtils.py:869
GaudiPython.HistoUtils.HistoFile.aida2root
aida2root
Definition: HistoUtils.py:1031
GaudiPython.HistoUtils._skewness_
def _skewness_(self)
Definition: HistoUtils.py:611
gaudirun.type
type
Definition: gaudirun.py:160
GaudiPython.HistoUtils.fill
def fill(histo, data, fun=lambda x:x, cut=lambda x:True, **kwargs)
Definition: HistoUtils.py:405
GaudiPython.HistoUtils._moment_
def _moment_(self, order, value=0)
Definition: HistoUtils.py:547
Write
Definition: Write.py:1
GaudiPython.HistoUtils._overflowIntegralFracErr_
def _overflowIntegralFracErr_(self)
Definition: HistoUtils.py:788
GaudiPython.HistoUtils.HistoFile.file
file
Definition: HistoUtils.py:1028
GaudiPython.HistoUtils._sumBinHeightErr_
def _sumBinHeightErr_(self)
Definition: HistoUtils.py:720
GaudiPython.HistoUtils._underflowIntegralFrac_
def _underflowIntegralFrac_(self)
Definition: HistoUtils.py:798
GaudiPython.HistoUtils._centralMomentErr_
def _centralMomentErr_(self, order)
Definition: HistoUtils.py:595
GaudiPython.HistoUtils._mean_
def _mean_(self)
Definition: HistoUtils.py:680
GaudiPython.HistoUtils.HistoFile.aidaTypes
aidaTypes
Definition: HistoUtils.py:1032
GaudiPython.HistoUtils.__dumpHisto__
def __dumpHisto__(histo, *args)
Definition: HistoUtils.py:969
GaudiPython.HistoUtils._nEff_
def _nEff_(self)
Definition: HistoUtils.py:670
GaudiPython.HistoUtils.getAsROOT
def getAsROOT(path, **kwargs)
Definition: HistoUtils.py:382