HLTTriggerResultGetter.py 20 KB
Newer Older
1
2
3
# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration

from TriggerJobOpts.TriggerFlags import TriggerFlags
4
from AthenaCommon.Logging import logging
5
from AthenaCommon.Include import include
6
from AthenaCommon.GlobalFlags import globalflags
7
8
9
10
11
12
13
14
15
16
17
18
from RegionSelector.RegSelSvcDefault import RegSelSvcDefault

from AthenaCommon.AppMgr import ServiceMgr, ToolSvc, theApp
from AthenaCommon.Include import include

from RecExConfig.Configured import Configured

from AthenaCommon.Constants import VERBOSE, DEBUG, INFO, ERROR
from TriggerJobOpts.TriggerFlags import TriggerFlags
from RecExConfig.RecAlgsFlags import recAlgs
from RecExConfig.RecFlags import rec

19
20
from TrigRoiConversion.TrigRoiConversionConf import RoiWriter

21

22
23
24
25
26
27
28
29
30
31
32
33
def  EDMDecodingVersion():

    log = logging.getLogger("EDMDecodingVersion.py")

    # change version only if not rerunning the trigger    
    TriggerFlags.EDMDecodingVersion = 2

    # run the AutoConfiguration
    from RecExConfig.AutoConfiguration import ConfigureInputType
    #ConfigureInputType()
    from RecExConfig.InputFilePeeker import inputFileSummary
    
34
35
    if globalflags.InputFormat.is_bytestream():
        # BYTESTREAM: decide Run1/Run2 based on Run number
36
37
38
39
40
41
        from RecExConfig.AutoConfiguration  import GetRunNumber
        runNumber = GetRunNumber()

        #Run1 data
        if runNumber > 0 and runNumber < 230000 :            
            TriggerFlags.EDMDecodingVersion = 1
42
            log.info("decoding version set to 1, because running on BS file from Run1")
43
44
45
46
47
48
49
50
51
            pass
    else:
        #Pool files
        from RecExConfig.ObjKeyStore import cfgKeyStore
        ItemDic=inputFileSummary.get("eventdata_itemsDic")
        ItemList=inputFileSummary.get('eventdata_itemsList')

        if cfgKeyStore.isInInputFile( "HLTResult", "HLTResult_EF" ):          
            TriggerFlags.EDMDecodingVersion = 1
52
            log.info("Decoding version set to 1, because HLTResult_EF found in pool file")
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
        elif cfgKeyStore.isInInputFile( "HLTResult", "HLTResult_HLT"):          
            TriggerFlags.EDMDecodingVersion = 2
        else:
            log.warning("No HLTResult found in pool file")
        pass
    pass
                




    ## if not (rec.readESD() or rec.readAOD()):
    ##     log.info("FPP Found rec.RunNumber=%s and autoConfiguration.RunNumber=%s"# and svcMgr.EventSelector.RunNumber=%s"
    ##              %(str(rec.RunNumber()),str(GetRunNumber())))#, str(svcMgr.EventSelector.RunNumber())))
            
         
                
        ## inputIsSimulation = False
        ## if inputFileSummary.has_key("evt_type"):
        ##     eventTypeList = inputFileSummary.get("evt_type")
        ##     if eventTypeList.__contains__("IS_SIMULATION") :
        ##         print "FPP Detected that the input file is a simulated dataset"
        ##         inputIsSimulation = True
        ##         pass
        ##     pass

            #from ByteStreamCnvSvc.ByteStreamCnvSvcConf import ByteStreamCnvSvc

            #    from AthenaCommon.GlobalFlags  import globalflags
            ## from RecExConfig.AutoConfiguration  import GetProjectName
            ## print "FPP projectName=%s"%str(GetProjectName())
        # Run1 data  

    # ESD/AOD files:
    

89
    log.info("EDMDecoding set to %s"%TriggerFlags.EDMDecodingVersion )
90
91
92
93
94
  
    return  True
        


95
96
97
98
99
100
101
102
103
104
105
106
class xAODConversionGetter(Configured):
    def configure(self):
        log = logging.getLogger('xAODConversionGetter.py')
        from AthenaCommon.AlgSequence import AlgSequence 
        topSequence = AlgSequence()

        #schedule xAOD conversions here
        from TrigBSExtraction.TrigBSExtractionConf import TrigHLTtoxAODConversion
        xaodconverter = TrigHLTtoxAODConversion()
        
        from TrigNavigation.TrigNavigationConfig import HLTNavigationOffline
        xaodconverter.Navigation = HLTNavigationOffline()
107

108
109
110
111
112
113
114
115
        from TrigEDMConfig.TriggerEDM import getPreregistrationList,getL2PreregistrationList,getEFPreregistrationList#,getHLTPreregistrationList
        xaodconverter.Navigation.ClassesToPreregister = getPreregistrationList(TriggerFlags.EDMDecodingVersion())
        ## if TriggerFlags.EDMDecodingVersion() == 2:
        ##     #        if TriggerFlags.doMergedHLTResult():
        ##     #if EDMDecodingVersion() =='Run2': #FPP
        ##     xaodconverter.Navigation.ClassesToPreregister = getHLTPreregistrationList()
        ## else:
        ##     xaodconverter.Navigation.ClassesToPreregister = list(set(getL2PreregistrationList()+getEFPreregistrationList()+getHLTPreregistrationList()))
116
117
118
119
120
121
122

        #we attempt to convert the entire old navigation (L2+EF)
        xaodconverter.BStoxAOD.ContainersToConvert = list(set(getL2PreregistrationList()+getEFPreregistrationList()))

        xaodconverter.HLTResultKey="HLTResult_EF"
        topSequence += xaodconverter

123
124
125
126
127
128
        # define list of HLT xAOD containers to be written to the output root file
        # (previously this was defined in HLTTriggerResultGetter def configure)
        from TrigEDMConfig.TriggerEDM import getTriggerEDMList
        self.xaodlist = {}
        self.xaodlist.update( getTriggerEDMList(TriggerFlags.ESDEDMSet(), 2 ))

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
        return True
    
        

class ByteStreamUnpackGetter(Configured):
    def configure(self):

        log = logging.getLogger("ByteStreamUnpackGetter.py")
        from AthenaCommon.AlgSequence import AlgSequence 
        topSequence = AlgSequence()
        
        #if TriggerFlags.readBS():
        log.info( "TriggerFlags.dataTakingConditions: %s" % TriggerFlags.dataTakingConditions() )
        # in MC this is always FullTrigger
        hasHLT = TriggerFlags.dataTakingConditions()=='HltOnly' or TriggerFlags.dataTakingConditions()=='FullTrigger'
        
        if hasHLT:
            from AthenaCommon.AppMgr import ServiceMgr
            # Decide based on the run number whether to assume a merged, or a
            # split HLT:
            if not TriggerFlags.doMergedHLTResult():
                ServiceMgr.ByteStreamAddressProviderSvc.TypeNames += [
                    "HLT::HLTResult/HLTResult_L2",
                    "HLT::HLTResult/HLTResult_EF" ]
            else:
                ServiceMgr.ByteStreamAddressProviderSvc.TypeNames += [
                    "HLT::HLTResult/HLTResult_HLT" ]
                pass
            pass

        # BS unpacking
        from TrigBSExtraction.TrigBSExtractionConf import TrigBSExtraction
        extr = TrigBSExtraction()
        
        if hasHLT:
            from TrigNavigation.TrigNavigationConfig import HLTNavigationOffline
            extr.Navigation = HLTNavigationOffline()
166
167

            from TrigEDMConfig.TriggerEDM import getEDMLibraries
168
            extr.Navigation.Dlls = getEDMLibraries()            
169
170
171
172
173

            from TrigEDMConfig.TriggerEDM import getPreregistrationList
            extr.Navigation.ClassesToPreregister = getPreregistrationList(TriggerFlags.EDMDecodingVersion())
            
            if TriggerFlags.doMergedHLTResult():
174
175
                extr.L2ResultKey=""
                extr.EFResultKey=""
176
177
            else:
                extr.HLTResultKey=""
178
179
180
181
182
183
184
185
186
187
188
189

            #
            # Configure DataScouting
            #
            from RecExConfig.InputFilePeeker import inputFileSummary
            if inputFileSummary['bs_metadata']['Stream'].startswith('calibration_DataScouting_') or TriggerFlags.doAlwaysUnpackDSResult():
                for stag in inputFileSummary['stream_tags']:
                    if (stag['stream_type'] == 'calibration') and (stag['stream_name'].startswith('DataScouting_')):
                        ds_tag = stag['stream_name'][0:15]
                        ServiceMgr.ByteStreamAddressProviderSvc.TypeNames += [ "HLT::HLTResult/"+ds_tag ]
                        extr.DSResultKeys += [ ds_tag ]

190
191
192
193
194
195
        else:            
            #if data doesn't have HLT info set HLTResult keys as empty strings to avoid warnings
            # but the extr alg must run
            extr.L2ResultKey=""
            extr.EFResultKey=""
            extr.HLTResultKey=""
196
            extr.DSResultKeys=[]
197
198
199
200
201
202
203
204
205

        topSequence += extr
        
        from TrigSerializeTP.TrigSerializeTPConf import TrigSerTPTool
        TrigSerToolTP = TrigSerTPTool('TrigSerTPTool')

        from AthenaCommon.AppMgr import ToolSvc
        ToolSvc += TrigSerToolTP
        from TrigEDMConfig.TriggerEDM import getTPList
206
        TrigSerToolTP.TPMap = getTPList((TriggerFlags.EDMDecodingVersion()))
207
208
209
210
211
        
        from TrigSerializeCnvSvc.TrigSerializeCnvSvcConf import TrigSerializeConvHelper
        TrigSerializeConvHelper = TrigSerializeConvHelper(doTP = True)
        ToolSvc += TrigSerializeConvHelper

212
213
214
215
216
217
218
219
        #
        # Configure L1Topo validation data algorithm
        #
        if hasHLT and TriggerFlags.doMergedHLTResult() and TriggerFlags.writeL1TopoValData() :
            from L1TopoValDataCnv.L1TopoValDataCnvConf import xAODMaker__L1TopoValDataCnvAlg
            L1TopoValDataCvnAlg = xAODMaker__L1TopoValDataCnvAlg()
            topSequence += L1TopoValDataCvnAlg

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        return True


class TrigDecisionGetter(Configured):
    #class to setup the writing or just making of TrigDecisionObject
    def configure(self):
        
        log = logging.getLogger("TrigDecisionGetter")

        from AthenaCommon.AlgSequence import AlgSequence 
        topSequence = AlgSequence()
        
        #if hasOnlyLVL1:
        #from RecExConfig.ObjKeyStore import objKeyStore
        #objKeyStore.addStreamESD('TrigDec::TrigDecision','TrigDecision')
        #objKeyStore.addStreamAOD('TrigDec::TrigDecision','TrigDecision')
        
        from RecExConfig.RecFlags import rec
        if ( rec.doWriteESD() or rec.doWriteAOD() or rec.doESD() or rec.doAOD() ) and \
239
               ( not ( rec.readAOD() or rec.readESD() or rec.doWriteBS()) ):
240
            log.info("Will write TrigDecision object to storegate")
241
            
242
243
            from TrigDecisionMaker.TrigDecisionMakerConfig import WriteTrigDecision
            trigDecWriter = WriteTrigDecision()
244
245
246
247

#            from TrigDecisionMaker.TrigDecisionMakerConfig import WritexAODTrigDecision
#            trigDecWriter = WritexAODTrigDecision()

248
249
250
251
252
253
254
255
            # inform TD maker that some parts may be missing
            if TriggerFlags.dataTakingConditions()=='Lvl1Only':
                topSequence.TrigDecMaker.doL2=False
                topSequence.TrigDecMaker.doEF=False
                topSequence.TrigDecMaker.doHLT=False
            elif TriggerFlags.dataTakingConditions()=='HltOnly':
                from AthenaCommon.AlgSequence import AlgSequence
                topSequence.TrigDecMaker.doL1=False
256
            # Decide based on the doMergedHLTResult to assume a merged, or a
257
258
259
260
261
262
263
264
265
266
            # split HLT:
            if not TriggerFlags.doMergedHLTResult():
                topSequence.TrigDecMaker.doHLT = False
            else:
                topSequence.TrigDecMaker.doL2 = False
                topSequence.TrigDecMaker.doEF = False
                pass
                
        else:
            log.info("Will not write TrigDecision object to storegate")
267
    
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        return True
    
    
class HLTTriggerResultGetter(Configured):

    log = logging.getLogger("HLTTriggerResultGetter.py")

    def _AddOPIToESD(self):

        log = logging.getLogger("HLTTriggerResultGetter.py")        
        
        if rec.doESD():
            from RecExConfig.InputFilePeeker import inputFileSummary
            if inputFileSummary.has_key('bs_metadata') and inputFileSummary['bs_metadata'].has_key('Stream'):
                stream=inputFileSummary['bs_metadata']['Stream']
                log.debug("the stream found in 'bs_metadata' is "+stream)
                if "express" in stream:
                    from TrigEDMConfig.TriggerEDM import getTypeAndKey,EDMDetails
286
                    type,key=getTypeAndKey("TrigOperationalInfo#HLT_EXPRESS_OPI_HLT")
287
288
                    if EDMDetails[type].has_key('collection'):
                        colltype = EDMDetails[type]['collection']
289
                        log.info("Adding HLT_EXPRESS_OPI_HLT to ESD for stream "+stream)                        
290
291
292
293
                        from RecExConfig.ObjKeyStore import objKeyStore
                        objKeyStore.addStreamESD(colltype, key)
                    return True
            else:
294
                log.warning("Could not determine stream of bytestream file, not adding HLT_EXPRESS_OPI_HLT to ESD.")
295
296
297
298
299
300
301
        return False

    def configure(self):

        log = logging.getLogger("HLTTriggerResultGetter.py")
        from RecExConfig.ObjKeyStore import objKeyStore

302
303
        # set EDMDecodingVersion
        EDMDecodingVersion()
304

305
306
307
308
        # Set AODFULL for data unless it was set explicitly already
        if TriggerFlags.AODEDMSet.isDefault() and globalflags.DataSource()=='data':
            TriggerFlags.AODEDMSet = 'AODFULL'
            
309
310
311
312
313
314
        from AthenaCommon.AlgSequence import AlgSequence
        topSequence = AlgSequence()
        log.info("BS unpacking (TF.readBS): %d" % TriggerFlags.readBS() )
        if TriggerFlags.readBS():
            bs = ByteStreamUnpackGetter()

315
316
317
318
319
        xAODContainers = {}
#        if not recAlgs.doTrigger():      #only convert when running on old data
        if TriggerFlags.EDMDecodingVersion()==1:
            xaodcnvrt = xAODConversionGetter()
            xAODContainers = xaodcnvrt.xaodlist
320
321

        if recAlgs.doTrigger() or TriggerFlags.doTriggerConfigOnly():
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
            tdt = TrigDecisionGetter()

        # TrigJetRec additions
        if rec.doWriteESD():
            objKeyStore.addStreamESD("JetKeyDescriptor","JetKeyMap")
            objKeyStore.addStreamESD("JetMomentMap","TrigJetRecMomentMap")

        if rec.doWriteAOD():
            objKeyStore.addStreamAOD("JetKeyDescriptor","JetKeyMap")
            objKeyStore.addStreamAOD("JetMomentMap","TrigJetRecMomentMap")
                    
        # ID truth
        if not rec.readESD() and (not rec.readAOD()) and TriggerFlags.doID() \
                and rec.doTruth():
            try:
                from TrigInDetTruthAlgs.TrigInDetTruthAlgsConfig import \
                    TrigIDTruthMaker
                topSequence += TrigIDTruthMaker()
            except Exception:
                log.warning( "Couldn't set up the trigger ID truth maker" )
                pass

        if rec.doESD() or rec.doAOD():
            from TrigEDMConfig.TriggerEDM import getTrigIDTruthList
            objKeyStore.addManyTypesStreamESD(getTrigIDTruthList(TriggerFlags.ESDEDMSet()))
            objKeyStore.addManyTypesStreamAOD(getTrigIDTruthList(TriggerFlags.AODEDMSet()))

349
350
351
352
353
354
        if (rec.doESD() or rec.doAOD()) and TriggerFlags.writeL1TopoValData():
            objKeyStore.addManyTypesStreamESD(['xAOD::TrigCompositeContainer#HLT_xAOD__TrigCompositeContainer_L1TopoValData',
                                               'xAOD::TrigCompositeAuxContainer#HLT_xAOD__TrigCompositeContainer_L1TopoValDataAux.'])
            objKeyStore.addManyTypesStreamAOD(['xAOD::TrigCompositeContainer#HLT_xAOD__TrigCompositeContainer_L1TopoValData',
                                               'xAOD::TrigCompositeAuxContainer#HLT_xAOD__TrigCompositeContainer_L1TopoValDataAux.'])
            log.debug("HLT_xAOD__TrigCompositeContainer_L1TopoValData(Aux.) for L1Topo validation added to the data.")
355

356
        if rec.doAOD() or rec.doWriteAOD():
357
358
359
360
361
362
363
            # schedule the RoiDescriptorStore conversion
            # log.warning( "HLTTriggerResultGetter - setting up RoiWriter" )
            topSequence += RoiWriter()
            # write out the RoiDescriptorStores
            from TrigEDMConfig.TriggerEDM import TriggerRoiList
            objKeyStore.addManyTypesStreamAOD( TriggerRoiList )

364
365
366
        #Are we adding operational info objects in ESD?
        added=self._AddOPIToESD()
        if added:
367
            log.debug("Operational Info object HLT_EXPRESS_OPI_HLT with extra information about express stream prescaling added to the data.")
368
369
370
371
372
373
        


        # ESD objects definitions
        _TriggerESDList = {}

374
        from TrigEDMConfig.TriggerEDM import getTriggerEDMList 
375
376
377
378
379
380
381
        # we have to store xAOD containers in the root file, NOT AOD,
        # if the xAOD container list is not empty
        if(xAODContainers):
            _TriggerESDList.update( xAODContainers )
        else:
            _TriggerESDList.update( getTriggerEDMList(TriggerFlags.ESDEDMSet(),  TriggerFlags.EDMDecodingVersion()) ) 
        
382
        log.info("ESD content set according to the ESDEDMSet flag: %s and EDM version %d" % (TriggerFlags.ESDEDMSet() ,TriggerFlags.EDMDecodingVersion()) )
383
384
385
386

        # AOD objects choice
        _TriggerAODList = {}
        
387
388
        #from TrigEDMConfig.TriggerEDM import getAODList    
        _TriggerAODList.update( getTriggerEDMList(TriggerFlags.AODEDMSet(),  TriggerFlags.EDMDecodingVersion()) ) 
389

390
391
        log.info("AOD content set according to the AODEDMSet flag: %s and EDM version %d" % (TriggerFlags.AODEDMSet(),TriggerFlags.EDMDecodingVersion()) )

392
393
        log.debug("ESD EDM list: %s", _TriggerESDList)
        log.debug("AOD EDM list: %s", _TriggerAODList)
394
        
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
        # Highlight what is in AOD list but not in ESD list, as this can cause
        # the "different number of entries in branch" problem, when it is in the
        # AOD list but the empty container per event is not created
        # Just compares keys of dicts, which are the class names, not their string keys in StoreGate
        not_in = [ element for element in  _TriggerAODList if element not in _TriggerESDList ]
        if (len(not_in)>0):
            log.warning("In AOD list but not in ESD list: ")
            log.warning(not_in)
        else:
            log.info("AOD list is subset of ESD list - good.")


        def _addSlimming(stream, thinningSvc, edm):
            from AthenaCommon.AlgSequence import AlgSequence 
            topSequence = AlgSequence()
410
            from TrigNavTools.TrigNavToolsConf import HLT__StreamTrigNavSlimming, HLT__TrigNavigationSlimming
411
412
            from TrigNavTools.TrigNavToolsConfig import navigationSlimming

413
414
            edmlist = list(y.split('-')[0] for x in edm.values() for y in x) #flatten names
          
415
            # from HLT result drop unrecorded features
416
417
418
            # slimmerHLT = HLT__StreamTrigNavSlimming('HLTNavSlimmer_%s'%stream)
            slimmerHLT = HLT__TrigNavigationSlimming('TrigNavigationSlimmer_%s'%stream)
            tHLT = navigationSlimming({'name':'HLTNav_%s'%stream, 'mode':'cleanup', 
419
420
421
                                                          'ThinningSvc':thinningSvc, 'result':'HLTResult_HLT',
                                                          'features':edmlist})
            #tHLT.SlimmingTool.OutputLevel=DEBUG
422
            tHLT.ActInPlace=True
423
            slimmerHLT.ThinningTool = tHLT
424
            print slimmerHLT.ThinningTool
425
            topSequence += slimmerHLT
426
            log.info("Configured slimming of HLT")
427
428
429
430
431
432
433
            del edmlist


        from AthenaCommon.AppMgr import ServiceMgr as svcMgr
        from AthenaServices.Configurables import ThinningSvc, createThinningSvc
        
        _doSlimming = True
434
        if _doSlimming and rec.doWriteAOD() and not (rec.readAOD() or rec.readESD()): 
435
436
437
438
439
            if not hasattr(svcMgr, 'ThinningSvc'): # if the default is there it is configured for AODs
                svcMgr += ThinningSvc(name='ThinningSvc', Streams=['StreamAOD'])             
            _addSlimming('StreamAOD', svcMgr.ThinningSvc, _TriggerAODList )
            log.info("configured navigation slimming for AOD output")
            
440
        if _doSlimming and rec.doWriteESD() and not rec.readESD(): 
441
442
443
444
445
            svcMgr += ThinningSvc(name='ESDThinningSvc', Streams=['StreamESD']) # the default is configured for AODs
            # this was recommended but does not work
            # from OutputStreamAthenaPool.MultipleStreamManager import MSMgr
            # svcMgr += createThinningSvc(svcName="ESDThinningSvc", outStreams=[MSMgr.GetStream('StreamESD').GetEventStream()])

446
447
448
449
450
451
            _addSlimming('StreamESD', svcMgr.ESDThinningSvc, _TriggerESDList )                
            log.info("configured navigation slimming for ESD output")              
            



452
453
454
455
456
457
458
459
460
        objKeyStore.addManyTypesStreamESD( _TriggerESDList )                        
        objKeyStore.addManyTypesStreamAOD( _TriggerAODList )        
            
        return True