Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-12-01 23:40:46

0001 #! /usr/bin/env python3
0002 
0003 from builtins import range
0004 import optparse
0005 import os
0006 import re
0007 from pprint import pprint
0008 
0009 epsilon = 1.e-4
0010 
0011 def getPieceFromObject (obj, description):
0012     """Returns piece from object """
0013     parsed = GenObject.parseVariableTofill (description)
0014     return GenObject.evaluateFunction (obj, parsed)
0015 
0016 def getDictFromObject (obj, varDict, prefix = ''):
0017     """Given a object and a prefix, fills an return dictionary with the
0018     proper values"""
0019     if prefix:
0020         obj = getPieceFromObject (obj, prefix)
0021     retval = {}
0022     for key, description in varDict.items():
0023         retval[key] = getPieceFromObject (obj, description)
0024     return retval
0025 
0026 
0027 def format (objDict, label, spacing=9, firstOnly = False):
0028     '''return a formatted string for given object'''
0029     value = objDict[label]
0030     if firstOnly:
0031         diff = 0.
0032     else:
0033         diff  = objDict['delta_' + label]
0034         
0035     problem = False
0036     if isinstance (value, float):
0037         formatString = '%%%d.%df' % (spacing, spacing - 5)
0038         retval = formatString % value
0039         if abs(diff) > epsilon:
0040             if options.delta:
0041                 retval += ' [' + formatString % (diff) + ']'
0042             else:
0043                 retval += ' (' + formatString % (value + diff) + ')'
0044         elif not firstOnly:
0045             retval += ' ' * (spacing + 3)
0046         return retval
0047     else:
0048         formatString = '%%%ds' % spacing
0049         retval = formatString % value
0050         if diff:
0051             if isinstance (value, str):
0052                 retval += ' (' + formatString % diff + ')'
0053             elif options.delta:
0054                 retval += ' [' + formatString % diff + ']'
0055             else:
0056                 retval += ' (' + formatString % (value + diff) + ')'
0057         elif not firstOnly:
0058             retval += ' ' * (spacing + 3)
0059         return retval
0060     
0061 
0062 if __name__ == "__main__":
0063     parser = optparse.OptionParser ("Usage: %prog bla.root lib.so var1 [var2]")
0064     parser.add_option ("--delta", dest="delta",
0065                        action="store_true", default=False,
0066                        help="Show deltas when difference is large enough.")
0067     parser.add_option ("--skipUndefined", dest="skipUndefined",
0068                        action="store_true", default=False,
0069                        help="Skip undefined variables without warning.")
0070     options, args = parser.parse_args()
0071     from Validation.Tools.GenObject import GenObject
0072     if len (args) <= 2:
0073         raise RuntimeError("Must provide root file, shlib location, "\
0074               "and at least one variable")
0075     rootFilename  = args.pop(0)
0076     shlib     = args.pop(0)
0077     variables = args
0078     # play with shlib and cFile names
0079     if not re.search (r'_C.so$', shlib) and not re.search (r'_C$', shlib):
0080         shlib += '_C'
0081     cFile = re.sub (r'_C$', r'.C', re.sub(r'\.so$','', shlib))
0082     if not os.path.exists (cFile):
0083         raise RuntimeError("Can not find accompying C file '%s'."  % cFile)
0084     if not os.path.exists (rootFilename):
0085         raise RuntimeError("Can not find root file '%s'."  % rootFilename)
0086     # regex
0087     diffContRE  = re.compile (r'^class goDiffCont_(\w+)')
0088     # diffRE      = re.compile (r'^class goDiff_(\w+)')
0089     variableREDict = {}
0090     for var in variables:
0091         variableREDict[var] = ( re.compile (r'\bdelta_%s\b' % var),
0092                                 re.compile (r'\bother_%s\b' % var) ) 
0093     source = open (cFile, 'r')
0094     stringSet    = set()
0095     typeFoundSet = set()
0096     name         = ''
0097 
0098     
0099     for line in source:
0100         match = diffContRE.search (line)
0101         if match:
0102             if name:
0103                 raise RuntimeError("Currently only supported for a single"\
0104                       " class at a time.")
0105             name = match.group(1)
0106             continue
0107         for key, regexTuple in variableREDict.items():
0108             if regexTuple[0].search(line):
0109                 typeFoundSet.add( key )
0110                 continue
0111             if regexTuple[1].search(line):
0112                 typeFoundSet.add( key )
0113                 stringSet.add   ( key )
0114     if not name:
0115         raise RuntimeError("Didn't find any Diff Container")
0116     working = []
0117     for var in variables:
0118         if var not in typeFoundSet:
0119             if not options.skipUndefined:
0120                 raise RuntimeError("Variable '%s' not found." % var)
0121         else:
0122             working.append (var)
0123     variables = working
0124     import ROOT
0125     if ROOT.gSystem.Load (shlib):
0126         raise RuntimeError("Can not load shilb '%s'." % shlib)
0127     rootfile = ROOT.TFile.Open (rootFilename)
0128     if not rootfile:
0129         raise RuntimeError("Failed to open root file '%s'" % rootFilename)
0130     tree = rootfile.Get ('diffTree')
0131     if not tree:
0132         raise RuntimeError("Failed to get 'diffTree'")
0133     size = tree.GetEntries()
0134     runeventDict = {'Run':'run', 'Event':'event'}
0135     indexSingleDict = {'index':'index'}
0136     indexDoubleDict = {'index':'index', 'delta_index':'delta_index'}
0137     infoSingleDict = {}
0138     infoDoubleDict = {}
0139     for var in variables:
0140         infoSingleDict[var] = infoDoubleDict[var] = var;        
0141         if var in stringSet:
0142             infoDoubleDict['delta_' + var] = 'other_' + var
0143         else:
0144             infoDoubleDict['delta_' + var] = 'delta_' + var
0145     for index in range (size):
0146         tree.GetEntry (index)
0147         runevent = getDictFromObject (tree, runeventDict, 'runevent')
0148         pprint (runevent)
0149         # first only
0150         firstOnlyColl  = getPieceFromObject (tree, name + '.firstOnly')
0151         size = firstOnlyColl.size()
0152         if size:            
0153             print("First Only:\n   index    ", end=' ')
0154             for var in variables:
0155                 print("%-12s" % (' ' + var), end=' ')
0156             print()
0157             print('-' * (12 + 11 * len(variables)))
0158         for index in range (size):
0159             firstOnly = firstOnlyColl[index]
0160             index = getDictFromObject (firstOnly, indexSingleDict)
0161             print('  ', format (index, 'index', 3, firstOnly = True), end=' ')
0162             info = getDictFromObject (firstOnly, infoSingleDict)
0163             for var in variables:
0164                 print('  ', format (info, var, firstOnly = True), end=' ')
0165             print()
0166         print()
0167         # second only
0168         secondOnlyColl = getPieceFromObject (tree, name + '.secondOnly')
0169         size = secondOnlyColl.size()
0170         if size:            
0171             print("Second Only:\n   index    ", end=' ')
0172             for var in variables:
0173                 print("%-12s" % (' ' + var), end=' ')
0174             print()
0175             print('-' * (12 + 11 * len(variables)))
0176         for index in range (size):
0177             secondOnly = secondOnlyColl[index]
0178             index = getDictFromObject (secondOnly, indexSingleDict)
0179             print('  ', format (index, 'index', 3, firstOnly = True), end=' ')
0180             info = getDictFromObject (secondOnly, infoSingleDict)
0181             for var in variables:
0182                 print('  ', format (info, var, firstOnly = True), end=' ')
0183             print()
0184         print()
0185         # both
0186         diffColl = getPieceFromObject (tree, name+'.diff')
0187         size = diffColl.size()
0188         if size:            
0189             print("Both:\n   index", end=' ')
0190             for var in variables:
0191                 print("%-24s" % ('          ' + var), end=' ')
0192             print()
0193             print('-' * (16 + 23 * len(variables)))
0194         for index in range (size):
0195             diff = diffColl[index]
0196             index = getDictFromObject (diff, indexDoubleDict)
0197             print('  ', format (index, 'index', 3), end=' ')
0198             info = getDictFromObject (diff, infoDoubleDict)
0199             for var in variables:
0200                 print('  ', format (info, var), end=' ')
0201             print()
0202         print()
0203