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

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
            TriggerFlags.doMergedHLTResult = False
43
            log.info("decoding version set to 1, because running on BS file from Run1")
44
45
46
47
48
49
50
            pass
    else:
        #Pool files
        from RecExConfig.ObjKeyStore import cfgKeyStore
        ItemDic=inputFileSummary.get("eventdata_itemsDic")
        ItemList=inputFileSummary.get('eventdata_itemsList')

51
        TriggerFlags.doMergedHLTResult = True
52
53
        if cfgKeyStore.isInInputFile( "HLTResult", "HLTResult_EF" ):          
            TriggerFlags.EDMDecodingVersion = 1
54
            TriggerFlags.doMergedHLTResult = False
55
            log.info("Decoding version set to 1, because HLTResult_EF found in pool file")
56
57
        elif cfgKeyStore.isInInputFile( "HLTResult", "HLTResult_HLT"):          
            TriggerFlags.EDMDecodingVersion = 2
58
59
        elif cfgKeyStore.isInInputFile( "xAOD::TrigCompositeContainer", "HLTSummary"):          
            TriggerFlags.EDMDecodingVersion = 3
60
        else:
61
            log.warning("Cannot recognise HLT EDM format, TriggerFlags.EDMDecodingVersion=%d" % TriggerFlags.EDMDecodingVersion())
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
        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:
    

94
    log.info("EDMDecoding set to %s"%TriggerFlags.EDMDecodingVersion )
95
96
97
98
99
  
    return  True
        


100
101
102
103
104
105
106
107
108
109
110
111
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()
112

113
114
        from TrigEDMConfig.TriggerEDM import getPreregistrationList,getL2PreregistrationList,getEFPreregistrationList
        from TrigEDMConfig.TriggerEDM import getEFRun1BSList,getEFRun2EquivalentList,getL2Run1BSList,getL2Run2EquivalentList#,getHLTPreregistrationList
115
116
117
118
119
120
121
        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()))
122
123

        #we attempt to convert the entire old navigation (L2+EF)
124
125
126
127
        #xaodconverter.BStoxAOD.ContainersToConvert = list(set(getL2PreregistrationList()+getEFPreregistrationList()))
        # we want only containers from Run 1 with the BS tag
        xaodconverter.BStoxAOD.ContainersToConvert = getL2Run1BSList() + getEFRun1BSList()
        xaodconverter.BStoxAOD.NewContainers = getL2Run2EquivalentList() + getEFRun2EquivalentList()
128
129
130
131

        xaodconverter.HLTResultKey="HLTResult_EF"
        topSequence += xaodconverter

132
133
134
135
136
137
        # 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 ))

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
        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()
175
176

            from TrigEDMConfig.TriggerEDM import getEDMLibraries
177
            extr.Navigation.Dlls = getEDMLibraries()            
178
179
180
181
182

            from TrigEDMConfig.TriggerEDM import getPreregistrationList
            extr.Navigation.ClassesToPreregister = getPreregistrationList(TriggerFlags.EDMDecodingVersion())
            
            if TriggerFlags.doMergedHLTResult():
183
184
                extr.L2ResultKey=""
                extr.EFResultKey=""
185
186
            else:
                extr.HLTResultKey=""
187
188
189
190
191
192
193
194
195
196
197
198

            #
            # 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 ]

199
200
201
202
203
204
        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=""
205
            extr.DSResultKeys=[]
206
207
208
209
210
211
212
213
214

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

        from AthenaCommon.AppMgr import ToolSvc
        ToolSvc += TrigSerToolTP
        from TrigEDMConfig.TriggerEDM import getTPList
215
        TrigSerToolTP.TPMap = getTPList((TriggerFlags.EDMDecodingVersion()))
216
217
218
219
220
        
        from TrigSerializeCnvSvc.TrigSerializeCnvSvcConf import TrigSerializeConvHelper
        TrigSerializeConvHelper = TrigSerializeConvHelper(doTP = True)
        ToolSvc += TrigSerializeConvHelper

221
222
223
224
        #
        # Configure L1Topo validation data algorithm
        #
        if hasHLT and TriggerFlags.doMergedHLTResult() and TriggerFlags.writeL1TopoValData() :
225
226
227
228
            # make sure that CTP_RDO is known (see also ATR-14683)
            ServiceMgr.ByteStreamAddressProviderSvc.TypeNames += [
                "CTP_RDO/CTP_RDO"
                ]
229
230
231
232
            from L1TopoValDataCnv.L1TopoValDataCnvConf import xAODMaker__L1TopoValDataCnvAlg
            L1TopoValDataCvnAlg = xAODMaker__L1TopoValDataCnvAlg()
            topSequence += L1TopoValDataCvnAlg

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        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 \
252
               ( not ( rec.readAOD() or rec.readESD() or rec.doWriteBS()) ):
253
            log.info("Will write TrigDecision object to storegate")
254
            
255
256
            from TrigDecisionMaker.TrigDecisionMakerConfig import WriteTrigDecision
            trigDecWriter = WriteTrigDecision()
257
258
259
260

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

261
262
263
264
265
266
267
268
            # 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
269
            # Decide based on the doMergedHLTResult to assume a merged, or a
270
271
272
273
274
275
276
277
278
279
            # 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")
280
    
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        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
299
                    type,key=getTypeAndKey("TrigOperationalInfo#HLT_EXPRESS_OPI_HLT")
300
301
                    if EDMDetails[type].has_key('collection'):
                        colltype = EDMDetails[type]['collection']
302
                        log.info("Adding HLT_EXPRESS_OPI_HLT to ESD for stream "+stream)                        
303
304
305
306
                        from RecExConfig.ObjKeyStore import objKeyStore
                        objKeyStore.addStreamESD(colltype, key)
                    return True
            else:
307
                log.warning("Could not determine stream of bytestream file, not adding HLT_EXPRESS_OPI_HLT to ESD.")
308
309
310
311
312
313
314
        return False

    def configure(self):

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

315
316
        # set EDMDecodingVersion
        EDMDecodingVersion()
317

318
319
320
321
        # Set AODFULL for data unless it was set explicitly already
        if TriggerFlags.AODEDMSet.isDefault() and globalflags.DataSource()=='data':
            TriggerFlags.AODEDMSet = 'AODFULL'
            
322
323
324
325
326
327
        from AthenaCommon.AlgSequence import AlgSequence
        topSequence = AlgSequence()
        log.info("BS unpacking (TF.readBS): %d" % TriggerFlags.readBS() )
        if TriggerFlags.readBS():
            bs = ByteStreamUnpackGetter()

328
329
330
331
332
        xAODContainers = {}
#        if not recAlgs.doTrigger():      #only convert when running on old data
        if TriggerFlags.EDMDecodingVersion()==1:
            xaodcnvrt = xAODConversionGetter()
            xAODContainers = xaodcnvrt.xaodlist
333
334

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

362
363
364
365
366
367
        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.")
368

369
        if rec.doAOD() or rec.doWriteAOD():
370
371
372
373
374
375
376
            # schedule the RoiDescriptorStore conversion
            # log.warning( "HLTTriggerResultGetter - setting up RoiWriter" )
            topSequence += RoiWriter()
            # write out the RoiDescriptorStores
            from TrigEDMConfig.TriggerEDM import TriggerRoiList
            objKeyStore.addManyTypesStreamAOD( TriggerRoiList )

377
378
379
        #Are we adding operational info objects in ESD?
        added=self._AddOPIToESD()
        if added:
380
            log.debug("Operational Info object HLT_EXPRESS_OPI_HLT with extra information about express stream prescaling added to the data.")
381
382
383
384
385
386
        


        # ESD objects definitions
        _TriggerESDList = {}

387
        from TrigEDMConfig.TriggerEDM import getTriggerEDMList 
388
389
390
391
392
393
394
        # 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()) ) 
        
395
        log.info("ESD content set according to the ESDEDMSet flag: %s and EDM version %d" % (TriggerFlags.ESDEDMSet() ,TriggerFlags.EDMDecodingVersion()) )
396
397
398
399

        # AOD objects choice
        _TriggerAODList = {}
        
400
401
        #from TrigEDMConfig.TriggerEDM import getAODList    
        _TriggerAODList.update( getTriggerEDMList(TriggerFlags.AODEDMSet(),  TriggerFlags.EDMDecodingVersion()) ) 
402

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

405
406
        log.debug("ESD EDM list: %s", _TriggerESDList)
        log.debug("AOD EDM list: %s", _TriggerAODList)
407
        
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
        # 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()
423
            from TrigNavTools.TrigNavToolsConf import HLT__StreamTrigNavSlimming, HLT__TrigNavigationSlimming
424
425
            from TrigNavTools.TrigNavToolsConfig import navigationSlimming

426
427
            edmlist = list(y.split('-')[0] for x in edm.values() for y in x) #flatten names
          
428
            # from HLT result drop unrecorded features
429
430
431
            # slimmerHLT = HLT__StreamTrigNavSlimming('HLTNavSlimmer_%s'%stream)
            slimmerHLT = HLT__TrigNavigationSlimming('TrigNavigationSlimmer_%s'%stream)
            tHLT = navigationSlimming({'name':'HLTNav_%s'%stream, 'mode':'cleanup', 
432
433
434
                                                          'ThinningSvc':thinningSvc, 'result':'HLTResult_HLT',
                                                          'features':edmlist})
            #tHLT.SlimmingTool.OutputLevel=DEBUG
435
            tHLT.ActInPlace=True
436
            slimmerHLT.ThinningTool = tHLT
437
            print slimmerHLT.ThinningTool
438
            topSequence += slimmerHLT
439
            log.info("Configured slimming of HLT")
440
441
442
443
444
445
            del edmlist


        from AthenaCommon.AppMgr import ServiceMgr as svcMgr
        from AthenaServices.Configurables import ThinningSvc, createThinningSvc
        
446
        if TriggerFlags.doNavigationSlimming() and rec.readRDO() and rec.doWriteAOD():
447
448
            if not hasattr(svcMgr, 'ThinningSvc'): # if the default is there it is configured for AODs
                svcMgr += ThinningSvc(name='ThinningSvc', Streams=['StreamAOD'])             
449
            _addSlimming('StreamAOD', svcMgr.ThinningSvc, _TriggerESDList ) #Use ESD item list also for AOD!
450
451
            log.info("configured navigation slimming for AOD output")
            
452
        if TriggerFlags.doNavigationSlimming() and rec.readRDO() and rec.doWriteESD():
453
454
            if not  hasattr(svcMgr, 'ESDThinningSvc'):
                svcMgr += ThinningSvc(name='ESDThinningSvc', Streams=['StreamESD']) # the default is configured for AODs
455
456
457
458
459
460
            _addSlimming('StreamESD', svcMgr.ESDThinningSvc, _TriggerESDList )                
            log.info("configured navigation slimming for ESD output")              
            



461
462
463
464
465
466
467
468
469
        objKeyStore.addManyTypesStreamESD( _TriggerESDList )                        
        objKeyStore.addManyTypesStreamAOD( _TriggerAODList )        
            
        return True