6 from TriggerMenuMT.HLT.Config.Utility.HLTMenuConfig
import HLTMenuConfig
8 from AthenaCommon.Logging
import logging
9 log = logging.getLogger(__name__)
13 return [
'Streaming',
'Monitor',
'Beamspot',
'Cosmic',
'Calib',
'EnhancedBias']
16 return [
'MinBias',
'Electron',
'Photon',
'Muon',
'Tau',
'Jet',
'Bjet',
'MET',
'UnconventionalTracking',
'HeavyIon']
19 return [
'Bjet',
'Egamma',
'Combined']
36 class to use filters for chains
39 self.
enabledSignatures = flags.Trigger.enabledSignatures
if flags.hasFlag(
"Trigger.enabledSignatures")
else []
40 self.
disabledSignatures = flags.Trigger.disabledSignatures
if flags.hasFlag(
"Trigger.disabledSignatures")
else []
41 self.
selectChains = flags.Trigger.selectChains
if flags.hasFlag(
"Trigger.selectChains")
else []
42 self.
disableChains = flags.Trigger.disableChains
if flags.hasFlag(
"Trigger.disableChains")
else []
60 """Singleton class for trigger menu"""
65 signatureDeps = {sig:[sig]
for sig
in allSigs}
67 signatureDeps.update({
69 'Bjet': [
'Bjet',
'Jet'],
71 'Egamma': [
'Electron',
'Photon'],
97 """Set chain filter for menu generation.
99 This can be any callable object taking two
100 arguments for signature and chain name and returning a boolean.
101 E.g. to only generate Egamma chains:
102 menu.setChainFilter(lambda slice,chain : slice=='Egamma').
104 In the special case that f is a functor with the list attributes
105 selectChains and/or disableChains, the contents will be explicitly
106 checked to be in the menu.
108 fname = f.__class__.__name__
if isinstance(f,object)
else f.__name__
110 if len(inspect.signature(f).parameters)!=2:
111 log.error(
'%s is not a valid chain filter. Function/callable needs take two arguments '
112 'for signature and chain name and return a boolean', fname)
114 log.warning(
'Setting chain filter to %s', fname)
120 def validSignature(currentSig, chainSig):
121 """Check if chain is assigned to the correct signature"""
122 reqd = GenerateMenuMT.getRequiredSignatures(currentSig)
123 isValid = chainSig.issubset( reqd )
124 log.debug(
"Chain signatures: %s, required signatures: %s",chainSig,reqd)
126 log.error(
"Chain signatures %s not a subset of required signatures %s",
set(chainSig),reqd)
129 from TriggerMenuMT.HLT.Config.Utility.DictFromChainName
import dictFromChainName
135 log.debug(
"Now processing chain: %s from signature %s", chain, sig)
138 chainDict[
'chainCounter'] = chainCounter
139 chainDict[
'prescale'] = 1
142 for sigfo, subsig
in chainDict[
'sigDicts'].
items():
152 if not validSignature(sig,
set(chainDict[
'signatures'])):
154 log.error(
'Chain %s assigned to signature %s but creates %s',
155 chainDict[
'chainName'], sig,
set(chainDict[
'signatures']))
157 raise RuntimeError(
'Incorrect assignment of chains to slices -- see preceding messages.')
160 """check if all the signature files can be imported and then import them"""
165 import_module =
'TriggerMenuMT.HLT.' + sig +
'.Generate' + ss +
'ChainDefs'
172 log.exception(
'Problems when importing ChainDef generating code for %s', sig)
174 traceback.print_exc()
182 combinations_in_menu = []
183 alignmentGroups_to_align =
set()
184 length_of_configs = {}
187 notify_increment =
max(
int(nchainDicts / 10),1)
188 for ichainDict, chainDict
in enumerate(self.
chainDicts):
189 log.debug(
"Next: getting chain configuration for chain %s ", chainDict[
'chainName'])
190 if ichainDict % notify_increment==0:
191 log.info(
"Generating HLT chain %d / %d", ichainDict+1, nchainDicts)
193 all_chains += [(chainDict,chainConfig,lengthOfChainConfigs)]
197 for config_length, config_grp
in lengthOfChainConfigs:
198 if config_grp
in length_of_configs:
199 if config_length > length_of_configs[config_grp]:
200 length_of_configs[config_grp] = config_length
202 length_of_configs[config_grp] = config_length
207 if len(
set(chainDict[
'alignmentGroups'])) > 1:
208 combinations_in_menu += [
list(
set(chainDict[
'alignmentGroups']))]
209 for align_group
in list(
set(chainDict[
'alignmentGroups'])):
210 alignmentGroups_to_align.update([align_group])
222 == Obtains chain configs for all chains in menu
225 from TriggerMenuMT.HLT.Config.Utility.MenuAlignmentTools
import MenuAlignment
226 from TriggerMenuMT.HLT.CommonSequences
import EventBuildingSequences, TLABuildingSequences
229 log.info(
"Will now get chains from the menu")
233 log.info(
"Will now get chain dictionaries for each chain")
236 if flags.Trigger.disableCPS:
237 log.warning(
'Removing all CPS group because the flag Trigger.disableCPS is set')
239 chainDict[
'groups'] = [g
for g
in chainDict[
'groups']
if not g.startswith(
'RATE:CPS_')]
242 log.debug(
"Importing the necessary signatures")
245 log.info(
"Will now generate the chain configuration for each chain")
248 log.info(
"Will now calculate the alignment parameters")
254 menuAlignment.analyse_combinations()
261 log.info(
'Aligning the following signatures: %s',
sorted(menuAlignment.sets_to_align))
262 log.debug(
'Length of each of the alignment groups: %s',self.
configLengthDict)
277 log.debug(
"[generateAllChainConfigs] chain %s has config lengths %s and alignment groups %s", chainDict[
'chainName'], lengthOfChainConfigs, chainDict[
'alignmentGroups'])
279 alignmentGroups = chainDict[
'alignmentGroups']
282 if len(
set(alignmentGroups)) == 1:
283 alignedChainConfig = menuAlignment.single_align(chainDict, chainConfig)
284 HLTMenuConfig.registerChain( chainDict )
285 chainConfigs.append( alignedChainConfig )
287 elif len(alignmentGroups) >= 2:
288 alignedChainConfig = menuAlignment.multi_align(chainDict, chainConfig, lengthOfChainConfigs)
289 HLTMenuConfig.registerChain( chainDict )
290 chainConfigs.append( alignedChainConfig )
293 log.error(
"Menu can't deal with combined chains with more than two alignmentGroups at the moment. oops...")
294 raise NotImplementedError(
"more than three alignment groups still needs implementing in ChainMerging.py, ATR-22206")
296 if not HLTMenuConfig.isChainRegistered(chainDict[
'chainName']):
297 log.error(
"Chain %s has not been registered in the menu!", chainDict[
'chainName'])
299 pp = pprint.PrettyPrinter(indent=4, depth=8)
300 log.error(
'The chain dictionary is: %s', pp.pformat(chainDict))
301 raise Exception(
"Please fix the menu or the chain.")
304 log.info(
"[generateAllChainConfigs] general alignment complete, will now align TLA chains")
305 TLABuildingSequences.alignTLASteps(chainConfigs, HLTMenuConfig.dicts())
306 log.info(
"[generateAllChainConfigs] general and TLA alignment complete, will now align PEB chains")
307 EventBuildingSequences.alignEventBuildingSteps(chainConfigs, HLTMenuConfig.dicts())
309 log.info(
"[generateAllChainConfigs] all chain configurations have been generated.")
315 == Returns the list of chain names that are in the menu
317 from TriggerMenuMT.HLT.Menu.MenuPrescaleConfig
import MenuPrescaleConfig
322 log.debug(
"Setup HLT menu with prescales: %s", self.
HLTPrescales)
335 for chain
in chainsToCheck:
338 if chain
in [c.name
for c
in self.
chainsInMenu[signame]]:
342 raise RuntimeError(f
'Request to enable/disable chain {chain} that is not in menu')
349 log.warning(
"There seem to be no chains in the menu - please check")
350 elif log.isEnabledFor(logging.DEBUG):
352 log.debug(
"The following chains were found in the menu:")
358 # Assembles the chain configuration and returns a chain object with (name, L1see and list of ChainSteps)
361 from TriggerMenuMT.HLT.Config.Utility.ChainDictTools
import splitInterSignatureChainDict
362 from TriggerMenuMT.HLT.Config.Utility.ComboHypoHandling
import addTopoInfo, comboConfigurator, topoLegIndices
363 from TriggerMenuMT.HLT.Config.Utility.ChainMerging
import mergeChainDefs
364 from TriggerMenuMT.HLT.CommonSequences
import EventBuildingSequences, TLABuildingSequences
369 if log.isEnabledFor(logging.DEBUG):
371 pp = pprint.PrettyPrinter(indent=4, depth=8)
372 log.debug(
'dictionary is: %s', pp.pformat(chainDicts))
375 listOfChainConfigs = []
376 perSig_lengthOfChainConfigs = []
378 for chainPartDict
in chainDicts:
379 chainPartConfig =
None
380 currentSig = chainPartDict[
'signature']
381 currentAlignGroup =
None
382 if len(chainPartDict[
'chainParts']) == 1:
383 currentAlignGroup = chainPartDict[
'chainParts'][0][
'alignmentGroup']
385 chainName = chainPartDict[
'chainName']
386 log.debug(
'Checking chainDict for chain %s in signature %s, alignment group %s' , chainName, currentSig, currentAlignGroup)
390 log.debug(
"[__generateChainConfigs] Trying to get chain config for %s", currentSig)
391 if currentSig
in [
'Electron',
'Photon',
'Muon',
'Tau',
'Bphysics'] :
395 if currentSig ==
'Test' and isinstance(chainPartConfig, tuple):
396 chainPartConfig = chainPartConfig[0]
398 log.error(
'[__generateChainConfigs] Problems creating ChainDef for chain %s ', chainName)
399 log.error(
'[__generateChainConfigs] I am in chain part\n %s ', chainPartDict)
400 log.exception(
'[__generateChainConfigs] Full chain dictionary is\n %s ', mainChainDict)
401 raise Exception(
'[__generateChainConfigs] Stopping menu generation. Please investigate the exception shown above.')
403 log.error(
'Chain %s cannot be generated - Signature "%s" not available', chainPartDict[
'chainName'], currentSig)
405 raise Exception(
'Stopping the execution. Please correct the configuration.')
407 log.debug(
"Chain %s \n chain config: %s",chainPartDict[
'chainName'],chainPartConfig)
409 listOfChainConfigs.append(chainPartConfig)
410 log.debug(
"[__generateChainConfigs] adding to the perSig_lengthOfChainConfigs list (%s, %s)",chainPartConfig.nSteps,chainPartConfig.alignmentGroups)
411 perSig_lengthOfChainConfigs.append((chainPartConfig.nSteps,chainPartConfig.alignmentGroups))
416 lengthOfChainConfigs = []
417 for nSteps, aGrps
in perSig_lengthOfChainConfigs:
418 if len(nSteps) != len(aGrps):
419 log.error(
"Chain part has %s steps and %s alignment groups - these don't match!",nSteps,aGrps)
421 for a,b
in zip(nSteps,aGrps):
422 lengthOfChainConfigs.append((a,b))
427 if len(listOfChainConfigs) == 0:
428 raise Exception(
'[__generateChainConfigs] No Chain Configuration found for {0}'.
format(mainChainDict[
'chainName']))
430 if len(listOfChainConfigs)>1:
431 log.debug(
"Merging strategy from dictionary: %s", mainChainDict[
"mergingStrategy"])
432 theChainConfig, perSig_lengthOfChainConfigs =
mergeChainDefs(listOfChainConfigs, mainChainDict, perSig_lengthOfChainConfigs)
433 lengthOfChainConfigs = []
434 for nSteps, aGrps
in perSig_lengthOfChainConfigs:
435 if len(nSteps) != len(aGrps):
436 log.error(
"Post-merged chain part has %s steps and %s alignment groups - these don't match!",nSteps,aGrps)
438 for a,b
in zip(nSteps,aGrps):
439 lengthOfChainConfigs.append((a,b))
441 theChainConfig = listOfChainConfigs[0]
443 for topoID
in range(len(mainChainDict[
'extraComboHypos'])):
444 thetopo = mainChainDict[
'extraComboHypos'][topoID].strip(string.digits).rstrip(topoLegIndices)
445 theChainConfig.addTopo((comboConfigurator[thetopo],thetopo))
448 if len(theChainConfig.topoMap) > 0:
449 log.debug(
"Trying to add extra ComboHypoTool for %s",mainChainDict[
'extraComboHypos'])
450 addTopoInfo(theChainConfig,mainChainDict,listOfChainConfigs,lengthOfChainConfigs)
452 log.error(
'[__generateChainConfigs] Problems creating ChainDef for chain %s ', chainName)
453 log.error(
'[__generateChainConfigs] I am in the extraComboHypos section, for %s ', mainChainDict[
'extraComboHypos'])
454 log.exception(
'[__generateChainConfigs] Full chain dictionary is\n %s ', mainChainDict)
455 raise Exception(
'[__generateChainConfigs] Stopping menu generation. Please investigate the exception shown above.')
456 except AttributeError:
457 raise Exception(
'[__generateChainConfigs] Stopping menu generation. Please investigate the exception shown above.')
460 eventBuildType = mainChainDict[
'eventBuildType']
463 if 'PhysicsTLA' in eventBuildType:
464 log.debug(
"Adding TLA Step for chain %s", mainChainDict[
'chainName'])
465 TLABuildingSequences.addTLAStep(flags, theChainConfig, mainChainDict)
466 log.debug(
'Configuring event building sequence %s for chain %s', eventBuildType, mainChainDict[
'chainName'])
467 EventBuildingSequences.addEventBuildingSequence(flags, theChainConfig, eventBuildType, mainChainDict)
468 except TypeError
as ex:
470 raise Exception(
'[__generateChainConfigs] Stopping menu generation for EventBuilding/TLA sequences. Please investigate the exception shown above.')
472 log.debug(
'[__generateChainConfigs] lengthOfChainConfigs %s, ChainConfigs %s ', lengthOfChainConfigs, theChainConfig)
473 return theChainConfig,lengthOfChainConfigs
477 max_steps =
max([len(cc.steps)
for cc
in chainConfigs], default=0)
478 steps_are_empty = [
True for i
in range(0,max_steps)]
480 for cc
in chainConfigs:
481 for istep, the_step
in enumerate(cc.steps):
482 if not the_step.isEmpty:
483 steps_are_empty[istep] =
False
485 emptySteps.append(the_step)
487 log.debug(
"Are there any fully empty steps? %s", steps_are_empty)
488 log.debug(
"The empty step(s) and associated chain(s) are: %s", emptySteps)
489 empty_step_indices = [i
for i,is_empty
in enumerate(steps_are_empty)
if is_empty]
491 if len(empty_step_indices) == 0:
495 getattr(self.
chainFilter,
"disableChains",
False)
or \
496 getattr(self.
chainFilter,
"disabledSignatures",
False)
or \
497 getattr(self.
chainFilter,
"enabledSignatures",
False) )
501 raise Exception(
"[resolveEmptySteps] Please find the reason for this empty step and resolve it / remove it from the menu: %s", emptySteps)
503 log.info(
"Will now delete steps %s (indexed from zero)",empty_step_indices)
505 for cc
in chainConfigs:
508 for istep,step
in enumerate(cc.steps):
509 if istep
not in empty_step_indices:
518 == Main function to generates L1, L1Topo and HLT menu CA, using class GenerateMenuMT
522 from TrigConfigSvc.TrigConfigSvcCfg
import generateL1Menu, createL1PrescalesFileFromMenu
523 from TriggerMenuMT.HLT.Menu.MenuPrescaleConfig
import MenuPrescaleConfig
531 menu.setChainFilter(chainsToGenerate)
532 log.debug(
"Filtering chains = %d", (menu.chainFilter
is not None))
533 finalListOfChainConfigs = menu.generateAllChainConfigs(flags)
534 log.info(
"Length of FinalListOfChainConfigs %s", len(finalListOfChainConfigs))
537 log.info(
"Applying HLT prescales")
539 (menu.L1Prescales, menu.HLTPrescales, menu.chainsInMenu) =
MenuPrescaleConfig(HLTMenuConfig, flags)
540 from TriggerMenuMT.HLT.Menu.MenuPrescaleConfig
import applyHLTPrescale
541 applyHLTPrescale(HLTMenuConfig, menu.HLTPrescales, menu.signaturesOverwritten)
545 finalListOfChainConfigs = menu.resolveEmptySteps(finalListOfChainConfigs)
547 log.debug(
"finalListOfChainConfig %s", finalListOfChainConfigs)
548 log.info(
"Making the HLT configuration tree")
549 menuAcc, CFseq_list =
makeHLTTree(flags, finalListOfChainConfigs)
551 from TriggerJobOpts.TriggerConfigFlags
import ROBPrefetching
552 if ROBPrefetching.InitialRoI
in flags.Trigger.ROBPrefetchingOptions:
553 from TrigGenericAlgs.TrigGenericAlgsConfig
import prefetchingInitialRoIConfig
556 log.info(
"Checking the L1HLTConsistency...")
557 from TriggerMenuMT.HLT.Config.Validation.CheckL1HLTConsistency
import checkL1HLTConsistency
560 log.info(
"Checking the Coherent Prescale assignments...")
561 from TriggerMenuMT.HLT.Config.Validation.CheckCPSGroups
import checkCPSGroups
565 GenerateMenuMT.clear()
566 from TriggerMenuMT.HLT.Config
import MenuComponents
567 MenuComponents._ComboHypoPool.clear()
574 Generate appropriate Control Flow Graph wiht all HLT algorithms
576 from TriggerMenuMT.HLT.Config.ControlFlow.HLTCFConfig
import decisionTreeFromChains, sequenceScanner
577 from TriggerJobOpts.TriggerConfig
import collectViewMakers
578 from AthenaConfiguration.ComponentAccumulator
import ComponentAccumulator
579 from AthenaCommon.CFElements
import seqAND
582 steps =
seqAND(
'HLTAllSteps')
583 finalDecisions, CFseq_list, menuAcc =
decisionTreeFromChains(flags, steps, chainConfigs, HLTMenuConfig.dictsList())
584 if log.getEffectiveLevel() <= logging.DEBUG:
585 menuAcc.printConfig()
589 if not successful_scan:
590 raise Exception(
"[makeHLTTree] At least one sequence is expected in more than one step. Check error messages and fix!")
593 for step
in finalDecisions:
594 flatDecisions.extend (step)
597 viewMakerMap = {vm.name:vm
for vm
in viewMakers}
598 for vmname, vm
in viewMakerMap.items():
599 log.debug(f
"[makeHLTTree] {vmname} InputMakerOutputDecisions: {vm.InputMakerOutputDecisions}")
600 if vmname.endswith(
"_probe"):
602 log.debug(f
"Setting InputCachedViews on {vmname} to read decisions from tag leg {vmname[:-6]}: {vm.InputMakerOutputDecisions}")
603 vm.InputCachedViews = viewMakerMap[vmname[:-6]].InputMakerOutputDecisions
605 log.debug(f
"Tag leg does not match probe: '{vmname[:-6]}', will not use cached views")
609 from TriggerMenuMT.HLT.Config.JSON.HLTMenuJSON
import generateJSON
610 generateJSON(flags, HLTMenuConfig.dictsList(), menuAcc.getSequence(
"HLTAllSteps"))
612 from TriggerMenuMT.HLT.Config.JSON.HLTPrescaleJSON
import generatePrescaleJSON
615 from TriggerMenuMT.HLT.Config.JSON.HLTMonitoringJSON
import generateDefaultMonitoringJSON
618 from AthenaCommon.CFElements
import checkSequenceConsistency
620 return acc, CFseq_list