CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
average.py
Go to the documentation of this file.
1 # Copyright (C) 2014 Colin Bernet
2 # https://github.com/cbernet/heppy/blob/master/LICENSE
3 
4 import math
5 import pickle
6 from PhysicsTools.HeppyCore.utils.diclist import diclist
7 
8 class Average(object):
9 
10  def __init__(self, name):
11  self.name = name
12  self.sumw = 0
13  self.sumwx = 0
14  self.sumwx2 = 0
15 
16  def add(self, value, weight=1.0):
17  """
18  Add a new sample to the average.
19  """
20  value = float(value) # avoids surprising results with integers
21  weight = float(weight)
22  self.sumw += weight
23  self.sumwx += weight * value
24  self.sumwx2 += weight * value * value
25 
26  def variance(self):
27  return abs( self.sumwx2 / self.sumw - \
28  self.sumwx * self.sumwx / (self.sumw*self.sumw) )
29 
30  def value(self):
31  """
32  Mean value
33  """
34  if self.sumw:
35  return self.sumwx / self.sumw
36  else:
37  return None
38 
39  def uncertainty(self):
40  """
41  Uncertainty on the mean value
42  """
43  if self.sumw:
44  return math.sqrt( self.variance() ) / math.sqrt( self.sumw )
45  else:
46  return None
47 
48  def average( self ):
49  """
50  Returns: mean value, uncertainty on mean value.
51  """
52  return self.value(), self.uncertainty()
53 
54  def __add__(self, other):
55  '''Add two averages, merging the two samples.'''
56  self.sumw += other.sumw
57  self.sumwx += other.sumwx
58  self.sumwx2 += other.sumwx2
59  return self
60 
61  def __iadd__(self, other):
62  '''Add two averages.'''
63  return self.__add__(other)
64 
65  def write(self, dirname):
66  '''Dump the average to a pickle file and to a text file in dirname.'''
67  pckfname = '{d}/{f}.pck'.format(d=dirname, f=self.name)
68  pckfile = open( pckfname, 'w' )
69  pickle.dump(self, pckfile)
70  txtfile = open( pckfname.replace('.pck', '.txt'), 'w')
71  txtfile.write( str(self) )
72  txtfile.write( '\n' )
73  txtfile.close()
74 
75  def __str__(self):
76  ave, unc = self.average()
77  tmp = None
78  if ave is not None:
79  tmp = 'Average {name:<15}: {average: 8.4f} +- {unc:8.4f}'
80  # tmp = 'Average {name:<15}: {average: 8.4f}'
81  tmp = tmp.format( name = self.name,
82  average = ave,
83  unc = unc
84  )
85  else:
86  tmp = 'Average {name:<15}: undefined (call Average.add)'\
87  .format( name = self.name)
88  return tmp
89 
90 
91 
93  def write(self, dirname):
94  map( lambda x: x.write(dirname), self)
def uncertainty
Definition: average.py:39
Abs< T >::type abs(const T &t)
Definition: Abs.h:22