CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
confdb.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 from __future__ import absolute_import
4 import sys
5 import re
6 import os
7 from .pipe import pipe as _pipe
8 from .options import globalTag
9 from itertools import islice
10 
11 def splitter(iterator, n):
12  i = iterator.__iter__()
13  while True:
14  l = list(islice(i, n))
15  if l:
16  yield l
17  else:
18  break
19 
20 
21 class HLTProcess(object):
22 
23  def __init__(self, configuration):
24  self.config = configuration
25  self.data = None
26  self.source = []
27  self.parent = []
28 
29  self.options = {
30  'essources' : [],
31  'esmodules' : [],
32  'modules' : [],
33  'sequences' : [],
34  'services' : [],
35  'paths' : [],
36  'psets' : [],
37  'blocks' : [],
38  }
39 
40  self.labels = {}
41  if self.config.fragment:
42  self.labels['process'] = 'fragment'
43  self.labels['dict'] = 'fragment.__dict__'
44  else:
45  self.labels['process'] = 'process'
46  self.labels['dict'] = 'process.__dict__'
47 
48  if self.config.prescale and (self.config.prescale.lower() != 'none'):
49  self.labels['prescale'] = self.config.prescale
50 
51  # get the configuration from ConfdB
52  from .confdbOfflineConverter import OfflineConverter
53  self.converter = OfflineConverter(version = self.config.menu.version, database = self.config.menu.database, proxy = self.config.proxy, proxyHost = self.config.proxy_host, proxyPort = self.config.proxy_port)
54  self.buildPathList()
55  self.buildOptions()
58  self.customize()
59 
61  if not self.config.setup:
62  return
63  ## if --setup is a python file, use directly that file as setup_cff.py
64  if ".py" in self.config.setup:
65  self.config.setupFile = self.config.setup.split(".py")[0]
66  return
67  args = ['--configName', self.config.setup ]
68  args.append('--noedsources')
69  args.append('--nopaths')
70  for key, vals in self.options.items():
71  if vals:
72  args.extend(('--'+key, ','.join(vals)))
73  args.append('--cff')
74  data, err = self.converter.query( *args )
75  if 'ERROR' in err or 'Exhausted Resultset' in err or 'CONFIG_NOT_FOUND' in err:
76  sys.stderr.write("%s: error while retrieving the HLT setup menu\n\n" % os.path.basename(sys.argv[0]))
77  sys.stderr.write(err + "\n\n")
78  sys.exit(1)
79  self.config.setupFile = "setup_"+self.config.setup[1:].replace("/","_")+"_cff"
80  outfile = open(self.config.setupFile+".py","w+")
81  outfile.write("# This file is automatically generated by hltGetConfiguration.\n" + data)
82 
84  if self.config.menu.run:
85  args = ['--runNumber', self.config.menu.run]
86  else:
87  args = ['--configName', self.config.menu.name ]
88  if not self.config.hilton:
89  # keep the original Source when running on Hilton
90  args.append('--noedsources')
91  for key, vals in self.options.items():
92  if vals:
93  args.extend(('--'+key, ','.join(vals)))
94  data, err = self.converter.query( *args )
95  if 'ERROR' in err or 'Exhausted Resultset' in err or 'CONFIG_NOT_FOUND' in err:
96  sys.stderr.write("%s: error while retrieving the HLT menu\n\n" % os.path.basename(sys.argv[0]))
97  sys.stderr.write(err + "\n\n")
98  sys.exit(1)
99  self.data = data
100 
101  def getPathList(self):
102  if self.config.menu.run:
103  args = ['--runNumber', self.config.menu.run]
104  else:
105  args = ['--configName', self.config.menu.name]
106  args.extend( (
107  '--cff',
108  '--noedsources',
109  '--noes',
110  '--noservices',
111  '--nosequences',
112  '--nomodules'
113  ) )
114 
115  data, err = self.converter.query( *args )
116  if 'ERROR' in err or 'Exhausted Resultset' in err or 'CONFIG_NOT_FOUND' in err:
117  sys.stderr.write("%s: error while retrieving the list of paths from the HLT menu\n\n" % os.path.basename(sys.argv[0]))
118  sys.stderr.write(err + "\n\n")
119  sys.exit(1)
120  filter = re.compile(r' *= *cms.(End|Final)?Path.*')
121  paths = [ filter.sub('', line) for line in data.splitlines() if filter.search(line) ]
122  return paths
123 
124 
125  @staticmethod
126  def expandWildcards(globs, collection):
127  # expand a list of unix-style wildcards matching a given collection
128  # wildcards with no matches are silently discarded
129  matches = []
130  for glob in globs:
131  negate = ''
132  if glob[0] == '-':
133  negate = '-'
134  glob = glob[1:]
135  # translate a unix-style glob expression into a regular expression
136  filter = re.compile(r'^' + glob.replace('?', '.').replace('*', '.*').replace('[!', '[^') + r'$')
137  matches.extend( negate + element for element in collection if filter.match(element) )
138  return matches
139 
140 
141  @staticmethod
142  def consolidateNegativeList(elements):
143  # consolidate a list of path exclusions and re-inclusions
144  # the result is the list of paths to be removed from the dump
145  result = set()
146  for element in elements:
147  if element[0] == '-':
148  result.add( element )
149  else:
150  result.discard( '-' + element )
151  return sorted( element for element in result )
152 
153  @staticmethod
154  def consolidatePositiveList(elements):
155  # consolidate a list of path selection and re-exclusions
156  # the result is the list of paths to be included in the dump
157  result = set()
158  for element in elements:
159  if element[0] == '-':
160  result.discard( element[1:] )
161  else:
162  result.add( element )
163  return sorted( element for element in result )
164 
165 
166  # dump the final configuration
167  def dump(self):
168  self.data = self.data % self.labels
169  if self.config.fragment:
170  self.data = re.sub( r'\bprocess\b', 'fragment', self.data )
171  self.data = re.sub( r'\bProcess\b', 'ProcessFragment', self.data )
172  return self.data
173 
174 
175  # add specific customizations
176  def specificCustomize(self):
177  # specific customizations now live in HLTrigger.Configuration.customizeHLTforALL.customizeHLTforAll(.,.)
178  if self.config.fragment:
179  self.data += """
180 # add specific customizations
181 from HLTrigger.Configuration.customizeHLTforALL import customizeHLTforAll
182 fragment = customizeHLTforAll(fragment,"%s")
183 """ % (self.config.type)
184  elif self.config.hilton:
185  # do not apply the STORM-specific customisation
186  pass
187  else:
188  if self.config.type=="Fake":
189  prefix = "run1"
190  elif self.config.type in ("Fake1","Fake2","2018"):
191  prefix = "run2"
192  else:
193  prefix = "run3"
194  _gtData = "auto:"+prefix+"_hlt_"+self.config.type
195  _gtMc = "auto:"+prefix+"_mc_" +self.config.type
196  self.data += """
197 # add specific customizations
198 _customInfo = {}
199 _customInfo['menuType' ]= "%s"
200 _customInfo['globalTags']= {}
201 _customInfo['globalTags'][True ] = "%s"
202 _customInfo['globalTags'][False] = "%s"
203 _customInfo['inputFiles']={}
204 _customInfo['inputFiles'][True] = "file:RelVal_Raw_%s_DATA.root"
205 _customInfo['inputFiles'][False] = "file:RelVal_Raw_%s_MC.root"
206 _customInfo['maxEvents' ]= %s
207 _customInfo['globalTag' ]= "%s"
208 _customInfo['inputFile' ]= %s
209 _customInfo['realData' ]= %s
210 
211 from HLTrigger.Configuration.customizeHLTforALL import customizeHLTforAll
212 %%(process)s = customizeHLTforAll(%%(process)s,"%s",_customInfo)
213 """ % (self.config.type,_gtData,_gtMc,self.config.type,self.config.type,self.config.events,self.config.globaltag,self.source,self.config.data,self.config.type)
214 
215  self.data += """
216 from HLTrigger.Configuration.customizeHLTforCMSSW import customizeHLTforCMSSW
217 %%(process)s = customizeHLTforCMSSW(%%(process)s,"%s")
218 """ % (self.config.type)
219 
220  # Eras-based customisations
221  self.data += """
222 # Eras-based customisations
223 from HLTrigger.Configuration.Eras import modifyHLTforEras
224 modifyHLTforEras(%(process)s)
225 """
226  # add the user-defined customization functions, if any
227  if self.config.customise:
228  self.data += "\n"
229  self.data += "#User-defined customization functions\n"
230  for customise in self.config.customise.split(","):
231  customiseValues = customise.split(".")
232  if len(customiseValues)>=3: raise Exception("--customise option cannot contain more than one dot.")
233  if len(customiseValues)==1:
234  customiseValues.append("customise")
235  customiseValues[0] = customiseValues[0].replace("/",".")
236  self.data += "from "+customiseValues[0]+" import "+customiseValues[1]+"\n"
237  self.data += "process = "+customiseValues[1]+"(process)\n"
238 
239 
240  # customize the configuration according to the options
241  def customize(self):
242 
243  # adapt the source to the current scenario
244  if not self.config.fragment:
245  self.build_source()
246 
247  # manual override some parameters
248  if self.config.type in ('HIon', ):
249  if self.config.data:
250  if not self.config.fragment:
251  self._fix_parameter( type = 'InputTag', value = 'rawDataCollector', replace = 'rawDataRepacker')
252 
253  # if requested, remove the HLT prescales
254  self.fixPrescales()
255 
256  # if requested, override all ED/HLTfilters to always pass ("open" mode)
257  self.instrumentOpenMode()
258 
259  # if requested, change all HLTTriggerTypeFilter EDFilters to accept only error events (SelectedTriggerType = 0)
261 
262  # if requested, instrument the self with the modules and EndPath needed for timing studies
263  self.instrumentTiming()
264 
265  # if requested, override the L1 self from the GlobalTag (Xml)
266  self.overrideL1MenuXml()
267 
268  # if requested, run the L1 emulator
269  self.runL1Emulator()
270 
271  # add process.load("setup_cff")
272  self.loadSetupCff()
273 
274  if self.config.fragment:
275  self.data += """
276 # dummify hltGetConditions in cff's
277 if 'hltGetConditions' in %(dict)s and 'HLTriggerFirstPath' in %(dict)s :
278  %(process)s.hltDummyConditions = cms.EDFilter( "HLTBool",
279  result = cms.bool( True )
280  )
281  %(process)s.HLTriggerFirstPath.replace(%(process)s.hltGetConditions,%(process)s.hltDummyConditions)
282 """
283 
284  # the scouting path issue:
285  # 1) for config fragments, we remove all output modules
286  # 2) however in old style datasets, the scouting output paths also run the unpackers which are needed
287  # 3) therefore they have to keep the scouting path but remove the scouting output module
288  # 4) in new style datasets, aka datasetpaths & finalpaths, the scouting unpackers are on another path and all of this is unnecessary
289  # 5) however its hard to detect whether we have new style or old style so we run this for both
290  # 6) therefore we end up with a superfluous Scouting*OutputPaths which are empty
291  for path in self.all_paths:
292  match = re.match(r'(Scouting\w+)Output$', path)
293  if match:
294  module = 'hltOutput' + match.group(1)
295  self.data = self.data.replace(path+' = cms.EndPath', path+' = cms.Path')
296  self.data = self.data.replace(' + process.'+module, '')
297  self.data = self.data.replace(' process.'+module, '')
298  else:
299 
300  # override the process name and adapt the relevant filters
301  self.overrideProcessName()
302 
303  # select specific Eras
304  self.addEras()
305 
306  # override the output modules to output root files
307  self.overrideOutput()
308 
309  # add global options
310  self.addGlobalOptions()
311 
312  # if requested or necessary, override the GlobalTag and connection strings (incl. L1!)
313  self.overrideGlobalTag()
314 
315  # request summary informations from the MessageLogger
316  self.updateMessageLogger()
317 
318  # replace DQMStore and DQMRootOutputModule with a configuration suitable for running offline
319  self.instrumentDQM()
320 
321  # add specific customisations
322  self.specificCustomize()
323 
324 
325  def addGlobalOptions(self):
326  # add global options
327  self.data += """
328 # limit the number of events to be processed
329 %%(process)s.maxEvents = cms.untracked.PSet(
330  input = cms.untracked.int32( %d )
331 )
332 """ % self.config.events
333 
334  self.data += """
335 # enable TrigReport, TimeReport and MultiThreading
336 %(process)s.options = cms.untracked.PSet(
337  wantSummary = cms.untracked.bool( True ),
338  numberOfThreads = cms.untracked.uint32( 4 ),
339  numberOfStreams = cms.untracked.uint32( 0 ),
340 )
341 """
342 
343  def _fix_parameter(self, **args):
344  """arguments:
345  name: parameter name (optional)
346  type: parameter type (look for tracked and untracked variants)
347  value: original value
348  replace: replacement value
349  """
350  if 'name' in args:
351  self.data = re.sub(
352  r'%(name)s = cms(?P<tracked>(?:\.untracked)?)\.%(type)s\( (?P<quote>["\']?)%(value)s(?P=quote)' % args,
353  r'%(name)s = cms\g<tracked>.%(type)s( \g<quote>%(replace)s\g<quote>' % args,
354  self.data)
355  else:
356  self.data = re.sub(
357  r'cms(?P<tracked>(?:\.untracked)?)\.%(type)s\( (?P<quote>["\']?)%(value)s(?P=quote)' % args,
358  r'cms\g<tracked>.%(type)s( \g<quote>%(replace)s\g<quote>' % args,
359  self.data)
360 
361 
362  def fixPrescales(self):
363  # update the PrescaleService to match the new list of paths
364  if self.options['paths']:
365  if self.options['paths'][0][0] == '-':
366  # drop requested paths
367  for minuspath in self.options['paths']:
368  path = minuspath[1:]
369  self.data = re.sub(r' cms.PSet\( pathName = cms.string\( "%s" \),\n prescales = cms.vuint32\( .* \)\n \),?\n' % path, '', self.data)
370  else:
371  # keep requested paths
372  for path in self.all_paths:
373  if path not in self.options['paths']:
374  self.data = re.sub(r' cms.PSet\( pathName = cms.string\( "%s" \),\n prescales = cms.vuint32\( .* \)\n \),?\n' % path, '', self.data)
375 
376  if self.config.prescale and (self.config.prescale.lower() != 'none'):
377  # TO DO: check that the requested prescale column is valid
378  self.data += """
379 # force the use of a specific HLT prescale column
380 if 'PrescaleService' in %(dict)s:
381  %(process)s.PrescaleService.forceDefault = True
382  %(process)s.PrescaleService.lvl1DefaultLabel = '%(prescale)s'
383 """
384 
385 
387  if self.config.open:
388  # find all EDfilters
389  filters = [ match[1] for match in re.findall(r'(process\.)?\b(\w+) = cms.EDFilter', self.data) ]
390  re_sequence = re.compile( r'cms\.(Path|Sequence)\((.*)\)' )
391  # remove existing 'cms.ignore' and '~' modifiers
392  self.data = re_sequence.sub( lambda line: re.sub( r'cms\.ignore *\( *((process\.)?\b(\w+)) *\)', r'\1', line.group(0) ), self.data )
393  self.data = re_sequence.sub( lambda line: re.sub( r'~', '', line.group(0) ), self.data )
394  # wrap all EDfilters with "cms.ignore( ... )", 1000 at a time (python 2.6 complains for too-big regular expressions)
395  for some in splitter(filters, 1000):
396  re_filters = re.compile( r'\b((process\.)?(' + r'|'.join(some) + r'))\b' )
397  self.data = re_sequence.sub( lambda line: re_filters.sub( r'cms.ignore( \1 )', line.group(0) ), self.data )
398 
399 
401  if self.config.errortype:
402  # change all HLTTriggerTypeFilter EDFilters to accept only error events (SelectedTriggerType = 0)
403  self._fix_parameter(name = 'SelectedTriggerType', type ='int32', value = '1', replace = '0')
404  self._fix_parameter(name = 'SelectedTriggerType', type ='int32', value = '2', replace = '0')
405  self._fix_parameter(name = 'SelectedTriggerType', type ='int32', value = '3', replace = '0')
406 
407 
408  def overrideGlobalTag(self):
409  # overwrite GlobalTag
410  # the logic is:
411  # - if a GlobalTag is specified on the command line:
412  # - override the global tag
413  # - if the GT is "auto:...", insert the code to read it from Configuration.AlCa.autoCond
414  # - if a GlobalTag is NOT specified on the command line:
415  # - when running on data, do nothing, and keep the global tag in the menu
416  # - when running on mc, take the GT from the configuration.type
417 
418  # override the GlobalTag connection string and pfnPrefix
419 
420  # when running on MC, override the global tag even if not specified on the command line
421  if not self.config.data and not self.config.globaltag:
422  if self.config.type in globalTag:
423  self.config.globaltag = globalTag[self.config.type]
424  else:
425  self.config.globaltag = globalTag['GRun']
426 
427  # if requested, override the L1 menu from the GlobalTag
428  if self.config.l1.override:
429  self.config.l1.tag = self.config.l1.override
430  self.config.l1.record = 'L1TUtmTriggerMenuRcd'
431  self.config.l1.connect = ''
432  self.config.l1.label = ''
433  if not self.config.l1.snapshotTime:
434  self.config.l1.snapshotTime = '9999-12-31 23:59:59.000'
435  self.config.l1cond = '%(tag)s,%(record)s,%(connect)s,%(label)s,%(snapshotTime)s' % self.config.l1.__dict__
436  else:
437  self.config.l1cond = None
438 
439  if self.config.globaltag or self.config.l1cond:
440  text = """
441 # override the GlobalTag, connection string and pfnPrefix
442 if 'GlobalTag' in %(dict)s:
443  from Configuration.AlCa.GlobalTag import GlobalTag as customiseGlobalTag
444  %(process)s.GlobalTag = customiseGlobalTag(%(process)s.GlobalTag"""
445  if self.config.globaltag:
446  text += ", globaltag = %s" % repr(self.config.globaltag)
447  if self.config.l1cond:
448  text += ", conditions = %s" % repr(self.config.l1cond)
449  text += ")\n"
450  self.data += text
451 
452  def overrideL1MenuXml(self):
453  # if requested, override the GlobalTag's L1T menu from an Xml file
454  if self.config.l1Xml.XmlFile:
455  text = """
456 # override the GlobalTag's L1T menu from an Xml file
457 from HLTrigger.Configuration.CustomConfigs import L1XML
458 %%(process)s = L1XML(%%(process)s,"%s")
459 """ % (self.config.l1Xml.XmlFile)
460  self.data += text
461 
462  def runL1Emulator(self):
463  # if requested, run the Full L1T emulator, then repack the data into a new RAW collection, to be used by the HLT
464  if self.config.emulator:
465  text = """
466 # run the Full L1T emulator, then repack the data into a new RAW collection, to be used by the HLT
467 from HLTrigger.Configuration.CustomConfigs import L1REPACK
468 %%(process)s = L1REPACK(%%(process)s,"%s")
469 """ % (self.config.emulator)
470  self.data += text
471 
472  def overrideOutput(self):
473  # if not runnign on Hilton, override the "online" ShmStreamConsumer output modules with "offline" PoolOutputModule's
474  # note for Run3 ShmStreamConsumer has been replaced with EvFOutputModule and later GlobalEvFOutputModule
475  # so we also do a replace there
476  if not self.config.hilton:
477  self.data = re.sub(
478  r'\b(process\.)?hltOutput(\w+) *= *cms\.OutputModule\( *"(ShmStreamConsumer)" *,',
479  r'%(process)s.hltOutput\2 = cms.OutputModule( "PoolOutputModule",\n fileName = cms.untracked.string( "output\2.root" ),\n fastCloning = cms.untracked.bool( False ),\n dataset = cms.untracked.PSet(\n filterName = cms.untracked.string( "" ),\n dataTier = cms.untracked.string( "RAW" )\n ),',
480  self.data
481  )
482  self.data = re.sub(
483  r'\b(process\.)?hltOutput(\w+) *= *cms\.OutputModule\( *"EvFOutputModule" *,\n use_compression = cms.untracked.bool\( True \),\n compression_algorithm = cms.untracked.string\( "ZLIB" \),\n compression_level = cms.untracked.int32\( 1 \),\n lumiSection_interval = cms.untracked.int32\( 0 \),\n(.+?),\n psetMap = cms.untracked.InputTag\( "hltPSetMap" \)\n',
484  r'\1hltOutput\2 = cms.OutputModule( "PoolOutputModule",\n fileName = cms.untracked.string( "output\2.root" ),\n fastCloning = cms.untracked.bool( False ),\n dataset = cms.untracked.PSet(\n filterName = cms.untracked.string( "" ),\n dataTier = cms.untracked.string( "RAW" )\n ),\n\3\n',
485  self.data,0,re.DOTALL
486  )
487  self.data = re.sub(
488  r'\b(process\.)?hltOutput(\w+) *= *cms\.OutputModule\( *"GlobalEvFOutputModule" *,\n use_compression = cms.untracked.bool\( True \),\n compression_algorithm = cms.untracked.string\( "ZLIB" \),\n compression_level = cms.untracked.int32\( 1 \),\n lumiSection_interval = cms.untracked.int32\( 0 \),\n(.+?),\n psetMap = cms.untracked.InputTag\( "hltPSetMap" \)\n',
489  r'\1hltOutput\2 = cms.OutputModule( "PoolOutputModule",\n fileName = cms.untracked.string( "output\2.root" ),\n fastCloning = cms.untracked.bool( False ),\n dataset = cms.untracked.PSet(\n filterName = cms.untracked.string( "" ),\n dataTier = cms.untracked.string( "RAW" )\n ),\n\3\n',
490  self.data,0,re.DOTALL
491  )
492  if not self.config.fragment and self.config.output == 'minimal':
493  # add a single output to keep the TriggerResults and TriggerEvent
494  self.data += """
495 # add a single "keep *" output
496 %(process)s.hltOutputMinimal = cms.OutputModule( "PoolOutputModule",
497  fileName = cms.untracked.string( "output.root" ),
498  fastCloning = cms.untracked.bool( False ),
499  dataset = cms.untracked.PSet(
500  dataTier = cms.untracked.string( 'AOD' ),
501  filterName = cms.untracked.string( '' )
502  ),
503  outputCommands = cms.untracked.vstring( 'drop *',
504  'keep edmTriggerResults_*_*_*',
505  'keep triggerTriggerEvent_*_*_*',
506  'keep GlobalAlgBlkBXVector_*_*_*',
507  'keep GlobalExtBlkBXVector_*_*_*',
508  'keep l1tEGammaBXVector_*_EGamma_*',
509  'keep l1tEtSumBXVector_*_EtSum_*',
510  'keep l1tJetBXVector_*_Jet_*',
511  'keep l1tMuonBXVector_*_Muon_*',
512  'keep l1tTauBXVector_*_Tau_*',
513  )
514 )
515 %(process)s.MinimalOutput = cms.FinalPath( %(process)s.hltOutputMinimal )
516 %(process)s.schedule.append( %(process)s.MinimalOutput )
517 """
518  elif not self.config.fragment and self.config.output == 'full':
519  # add a single "keep *" output
520  self.data += """
521 # add a single "keep *" output
522 %(process)s.hltOutputFull = cms.OutputModule( "PoolOutputModule",
523  fileName = cms.untracked.string( "output.root" ),
524  fastCloning = cms.untracked.bool( False ),
525  dataset = cms.untracked.PSet(
526  dataTier = cms.untracked.string( 'RECO' ),
527  filterName = cms.untracked.string( '' )
528  ),
529  outputCommands = cms.untracked.vstring( 'keep *' )
530 )
531 %(process)s.FullOutput = cms.FinalPath( %(process)s.hltOutputFull )
532 %(process)s.schedule.append( %(process)s.FullOutput )
533 """
534 
535  # select specific Eras
536  def addEras(self):
537  if self.config.eras is None:
538  return
539  from Configuration.StandardSequences.Eras import eras
540  erasSplit = self.config.eras.split(',')
541  self.data = re.sub(r'process = cms.Process\( *"\w+"', '\n'.join(eras.pythonCfgLines[era] for era in erasSplit)+'\n\g<0>, '+', '.join(era for era in erasSplit), self.data)
542 
543  # select specific Eras
544  def loadSetupCff(self):
545  if self.config.setup is None:
546  return
547  processLine = self.data.find("\n",self.data.find("cms.Process"))
548  self.data = self.data[:processLine]+'\nprocess.load("%s")'%self.config.setupFile+self.data[processLine:]
549 
550  # override the process name and adapt the relevant filters
552  if self.config.name is None:
553  return
554 
555  # sanitise process name
556  self.config.name = self.config.name.replace("_","")
557  # override the process name
558  quote = '[\'\"]'
559  self.data = re.compile(r'^(process\s*=\s*cms\.Process\(\s*' + quote + r')\w+(' + quote + r'\s*\).*)$', re.MULTILINE).sub(r'\1%s\2' % self.config.name, self.data, 1)
560 
561  # when --setup option is used, remove possible errors from PrescaleService due to missing HLT paths.
562  if self.config.setup: self.data += """
563 # avoid PrescaleService error due to missing HLT paths
564 if 'PrescaleService' in process.__dict__:
565  for pset in reversed(process.PrescaleService.prescaleTable):
566  if not hasattr(process,pset.pathName.value()):
567  process.PrescaleService.prescaleTable.remove(pset)
568 """
569 
570 
572  # request summary informations from the MessageLogger
573  self.data += """
574 # show summaries from trigger analysers used at HLT
575 if 'MessageLogger' in %(dict)s:
576  %(process)s.MessageLogger.TriggerSummaryProducerAOD = cms.untracked.PSet()
577  %(process)s.MessageLogger.L1GtTrigReport = cms.untracked.PSet()
578  %(process)s.MessageLogger.L1TGlobalSummary = cms.untracked.PSet()
579  %(process)s.MessageLogger.HLTrigReport = cms.untracked.PSet()
580  %(process)s.MessageLogger.FastReport = cms.untracked.PSet()
581  %(process)s.MessageLogger.ThroughputService = cms.untracked.PSet()
582 """
583 
584 
585  def loadAdditionalConditions(self, comment, *conditions):
586  # load additional conditions
587  self.data += """
588 # %s
589 if 'GlobalTag' in %%(dict)s:
590 """ % comment
591  for condition in conditions:
592  self.data += """ %%(process)s.GlobalTag.toGet.append(
593  cms.PSet(
594  record = cms.string( '%(record)s' ),
595  tag = cms.string( '%(tag)s' ),
596  label = cms.untracked.string( '%(label)s' ),
597  )
598  )
599 """ % condition
600 
601 
602  def loadCffCommand(self, module):
603  # load a cfi or cff module
604  if self.config.fragment:
605  return 'from %s import *\n' % module
606  else:
607  return 'process.load( "%s" )\n' % module
608 
609  def loadCff(self, module):
610  self.data += self.loadCffCommand(module)
611 
612 
613  def overrideParameters(self, module, parameters):
614  # override a module's parameter if the module is present in the configuration
615  self.data += "if '%s' in %%(dict)s:\n" % module
616  for (parameter, value) in parameters:
617  self.data += " %%(process)s.%s.%s = %s\n" % (module, parameter, value)
618  self.data += "\n"
619 
620 
622  if label in self.data:
623  label_re = r'\b(process\.)?' + label
624  self.data = re.sub(r' *(\+|,) *' + label_re, '', self.data)
625  self.data = re.sub(label_re + r' *(\+|,) *', '', self.data)
626  self.data = re.sub(label_re, '', self.data)
627 
628 
629  def instrumentTiming(self):
630 
631  if self.config.timing:
632  self.data += """
633 # instrument the menu with the modules and EndPath needed for timing studies
634 """
635 
636  self.data += '\n# configure the FastTimerService\n'
637  self.loadCff('HLTrigger.Timer.FastTimerService_cfi')
638 
639  self.data += """# print a text summary at the end of the job
640 %(process)s.FastTimerService.printEventSummary = False
641 %(process)s.FastTimerService.printRunSummary = False
642 %(process)s.FastTimerService.printJobSummary = True
643 
644 # enable DQM plots
645 %(process)s.FastTimerService.enableDQM = True
646 
647 # enable per-path DQM plots (starting with CMSSW 9.2.3-patch2)
648 %(process)s.FastTimerService.enableDQMbyPath = True
649 
650 # enable per-module DQM plots
651 %(process)s.FastTimerService.enableDQMbyModule = True
652 
653 # enable per-event DQM plots vs lumisection
654 %(process)s.FastTimerService.enableDQMbyLumiSection = True
655 %(process)s.FastTimerService.dqmLumiSectionsRange = 2500
656 
657 # set the time resolution of the DQM plots
658 %(process)s.FastTimerService.dqmTimeRange = 2000.
659 %(process)s.FastTimerService.dqmTimeResolution = 10.
660 %(process)s.FastTimerService.dqmPathTimeRange = 1000.
661 %(process)s.FastTimerService.dqmPathTimeResolution = 5.
662 %(process)s.FastTimerService.dqmModuleTimeRange = 200.
663 %(process)s.FastTimerService.dqmModuleTimeResolution = 1.
664 
665 # set the base DQM folder for the plots
666 %(process)s.FastTimerService.dqmPath = 'HLT/TimerService'
667 %(process)s.FastTimerService.enableDQMbyProcesses = False
668 """
669 
670 
671  def instrumentDQM(self):
672  if not self.config.hilton:
673  # remove any reference to the hltDQMFileSaver and hltDQMFileSaverPB:
674  # note the convert options remove the module itself,
675  # here we are just removing the references in paths, sequences, etc
676  self.removeElementFromSequencesTasksAndPaths('hltDQMFileSaverPB')
677  self.removeElementFromSequencesTasksAndPaths('hltDQMFileSaver')
678 
679  # instrument the HLT menu with DQMStore and DQMRootOutputModule suitable for running offline
680  dqmstore = "\n# load the DQMStore and DQMRootOutputModule\n"
681  dqmstore += self.loadCffCommand('DQMServices.Core.DQMStore_cfi')
682  dqmstore += """
683 %(process)s.dqmOutput = cms.OutputModule("DQMRootOutputModule",
684  fileName = cms.untracked.string("DQMIO.root")
685 )
686 """
687  empty_path = re.compile(r'.*\b(process\.)?DQMOutput = cms\.(Final|End)Path\( *\).*')
688  other_path = re.compile(r'(.*\b(process\.)?DQMOutput = cms\.(Final|End)Path\()(.*)')
689  if empty_path.search(self.data):
690  # replace an empty DQMOutput path
691  self.data = empty_path.sub(dqmstore + '\n%(process)s.DQMOutput = cms.FinalPath( %(process)s.dqmOutput )\n', self.data)
692  elif other_path.search(self.data):
693  # prepend the dqmOutput to the DQMOutput path
694  self.data = other_path.sub(dqmstore + r'\g<1> %(process)s.dqmOutput +\g<4>', self.data)
695  else:
696  # create a new DQMOutput path with the dqmOutput module
697  self.data += dqmstore
698  self.data += '\n%(process)s.DQMOutput = cms.FinalPath( %(process)s.dqmOutput )\n'
699  self.data += '%(process)s.schedule.append( %(process)s.DQMOutput )\n'
700 
701 
702  @staticmethod
703  def dumppaths(paths):
704  sys.stderr.write('Path selection:\n')
705  for path in paths:
706  sys.stderr.write('\t%s\n' % path)
707  sys.stderr.write('\n\n')
708 
709  def buildPathList(self):
710  self.all_paths = self.getPathList()
711 
712  if self.config.paths:
713  # no path list was requested, dump the full table, minus unsupported / unwanted paths
714  paths = self.config.paths.split(',')
715  else:
716  # dump only the requested paths, plus the eventual output endpaths
717  paths = []
718 
719  # 'none' should remove all outputs
720  # 'dqm' should remove all outputs but DQMHistograms
721  # 'minimal' should remove all outputs but DQMHistograms, and add a single output module to keep the TriggerResults and TriggerEvent
722  # 'full' should remove all outputs but DQMHistograms, and add a single output module to "keep *"
723  # See also the `overrideOutput` method
724  if self.config.fragment or self.config.output in ('none', ):
725  if self.config.paths:
726  # keep only the Paths and EndPaths requested explicitly
727  pass
728  else:
729  # drop all output EndPaths but the Scouting ones, and drop the RatesMonitoring and DQMHistograms
730  paths.append( "-*Output" )
731  paths.append( "-RatesMonitoring")
732  paths.append( "-DQMHistograms")
733  if self.config.fragment: paths.append( "Scouting*Output" )
734 
735  elif self.config.output in ('dqm', 'minimal', 'full'):
736  if self.config.paths:
737  # keep only the Paths and EndPaths requested explicitly, and the DQMHistograms
738  paths.append( "DQMHistograms" )
739  else:
740  # drop all output EndPaths but the Scouting ones, and drop the RatesMonitoring
741  paths.append( "-*Output" )
742  paths.append( "-RatesMonitoring")
743  if self.config.fragment: paths.append( "Scouting*Output" )
744 
745  else:
746  if self.config.paths:
747  # keep all output EndPaths, including the DQMHistograms
748  paths.append( "*Output" )
749  paths.append( "DQMHistograms" )
750  else:
751  # keep all Paths and EndPaths
752  pass
753 
754  # drop unwanted paths for profiling (and timing studies)
755  if self.config.profiling:
756  paths.append( "-HLTAnalyzerEndpath" )
757 
758  # this should never be in any dump (nor online menu)
759  paths.append( "-OfflineOutput" )
760 
761  # expand all wildcards
762  paths = self.expandWildcards(paths, self.all_paths)
763 
764  if self.config.paths:
765  # do an "additive" consolidation
766  paths = self.consolidatePositiveList(paths)
767  if not paths:
768  raise RuntimeError('Error: option "--paths %s" does not select any valid paths' % self.config.paths)
769  else:
770  # do a "subtractive" consolidation
771  paths = self.consolidateNegativeList(paths)
772  self.options['paths'] = paths
773 
774  def buildOptions(self):
775  # common configuration for all scenarios
776  self.options['services'].append( "-DQM" )
777  self.options['services'].append( "-FUShmDQMOutputService" )
778  self.options['services'].append( "-MicroStateService" )
779  self.options['services'].append( "-ModuleWebRegistry" )
780  self.options['services'].append( "-TimeProfilerService" )
781 
782  # remove the DAQ modules and the online definition of the DQMStore and DQMFileSaver
783  # unless a hilton-like configuration has been requested
784  if not self.config.hilton:
785  self.options['services'].append( "-EvFDaqDirector" )
786  self.options['services'].append( "-FastMonitoringService" )
787  self.options['services'].append( "-DQMStore" )
788  self.options['modules'].append( "-hltDQMFileSaver" )
789  self.options['modules'].append( "-hltDQMFileSaverPB" )
790 
791  if self.config.fragment:
792  # extract a configuration file fragment
793  self.options['essources'].append( "-GlobalTag" )
794  self.options['essources'].append( "-HepPDTESSource" )
795  self.options['essources'].append( "-XMLIdealGeometryESSource" )
796  self.options['essources'].append( "-eegeom" )
797  self.options['essources'].append( "-es_hardcode" )
798  self.options['essources'].append( "-magfield" )
799 
800  self.options['esmodules'].append( "-SlaveField0" )
801  self.options['esmodules'].append( "-SlaveField20" )
802  self.options['esmodules'].append( "-SlaveField30" )
803  self.options['esmodules'].append( "-SlaveField35" )
804  self.options['esmodules'].append( "-SlaveField38" )
805  self.options['esmodules'].append( "-SlaveField40" )
806  self.options['esmodules'].append( "-VBF0" )
807  self.options['esmodules'].append( "-VBF20" )
808  self.options['esmodules'].append( "-VBF30" )
809  self.options['esmodules'].append( "-VBF35" )
810  self.options['esmodules'].append( "-VBF38" )
811  self.options['esmodules'].append( "-VBF40" )
812  self.options['esmodules'].append( "-CSCGeometryESModule" )
813  self.options['esmodules'].append( "-CaloGeometryBuilder" )
814  self.options['esmodules'].append( "-CaloTowerHardcodeGeometryEP" )
815  self.options['esmodules'].append( "-CastorHardcodeGeometryEP" )
816  self.options['esmodules'].append( "-DTGeometryESModule" )
817  self.options['esmodules'].append( "-EcalBarrelGeometryEP" )
818  self.options['esmodules'].append( "-EcalElectronicsMappingBuilder" )
819  self.options['esmodules'].append( "-EcalEndcapGeometryEP" )
820  self.options['esmodules'].append( "-EcalLaserCorrectionService" )
821  self.options['esmodules'].append( "-EcalPreshowerGeometryEP" )
822  self.options['esmodules'].append( "-GEMGeometryESModule" )
823  self.options['esmodules'].append( "-HcalHardcodeGeometryEP" )
824  self.options['esmodules'].append( "-HcalTopologyIdealEP" )
825  self.options['esmodules'].append( "-MuonNumberingInitialization" )
826  self.options['esmodules'].append( "-ParametrizedMagneticFieldProducer" )
827  self.options['esmodules'].append( "-RPCGeometryESModule" )
828  self.options['esmodules'].append( "-SiStripGainESProducer" )
829  self.options['esmodules'].append( "-SiStripRecHitMatcherESProducer" )
830  self.options['esmodules'].append( "-SiStripQualityESProducer" )
831  self.options['esmodules'].append( "-StripCPEfromTrackAngleESProducer" )
832  self.options['esmodules'].append( "-TrackerAdditionalParametersPerDetESModule" )
833  self.options['esmodules'].append( "-TrackerDigiGeometryESModule" )
834  self.options['esmodules'].append( "-TrackerGeometricDetESModule" )
835  self.options['esmodules'].append( "-VolumeBasedMagneticFieldESProducer" )
836  self.options['esmodules'].append( "-ZdcHardcodeGeometryEP" )
837  self.options['esmodules'].append( "-hcal_db_producer" )
838  self.options['esmodules'].append( "-L1GtTriggerMaskAlgoTrigTrivialProducer" )
839  self.options['esmodules'].append( "-L1GtTriggerMaskTechTrigTrivialProducer" )
840  self.options['esmodules'].append( "-hltESPEcalTrigTowerConstituentsMapBuilder" )
841  self.options['esmodules'].append( "-hltESPGlobalTrackingGeometryESProducer" )
842  self.options['esmodules'].append( "-hltESPMuonDetLayerGeometryESProducer" )
843  self.options['esmodules'].append( "-hltESPTrackerRecoGeometryESProducer" )
844  self.options['esmodules'].append( "-trackerTopology" )
845 
846  self.options['esmodules'].append( "-CaloTowerGeometryFromDBEP" )
847  self.options['esmodules'].append( "-CastorGeometryFromDBEP" )
848  self.options['esmodules'].append( "-EcalBarrelGeometryFromDBEP" )
849  self.options['esmodules'].append( "-EcalEndcapGeometryFromDBEP" )
850  self.options['esmodules'].append( "-EcalPreshowerGeometryFromDBEP" )
851  self.options['esmodules'].append( "-HcalGeometryFromDBEP" )
852  self.options['esmodules'].append( "-ZdcGeometryFromDBEP" )
853  self.options['esmodules'].append( "-XMLFromDBSource" )
854  self.options['esmodules'].append( "-sistripconn" )
855 
856  self.options['services'].append( "-MessageLogger" )
857 
858  self.options['psets'].append( "-maxEvents" )
859  self.options['psets'].append( "-options" )
860 
861  # remove Scouting OutputModules even though the EndPaths are kept
862  self.options['modules'].append( "-hltOutputScoutingCaloMuon" )
863  self.options['modules'].append( "-hltOutputScoutingPF" )
864 
865  if self.config.fragment or (self.config.prescale and (self.config.prescale.lower() == 'none')):
866  self.options['services'].append( "-PrescaleService" )
867 
868  if self.config.fragment or self.config.timing:
869  self.options['services'].append( "-FastTimerService" )
870 
871 
872  def append_filenames(self, name, filenames):
873  if len(filenames) > 255:
874  token_open = "( *("
875  token_close = ") )"
876  else:
877  token_open = "("
878  token_close = ")"
879 
880  self.data += " %s = cms.untracked.vstring%s\n" % (name, token_open)
881  for line in filenames:
882  self.data += " '%s',\n" % line
883  self.data += " %s,\n" % (token_close)
884 
885 
886  def expand_filenames(self, input):
887  # check if the input is a dataset or a list of files
888  if input[0:8] == 'dataset:':
889  from .dasFileQuery import dasFileQuery
890  # extract the dataset name, and use DAS to fine the list of LFNs
891  dataset = input[8:]
892  files = dasFileQuery(dataset)
893  else:
894  # assume a comma-separated list of input files
895  files = input.split(',')
896  return files
897 
898  def build_source(self):
899  if self.config.hilton:
900  # use the DAQ source
901  return
902 
903  if self.config.input:
904  # if a dataset or a list of input files was given, use it
905  self.source = self.expand_filenames(self.config.input)
906  elif self.config.data:
907  # offline we can run on data...
908  self.source = [ "file:RelVal_Raw_%s_DATA.root" % self.config.type ]
909  else:
910  # ...or on mc
911  self.source = [ "file:RelVal_Raw_%s_MC.root" % self.config.type ]
912 
913  if self.config.parent:
914  # if a dataset or a list of input files was given for the parent data, use it
915  self.parent = self.expand_filenames(self.config.parent)
916 
917  self.data += """
918 # source module (EDM inputs)
919 %(process)s.source = cms.Source( "PoolSource",
920 """
921  self.append_filenames("fileNames", self.source)
922  if (self.parent):
923  self.append_filenames("secondaryFileNames", self.parent)
924  self.data += """\
925  inputCommands = cms.untracked.vstring(
926  'keep *'
927  )
928 )
929 """
def _fix_parameter
Definition: confdb.py:343
def overrideL1MenuXml
Definition: confdb.py:452
def addGlobalOptions
Definition: confdb.py:325
def getSetupConfigurationFromDB
Definition: confdb.py:60
def overrideOutput
Definition: confdb.py:472
def expand_filenames
Definition: confdb.py:886
boost::dynamic_bitset append(const boost::dynamic_bitset<> &bs1, const boost::dynamic_bitset<> &bs2)
this method takes two bitsets bs1 and bs2 and returns result of bs2 appended to the end of bs1 ...
def splitter
Definition: confdb.py:11
def overrideProcessName
Definition: confdb.py:551
def specificCustomize
Definition: confdb.py:176
def consolidateNegativeList
Definition: confdb.py:142
def instrumentErrorEventType
Definition: confdb.py:400
def append_filenames
Definition: confdb.py:872
def consolidatePositiveList
Definition: confdb.py:154
def expandWildcards
Definition: confdb.py:126
def overrideGlobalTag
Definition: confdb.py:408
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def removeElementFromSequencesTasksAndPaths
Definition: confdb.py:621
def getRawConfigurationFromDB
Definition: confdb.py:83
def overrideParameters
Definition: confdb.py:613
def loadCffCommand
Definition: confdb.py:602
def instrumentTiming
Definition: confdb.py:629
def instrumentOpenMode
Definition: confdb.py:386
def updateMessageLogger
Definition: confdb.py:571
def loadAdditionalConditions
Definition: confdb.py:585