CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_2_7_hltpatch1/src/RecoLuminosity/LumiDB/python/CommonUtil.py

Go to the documentation of this file.
00001 '''This module collects some frequently used helper functions
00002 '''
00003 import time,ast,re,json,coral,array
00004 def flatten(obj):
00005     '''Given nested lists or tuples, returns a single flattened list'''
00006     result = []
00007     for piece in obj:
00008         if hasattr (piece, '__iter__') and not isinstance (piece, basestring):
00009             result.extend( flatten (piece) )
00010         else:
00011             result.append (piece)
00012     return result
00013 
00014 def lumiUnitForPrint(t):
00015     '''
00016     input : largest lumivalue
00017     output: (unitstring,denomitor)
00018     '''
00019     unitstring='/ub'
00020     denomitor=1.0
00021     if t>=1.0e3 and t<1.0e06:
00022         denomitor=1.0e3
00023         unitstring='/nb'
00024     elif t>=1.0e6 and t<1.0e9:
00025         denomitor=1.0e6
00026         unitstring='/pb'
00027     elif t>=1.0e9 and t<1.0e12:
00028         denomitor=1.0e9
00029         unitstring='/fb'
00030     elif t>=1.0e12 and t<1.0e15:
00031         denomitor=1.0e12
00032         unitstring='/ab'
00033     elif t<1.0 and t>=1.0e-3: #left direction
00034         denomitor=1.0e-03
00035         unitstring='/mb'
00036     elif t<1.0e-03 and t>=1.0e-06:
00037         denomitor=1.0e-06
00038         unitstring='/b'
00039     elif t<1.0e-06 and t>=1.0e-09:
00040         denomitor=1.0e-9
00041         unitstring='/kb'
00042     return (unitstring,denomitor)
00043 def guessUnit(inverseubval):
00044     '''
00045     input:
00046         float value in 1/ub
00047     output:
00048         printable value (value(float),unit(str)) unit in [1/kb,1/b,1/mb,1/ub,1/nb,1/pb,1/fb]
00049     '''
00050     if inverseubval>=1.0e-09 and inverseubval<1.0e-06:
00051         denomitor=1.0e-09
00052         unitstring='/kb'
00053         return (float(inverseubval)/float(denomitor),unitstring)
00054     if inverseubval>=1.0e-06 and inverseubval<1.0e-03:
00055         denomitor=1.0e-06
00056         unitstring='/b'
00057         return (float(inverseubval)/float(denomitor),unitstring)
00058     if inverseubval>=1.0e-03 and inverseubval<1.0:
00059         denomitor=1.0e-03
00060         unitstring='/mb'
00061         return (float(inverseubval)/float(denomitor),unitstring)
00062     if inverseubval>=1.0 and inverseubval<1.0e3:
00063         unitstring='/ub'
00064         return (inverseubval,unitstring)
00065     if inverseubval>=1.0e3 and inverseubval<1.0e06:
00066         denomitor=1.0e3
00067         unitstring='/nb'
00068         return (float(inverseubval)/float(denomitor),unitstring)
00069     if inverseubval>=1.0e6 and inverseubval<1.0e9:
00070         denomitor=1.0e6
00071         unitstring='/pb'
00072         return (float(inverseubval)/float(denomitor),unitstring)
00073     if inverseubval>=1.0e9 and inverseubval<1.0e12:
00074         denomitor=1.0e9
00075         unitstring='/fb'
00076         return (float(inverseubval)/float(denomitor),unitstring)
00077     if inverseubval>=1.0e12 and inverseubval<1.0e15:
00078         denomitor=1.0e12
00079         unitstring='/ab'
00080         return (float(inverseubval)/float(denomitor),unitstring)
00081     return (float(inverseubval),'/ub')
00082 def pairwise(lst):
00083     """
00084     yield item i and item i+1 in lst. e.g.
00085     (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None)
00086     
00087     from https://code.activestate.com/recipes/409825-look-ahead-one-item-during-iteration
00088     """
00089     if not len(lst): return
00090     #yield None, lst[0]
00091     for i in range(len(lst)-1):
00092         yield lst[i], lst[i+1]
00093     yield lst[-1], None
00094 def findInList(mylist,element):
00095     """
00096     check if an element is in the list
00097     """
00098     pos=-1
00099     try:
00100         pos=mylist.index(element)
00101     except ValueError:
00102         pos=-1
00103     return pos!=-1
00104 def is_intstr(s):
00105     """test if a string can be converted to a int
00106     """
00107     try:
00108         int(s)
00109         return True
00110     except ValueError:
00111         return False
00112 def is_floatstr(s):
00113     """
00114     test if a string can be converted to a float
00115     """
00116     try:
00117         float(s)
00118         return True
00119     except ValueError:
00120         return False
00121 def count_dups(l):
00122     """
00123     report the number of duplicates in a python list
00124     """
00125     from collections import defaultdict
00126     tally=defaultdict(int)
00127     for x in l:
00128         tally[x]+=1
00129     return tally.items()
00130 def transposed(lists, defaultval=None):
00131     """
00132     transposing list of lists
00133     from https://code.activestate.com/recipes/410687-transposing-a-list-of-lists-with-different-lengths/
00134     """
00135     if not lists: return []
00136     #return map(lambda *row: [elem or defaultval for elem in row], *lists)
00137     return map(lambda *row: [elem for elem in row or defaultval], *lists)
00138 def pack(high,low):
00139     """pack high,low 32bit unsigned int to one unsigned 64bit long long
00140        Note:the print value of result number may appear signed, if the sign bit is used.
00141     """
00142     h=high<<32
00143     return (h|low)
00144 def packToString(high,low):
00145     """pack high,low 32bit unsigned int to one unsigned 64bit long long in string format
00146        Note:the print value of result number may appear signed, if the sign bit is used.
00147     """
00148     fmt="%u"
00149     return fmt%pack(high,low)
00150 def unpack(i):
00151     """unpack 64bit unsigned long long into 2 32bit unsigned int, return tuple (high,low)
00152     """
00153     high=i>>32
00154     low=i&0xFFFFFFFF
00155     return(high,low)
00156 def unpackFromString(i):
00157     """unpack 64bit unsigned long long in string format into 2 32bit unsigned int, return tuple(high,low)
00158     """
00159     return unpack(int(i))
00160 def timeStamptoDate(i):
00161     """convert 64bit timestamp to local date in string format
00162     """
00163     return time.ctime(unpack(i)[0])
00164 def timeStamptoUTC(i):
00165     """convert 64bit timestamp to Universal Time in string format
00166     """
00167     t=unpack(i)[0]
00168     return time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(t))
00169 def unpackLumiid(i):
00170     """unpack 64bit lumiid to dictionary {'run','lumisection'}
00171     """
00172     j=unpack(i)
00173     return {'run':j[0],'lumisection':j[1]}
00174 def inclusiveRange(start,stop,step):
00175     """return range including the stop value
00176     """
00177     v=start
00178     while v<stop:
00179         yield v
00180         v+=step
00181     if v>=stop:
00182         yield stop
00183         
00184 def tolegalJSON(inputstring):
00185    '''
00186    convert json like string to legal json string
00187    add double quote around json keys if they are not there, change single quote to double quote around keys
00188    '''
00189    strresult=inputstring.strip()
00190    strresult=re.sub("\s+","",strresult)
00191    try:
00192        mydict=ast.literal_eval(strresult)
00193    except SyntaxError:
00194        print 'error in converting string to dict'
00195        raise
00196    result={}
00197    for k,v in mydict.items():
00198        if not isinstance(k,str):
00199            result[str(k)]=v
00200        else:
00201            result[k]=v
00202    return re.sub("'",'"',str(result))
00203 
00204 def packArraytoBlob(iarray):
00205     '''
00206     Inputs:
00207     inputarray: a python array
00208     '''
00209     result=coral.Blob()
00210     result.write(iarray.tostring())
00211     return result
00212 
00213 def unpackBlobtoArray(iblob,itemtypecode):
00214     '''
00215     Inputs:
00216     iblob: coral.Blob
00217     itemtypecode: python array type code 
00218     '''
00219     if itemtypecode not in ['c','b','B','u','h','H','i','I','l','L','f','d']:
00220         raise RuntimeError('unsupported typecode '+itemtypecode)
00221     result=array.array(itemtypecode)
00222     blobstr=iblob.readline()
00223     if not blobstr :
00224         return None
00225     result.fromstring(blobstr)
00226     return result
00227 
00228 def packListstrtoCLOB(iListstr,separator=','):
00229     '''
00230     pack list of string of comma separated large string CLOB
00231     '''
00232     return separator.join(iListstr)
00233 
00234 def unpackCLOBtoListstr(iStr,separator=','):
00235     '''
00236     unpack a large string to list of string
00237     '''
00238     return [i.strip() for i in iStr.strip().split(separator)]
00239 
00240 def splitlistToRangeString (inPut):
00241     result = []
00242     first = inPut[0]
00243     last = inPut[0]
00244     result.append ([inPut[0]])
00245     counter = 0
00246     for i in inPut[1:]:
00247         if i == last+1:
00248             result[counter].append (i)
00249         else:
00250             counter += 1
00251             result.append ([i])
00252         last = i
00253     return ', '.join (['['+str (min (x))+'-'+str (max (x))+']' for x in result])    
00254 
00255 if __name__=='__main__':
00256     nested=[[[1,2],[6,6,8]],[[3,4,5],[4,5]]]
00257     print 'flattened ',flatten(nested)
00258     a=[1,2,3,4,5]
00259     for i,j in pairwise(a):
00260         if j :
00261             print i,j
00262     lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
00263     print count_dups(lst)
00264     seqbag=[[1,2,3],[1,3,3],[1,4,6],[4,5,6,7],[8,9]]
00265     print 'before ',seqbag
00266     print 'after ',transposed(seqbag,None)
00267     print [i for i in inclusiveRange(1,3,1)]
00268     
00269     result=tolegalJSON('{1:[],2:[[1,3],[4,5]]}')
00270     print result
00271     pp=json.loads(result)
00272     print pp["2"]
00273     result=tolegalJSON("{'1':[],'2':[[1,3],[4,5]]}")
00274     print result
00275     pp=json.loads(result)
00276     print pp["2"]
00277     result=tolegalJSON('{"1":[],"2":[[1,3],[4,5]]}')
00278     print result
00279     pp=json.loads(result)
00280     print pp["2"]
00281     
00282     a=array.array('f')
00283     a.append(1.3)
00284     a.append(1.4)
00285     a.append(2.3)
00286     a.append(6.3)
00287     myblob=packArraytoBlob(a)
00288     print myblob.size()
00289     print unpackBlobtoArray(myblob,'f')
00290     b=array.array('f')
00291     myblob=packArraytoBlob(b)
00292     print myblob.size()
00293     a=['aa_f', 'bb', 'dfc']
00294     print packListstrtoCLOB(a)