forked from cms-sw/cmssw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenObject.py
executable file
·1632 lines (1508 loc) · 69.1 KB
/
GenObject.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## Note: Please do not use or modify any data or functions with a
## leading underscore. If you "mess" with the internal structure,
## the classes may not function as intended.
from builtins import range
from FWCore.Utilities.Enumerate import Enumerate
from DataFormats.FWLite import Events, Handle
import re
import os
import copy
import pprint
import random
import sys
import inspect
import ROOT
from functools import reduce
ROOT.gROOT.SetBatch()
# regex for reducing 'warn()' filenames
filenameRE = re.compile (r'.+/Validation/Tools/')
# Whether warn() should print anythingg
quietWarn = False
def setQuietWarn (quiet = True):
global quietWarn
quietWarn = quiet
def warn (*args, **kwargs):
"""print out warning with line number and rest of arguments"""
if quietWarn: return
frame = inspect.stack()[1]
filename = frame[1]
lineNum = frame[2]
#print filename, filenameRE
filename = filenameRE.sub ('', filename)
#print "after '%s'" % filename
blankLines = kwargs.get('blankLines', 0)
if blankLines:
print('\n' * blankLines)
spaces = kwargs.get('spaces', 0)
if spaces:
print(' ' * spaces, end=' ')
if len (args):
print("%s (%s): " % (filename, lineNum), end=' ')
for arg in args:
print(arg, end=' ')
print()
else:
print("%s (%s):" % (filename, lineNum))
class GenObject (object):
"""Infrastruture to define general objects and their attributes."""
########################
## Static Member Data ##
########################
types = Enumerate ("float int long string", "type")
_objFunc = Enumerate ("obj func", "of")
_cppType = dict ( {types.float : 'double',
types.int : 'int',
types.long : 'long',
types.string : 'std::string' } )
_basicSet = set( [types.float, types.int, types.float,
types.string] )
_defaultValue = dict ( {types.float : 0.,
types.int : 0,
types.long : 0,
types.string : '""' } )
_objsDict = {} # info about GenObjects
_equivDict = {} # hold info about 'equivalent' muons
_ntupleDict = {} # information about different ntuples
_tofillDict = {} # information on how to fill from different ntuples
_rootObjectDict = {} # hold objects and stl::vectors to objects
# hooked up to a root tree
_rootClassDict = {} # holds classes (not instances) associated with
# a given GenObject
_kitchenSinkDict = {} # dictionary that holds everything else...
_runEventList = []
_runEventListDone = False
uselessReturnCode = 1 << 7 # pick a unique return code
####################
## Compile Regexs ##
####################
_nonSpacesRE = re.compile (r'\S')
_colonRE = re.compile (r'\s*:\s*')
_singleColonRE = re.compile (r'(.+?):(.+)')
_doubleColonRE = re.compile (r'(.+?):(.+?):(.+)')
_doublePercentRE = re.compile (r'%%')
_parenRE = re.compile (r'(.+)\((.*)\)')
_spacesRE = re.compile (r'\s+')
_dotRE = re.compile (r'\s*\.\s*')
_commaRE = re.compile (r'\s*,\s*')
_singleQuoteRE = re.compile (r'^\'(.+)\'$')
_doubleQuoteRE = re.compile (r'^\"(.+)\"$')
_bracketRE = re.compile (r'\[\s*(.+?)\s*\]')
_commentRE = re.compile (r'#.+$')
_aliasRE = re.compile (r'alias=(\S+)', re.IGNORECASE)
_labelRE = re.compile (r'label=(\S+)', re.IGNORECASE)
_typeRE = re.compile (r'type=(\S+)', re.IGNORECASE)
_singletonRE = re.compile (r'singleton', re.IGNORECASE)
_typeRE = re.compile (r'type=(\S+)', re.IGNORECASE)
_defaultRE = re.compile (r'default=(\S+)', re.IGNORECASE)
_shortcutRE = re.compile (r'shortcut=(\S+)', re.IGNORECASE)
_precRE = re.compile (r'prec=(\S+)', re.IGNORECASE)
_formRE = re.compile (r'form=(\S+)', re.IGNORECASE)
_nonAlphaRE = re.compile (r'\W')
_percentAsciiRE = re.compile (r'%([0-9a-fA-F]{2})')
#############################
## Static Member Functions ##
#############################
@staticmethod
def char2ascii (match):
return "%%%02x" % ord (match.group(0))
@staticmethod
def ascii2char (match):
return chr( int( match.group(1), 16 ) )
@staticmethod
def encodeNonAlphanumerics (line):
"""Use a web like encoding of characters that are non-alphanumeric"""
return GenObject._nonAlphaRE.sub( GenObject.char2ascii, line )
@staticmethod
def decodeNonAlphanumerics (line):
"""Decode lines encoded with encodeNonAlphanumerics()"""
return GenObject._percentAsciiRE.sub( GenObject.ascii2char, line )
@staticmethod
def addObjectVariable (obj, var, **optionsDict):
""" User passes in in object and variable names."""
if 'varType' not in optionsDict:
optionsDict['varType'] = GenObject.types.float
varType = optionsDict['varType']
if not GenObject.types.isValidValue (varType):
print("Type '%s' not valid. Skipping (%s, %s, %s)." % \
(varType, obj, var, varType))
return
if 'default' not in optionsDict:
optionsDict['default'] = GenObject._defaultValue[varType]
if obj.startswith ("_") or var.startswith ("_"):
print("Skipping (%s, %s, %s) because of leading underscore." % \
(obj, var, varType))
return
GenObject._objsDict.setdefault (obj, {}).setdefault (var, optionsDict)
@staticmethod
def getVariableProperty (obj, var, key):
"""Returns property assoicated with 'key' for variable 'var'
of object 'obj'. Returns 'None' if any of the above are not
defined."""
return GenObject._objsDict.get (obj, {}).get (var, {}). get (key, None)
@staticmethod
def setEquivExpression (obj, variable, precision):
"""Adds an equivalence constraint. Must have at least one to
compare GO objects."""
if obj.startswith ("_"):
print("Skipping (%s, %s) because of leading underscore." % \
(obj, expression))
return
GenObject._equivDict.setdefault (obj,[]).append ( (variable,
precision) )
@staticmethod
def printGlobal():
"""Meant for debugging, but ok if called by user"""
print("objs: ")
pprint.pprint (GenObject._objsDict, indent=4)
print("equiv: ")
pprint.pprint (GenObject._equivDict, indent=4)
print("ntuple: ")
pprint.pprint (GenObject._ntupleDict, indent=4)
print("tofill: ")
pprint.pprint (GenObject._tofillDict, indent=4)
print("kitchenSink: ")
pprint.pprint (GenObject._kitchenSinkDict, indent=4)
print("rootClassDict")
pprint.pprint (GenObject._rootClassDict, indent=4)
@staticmethod
def checksum (str):
"""Returns a string of hex value of a checksum of input
string."""
return hex( reduce( lambda x, y : x + y, map(ord, str) ) )[2:]
@staticmethod
def rootClassName (objName):
"""Returns the name of the equivalent Root object"""
return "go_" + objName
@staticmethod
def rootDiffClassName (objName):
"""Returns the name of the equivalent Root diff object"""
return "goDiff_" + objName
@staticmethod
def rootDiffContClassName (objName):
"""Returns the name of the equivalent Root diff container
object"""
return "goDiffCont_" + objName
@staticmethod
def _setupClassHeader (className, noColon = False):
"""Returns a string with the class header for a class
'classname'"""
retval = "\nclass %s\n{\n public:\n" % className
retval += " typedef std::vector< %s > Collection;\n\n" % className
# constructor
if noColon:
retval += " %s()" % className
else:
retval += " %s() :\n" % className
return retval
@staticmethod
def _finishClassHeader (className, datadec):
"""Returns a stringg with the end of a class definition"""
retval = "\n {}\n" + datadec + "};\n"
retval += "#ifdef __MAKECINT__\n#pragma link C++ class " + \
"vector< %s >+;\n#endif\n\n" % className
return retval
@staticmethod
def _createCppClass (objName):
"""Returns a string containing the '.C' file necessary to
generate a shared object library with dictionary."""
if objName not in GenObject._objsDict:
# not good
print("Error: GenObject does not know about object '%s'." % objName)
raise RuntimeError("Failed to create C++ class.")
className = GenObject.rootClassName (objName)
diffName = GenObject.rootDiffClassName (objName)
contName = GenObject.rootDiffContClassName (objName)
goClass = GenObject._setupClassHeader (className)
diffClass = GenObject._setupClassHeader (diffName)
contClass = GenObject._setupClassHeader (contName, noColon = True)
goDataDec = diffDataDec = contDataDec = "\n // data members\n"
first = True
for key in sorted( GenObject._objsDict[objName].keys() ):
if key.startswith ("_"): continue
varTypeList = GenObject._objsDict[objName][key]
cppType = GenObject._cppType[ varTypeList['varType'] ]
default = varTypeList['default']
if first:
first = False
else:
goClass += ",\n"
diffClass += ',\n'
goClass += " %s (%s)" % (key, default)
goDataDec += " %s %s;\n" % (cppType, key)
# is this a basic class?
goType = varTypeList['varType']
if goType in GenObject._basicSet:
# basic type
diffClass += " %s (%s),\n" % (key, default)
diffDataDec += " %s %s;\n" % (cppType, key)
if goType == GenObject.types.string:
# string
otherKey = 'other_' + key
diffClass += " %s (%s)" % (otherKey, default)
diffDataDec += " %s %s;\n" % (cppType, otherKey)
else:
# float, long, or int
deltaKey = 'delta_' + key
diffClass += " %s (%s)" % (deltaKey, default)
diffDataDec += " %s %s;\n" % (cppType, deltaKey)
else:
raise RuntimeError("Shouldn't be here yet.")
# definition
# do contClass
if GenObject.isSingleton (objName):
# singleton
contDataDec += " %s diff;\n" % diffName
contDataDec += " void setDiff (const %s &rhs)" % diffName + \
" { diff = rhs; }\n"
else:
# vector of objects
contDataDec += " void clear() {firstOnly.clear(); secondOnly.clear(); diff.clear(); }\n"
contDataDec += " %s::Collection firstOnly;\n" % className
contDataDec += " %s::Collection secondOnly;\n" % className
contDataDec += " %s::Collection diff;\n" % diffName
# give me a way to clear them all at once
# Finish off the classes
goClass += GenObject._finishClassHeader (className, goDataDec)
diffClass += GenObject._finishClassHeader (diffName, diffDataDec)
contClass += GenObject._finishClassHeader (contName, contDataDec)
if objName == 'runevent':
# we don't want a diff class for this
diffClass = ''
contClass = ''
return goClass + diffClass + contClass
@staticmethod
def _loadGoRootLibrary ():
"""Loads Root shared object library associated with all
defined GenObjects. Will create library if necessary."""
print("Loading GO Root Library")
key = "_loadedLibrary"
if GenObject._kitchenSinkDict.get (key):
# Already done, don't do it again:
return
# Mark it as done
GenObject._kitchenSinkDict[key] = True
# Generate source code
sourceCode = "#include <string>\n#include <vector>\n" \
+ "using namespace std;\n"
for objClassName in sorted( GenObject._objsDict.keys() ):
sourceCode += GenObject._createCppClass (objClassName)
GenObjectRootLibDir = "genobjectrootlibs"
if not os.path.exists (GenObjectRootLibDir):
os.mkdir (GenObjectRootLibDir)
key = GenObject.checksum( sourceCode )
basename = "%s_%s" % ("GenObject", key)
SO = "%s/%s_C" % (GenObjectRootLibDir, basename)
linuxSO = "%s.so" % SO
windowsSO = "%s.dll" % SO
if not os.path.exists (linuxSO) and not os.path.exists (windowsSO):
print("creating SO")
filename = "%s/%s.C" % (GenObjectRootLibDir, basename)
if not os.path.exists (filename):
print("creating .C file")
target = open (filename, "w")
target.write (sourceCode)
target.close()
else:
print("%s exists" % filename)
## command = "echo .L %s+ | root.exe -b" % filename
## os.system (command)
ROOT.gSystem.CompileMacro (filename, "k")
else:
print("loading %s" % SO)
ROOT.gSystem.Load(SO)
return
@staticmethod
def _tofillGenObject():
"""Makes sure that I know how to read root files I made myself"""
genObject = "GenObject"
ntupleDict = GenObject._ntupleDict.setdefault (genObject, {})
ntupleDict['_useChain'] = True
ntupleDict['_tree'] = "goTree"
for objName in GenObject._objsDict.keys():
rootObjName = GenObject.rootClassName (objName)
if GenObject.isSingleton (objName):
ntupleDict[objName] = objName
else:
ntupleDict[objName] = objName + "s"
tofillDict = GenObject._tofillDict.\
setdefault (genObject, {}).\
setdefault (objName, {})
for varName in GenObject._objsDict [objName].keys():
# if the key starts with an '_', then it is not a
# variable, so don't treat it as one.
if varName.startswith ("_"):
continue
tofillDict[varName] = [ [(varName, GenObject._objFunc.obj)],
{}]
@staticmethod
def prepareToLoadGenObject():
"""Makes all necessary preparations to load root files created
by GenObject."""
GenObject._tofillGenObject()
GenObject._loadGoRootLibrary()
@staticmethod
def parseVariableTofill (fillname):
"""Returns tofill tuple made from string"""
parts = GenObject._dotRE.split (fillname)
partsList = []
for part in parts:
parenMatch = GenObject._parenRE.search (part)
mode = GenObject._objFunc.obj
parens = []
if parenMatch:
part = parenMatch.group (1)
mode = GenObject._objFunc.func
parens = \
GenObject._convertStringToParameters \
(parenMatch.group (2))
partsList.append( (part, mode, parens) )
return partsList
@staticmethod
def _fixLostGreaterThans (handle):
offset = handle.count ('<') - handle.count('>')
if not offset:
return handle
if offset < 0:
print("Huh? Too few '<' for each '>' in handle '%'" % handle)
return handle
return handle + ' >' * offset
@staticmethod
def loadConfigFile (configFile):
"""Loads configuration file"""
objName = ""
tupleName = ""
tofillName = ""
modeEnum = Enumerate ("none define tofill ntuple", "mode")
mode = modeEnum.none
try:
config = open (configFile, 'r')
except:
raise RuntimeError("Can't open configuration '%s'" % configFile)
for lineNum, fullLine in enumerate (config):
fullLine = fullLine.strip()
# get rid of comments
line = GenObject._commentRE.sub ('', fullLine)
# Is there anything on this line?
if not GenObject._nonSpacesRE.search (line):
# Nothing to see here folks. Keep moving....
continue
###################
## Bracket Match ##
###################
bracketMatch = GenObject._bracketRE.search (line)
if bracketMatch:
# a header
section = bracketMatch.group(1)
words = GenObject._spacesRE.split( section )
if len (words) < 1:
raise RuntimeError("Don't understand line '%s'(%d)" \
% (fullLine, lineNum))
# The first word is the object name
# reset the rest of the list
objName = words[0]
words = words[1:]
colonWords = GenObject._colonRE.split (objName)
if len (colonWords) > 3:
raise RuntimeError("Don't understand line '%s'(%d)" \
% (fullLine, lineNum))
if len (colonWords) == 1:
##########################
## GenObject Definition ##
##########################
mode = modeEnum.define
for word in words:
if GenObject._singletonRE.match (word):
#GenObject._singletonSet.add (objName)
objsDict = GenObject._objsDict.\
setdefault (objName, {})
objsDict['_singleton'] = True
continue
# If we're still here, then we didn't have a valid
# option. Complain vociferously
print("I don't understand '%s' in section '%s' : %s" \
% (word, section, mode))
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
elif len (colonWords) == 2:
#######################
## Ntuple Definition ##
#######################
mode = modeEnum.ntuple
ntupleDict = GenObject._ntupleDict.\
setdefault (colonWords[0], {})
ntupleDict['_tree'] = colonWords[1]
else:
##########################
## Object 'tofill' Info ##
##########################
mode = modeEnum.tofill
objName = colonWords [0]
tupleName = colonWords [1]
tofillName = colonWords [2]
ntupleDict = GenObject._ntupleDict.\
setdefault (tupleName, {})
ntupleDict[objName] = tofillName
for word in words:
# label
labelMatch = GenObject._labelRE.search (word)
if labelMatch:
label = tuple( GenObject._commaRE.\
split( labelMatch.group (1) ) )
ntupleDict.setdefault ('_label', {}).\
setdefault (tofillName,
label)
continue
# shortcut
shortcutMatch = GenObject._shortcutRE.search (word)
if shortcutMatch:
shortcutFill = \
GenObject.\
parseVariableTofill ( shortcutMatch.\
group(1) )
ntupleDict.setdefault ('_shortcut', {}).\
setdefault (tofillName,
shortcutFill)
continue
# type/handle
typeMatch = GenObject._typeRE.search (word)
if typeMatch:
handleString = \
GenObject.\
_fixLostGreaterThans (typeMatch.group(1))
handle = Handle( handleString )
ntupleDict.setdefault ('_handle', {}).\
setdefault (tofillName,
handle)
continue
# alias
aliasMatch = GenObject._aliasRE.search (word)
if aliasMatch:
ntupleDict.setdefault ('_alias', {}).\
setdefault (tofillName,
aliasMatch.\
group(1))
continue
# is this a lost '<'
if word == '>':
continue
# If we're still here, then we didn't have a valid
# option. Complain vociferously
print("I don't understand '%s' in section '%s' : %s" \
% (word, section, mode))
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
##############
## Variable ##
##############
else:
# a variable
if modeEnum.none == mode:
# Poorly formatted 'section' tag
print("I don't understand line '%s'." % fullLine)
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
colonWords = GenObject._colonRE.split (line, 1)
if len (colonWords) < 2:
# Poorly formatted 'section' tag
print("I don't understand line '%s'." % fullLine)
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
varName = colonWords[0]
option = colonWords[1]
if option:
pieces = GenObject._spacesRE.split (option)
else:
pieces = []
if modeEnum.define == mode:
#########################
## Variable Definition ##
#########################
# is this a variable or an option?
if varName.startswith("-"):
# this is an option
if "-equiv" == varName.lower():
for part in pieces:
halves = part.split (",")
if 2 != len (halves):
print("Problem with -equiv '%s' in '%s'" % \
(part, section))
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
if halves[1]:
halves[1] = float (halves[1])
if not halves[1] >= 0:
print("Problem with -equiv ",\
"'%s' in '%s'" % \
(part, section))
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
GenObject.setEquivExpression (section,
halves[0],
halves[1])
continue
# If we're here, then this is a variable
optionsDict = {}
for word in pieces:
typeMatch = GenObject._typeRE.search (word)
if typeMatch and \
GenObject.types.isValidKey (typeMatch.group(1)):
varType = typeMatch.group(1).lower()
optionsDict['varType'] = GenObject.types (varType)
continue
defaultMatch = GenObject._defaultRE.search (word)
if defaultMatch:
optionsDict['default'] = defaultMatch.group(1)
continue
precMatch = GenObject._precRE.search (word)
if precMatch:
optionsDict['prec'] = float (precMatch.group (1))
continue
formMatch = GenObject._formRE.search (word)
if formMatch:
form = GenObject._doublePercentRE.\
sub ('%', formMatch.group (1))
optionsDict['form'] = form
continue
# If we're still here, then we didn't have a valid
# option. Complain vociferously
print("I don't understand '%s' in section '%s'." \
% (word, option))
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
GenObject.addObjectVariable (objName, varName, \
**optionsDict)
else: # if modeEnum.define != mode
############################
## Variable 'tofill' Info ##
############################
if len (pieces) < 1:
continue
fillname, pieces = pieces[0], pieces[1:]
# I don't yet have any options available here, but
# I'm keeping the code here for when I add them.
optionsDict = {}
for word in pieces:
# If we're still here, then we didn't have a valid
# option. Complain vociferously
print("I don't understand '%s' in section '%s'." \
% (word, option))
raise RuntimeError("Config file parser error '%s'(%d)" \
% (fullLine, lineNum))
tofillDict = GenObject._tofillDict.\
setdefault (tupleName, {}).\
setdefault (objName, {})
partsList = GenObject.parseVariableTofill (fillname)
tofillDict[varName] = [partsList, optionsDict]
# for line
for objName in GenObject._objsDict:
# if this isn't a singleton, add 'index' as a variable
if not GenObject.isSingleton (objName):
GenObject.addObjectVariable (objName, 'index',
varType = GenObject.types.int,
form = '%3d')
@staticmethod
def changeVariable (tupleName, objName, varName, fillname):
"""Updates the definition used to go from a Root object to a
GenObject. 'tupleName' and 'objName' must already be defined."""
parts = GenObject._dotRE.split (fillname)
partsList = []
for part in parts:
parenMatch = GenObject._parenRE.search (part)
mode = GenObject._objFunc.obj
parens = []
if parenMatch:
part = parenMatch.group (1)
mode = GenObject._objFunc.func
parens = \
GenObject._convertStringToParameters \
(parenMatch.group (2))
partsList.append( (part, mode, parens) )
GenObject._tofillDict[tupleName][objName][varName] = [partsList, {}]
@staticmethod
def evaluateFunction (obj, partsList, debug=False):
"""Evaluates function described in partsList on obj"""
for part in partsList:
if debug: warn (part, spaces=15)
obj = getattr (obj, part[0])
if debug: warn (obj, spaces=15)
# if this is a function instead of a data member, make
# sure you call it with its arguments:
if GenObject._objFunc.func == part[1]:
# Arguments are stored as a list in part[2]
obj = obj (*part[2])
if debug: warn (obj, spaces=18)
return obj
@staticmethod
def _genObjectClone (objName, tupleName, obj, index = -1):
"""Creates a GenObject copy of Root object"""
debug = GenObject._kitchenSinkDict.get ('debug', False)
if objName == 'runevent':
debug = False
tofillObjDict = GenObject._tofillDict.get(tupleName, {})\
.get(objName, {})
genObj = GenObject (objName)
origObj = obj
if debug: warn (objName, spaces = 9)
for genVar, ntDict in tofillObjDict.items():
if debug: warn (genVar, spaces = 12)
# lets work our way down the list
partsList = ntDict[0]
# start off with the original object
obj = GenObject.evaluateFunction (origObj, partsList, debug)
if debug: warn (obj, spaces=12)
setattr (genObj, genVar, obj)
# Do I need to store the index of this object?
if index >= 0:
setattr (genObj, 'index', index)
return genObj
@staticmethod
def _rootObjectCopy (goSource, rootTarget):
"""Copies information from goSourse into Root Object"""
objName = goSource._objName
for varName in GenObject._objsDict [objName].keys():
# if the key starts with an '_', then it is not a
# variable, so don't treat it as one.
if varName.startswith ("_"):
continue
setattr( rootTarget, varName, goSource (varName) )
@staticmethod
def _rootObjectClone (obj):
"""Creates the approprite type of Root object and copies the
information into it from the GO object."""
objName = obj._objName
classObj = GenObject._rootClassDict.get (objName)
if not classObj:
goName = GenObject.rootClassName (objName)
classObj = GenObject._rootClassDict[ goName ]
rootObj = classObj()
for varName in GenObject._objsDict [objName].keys():
setattr( rootObj, varName, obj (varName) )
return rootObj
@staticmethod
def _rootDiffObject (obj1, obj2, rootObj = 0):
"""Given to GOs, it will create and fill the corresponding
root diff object"""
objName = obj1._objName
# if we don't already have a root object, create one
if not rootObj:
diffName = GenObject.rootDiffClassName( objName )
rootObj = GenObject._rootClassDict[diffName]()
for varName in GenObject._objsDict [objName].keys():
if varName.startswith ("_"): continue
goType = GenObject._objsDict[objName][varName]['varType']
if not goType in GenObject._basicSet:
# not yet
continue
setattr( rootObj, varName, obj1 (varName) )
if goType == GenObject.types.string:
# string
otherName = 'other_' + varName
if obj1 (varName) != obj2 (varName):
# don't agree
setattr( rootObj, otherName, obj2 (varName) )
else:
# agree
setattr( rootObj, otherName, '' )
else:
# float, long, or int
deltaName = 'delta_' + varName
setattr( rootObj, deltaName,
obj2 (varName) - obj1 (varName) )
return rootObj
@staticmethod
def setupOutputTree (outputFile, treeName, treeDescription = "",
otherNtupleName = ""):
"""Opens the output file, loads all of the necessary shared
object libraries, and returns the output file and tree. If
'otherNtupleName' is given, it will check and make sure that
only objects that are defined in it are written out."""
rootfile = ROOT.TFile.Open (outputFile, "recreate")
tree = ROOT.TTree (treeName, treeDescription)
GenObject._loadGoRootLibrary()
for objName in sorted (GenObject._objsDict.keys()):
classname = GenObject.rootClassName (objName)
rootObj = \
GenObject._rootClassDict[objName] = \
getattr (ROOT, classname)
if GenObject.isSingleton (objName):
# singleton object
obj = GenObject._rootObjectDict[objName] = rootObj()
tree.Branch (objName, classname, obj)
else:
# vector of objects - PLEASE don't forget the '()' on
# the end of the declaration. Without this, you are
# defining a type, not instantiating an object.
vec = \
GenObject._rootObjectDict[objName] = \
ROOT.std.vector( rootObj )()
branchName = objName + "s"
vecName = "vector<%s>" % classname
tree.Branch( branchName, vecName, vec)
# end else if isSingleton
# end for objName
return rootfile, tree
@staticmethod
def setupDiffOutputTree (outputFile, diffName, missingName,
diffDescription = '', missingDescription = ''):
"""Opens the diff output file, loads all of the necessary
shared object libraries, and returns the output file and tree.b"""
rootfile = ROOT.TFile.Open (outputFile, "recreate")
GenObject._loadGoRootLibrary()
# diff tree
diffTree = ROOT.TTree (diffName, diffDescription)
runEventObject = getattr (ROOT, 'go_runevent')()
diffTree.Branch ('runevent', 'go_runevent', runEventObject)
GenObject._rootClassDict['runevent'] = runEventObject
for objName in sorted (GenObject._objsDict.keys()):
if objName == 'runevent': continue
classname = GenObject.rootClassName (objName)
GenObject._rootClassDict[classname] = getattr (ROOT, classname)
contName = GenObject.rootDiffContClassName (objName)
diffName = GenObject.rootDiffClassName (objName)
rootObj = GenObject._rootClassDict[contName] = \
getattr (ROOT, contName)
GenObject._rootClassDict[diffName] = getattr (ROOT, diffName)
obj = GenObject._rootObjectDict[objName] = rootObj()
diffTree.Branch (objName, contName, obj)
# missing tree
missingTree = ROOT.TTree (missingName, missingDescription)
rootRunEventClass = getattr (ROOT, 'go_runevent')
firstOnly = GenObject._rootClassDict['firstOnly'] = \
ROOT.std.vector( rootRunEventClass ) ()
secondOnly = GenObject._rootClassDict['secondOnly'] = \
ROOT.std.vector( rootRunEventClass ) ()
missingTree.Branch ('firstOnly', 'vector<go_runevent>', firstOnly)
missingTree.Branch ('secondOnly', 'vector<go_runevent>', secondOnly)
return rootfile, diffTree, missingTree
@staticmethod
def _fillRootObjects (event):
"""Fills root objects from GenObject 'event'"""
for objName, obj in sorted (event.items()):
if GenObject.isSingleton (objName):
# Just one
GenObject._rootObjectCopy (obj,
GenObject._rootObjectDict[objName])
else:
# a vector
vec = GenObject._rootObjectDict[objName]
vec.clear()
for goObj in obj:
vec.push_back( GenObject._rootObjectClone (goObj) )
@staticmethod
def _fillRootDiffs (event1, event2):
"""Fills root diff containers from two GenObject 'event's"""
@staticmethod
def isSingleton (objName):
"""Returns true if object is a singleton"""
return GenObject._objsDict[objName].get('_singleton')
@staticmethod
def loadEventFromTree (eventTree, eventIndex,
onlyRunEvent = False):
"""Loads event information from Root file (as interfaced by
'cmstools.EventTree' or 'ROOT.TChain'). Returns a dictionary
'event' containing lists of objects or singleton object. If
'onlyRunEvent' is et to True, then only run and event number
is read in from the tree."""
debug = GenObject._kitchenSinkDict.get ('debug', False)
tupleName = GenObject._kitchenSinkDict[eventTree]['tupleName']
event = {}
# is this a cint tree
isChain = eventTree.__class__.__name__ == 'TChain'
if isChain:
# This means that 'eventTree' is a ROOT.TChain
eventTree.GetEntry (eventIndex)
else:
# This means that 'eventTree' is a FWLite Events
eventTree.to(eventIndex)
tofillDict = GenObject._tofillDict.get (tupleName)
ntupleDict = GenObject._ntupleDict.get (tupleName)
if not tofillDict:
print("Don't know how to fill from '%s' ntuple." % tupleName)
return
eventBranchName = ntupleDict['runevent']
for objName in tofillDict:
branchName = ntupleDict[objName]
if onlyRunEvent and branchName != eventBranchName:
# not now
continue
# Have we been given 'tofill' info for this object?
if not branchName:
# guess not
continue
if isChain:
# Root TChain
objects = getattr (eventTree, branchName)
else:
# FWLite
shortcut = ntupleDict.get('_shortcut', {}).get(branchName)
if shortcut:
objects = GenObject.evaluateFunction (eventTree, shortcut)
else:
eventTree.toBegin()
handle = ntupleDict.get('_handle', {}).get(branchName)
label = ntupleDict.get('_label' , {}).get(branchName)
if not handle or not label:
raise RuntimeError("Missing handle or label for '%s'"\
% branchName)
if not eventTree.getByLabel (label, handle):
raise RuntimeError("not able to get %s for %s" \
% (label, branchName))
objects = handle.product()
# is this a singleton?
if GenObject.isSingleton (objName):
event[objName] = GenObject.\
_genObjectClone (objName,
tupleName,
objects)
continue
# if we're here then we have a vector of items
if debug: warn (objName, spaces = 3)
event[objName] = []
for index, obj in enumerate (objects):
event[objName].append( GenObject.\
_genObjectClone (objName,
tupleName,
obj,
index) )
del objects
# end for obj
## if not isChain:
## del rootEvent
# end for objName
return event
@staticmethod
def printEvent (event):
"""Prints out event dictionary. Mostly for debugging"""
# Print out all singletons first
for objName, obj in sorted (event.items()):
#obj = event[objName]
# is this a singleton?
if GenObject.isSingleton (objName):
print("%s: %s" % (objName, obj))
# Now print out all vectors
for objName, obj in sorted (event.items()):
#obj = event[objName]
# is this a singleton?
if not GenObject.isSingleton (objName):
# o.k. obj is a vector
print("%s:" % objName)
for single in obj:
print(" ", single)
print()
@staticmethod
def setAliases (eventTree, tupleName):
"""runs SetAlias on all saved aliases"""
aliases = GenObject._ntupleDict[tupleName].get('_alias', {})
for name, alias in aliases.items():
eventTree.SetAlias (name, alias)
@staticmethod
def changeAlias (tupleName, name, alias):
"""Updates an alias for an object for a given tuple"""
aliasDict = GenObject._ntupleDict[tupleName]['_alias']
if name not in aliasDict:
raise RuntimeError("unknown name '%s' in tuple '%s'" % \
(name, tupleName))
aliasDict[name] = alias
@staticmethod
def changeLabel (tupleName, objectName, label):
"""Updates an label for an object for a given tuple"""
labelDict = GenObject._ntupleDict[tupleName]['_label']
if objectName not in labelDict:
raise RuntimeError("unknown name '%s' in tuple '%s'" % \
(objectName, tupleName))
label = tuple( GenObject._commaRE.split( label ) )
labelDict[objectName] = label
@staticmethod