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