CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
counter.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 pickle
5 from PhysicsTools.HeppyCore.utils.diclist import diclist
6 
7 class Counter(diclist):
8 
9  def __init__(self, name):
10  self.name = name
11  super(Counter, self).__init__()
12 
13  def register(self, level):
14  self.add( level, [level, 0] )
15 
16  def inc(self, level, nentries=1):
17  '''Call this function to create a level for this counter,
18  or to increment an existing level.
19  '''
20  if level not in self.dico:
21  raise ValueError('level', level, 'has not been registered')
22  # self.add( level, [level, nentries])
23  else:
24  self[level][1] += nentries
25 
26  def __add__(self, other):
27  '''Add two counters (+).'''
28  size = max( len(self), len(other))
29  # import pdb; pdb.set_trace()
30  for i in range(0, size):
31  if i>=len(other):
32  # this line exists only in this counter, leave it as is
33  continue
34  elif i>=len(self):
35  self.register( other[i][0])
36  self.inc( other[i][0], other[i][1] )
37  else:
38  # exists in both
39  if self[i][0] != other[i][0]:
40  err = ['cannot add these counters:', str(self), str(other)]
41  raise ValueError('\n'.join(err))
42  else:
43  self.inc( other[i][0], other[i][1] )
44  return self
45 
46  def __iadd__(self, other):
47  '''Add two counters (+=).'''
48  return self.__add__(other)
49 
50  def write(self, dirname):
51  '''Dump the counter to a pickle file and to a text file in dirname.'''
52  pckfname = '{d}/{f}.pck'.format(d=dirname, f=self.name)
53  pckfname = pckfname.replace('*','STAR')
54  pckfile = open( pckfname, 'w' )
55  pickle.dump(self, pckfile)
56  txtfile = open( pckfname.replace('.pck', '.txt'), 'w')
57  txtfile.write( str(self) )
58  txtfile.write( '\n' )
59  txtfile.close()
60 
61  def __str__(self):
62  retstr = 'Counter %s :\n' % self.name
63  prev = None
64  init = None
65  for level, count in self:
66  if prev == None:
67  prev = count
68  init = count
69  if prev == 0:
70  eff1 = -1.
71  else:
72  eff1 = float(count)/prev
73  if init == 0:
74  eff2 = -1.
75  else:
76  eff2 = float(count)/init
77  retstr += '\t {level:<40} {count:>9} \t {eff1:4.2f} \t {eff2:6.4f}\n'.format(
78  level=level,
79  count=count,
80  eff1=eff1,
81  eff2=eff2 )
82  prev = count
83  return retstr
84 
85 
86 
87 
89  '''
90  TODO: could be a diclist?
91  '''
92 
93  def __init__( self ):
94  self.counters = []
95  self.ranks = {}
96 
97  def addCounter(self, name):
98  self.ranks[ name ] = len( self.counters )
99  self.counters.append( Counter(name) )
100 
101  def counter(self, name):
102  return self.counters[ self.ranks[name] ]
103 
104  def write(self, dirname):
105  map( lambda x: x.write(dirname), self.counters)
106 
107  def __str__(self):
108  prints = map( str, self.counters )
109  return '\n'.join(prints)
110 
111  def __getitem__(self, name):
112  return self.counter(name)
113 
114 if __name__ == '__main__':
115 
116  c = Counter('Test')
117  c.register('a')
118  c.register('b')
119  c.inc('a')
120  print c
121 
122  cs = Counters()
123  cs.addCounter('test')
124  cs.counter('test').register('a')
125  cs.counter('test').register('b')
126  cs.addCounter('test2')
127  cs.counter('test2').register('a')
128  cs.counter('test').inc('a')
129  cs.counter('test').inc('a')
130  cs.counter('test').inc('b')
131  cs.counter('test2').inc('a')
132 
133  print cs
134 
135  cs.write('.')
136  print 'loading ...'
137  file = open('test.pck')
138  lcs = pickle.load(file)
139  print lcs
140 
141  c1 = cs.counter('test2')
142 
143  print 'test addition, adding test and test2'
144  import copy
145  c2 = cs.counter('test')
146  c1 += c2
147  print c1
148 
149  print 'test addition : incompatible'
150  c = Counter('Test3')
151  c.register('b')
152  c.inc('b')
153  c1 += c
154  print c1
def __init__
Definition: counter.py:9
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
list object
Definition: dbtoconf.py:77