CMS 3D CMS Logo

CommonUtil.py
Go to the documentation of this file.
1 '''This module collects some frequently used helper functions
2 '''
3 from __future__ import print_function
4 import time,ast,re,json,coral,array
5 def flatten(obj):
6  '''Given nested lists or tuples, returns a single flattened list'''
7  result = []
8  for piece in obj:
9  if hasattr (piece, '__iter__') and not isinstance (piece, str):
10  result.extend( flatten (piece) )
11  else:
12  result.append (piece)
13  return result
14 
15 def parseTime(iTime):
16  '''
17  input string of the ("^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$|^\d{6}$|^\d{4}$" format
18  output (runnum,fillnum,timeStr)
19  '''
20  if not iTime: return (None,None,None)
21  p=re.compile('^\d\d/\d\d/\d\d \d\d:\d\d:\d\d$')
22  if re.match(p,iTime):
23  return (None,None,iTime)
24  p=re.compile('^\d{6}$')
25  if re.match(p,iTime):
26  return (int(iTime),None,None)
27  p=re.compile('^\d{4}$')
28  if re.match(p,iTime):
29  return (None,int(iTime),None)
30 
32  '''
33  input : largest lumivalue
34  output: (unitstring,denomitor)
35  '''
36  unitstring='/ub'
37  denomitor=1.0
38  if t>=1.0e3 and t<1.0e06:
39  denomitor=1.0e3
40  unitstring='/nb'
41  elif t>=1.0e6 and t<1.0e9:
42  denomitor=1.0e6
43  unitstring='/pb'
44  elif t>=1.0e9 and t<1.0e12:
45  denomitor=1.0e9
46  unitstring='/fb'
47  elif t>=1.0e12 and t<1.0e15:
48  denomitor=1.0e12
49  unitstring='/ab'
50  elif t<1.0 and t>=1.0e-3: #left direction
51  denomitor=1.0e-03
52  unitstring='/mb'
53  elif t<1.0e-03 and t>=1.0e-06:
54  denomitor=1.0e-06
55  unitstring='/b'
56  elif t<1.0e-06 and t>=1.0e-09:
57  denomitor=1.0e-9
58  unitstring='/kb'
59  return (unitstring,denomitor)
60 def guessUnit(inverseubval):
61  '''
62  input:
63  float value in 1/ub
64  output:
65  printable value (value(float),unit(str)) unit in [1/kb,1/b,1/mb,1/ub,1/nb,1/pb,1/fb]
66  '''
67  if inverseubval>=1.0e-09 and inverseubval<1.0e-06:
68  denomitor=1.0e-09
69  unitstring='/kb'
70  return (float(inverseubval)/float(denomitor),unitstring)
71  if inverseubval>=1.0e-06 and inverseubval<1.0e-03:
72  denomitor=1.0e-06
73  unitstring='/b'
74  return (float(inverseubval)/float(denomitor),unitstring)
75  if inverseubval>=1.0e-03 and inverseubval<1.0:
76  denomitor=1.0e-03
77  unitstring='/mb'
78  return (float(inverseubval)/float(denomitor),unitstring)
79  if inverseubval>=1.0 and inverseubval<1.0e3:
80  unitstring='/ub'
81  return (inverseubval,unitstring)
82  if inverseubval>=1.0e3 and inverseubval<1.0e06:
83  denomitor=1.0e3
84  unitstring='/nb'
85  return (float(inverseubval)/float(denomitor),unitstring)
86  if inverseubval>=1.0e6 and inverseubval<1.0e9:
87  denomitor=1.0e6
88  unitstring='/pb'
89  return (float(inverseubval)/float(denomitor),unitstring)
90  if inverseubval>=1.0e9 and inverseubval<1.0e12:
91  denomitor=1.0e9
92  unitstring='/fb'
93  return (float(inverseubval)/float(denomitor),unitstring)
94  if inverseubval>=1.0e12 and inverseubval<1.0e15:
95  denomitor=1.0e12
96  unitstring='/ab'
97  return (float(inverseubval)/float(denomitor),unitstring)
98  return (float(inverseubval),'/ub')
99 def pairwise(lst):
100  """
101  yield item i and item i+1 in lst. e.g.
102  (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None)
103 
104  from http://code.activestate.com/recipes/409825-look-ahead-one-item-during-iteration
105  """
106  if not len(lst): return
107  #yield None, lst[0]
108  for i in range(len(lst)-1):
109  yield lst[i], lst[i+1]
110  yield lst[-1], None
111 def findInList(mylist,element):
112  """
113  check if an element is in the list
114  """
115  pos=-1
116  try:
117  pos=mylist.index(element)
118  except ValueError:
119  pos=-1
120  return pos!=-1
121 def is_intstr(s):
122  """test if a string can be converted to a int
123  """
124  try:
125  int(s)
126  return True
127  except ValueError:
128  return False
129 def is_floatstr(s):
130  """
131  test if a string can be converted to a float
132  """
133  try:
134  float(s)
135  return True
136  except ValueError:
137  return False
138 def count_dups(l):
139  """
140  report the number of duplicates in a python list
141  """
142  from collections import defaultdict
143  tally=defaultdict(int)
144  for x in l:
145  tally[x]+=1
146  return tally.items()
147 def transposed(lists, defaultval=None):
148  """
149  transposing list of lists
150  from http://code.activestate.com/recipes/410687-transposing-a-list-of-lists-with-different-lengths/
151  """
152  if not lists: return []
153  #return map(lambda *row: [elem or defaultval for elem in row], *lists)
154  return map(lambda *row: [elem for elem in row or defaultval], *lists)
155 def pack(high,low):
156  """pack high,low 32bit unsigned int to one unsigned 64bit long long
157  Note:the print value of result number may appear signed, if the sign bit is used.
158  """
159  h=high<<32
160  return (h|low)
161 def packToString(high,low):
162  """pack high,low 32bit unsigned int to one unsigned 64bit long long in string format
163  Note:the print value of result number may appear signed, if the sign bit is used.
164  """
165  fmt="%u"
166  return fmt%pack(high,low)
167 def unpack(i):
168  """unpack 64bit unsigned long long into 2 32bit unsigned int, return tuple (high,low)
169  """
170  high=i>>32
171  low=i&0xFFFFFFFF
172  return(high,low)
174  """unpack 64bit unsigned long long in string format into 2 32bit unsigned int, return tuple(high,low)
175  """
176  return unpack(int(i))
178  """convert 64bit timestamp to local date in string format
179  """
180  return time.ctime(unpack(i)[0])
182  """convert 64bit timestamp to Universal Time in string format
183  """
184  t=unpack(i)[0]
185  return time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(t))
187  """unpack 64bit lumiid to dictionary {'run','lumisection'}
188  """
189  j=unpack(i)
190  return {'run':j[0],'lumisection':j[1]}
191 def inclusiveRange(start,stop,step):
192  """return range including the stop value
193  """
194  v=start
195  while v<stop:
196  yield v
197  v+=step
198  if v>=stop:
199  yield stop
200 
201 def tolegalJSON(inputstring):
202  '''
203  convert json like string to legal json string
204  add double quote around json keys if they are not there, change single quote to double quote around keys
205  '''
206  strresult=inputstring.strip()
207  strresult=re.sub("\s+","",strresult)
208  try:
209  mydict=ast.literal_eval(strresult)
210  except SyntaxError:
211  print('error in converting string to dict')
212  raise
213  result={}
214  for k,v in mydict.items():
215  if not isinstance(k,str):
216  result[str(k)]=v
217  else:
218  result[k]=v
219  return re.sub("'",'"',str(result))
220 
221 def packArraytoBlob(iarray):
222  '''
223  Inputs:
224  inputarray: a python array
225  '''
226  result=coral.Blob()
227  result.write(iarray.tostring())
228  return result
229 
230 def unpackBlobtoArray(iblob,itemtypecode):
231  '''
232  Inputs:
233  iblob: coral.Blob
234  itemtypecode: python array type code
235  '''
236  if itemtypecode not in ['c','b','B','u','h','H','i','I','l','L','f','d']:
237  raise RuntimeError('unsupported typecode '+itemtypecode)
238  result=array.array(itemtypecode)
239  blobstr=iblob.readline()
240  if not blobstr :
241  return None
242  result.fromstring(blobstr)
243  return result
244 
245 def packListstrtoCLOB(iListstr,separator=','):
246  '''
247  pack list of string of comma separated large string CLOB
248  '''
249  return separator.join(iListstr)
250 
251 def unpackCLOBtoListstr(iStr,separator=','):
252  '''
253  unpack a large string to list of string
254  '''
255  return [i.strip() for i in iStr.strip().split(separator)]
256 
258  result = []
259  first = inPut[0]
260  last = inPut[0]
261  result.append ([inPut[0]])
262  counter = 0
263  for i in inPut[1:]:
264  if i == last+1:
265  result[counter].append (i)
266  else:
267  counter += 1
268  result.append ([i])
269  last = i
270  return ', '.join (['['+str (min (x))+'-'+str (max (x))+']' for x in result])
271 
272 def parselumicorrector(correctorStr):
273  '''
274  output: (functionname,parametersinuppercase[])
275  '''
276  cleancorrectorStr=correctorStr.replace(' ','')#in case of whitespace by mistake
277  [correctorFunc,paramsStr]=cleancorrectorStr.split(':')
278  params=paramsStr.split(',')
279  return (correctorFunc,params)
280 
281 if __name__=='__main__':
282  nested=[[[1,2],[6,6,8]],[[3,4,5],[4,5]]]
283  print('flattened ',flatten(nested))
284  a=[1,2,3,4,5]
285  for i,j in pairwise(a):
286  if j :
287  print(i,j)
288  lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
289  print(count_dups(lst))
290  seqbag=[[1,2,3],[1,3,3],[1,4,6],[4,5,6,7],[8,9]]
291  print('before ',seqbag)
292  print('after ',transposed(seqbag,None))
293  print([i for i in inclusiveRange(1,3,1)])
294 
295  result=tolegalJSON('{1:[],2:[[1,3],[4,5]]}')
296  print(result)
297  pp=json.loads(result)
298  print(pp["2"])
299  result=tolegalJSON("{'1':[],'2':[[1,3],[4,5]]}")
300  print(result)
301  pp=json.loads(result)
302  print(pp["2"])
303  result=tolegalJSON('{"1":[],"2":[[1,3],[4,5]]}')
304  print(result)
305  pp=json.loads(result)
306  print(pp["2"])
307 
308  a=array.array('f')
309  a.append(1.3)
310  a.append(1.4)
311  a.append(2.3)
312  a.append(6.3)
313  myblob=packArraytoBlob(a)
314  print(myblob.size())
315  print(unpackBlobtoArray(myblob,'f'))
316  b=array.array('f')
317  myblob=packArraytoBlob(b)
318  print(myblob.size())
319  a=['aa_f', 'bb', 'dfc']
def tolegalJSON(inputstring)
Definition: CommonUtil.py:201
def unpackBlobtoArray(iblob, itemtypecode)
Definition: CommonUtil.py:230
def unpackFromString(i)
Definition: CommonUtil.py:173
def findInList(mylist, element)
Definition: CommonUtil.py:111
def packListstrtoCLOB(iListstr, separator=')
Definition: CommonUtil.py:245
def guessUnit(inverseubval)
Definition: CommonUtil.py:60
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:65
def unpackLumiid(i)
Definition: CommonUtil.py:186
return((rh^lh)&mask)
def timeStamptoUTC(i)
Definition: CommonUtil.py:181
def splitlistToRangeString(inPut)
Definition: CommonUtil.py:257
def unpackCLOBtoListstr(iStr, separator=')
Definition: CommonUtil.py:251
def pairwise(lst)
Definition: CommonUtil.py:99
def is_intstr(s)
Definition: CommonUtil.py:121
def transposed(lists, defaultval=None)
Definition: CommonUtil.py:147
def flatten(obj)
Definition: CommonUtil.py:5
def parseTime(iTime)
Definition: CommonUtil.py:15
def timeStamptoDate(i)
Definition: CommonUtil.py:177
def is_floatstr(s)
Definition: CommonUtil.py:129
def lumiUnitForPrint(t)
Definition: CommonUtil.py:31
def packArraytoBlob(iarray)
Definition: CommonUtil.py:221
def count_dups(l)
Definition: CommonUtil.py:138
def unpack(i)
Definition: CommonUtil.py:167
def packToString(high, low)
Definition: CommonUtil.py:161
def pack(high, low)
Definition: CommonUtil.py:155
def parselumicorrector(correctorStr)
Definition: CommonUtil.py:272
#define str(s)
double split
Definition: MVATrainer.cc:139
def inclusiveRange(start, stop, step)
Definition: CommonUtil.py:191