CMS 3D CMS Logo

ConfigBuilder.py
Go to the documentation of this file.
1 #! /usr/bin/env python3
2 
3 from __future__ import print_function
4 __version__ = "$Revision: 1.19 $"
5 __source__ = "$Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v $"
6 
7 import FWCore.ParameterSet.Config as cms
8 from FWCore.ParameterSet.Modules import _Module
9 # The following import is provided for backward compatibility reasons.
10 # The function used to be defined in this file.
11 from FWCore.ParameterSet.MassReplace import massReplaceInputTag as MassReplaceInputTag
12 
13 import hashlib
14 import sys
15 import re
16 import collections
17 from subprocess import Popen,PIPE
18 import FWCore.ParameterSet.DictTypes as DictTypes
19 class Options:
20  pass
21 
22 # the canonical defaults
23 defaultOptions = Options()
24 defaultOptions.datamix = 'DataOnSim'
25 defaultOptions.isMC=False
26 defaultOptions.isData=True
27 defaultOptions.step=''
28 defaultOptions.pileup='NoPileUp'
29 defaultOptions.pileup_input = None
30 defaultOptions.pileup_dasoption = ''
31 defaultOptions.geometry = 'SimDB'
32 defaultOptions.geometryExtendedOptions = ['ExtendedGFlash','Extended','NoCastor']
33 defaultOptions.magField = ''
34 defaultOptions.conditions = None
35 defaultOptions.scenarioOptions=['pp','cosmics','nocoll','HeavyIons']
36 defaultOptions.harvesting= 'AtRunEnd'
37 defaultOptions.gflash = False
38 defaultOptions.number = -1
39 defaultOptions.number_out = None
40 defaultOptions.arguments = ""
41 defaultOptions.name = "NO NAME GIVEN"
42 defaultOptions.evt_type = ""
43 defaultOptions.filein = ""
44 defaultOptions.dasquery=""
45 defaultOptions.dasoption=""
46 defaultOptions.secondfilein = ""
47 defaultOptions.customisation_file = []
48 defaultOptions.customisation_file_unsch = []
49 defaultOptions.customise_commands = ""
50 defaultOptions.inline_custom=False
51 defaultOptions.particleTable = 'pythiapdt'
52 defaultOptions.particleTableList = ['pythiapdt','pdt']
53 defaultOptions.dirin = ''
54 defaultOptions.dirout = ''
55 defaultOptions.filetype = 'EDM'
56 defaultOptions.fileout = 'output.root'
57 defaultOptions.filtername = ''
58 defaultOptions.lazy_download = False
59 defaultOptions.custom_conditions = ''
60 defaultOptions.hltProcess = ''
61 defaultOptions.eventcontent = None
62 defaultOptions.datatier = None
63 defaultOptions.inlineEventContent = True
64 defaultOptions.inlineObjets =''
65 defaultOptions.hideGen=False
66 from Configuration.StandardSequences.VtxSmeared import VtxSmearedDefaultKey,VtxSmearedHIDefaultKey
67 defaultOptions.beamspot=None
68 defaultOptions.outputDefinition =''
69 defaultOptions.inputCommands = None
70 defaultOptions.outputCommands = None
71 defaultOptions.inputEventContent = ''
72 defaultOptions.dropDescendant = False
73 defaultOptions.relval = None
74 defaultOptions.profile = None
75 defaultOptions.isRepacked = False
76 defaultOptions.restoreRNDSeeds = False
77 defaultOptions.donotDropOnInput = ''
78 defaultOptions.python_filename =''
79 defaultOptions.io=None
80 defaultOptions.lumiToProcess=None
81 defaultOptions.fast=False
82 defaultOptions.runsAndWeightsForMC = None
83 defaultOptions.runsScenarioForMC = None
84 defaultOptions.runsAndWeightsForMCIntegerWeights = None
85 defaultOptions.runsScenarioForMCIntegerWeights = None
86 defaultOptions.runUnscheduled = False
87 defaultOptions.timeoutOutput = False
88 defaultOptions.nThreads = '1'
89 defaultOptions.nStreams = '0'
90 defaultOptions.nConcurrentLumis = '0'
91 defaultOptions.nConcurrentIOVs = '1'
92 
93 # some helper routines
94 def dumpPython(process,name):
95  theObject = getattr(process,name)
96  if isinstance(theObject,cms.Path) or isinstance(theObject,cms.EndPath) or isinstance(theObject,cms.Sequence):
97  return "process."+name+" = " + theObject.dumpPython()
98  elif isinstance(theObject,_Module) or isinstance(theObject,cms.ESProducer):
99  return "process."+name+" = " + theObject.dumpPython()+"\n"
100  else:
101  return "process."+name+" = " + theObject.dumpPython()+"\n"
102 def filesFromList(fileName,s=None):
103  import os
104  import FWCore.ParameterSet.Config as cms
105  prim=[]
106  sec=[]
107  for line in open(fileName,'r'):
108  if line.count(".root")>=2:
109  #two files solution...
110  entries=line.replace("\n","").split()
111  prim.append(entries[0])
112  sec.append(entries[1])
113  elif (line.find(".root")!=-1):
114  entry=line.replace("\n","")
115  prim.append(entry)
116  # remove any duplicates
117  prim = sorted(list(set(prim)))
118  sec = sorted(list(set(sec)))
119  if s:
120  if not hasattr(s,"fileNames"):
121  s.fileNames=cms.untracked.vstring(prim)
122  else:
123  s.fileNames.extend(prim)
124  if len(sec)!=0:
125  if not hasattr(s,"secondaryFileNames"):
126  s.secondaryFileNames=cms.untracked.vstring(sec)
127  else:
128  s.secondaryFileNames.extend(sec)
129  print("found files: ",prim)
130  if len(prim)==0:
131  raise Exception("There are not files in input from the file list")
132  if len(sec)!=0:
133  print("found parent files:",sec)
134  return (prim,sec)
135 
136 def filesFromDASQuery(query,option="",s=None):
137  import os,time
138  import FWCore.ParameterSet.Config as cms
139  prim=[]
140  sec=[]
141  print("the query is",query)
142  eC=5
143  count=0
144  while eC!=0 and count<3:
145  if count!=0:
146  print('Sleeping, then retrying DAS')
147  time.sleep(100)
148  p = Popen('dasgoclient %s --query "%s"'%(option,query), stdout=PIPE,shell=True, universal_newlines=True)
149  pipe=p.stdout.read()
150  tupleP = os.waitpid(p.pid, 0)
151  eC=tupleP[1]
152  count=count+1
153  if eC==0:
154  print("DAS succeeded after",count,"attempts",eC)
155  else:
156  print("DAS failed 3 times- I give up")
157  for line in pipe.split('\n'):
158  if line.count(".root")>=2:
159  #two files solution...
160  entries=line.replace("\n","").split()
161  prim.append(entries[0])
162  sec.append(entries[1])
163  elif (line.find(".root")!=-1):
164  entry=line.replace("\n","")
165  prim.append(entry)
166  # remove any duplicates
167  prim = sorted(list(set(prim)))
168  sec = sorted(list(set(sec)))
169  if s:
170  if not hasattr(s,"fileNames"):
171  s.fileNames=cms.untracked.vstring(prim)
172  else:
173  s.fileNames.extend(prim)
174  if len(sec)!=0:
175  if not hasattr(s,"secondaryFileNames"):
176  s.secondaryFileNames=cms.untracked.vstring(sec)
177  else:
178  s.secondaryFileNames.extend(sec)
179  print("found files: ",prim)
180  if len(sec)!=0:
181  print("found parent files:",sec)
182  return (prim,sec)
183 
184 def anyOf(listOfKeys,dict,opt=None):
185  for k in listOfKeys:
186  if k in dict:
187  toReturn=dict[k]
188  dict.pop(k)
189  return toReturn
190  if opt!=None:
191  return opt
192  else:
193  raise Exception("any of "+','.join(listOfKeys)+" are mandatory entries of --output options")
194 
196  """The main building routines """
197 
198  def __init__(self, options, process = None, with_output = False, with_input = False ):
199  """options taken from old cmsDriver and optparse """
200 
201  options.outfile_name = options.dirout+options.fileout
202 
203  self._options = options
204 
205  if self._options.isData and options.isMC:
206  raise Exception("ERROR: You may specify only --data or --mc, not both")
207  #if not self._options.conditions:
208  # raise Exception("ERROR: No conditions given!\nPlease specify conditions. E.g. via --conditions=IDEAL_30X::All")
209 
210  # check that MEtoEDMConverter (running in ENDJOB) and DQMIO don't run in the same job
211  if 'ENDJOB' in self._options.step:
212  if (hasattr(self._options,"outputDefinition") and \
213  self._options.outputDefinition != '' and \
214  any(anyOf(['t','tier','dataTier'],outdic) == 'DQMIO' for outdic in eval(self._options.outputDefinition))) or \
215  (hasattr(self._options,"datatier") and \
216  self._options.datatier and \
217  'DQMIO' in self._options.datatier):
218  print("removing ENDJOB from steps since not compatible with DQMIO dataTier")
219  self._options.step=self._options.step.replace(',ENDJOB','')
220 
221 
222 
223  # what steps are provided by this class?
224  stepList = [re.sub(r'^prepare_', '', methodName) for methodName in ConfigBuilder.__dict__ if methodName.startswith('prepare_')]
225  self.stepMap={}
226  self.stepKeys=[]
227  for step in self._options.step.split(","):
228  if step=='': continue
229  stepParts = step.split(":")
230  stepName = stepParts[0]
231  if stepName not in stepList and not stepName.startswith('re'):
232  raise ValueError("Step "+stepName+" unknown")
233  if len(stepParts)==1:
234  self.stepMap[stepName]=""
235  elif len(stepParts)==2:
236  self.stepMap[stepName]=stepParts[1].split('+')
237  elif len(stepParts)==3:
238  self.stepMap[stepName]=(stepParts[2].split('+'),stepParts[1])
239  else:
240  raise ValueError("Step definition "+step+" invalid")
241  self.stepKeys.append(stepName)
242 
243  #print "map of steps is:",self.stepMap
244 
245  self.with_output = with_output
246  self.process=process
247 
248  if hasattr(self._options,"no_output_flag") and self._options.no_output_flag:
249  self.with_output = False
250  self.with_input = with_input
251  self.imports = []
252  self.create_process()
253  self.define_Configs()
254  self.schedule = list()
255 
256  # we are doing three things here:
257  # creating a process to catch errors
258  # building the code to re-create the process
259 
261  # TODO: maybe a list of to be dumped objects would help as well
262  self.blacklist_paths = []
263  self.addedObjects = []
265 
271 
272  def profileOptions(self):
273  """
274  addIgProfService
275  Function to add the igprof profile service so that you can dump in the middle
276  of the run.
277  """
278  profileOpts = self._options.profile.split(':')
279  profilerStart = 1
280  profilerInterval = 100
281  profilerFormat = None
282  profilerJobFormat = None
283 
284  if len(profileOpts):
285  #type, given as first argument is unused here
286  profileOpts.pop(0)
287  if len(profileOpts):
288  startEvent = profileOpts.pop(0)
289  if not startEvent.isdigit():
290  raise Exception("%s is not a number" % startEvent)
291  profilerStart = int(startEvent)
292  if len(profileOpts):
293  eventInterval = profileOpts.pop(0)
294  if not eventInterval.isdigit():
295  raise Exception("%s is not a number" % eventInterval)
296  profilerInterval = int(eventInterval)
297  if len(profileOpts):
298  profilerFormat = profileOpts.pop(0)
299 
300 
301  if not profilerFormat:
302  profilerFormat = "%s___%s___%%I.gz" % (
303  self._options.evt_type.replace("_cfi", ""),
304  hashlib.md5(
305  (str(self._options.step) + str(self._options.pileup) + str(self._options.conditions) +
306  str(self._options.datatier) + str(self._options.profileTypeLabel)).encode('utf-8')
307  ).hexdigest()
308  )
309  if not profilerJobFormat and profilerFormat.endswith(".gz"):
310  profilerJobFormat = profilerFormat.replace(".gz", "_EndOfJob.gz")
311  elif not profilerJobFormat:
312  profilerJobFormat = profilerFormat + "_EndOfJob.gz"
313 
314  return (profilerStart,profilerInterval,profilerFormat,profilerJobFormat)
315 
316  def load(self,includeFile):
317  includeFile = includeFile.replace('/','.')
318  self.process.load(includeFile)
319  return sys.modules[includeFile]
320 
321  def loadAndRemember(self, includeFile):
322  """helper routine to load am memorize imports"""
323  # we could make the imports a on-the-fly data method of the process instance itself
324  # not sure if the latter is a good idea
325  includeFile = includeFile.replace('/','.')
326  self.imports.append(includeFile)
327  self.process.load(includeFile)
328  return sys.modules[includeFile]
329 
330  def executeAndRemember(self, command):
331  """helper routine to remember replace statements"""
332  self.additionalCommands.append(command)
333  if not command.strip().startswith("#"):
334  # substitute: process.foo = process.bar -> self.process.foo = self.process.bar
335  import re
336  exec(re.sub(r"([^a-zA-Z_0-9]|^)(process)([^a-zA-Z_0-9])",r"\1self.process\3",command))
337  #exec(command.replace("process.","self.process."))
338 
339  def addCommon(self):
340  if 'HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys():
341  self.process.options.Rethrow = ['ProductNotFound']
342  self.process.options.fileMode = 'FULLMERGE'
343 
344  self.addedObjects.append(("","options"))
345 
346  if self._options.lazy_download:
347  self.process.AdaptorConfig = cms.Service("AdaptorConfig",
348  stats = cms.untracked.bool(True),
349  enable = cms.untracked.bool(True),
350  cacheHint = cms.untracked.string("lazy-download"),
351  readHint = cms.untracked.string("read-ahead-buffered")
352  )
353  self.addedObjects.append(("Setup lazy download","AdaptorConfig"))
354 
355  #self.process.cmsDriverCommand = cms.untracked.PSet( command=cms.untracked.string('cmsDriver.py '+self._options.arguments) )
356  #self.addedObjects.append(("what cmsDriver command was used","cmsDriverCommand"))
357 
358  if self._options.profile:
359  (start, interval, eventFormat, jobFormat)=self.profileOptions()
360  self.process.IgProfService = cms.Service("IgProfService",
361  reportFirstEvent = cms.untracked.int32(start),
362  reportEventInterval = cms.untracked.int32(interval),
363  reportToFileAtPostEvent = cms.untracked.string("| gzip -c > %s"%(eventFormat)),
364  reportToFileAtPostEndJob = cms.untracked.string("| gzip -c > %s"%(jobFormat)))
365  self.addedObjects.append(("Setup IGProf Service for profiling","IgProfService"))
366 
367  def addMaxEvents(self):
368  """Here we decide how many evts will be processed"""
369  self.process.maxEvents.input = int(self._options.number)
370  if self._options.number_out:
371  self.process.maxEvents.output = int(self._options.number_out)
372  self.addedObjects.append(("","maxEvents"))
373 
374  def addSource(self):
375  """Here the source is built. Priority: file, generator"""
376  self.addedObjects.append(("Input source","source"))
377 
378  def filesFromOption(self):
379  for entry in self._options.filein.split(','):
380  print("entry",entry)
381  if entry.startswith("filelist:"):
382  filesFromList(entry[9:],self.process.source)
383  elif entry.startswith("dbs:") or entry.startswith("das:"):
384  filesFromDASQuery('file dataset = %s'%(entry[4:]),self._options.dasoption,self.process.source)
385  else:
386  self.process.source.fileNames.append(self._options.dirin+entry)
387  if self._options.secondfilein:
388  if not hasattr(self.process.source,"secondaryFileNames"):
389  raise Exception("--secondfilein not compatible with "+self._options.filetype+"input type")
390  for entry in self._options.secondfilein.split(','):
391  print("entry",entry)
392  if entry.startswith("filelist:"):
393  self.process.source.secondaryFileNames.extend((filesFromList(entry[9:]))[0])
394  elif entry.startswith("dbs:") or entry.startswith("das:"):
395  self.process.source.secondaryFileNames.extend((filesFromDASQuery('file dataset = %s'%(entry[4:]),self._options.dasoption))[0])
396  else:
397  self.process.source.secondaryFileNames.append(self._options.dirin+entry)
398 
399  if self._options.filein or self._options.dasquery:
400  if self._options.filetype == "EDM":
401  self.process.source=cms.Source("PoolSource",
402  fileNames = cms.untracked.vstring(),
403  secondaryFileNames= cms.untracked.vstring())
404  filesFromOption(self)
405  elif self._options.filetype == "DAT":
406  self.process.source=cms.Source("NewEventStreamFileReader",fileNames = cms.untracked.vstring())
407  filesFromOption(self)
408  elif self._options.filetype == "LHE":
409  self.process.source=cms.Source("LHESource", fileNames = cms.untracked.vstring())
410  if self._options.filein.startswith("lhe:"):
411  #list the article directory automatically
412  args=self._options.filein.split(':')
413  article=args[1]
414  print('LHE input from article ',article)
415  location='/store/lhe/'
416  import os
417  textOfFiles=os.popen('cmsLHEtoEOSManager.py -l '+article)
418  for line in textOfFiles:
419  for fileName in [x for x in line.split() if '.lhe' in x]:
420  self.process.source.fileNames.append(location+article+'/'+fileName)
421  #check first if list of LHE files is loaded (not empty)
422  if len(line)<2:
423  print('Issue to load LHE files, please check and try again.')
424  sys.exit(-1)
425  #Additional check to protect empty fileNames in process.source
426  if len(self.process.source.fileNames)==0:
427  print('Issue with empty filename, but can pass line check')
428  sys.exit(-1)
429  if len(args)>2:
430  self.process.source.skipEvents = cms.untracked.uint32(int(args[2]))
431  else:
432  filesFromOption(self)
433 
434  elif self._options.filetype == "DQM":
435  self.process.source=cms.Source("DQMRootSource",
436  fileNames = cms.untracked.vstring())
437  filesFromOption(self)
438 
439  elif self._options.filetype == "DQMDAQ":
440  # FIXME: how to configure it if there are no input files specified?
441  self.process.source=cms.Source("DQMStreamerReader")
442 
443 
444  if ('HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys()) and (not self._options.filetype == "DQM"):
445  self.process.source.processingMode = cms.untracked.string("RunsAndLumis")
446 
447  if self._options.dasquery!='':
448  self.process.source=cms.Source("PoolSource", fileNames = cms.untracked.vstring(),secondaryFileNames = cms.untracked.vstring())
449  filesFromDASQuery(self._options.dasquery,self._options.dasoption,self.process.source)
450 
451  if ('HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys()) and (not self._options.filetype == "DQM"):
452  self.process.source.processingMode = cms.untracked.string("RunsAndLumis")
453 
454 
455  if 'GEN' in self.stepMap.keys() and not self._options.filetype == "LHE":
456  if self._options.inputCommands:
457  self._options.inputCommands+=',drop LHEXMLStringProduct_*_*_*,'
458  else:
459  self._options.inputCommands='keep *, drop LHEXMLStringProduct_*_*_*,'
460 
461  if self.process.source and self._options.inputCommands and not self._options.filetype == "LHE":
462  if not hasattr(self.process.source,'inputCommands'): self.process.source.inputCommands=cms.untracked.vstring()
463  for command in self._options.inputCommands.split(','):
464  # remove whitespace around the keep/drop statements
465  command = command.strip()
466  if command=='': continue
467  self.process.source.inputCommands.append(command)
468  if not self._options.dropDescendant:
469  self.process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(False)
470 
471  if self._options.lumiToProcess:
472  import FWCore.PythonUtilities.LumiList as LumiList
473  self.process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange( LumiList.LumiList(self._options.lumiToProcess).getCMSSWString().split(',') )
474 
475  if 'GEN' in self.stepMap.keys() or 'LHE' in self.stepMap or (not self._options.filein and hasattr(self._options, "evt_type")):
476  if self.process.source is None:
477  self.process.source=cms.Source("EmptySource")
478 
479  # modify source in case of run-dependent MC
480  self.runsAndWeights=None
481  if self._options.runsAndWeightsForMC or self._options.runsScenarioForMC :
482  if not self._options.isMC :
483  raise Exception("options --runsAndWeightsForMC and --runsScenarioForMC are only valid for MC")
484  if self._options.runsAndWeightsForMC:
485  self.runsAndWeights = eval(self._options.runsAndWeightsForMC)
486  else:
487  from Configuration.StandardSequences.RunsAndWeights import RunsAndWeights
488  if isinstance(RunsAndWeights[self._options.runsScenarioForMC], str):
489  __import__(RunsAndWeights[self._options.runsScenarioForMC])
490  self.runsAndWeights = sys.modules[RunsAndWeights[self._options.runsScenarioForMC]].runProbabilityDistribution
491  else:
492  self.runsAndWeights = RunsAndWeights[self._options.runsScenarioForMC]
493 
494  if self.runsAndWeights:
495  import SimGeneral.Configuration.ThrowAndSetRandomRun as ThrowAndSetRandomRun
497  self.additionalCommands.append('import SimGeneral.Configuration.ThrowAndSetRandomRun as ThrowAndSetRandomRun')
498  self.additionalCommands.append('ThrowAndSetRandomRun.throwAndSetRandomRun(process.source,%s)'%(self.runsAndWeights))
499 
500  # modify source in case of run-dependent MC (Run-3 method)
502  if self._options.runsAndWeightsForMCIntegerWeights or self._options.runsScenarioForMCIntegerWeights:
503  if not self._options.isMC :
504  raise Exception("options --runsAndWeightsForMCIntegerWeights and --runsScenarioForMCIntegerWeights are only valid for MC")
505  if self._options.runsAndWeightsForMCIntegerWeights:
506  self.runsAndWeightsInt = eval(self._options.runsAndWeightsForMCIntegerWeights)
507  else:
508  from Configuration.StandardSequences.RunsAndWeights import RunsAndWeights
509  if isinstance(RunsAndWeights[self._options.runsScenarioForMCIntegerWeights], str):
510  __import__(RunsAndWeights[self._options.runsScenarioForMCIntegerWeights])
511  self.runsAndWeightsInt = sys.modules[RunsAndWeights[self._options.runsScenarioForMCIntegerWeights]].runProbabilityDistribution
512  else:
513  self.runsAndWeightsInt = RunsAndWeights[self._options.runsScenarioForMCIntegerWeights]
514 
515  if self.runsAndWeightsInt:
516  if not self._options.relval:
517  raise Exception("--relval option required when using --runsAndWeightsInt")
518  if 'DATAMIX' in self._options.step:
519  from SimGeneral.Configuration.LumiToRun import lumi_to_run
520  total_events, events_per_job = self._options.relval.split(',')
521  lumi_to_run_mapping = lumi_to_run(self.runsAndWeightsInt, int(total_events), int(events_per_job))
522  self.additionalCommands.append("process.source.firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID(*[cms.LuminosityBlockID(x,y) for x,y in " + str(lumi_to_run_mapping) + "])")
523 
524  return
525 
526  def addOutput(self):
527  """ Add output module to the process """
528  result=""
529  if self._options.outputDefinition:
530  if self._options.datatier:
531  print("--datatier & --eventcontent options ignored")
532 
533  #new output convention with a list of dict
534  outList = eval(self._options.outputDefinition)
535  for (id,outDefDict) in enumerate(outList):
536  outDefDictStr=outDefDict.__str__()
537  if not isinstance(outDefDict,dict):
538  raise Exception("--output needs to be passed a list of dict"+self._options.outputDefinition+" is invalid")
539  #requires option: tier
540  theTier=anyOf(['t','tier','dataTier'],outDefDict)
541  #optional option: eventcontent, filtername, selectEvents, moduleLabel, filename
542 
543  theStreamType=anyOf(['e','ec','eventContent','streamType'],outDefDict,theTier)
544  theFilterName=anyOf(['f','ftN','filterName'],outDefDict,'')
545  theSelectEvent=anyOf(['s','sE','selectEvents'],outDefDict,'')
546  theModuleLabel=anyOf(['l','mL','moduleLabel'],outDefDict,'')
547  theExtraOutputCommands=anyOf(['o','oC','outputCommands'],outDefDict,'')
548  # module label has a particular role
549  if not theModuleLabel:
550  tryNames=[theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+'output',
551  theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+theFilterName+'output',
552  theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+theFilterName+theSelectEvent.split(',')[0].replace(':','for').replace(' ','')+'output'
553  ]
554  for name in tryNames:
555  if not hasattr(self.process,name):
556  theModuleLabel=name
557  break
558  if not theModuleLabel:
559  raise Exception("cannot find a module label for specification: "+outDefDictStr)
560  if id==0:
561  defaultFileName=self._options.outfile_name
562  else:
563  defaultFileName=self._options.outfile_name.replace('.root','_in'+theTier+'.root')
564 
565  theFileName=self._options.dirout+anyOf(['fn','fileName'],outDefDict,defaultFileName)
566  if not theFileName.endswith('.root'):
567  theFileName+='.root'
568 
569  if len(outDefDict):
570  raise Exception("unused keys from --output options: "+','.join(outDefDict.keys()))
571  if theStreamType=='DQMIO': theStreamType='DQM'
572  if theStreamType=='ALL':
573  theEventContent = cms.PSet(outputCommands = cms.untracked.vstring('keep *'))
574  else:
575  theEventContent = getattr(self.process, theStreamType+"EventContent")
576 
577 
578  addAlCaSelects=False
579  if theStreamType=='ALCARECO' and not theFilterName:
580  theFilterName='StreamALCACombined'
581  addAlCaSelects=True
582 
583  CppType='PoolOutputModule'
584  if self._options.timeoutOutput:
585  CppType='TimeoutPoolOutputModule'
586  if theStreamType=='DQM' and theTier=='DQMIO': CppType='DQMRootOutputModule'
587  output = cms.OutputModule(CppType,
588  theEventContent.clone(),
589  fileName = cms.untracked.string(theFileName),
590  dataset = cms.untracked.PSet(
591  dataTier = cms.untracked.string(theTier),
592  filterName = cms.untracked.string(theFilterName))
593  )
594  if not theSelectEvent and hasattr(self.process,'generation_step') and theStreamType!='LHE':
595  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('generation_step'))
596  if not theSelectEvent and hasattr(self.process,'filtering_step'):
597  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filtering_step'))
598  if theSelectEvent:
599  output.SelectEvents =cms.untracked.PSet(SelectEvents = cms.vstring(theSelectEvent))
600 
601  if addAlCaSelects:
602  if not hasattr(output,'SelectEvents'):
603  output.SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring())
604  for alca in self.AlCaPaths:
605  output.SelectEvents.SelectEvents.extend(getattr(self.process,'OutALCARECO'+alca).SelectEvents.SelectEvents)
606 
607 
608  if hasattr(self.process,theModuleLabel):
609  raise Exception("the current process already has a module "+theModuleLabel+" defined")
610  #print "creating output module ",theModuleLabel
611  setattr(self.process,theModuleLabel,output)
612  outputModule=getattr(self.process,theModuleLabel)
613  setattr(self.process,theModuleLabel+'_step',cms.EndPath(outputModule))
614  path=getattr(self.process,theModuleLabel+'_step')
615  self.schedule.append(path)
616 
617  if not self._options.inlineEventContent and hasattr(self.process,theStreamType+"EventContent"):
618  def doNotInlineEventContent(instance,label = "cms.untracked.vstring(process."+theStreamType+"EventContent.outputCommands)"): return label
619  outputModule.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
620  if theExtraOutputCommands:
621  if not isinstance(theExtraOutputCommands,list):
622  raise Exception("extra ouput command in --option must be a list of strings")
623  if hasattr(self.process,theStreamType+"EventContent"):
624  self.executeAndRemember('process.%s.outputCommands.extend(%s)'%(theModuleLabel,theExtraOutputCommands))
625  else:
626  outputModule.outputCommands.extend(theExtraOutputCommands)
627 
628  result+="\nprocess."+theModuleLabel+" = "+outputModule.dumpPython()
629 
630 
631  return result
632 
633  streamTypes=self._options.eventcontent.split(',')
634  tiers=self._options.datatier.split(',')
635  if not self._options.outputDefinition and len(streamTypes)!=len(tiers):
636  raise Exception("number of event content arguments does not match number of datatier arguments")
637 
638  # if the only step is alca we don't need to put in an output
639  if self._options.step.split(',')[0].split(':')[0] == 'ALCA':
640  return "\n"
641 
642  for i,(streamType,tier) in enumerate(zip(streamTypes,tiers)):
643  if streamType=='': continue
644  if streamType == 'ALCARECO' and not 'ALCAPRODUCER' in self._options.step: continue
645  if streamType=='DQMIO': streamType='DQM'
646  eventContent=streamType
647 
648  if streamType == "NANOEDMAOD" :
649  eventContent = "NANOAOD"
650  elif streamType == "NANOEDMAODSIM" :
651  eventContent = "NANOAODSIM"
652  theEventContent = getattr(self.process, eventContent+"EventContent")
653  if i==0:
654  theFileName=self._options.outfile_name
655  theFilterName=self._options.filtername
656  else:
657  theFileName=self._options.outfile_name.replace('.root','_in'+streamType+'.root')
658  theFilterName=self._options.filtername
659  CppType='PoolOutputModule'
660  if self._options.timeoutOutput:
661  CppType='TimeoutPoolOutputModule'
662  if streamType=='DQM' and tier=='DQMIO': CppType='DQMRootOutputModule'
663  if "NANOAOD" in streamType : CppType='NanoAODOutputModule'
664  output = cms.OutputModule(CppType,
665  theEventContent,
666  fileName = cms.untracked.string(theFileName),
667  dataset = cms.untracked.PSet(dataTier = cms.untracked.string(tier),
668  filterName = cms.untracked.string(theFilterName)
669  )
670  )
671  if hasattr(self.process,"generation_step") and streamType!='LHE':
672  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('generation_step'))
673  if hasattr(self.process,"filtering_step"):
674  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filtering_step'))
675 
676  if streamType=='ALCARECO':
677  output.dataset.filterName = cms.untracked.string('StreamALCACombined')
678 
679  if "MINIAOD" in streamType:
680  from PhysicsTools.PatAlgos.slimming.miniAOD_tools import miniAOD_customizeOutput
682 
683  outputModuleName=streamType+'output'
684  setattr(self.process,outputModuleName,output)
685  outputModule=getattr(self.process,outputModuleName)
686  setattr(self.process,outputModuleName+'_step',cms.EndPath(outputModule))
687  path=getattr(self.process,outputModuleName+'_step')
688  self.schedule.append(path)
689 
690  if self._options.outputCommands and streamType!='DQM':
691  for evct in self._options.outputCommands.split(','):
692  if not evct: continue
693  self.executeAndRemember("process.%s.outputCommands.append('%s')"%(outputModuleName,evct.strip()))
694 
695  if not self._options.inlineEventContent:
696  tmpstreamType=streamType
697  if "NANOEDM" in tmpstreamType :
698  tmpstreamType=tmpstreamType.replace("NANOEDM","NANO")
699  def doNotInlineEventContent(instance,label = "process."+tmpstreamType+"EventContent.outputCommands"):
700  return label
701  outputModule.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
702 
703  result+="\nprocess."+outputModuleName+" = "+outputModule.dumpPython()
704 
705  return result
706 
707  def addStandardSequences(self):
708  """
709  Add selected standard sequences to the process
710  """
711  # load the pile up file
712  if self._options.pileup:
713  pileupSpec=self._options.pileup.split(',')[0]
714 
715  # Does the requested pile-up scenario exist?
716  from Configuration.StandardSequences.Mixing import Mixing,defineMixing
717  if not pileupSpec in Mixing and '.' not in pileupSpec and 'file:' not in pileupSpec:
718  message = pileupSpec+' is not a know mixing scenario:\n available are: '+'\n'.join(Mixing.keys())
719  raise Exception(message)
720 
721  # Put mixing parameters in a dictionary
722  if '.' in pileupSpec:
723  mixingDict={'file':pileupSpec}
724  elif pileupSpec.startswith('file:'):
725  mixingDict={'file':pileupSpec[5:]}
726  else:
727  import copy
728  mixingDict=copy.copy(Mixing[pileupSpec])
729  if len(self._options.pileup.split(','))>1:
730  mixingDict.update(eval(self._options.pileup[self._options.pileup.find(',')+1:]))
731 
732  # Load the pu cfg file corresponding to the requested pu scenario
733  if 'file:' in pileupSpec:
734  #the file is local
735  self.process.load(mixingDict['file'])
736  print("inlining mixing module configuration")
737  self._options.inlineObjets+=',mix'
738  else:
739  self.loadAndRemember(mixingDict['file'])
740 
741  mixingDict.pop('file')
742  if not "DATAMIX" in self.stepMap.keys(): # when DATAMIX is present, pileup_input refers to pre-mixed GEN-RAW
743  if self._options.pileup_input:
744  if self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:'):
745  mixingDict['F']=filesFromDASQuery('file dataset = %s'%(self._options.pileup_input[4:],),self._options.pileup_dasoption)[0]
746  elif self._options.pileup_input.startswith("filelist:"):
747  mixingDict['F']=(filesFromList(self._options.pileup_input[9:]))[0]
748  else:
749  mixingDict['F']=self._options.pileup_input.split(',')
750  specialization=defineMixing(mixingDict)
751  for command in specialization:
752  self.executeAndRemember(command)
753  if len(mixingDict)!=0:
754  raise Exception('unused mixing specification: '+mixingDict.keys().__str__())
755 
756 
757  # load the geometry file
758  try:
759  if len(self.stepMap):
760  self.loadAndRemember(self.GeometryCFF)
761  if ('SIM' in self.stepMap or 'reSIM' in self.stepMap) and not self._options.fast:
763  if self.geometryDBLabel:
764  self.executeAndRemember('if hasattr(process, "XMLFromDBSource"): process.XMLFromDBSource.label="%s"'%(self.geometryDBLabel))
765  self.executeAndRemember('if hasattr(process, "DDDetectorESProducerFromDB"): process.DDDetectorESProducerFromDB.label="%s"'%(self.geometryDBLabel))
766 
767  except ImportError:
768  print("Geometry option",self._options.geometry,"unknown.")
769  raise
770 
771  if len(self.stepMap):
772  self.loadAndRemember(self.magFieldCFF)
773 
774  for stepName in self.stepKeys:
775  stepSpec = self.stepMap[stepName]
776  print("Step:", stepName,"Spec:",stepSpec)
777  if stepName.startswith('re'):
778 
779  if stepName[2:] not in self._options.donotDropOnInput:
780  self._options.inputEventContent='%s,%s'%(stepName.upper(),self._options.inputEventContent)
781  stepName=stepName[2:]
782  if stepSpec=="":
783  getattr(self,"prepare_"+stepName)(sequence = getattr(self,stepName+"DefaultSeq"))
784  elif isinstance(stepSpec, list):
785  getattr(self,"prepare_"+stepName)(sequence = '+'.join(stepSpec))
786  elif isinstance(stepSpec, tuple):
787  getattr(self,"prepare_"+stepName)(sequence = ','.join([stepSpec[1],'+'.join(stepSpec[0])]))
788  else:
789  raise ValueError("Invalid step definition")
790 
791  if self._options.restoreRNDSeeds!=False:
792  #it is either True, or a process name
793  if self._options.restoreRNDSeeds==True:
794  self.executeAndRemember('process.RandomNumberGeneratorService.restoreStateLabel=cms.untracked.string("randomEngineStateProducer")')
795  else:
796  self.executeAndRemember('process.RandomNumberGeneratorService.restoreStateTag=cms.untracked.InputTag("randomEngineStateProducer","","%s")'%(self._options.restoreRNDSeeds))
797  if self._options.inputEventContent or self._options.inputCommands:
798  if self._options.inputCommands:
799  self._options.inputCommands+='keep *_randomEngineStateProducer_*_*,'
800  else:
801  self._options.inputCommands='keep *_randomEngineStateProducer_*_*,'
802 
803 
804  def completeInputCommand(self):
805  if self._options.inputEventContent:
806  import copy
807  def dropSecondDropStar(iec):
808  #drop occurence of 'drop *' in the list
809  count=0
810  for item in iec:
811  if item=='drop *':
812  if count!=0:
813  iec.remove(item)
814  count+=1
815 
816 
817  if not hasattr(self.process.source,'inputCommands'): self.process.source.inputCommands=cms.untracked.vstring()
818  for evct in self._options.inputEventContent.split(','):
819  if evct=='': continue
820  theEventContent = getattr(self.process, evct+"EventContent")
821  if hasattr(theEventContent,'outputCommands'):
822  self.process.source.inputCommands.extend(copy.copy(theEventContent.outputCommands))
823  if hasattr(theEventContent,'inputCommands'):
824  self.process.source.inputCommands.extend(copy.copy(theEventContent.inputCommands))
825 
826  dropSecondDropStar(self.process.source.inputCommands)
827 
828  if not self._options.dropDescendant:
829  self.process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(False)
830 
831 
832  return
833 
834  def addConditions(self):
835  """Add conditions to the process"""
836  if not self._options.conditions: return
837 
838  if 'FrontierConditions_GlobalTag' in self._options.conditions:
839  print('using FrontierConditions_GlobalTag in --conditions is not necessary anymore and will be deprecated soon. please update your command line')
840  self._options.conditions = self._options.conditions.replace("FrontierConditions_GlobalTag,",'')
841 
843  from Configuration.AlCa.GlobalTag import GlobalTag
844  self.process.GlobalTag = GlobalTag(self.process.GlobalTag, self._options.conditions, self._options.custom_conditions)
845  self.additionalCommands.append('from Configuration.AlCa.GlobalTag import GlobalTag')
846  self.additionalCommands.append('process.GlobalTag = GlobalTag(process.GlobalTag, %s, %s)' % (repr(self._options.conditions), repr(self._options.custom_conditions)))
847 
848 
849  def addCustomise(self,unsch=0):
850  """Include the customise code """
851 
852  custOpt=[]
853  if unsch==0:
854  for c in self._options.customisation_file:
855  custOpt.extend(c.split(","))
856  else:
857  for c in self._options.customisation_file_unsch:
858  custOpt.extend(c.split(","))
859 
860  custMap=DictTypes.SortedKeysDict()
861  for opt in custOpt:
862  if opt=='': continue
863  if opt.count('.')>1:
864  raise Exception("more than . in the specification:"+opt)
865  fileName=opt.split('.')[0]
866  if opt.count('.')==0: rest='customise'
867  else:
868  rest=opt.split('.')[1]
869  if rest=='py': rest='customise' #catch the case of --customise file.py
870 
871  if fileName in custMap:
872  custMap[fileName].extend(rest.split('+'))
873  else:
874  custMap[fileName]=rest.split('+')
875 
876  if len(custMap)==0:
877  final_snippet='\n'
878  else:
879  final_snippet='\n# customisation of the process.\n'
880 
881  allFcn=[]
882  for opt in custMap:
883  allFcn.extend(custMap[opt])
884  for fcn in allFcn:
885  if allFcn.count(fcn)!=1:
886  raise Exception("cannot specify twice "+fcn+" as a customisation method")
887 
888  for f in custMap:
889  # let python search for that package and do syntax checking at the same time
890  packageName = f.replace(".py","").replace("/",".")
891  __import__(packageName)
892  package = sys.modules[packageName]
893 
894  # now ask the package for its definition and pick .py instead of .pyc
895  customiseFile = re.sub(r'\.pyc$', '.py', package.__file__)
896 
897  final_snippet+='\n# Automatic addition of the customisation function from '+packageName+'\n'
898  if self._options.inline_custom:
899  for line in file(customiseFile,'r'):
900  if "import FWCore.ParameterSet.Config" in line:
901  continue
902  final_snippet += line
903  else:
904  final_snippet += 'from %s import %s \n'%(packageName,','.join(custMap[f]))
905  for fcn in custMap[f]:
906  print("customising the process with",fcn,"from",f)
907  if not hasattr(package,fcn):
908  #bound to fail at run time
909  raise Exception("config "+f+" has no function "+fcn)
910  #execute the command
911  self.process=getattr(package,fcn)(self.process)
912  #and print it in the configuration
913  final_snippet += "\n#call to customisation function "+fcn+" imported from "+packageName
914  final_snippet += "\nprocess = %s(process)\n"%(fcn,)
915 
916  if len(custMap)!=0:
917  final_snippet += '\n# End of customisation functions\n'
918 
919 
920  return final_snippet
921 
922  def addCustomiseCmdLine(self):
923  final_snippet='\n# Customisation from command line\n'
924  if self._options.customise_commands:
925  import string
926  for com in self._options.customise_commands.split('\\n'):
927  com=com.lstrip()
928  self.executeAndRemember(com)
929  final_snippet +='\n'+com
930 
931  return final_snippet
932 
933  #----------------------------------------------------------------------------
934  # here the methods to define the python includes for each step or
935  # conditions
936  #----------------------------------------------------------------------------
937  def define_Configs(self):
938  if len(self.stepMap):
939  self.loadAndRemember('Configuration/StandardSequences/Services_cff')
940  if self._options.particleTable not in defaultOptions.particleTableList:
941  print('Invalid particle table provided. Options are:')
942  print(defaultOptions.particleTable)
943  sys.exit(-1)
944  else:
945  if len(self.stepMap):
946  self.loadAndRemember('SimGeneral.HepPDTESSource.'+self._options.particleTable+'_cfi')
947 
948  self.loadAndRemember('FWCore/MessageService/MessageLogger_cfi')
949 
950  self.ALCADefaultCFF="Configuration/StandardSequences/AlCaRecoStreams_cff"
951  self.GENDefaultCFF="Configuration/StandardSequences/Generator_cff"
952  self.SIMDefaultCFF="Configuration/StandardSequences/Sim_cff"
953  self.DIGIDefaultCFF="Configuration/StandardSequences/Digi_cff"
954  self.DIGI2RAWDefaultCFF="Configuration/StandardSequences/DigiToRaw_cff"
955  self.L1EMDefaultCFF='Configuration/StandardSequences/SimL1Emulator_cff'
956  self.L1MENUDefaultCFF="Configuration/StandardSequences/L1TriggerDefaultMenu_cff"
957  self.HLTDefaultCFF="Configuration/StandardSequences/HLTtable_cff"
958  self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_Data_cff"
959  if self._options.isRepacked: self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_DataMapper_cff"
960  self.L1RecoDefaultCFF="Configuration/StandardSequences/L1Reco_cff"
961  self.L1TrackTriggerDefaultCFF="Configuration/StandardSequences/L1TrackTrigger_cff"
962  self.RECODefaultCFF="Configuration/StandardSequences/Reconstruction_Data_cff"
963  self.RECOSIMDefaultCFF="Configuration/StandardSequences/RecoSim_cff"
964  self.PATDefaultCFF="Configuration/StandardSequences/PAT_cff"
965  self.NANODefaultCFF="PhysicsTools/NanoAOD/nano_cff"
966  self.NANOGENDefaultCFF="PhysicsTools/NanoAOD/nanogen_cff"
967  self.EIDefaultCFF=None
968  self.SKIMDefaultCFF="Configuration/StandardSequences/Skims_cff"
969  self.POSTRECODefaultCFF="Configuration/StandardSequences/PostRecoGenerator_cff"
970  self.VALIDATIONDefaultCFF="Configuration/StandardSequences/Validation_cff"
971  self.L1HwValDefaultCFF = "Configuration/StandardSequences/L1HwVal_cff"
972  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOffline_cff"
973  self.HARVESTINGDefaultCFF="Configuration/StandardSequences/Harvesting_cff"
974  self.ALCAHARVESTDefaultCFF="Configuration/StandardSequences/AlCaHarvesting_cff"
975  self.ENDJOBDefaultCFF="Configuration/StandardSequences/EndOfProcess_cff"
976  self.ConditionsDefaultCFF = "Configuration/StandardSequences/FrontierConditions_GlobalTag_cff"
977  self.CFWRITERDefaultCFF = "Configuration/StandardSequences/CrossingFrameWriter_cff"
978  self.REPACKDefaultCFF="Configuration/StandardSequences/DigiToRaw_Repack_cff"
979 
980  if "DATAMIX" in self.stepMap.keys():
981  self.DATAMIXDefaultCFF="Configuration/StandardSequences/DataMixer"+self._options.datamix+"_cff"
982  self.DIGIDefaultCFF="Configuration/StandardSequences/DigiDM_cff"
983  self.DIGI2RAWDefaultCFF="Configuration/StandardSequences/DigiToRawDM_cff"
984  self.L1EMDefaultCFF='Configuration/StandardSequences/SimL1EmulatorDM_cff'
985 
986  self.ALCADefaultSeq=None
987  self.LHEDefaultSeq='externalLHEProducer'
988  self.GENDefaultSeq='pgen'
989  self.SIMDefaultSeq='psim'
990  self.DIGIDefaultSeq='pdigi'
992  self.DIGI2RAWDefaultSeq='DigiToRaw'
993  self.HLTDefaultSeq='GRun'
994  self.L1DefaultSeq=None
999  self.RAW2DIGIDefaultSeq='RawToDigi'
1000  self.L1RecoDefaultSeq='L1Reco'
1001  self.L1TrackTriggerDefaultSeq='L1TrackTrigger'
1002  if self._options.fast or ('RAW2DIGI' in self.stepMap and 'RECO' in self.stepMap):
1003  self.RECODefaultSeq='reconstruction'
1004  else:
1005  self.RECODefaultSeq='reconstruction_fromRECO'
1006  self.RECOSIMDefaultSeq='recosim'
1007  self.EIDefaultSeq='top'
1009  self.L1HwValDefaultSeq='L1HwVal'
1010  self.DQMDefaultSeq='DQMOffline'
1012  self.ENDJOBDefaultSeq='endOfProcess'
1013  self.REPACKDefaultSeq='DigiToRawRepack'
1014  self.PATDefaultSeq='miniAOD'
1015  self.PATGENDefaultSeq='miniGEN'
1016  #TODO: Check based of file input
1017  self.NANOGENDefaultSeq='nanogenSequence'
1018  self.NANODefaultSeq='nanoSequence'
1020  self.EVTCONTDefaultCFF="Configuration/EventContent/EventContent_cff"
1022  if not self._options.beamspot:
1023  self._options.beamspot=VtxSmearedDefaultKey
1024 
1025  # if its MC then change the raw2digi
1026  if self._options.isMC==True:
1027  self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_cff"
1028  self.RECODefaultCFF="Configuration/StandardSequences/Reconstruction_cff"
1029  self.PATDefaultCFF="Configuration/StandardSequences/PATMC_cff"
1030  self.PATGENDefaultCFF="Configuration/StandardSequences/PATGEN_cff"
1031  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineMC_cff"
1032  self.ALCADefaultCFF="Configuration/StandardSequences/AlCaRecoStreamsMC_cff"
1033  self.NANODefaultSeq='nanoSequenceMC'
1034  else:
1035  self._options.beamspot = None
1036 
1037  #patch for gen, due to backward incompatibility
1038  if 'reGEN' in self.stepMap:
1039  self.GENDefaultSeq='fixGenInfo'
1040 
1041  if self._options.scenario=='cosmics':
1042  self._options.pileup='Cosmics'
1043  self.DIGIDefaultCFF="Configuration/StandardSequences/DigiCosmics_cff"
1044  self.RECODefaultCFF="Configuration/StandardSequences/ReconstructionCosmics_cff"
1045  self.SKIMDefaultCFF="Configuration/StandardSequences/SkimsCosmics_cff"
1046  self.EVTCONTDefaultCFF="Configuration/EventContent/EventContentCosmics_cff"
1047  self.VALIDATIONDefaultCFF="Configuration/StandardSequences/ValidationCosmics_cff"
1048  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineCosmics_cff"
1049  if self._options.isMC==True:
1050  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineCosmicsMC_cff"
1051  self.HARVESTINGDefaultCFF="Configuration/StandardSequences/HarvestingCosmics_cff"
1052  self.RECODefaultSeq='reconstructionCosmics'
1053  self.DQMDefaultSeq='DQMOfflineCosmics'
1054 
1055  if self._options.scenario=='HeavyIons':
1056  if not self._options.beamspot:
1057  self._options.beamspot=VtxSmearedHIDefaultKey
1058  self.HLTDefaultSeq = 'HIon'
1059  self.VALIDATIONDefaultCFF="Configuration/StandardSequences/ValidationHeavyIons_cff"
1060  self.VALIDATIONDefaultSeq=''
1061  self.EVTCONTDefaultCFF="Configuration/EventContent/EventContentHeavyIons_cff"
1062  self.RECODefaultCFF="Configuration/StandardSequences/ReconstructionHeavyIons_cff"
1063  self.RECODefaultSeq='reconstructionHeavyIons'
1064  self.ALCADefaultCFF = "Configuration/StandardSequences/AlCaRecoStreamsHeavyIons_cff"
1065  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineHeavyIons_cff"
1066  self.DQMDefaultSeq='DQMOfflineHeavyIons'
1067  self.SKIMDefaultCFF="Configuration/StandardSequences/SkimsHeavyIons_cff"
1068  self.HARVESTINGDefaultCFF="Configuration/StandardSequences/HarvestingHeavyIons_cff"
1069  if self._options.isMC==True:
1070  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineHeavyIonsMC_cff"
1071 
1072 
1075  self.USERDefaultSeq='user'
1076  self.USERDefaultCFF=None
1078  # the magnetic field
1079  self.magFieldCFF = 'Configuration/StandardSequences/MagneticField_'+self._options.magField.replace('.','')+'_cff'
1080  self.magFieldCFF = self.magFieldCFF.replace("__",'_')
1081 
1082  # the geometry
1083  self.GeometryCFF='Configuration/StandardSequences/GeometryRecoDB_cff'
1085  simGeometry=''
1086  if self._options.fast:
1087  if 'start' in self._options.conditions.lower():
1088  self.GeometryCFF='FastSimulation/Configuration/Geometries_START_cff'
1089  else:
1090  self.GeometryCFF='FastSimulation/Configuration/Geometries_MC_cff'
1091  else:
1092  def inGeometryKeys(opt):
1093  from Configuration.StandardSequences.GeometryConf import GeometryConf
1094  if opt in GeometryConf:
1095  return GeometryConf[opt]
1096  else:
1097  return opt
1098 
1099  geoms=self._options.geometry.split(',')
1100  if len(geoms)==1: geoms=inGeometryKeys(geoms[0]).split(',')
1101  if len(geoms)==2:
1102  #may specify the reco geometry
1103  if '/' in geoms[1] or '_cff' in geoms[1]:
1104  self.GeometryCFF=geoms[1]
1105  else:
1106  self.GeometryCFF='Configuration/Geometry/Geometry'+geoms[1]+'_cff'
1107 
1108  if (geoms[0].startswith('DB:')):
1109  self.SimGeometryCFF='Configuration/StandardSequences/GeometrySimDB_cff'
1110  self.geometryDBLabel=geoms[0][3:]
1111  print("with DB:")
1112  else:
1113  if '/' in geoms[0] or '_cff' in geoms[0]:
1114  self.SimGeometryCFF=geoms[0]
1115  else:
1116  simGeometry=geoms[0]
1117  if self._options.gflash==True:
1118  self.SimGeometryCFF='Configuration/Geometry/Geometry'+geoms[0]+'GFlash_cff'
1119  else:
1120  self.SimGeometryCFF='Configuration/Geometry/Geometry'+geoms[0]+'_cff'
1121 
1122  # synchronize the geometry configuration and the FullSimulation sequence to be used
1123  if simGeometry not in defaultOptions.geometryExtendedOptions:
1124  self.SIMDefaultCFF="Configuration/StandardSequences/SimIdeal_cff"
1125 
1126  if self._options.scenario=='nocoll' or self._options.scenario=='cosmics':
1127  self.SIMDefaultCFF="Configuration/StandardSequences/SimNOBEAM_cff"
1128  self._options.beamspot='NoSmear'
1129 
1130  # fastsim requires some changes to the default cff files and sequences
1131  if self._options.fast:
1132  self.SIMDefaultCFF = 'FastSimulation.Configuration.SimIdeal_cff'
1133  self.RECODefaultCFF= 'FastSimulation.Configuration.Reconstruction_AftMix_cff'
1134  self.RECOBEFMIXDefaultCFF = 'FastSimulation.Configuration.Reconstruction_BefMix_cff'
1135  self.RECOBEFMIXDefaultSeq = 'reconstruction_befmix'
1136  self.NANODefaultSeq = 'nanoSequenceFS'
1137  self.DQMOFFLINEDefaultCFF="DQMOffline.Configuration.DQMOfflineFS_cff"
1138 
1139  # Mixing
1140  if self._options.pileup=='default':
1141  from Configuration.StandardSequences.Mixing import MixingDefaultKey
1142  self._options.pileup=MixingDefaultKey
1143 
1144 
1145  #not driven by a default cff anymore
1146  if self._options.isData:
1147  self._options.pileup=None
1148 
1149 
1152  # for alca, skims, etc
1153  def addExtraStream(self, name, stream, workflow='full'):
1154  # define output module and go from there
1155  output = cms.OutputModule("PoolOutputModule")
1156  if stream.selectEvents.parameters_().__len__()!=0:
1157  output.SelectEvents = stream.selectEvents
1158  else:
1159  output.SelectEvents = cms.untracked.PSet()
1160  output.SelectEvents.SelectEvents=cms.vstring()
1161  if isinstance(stream.paths,tuple):
1162  for path in stream.paths:
1163  output.SelectEvents.SelectEvents.append(path.label())
1164  else:
1165  output.SelectEvents.SelectEvents.append(stream.paths.label())
1166 
1167 
1168 
1169  if isinstance(stream.content,str):
1170  evtPset=getattr(self.process,stream.content)
1171  for p in evtPset.parameters_():
1172  setattr(output,p,getattr(evtPset,p))
1173  if not self._options.inlineEventContent:
1174  def doNotInlineEventContent(instance,label = "process."+stream.content+".outputCommands"):
1175  return label
1176  output.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
1177  else:
1178  output.outputCommands = stream.content
1179 
1180 
1181  output.fileName = cms.untracked.string(self._options.dirout+stream.name+'.root')
1182 
1183  output.dataset = cms.untracked.PSet( dataTier = stream.dataTier,
1184  filterName = cms.untracked.string(stream.name))
1185 
1186  if self._options.filtername:
1187  output.dataset.filterName= cms.untracked.string(self._options.filtername+"_"+stream.name)
1188 
1189  #add an automatic flushing to limit memory consumption
1190  output.eventAutoFlushCompressedSize=cms.untracked.int32(5*1024*1024)
1191 
1192  if workflow in ("producers,full"):
1193  if isinstance(stream.paths,tuple):
1194  for path in stream.paths:
1195  self.schedule.append(path)
1196  else:
1197  self.schedule.append(stream.paths)
1198 
1199 
1200  # in case of relvals we don't want to have additional outputs
1201  if (not self._options.relval) and workflow in ("full","output"):
1202  self.additionalOutputs[name] = output
1203  setattr(self.process,name,output)
1204 
1205  if workflow == 'output':
1206  # adjust the select events to the proper trigger results from previous process
1207  filterList = output.SelectEvents.SelectEvents
1208  for i, filter in enumerate(filterList):
1209  filterList[i] = filter+":"+self._options.triggerResultsProcess
1210 
1211  return output
1212 
1213  #----------------------------------------------------------------------------
1214  # here the methods to create the steps. Of course we are doing magic here ;)
1215  # prepare_STEPNAME modifies self.process and what else's needed.
1216  #----------------------------------------------------------------------------
1217 
1218  def loadDefaultOrSpecifiedCFF(self, sequence,defaultCFF):
1219  if ( len(sequence.split('.'))==1 ):
1220  l=self.loadAndRemember(defaultCFF)
1221  elif ( len(sequence.split('.'))==2 ):
1222  l=self.loadAndRemember(sequence.split('.')[0])
1223  sequence=sequence.split('.')[1]
1224  else:
1225  print("sub sequence configuration must be of the form dir/subdir/cff.a+b+c or cff.a")
1226  print(sequence,"not recognized")
1227  raise
1228  return l
1229 
1230  def scheduleSequence(self,seq,prefix,what='Path'):
1231  if '*' in seq:
1232  #create only one path with all sequences in it
1233  for i,s in enumerate(seq.split('*')):
1234  if i==0:
1235  setattr(self.process,prefix,getattr(cms,what)( getattr(self.process, s) ))
1236  else:
1237  p=getattr(self.process,prefix)
1238  tmp = getattr(self.process, s)
1239  if isinstance(tmp, cms.Task):
1240  p.associate(tmp)
1241  else:
1242  p+=tmp
1243  self.schedule.append(getattr(self.process,prefix))
1244  return
1245  else:
1246  #create as many path as many sequences
1247  if not '+' in seq:
1248  if self.nextScheduleIsConditional:
1249  self.conditionalPaths.append(prefix)
1250  setattr(self.process,prefix,getattr(cms,what)( getattr(self.process, seq) ))
1251  self.schedule.append(getattr(self.process,prefix))
1252  else:
1253  for i,s in enumerate(seq.split('+')):
1254  sn=prefix+'%d'%(i)
1255  setattr(self.process,sn,getattr(cms,what)( getattr(self.process, s) ))
1256  self.schedule.append(getattr(self.process,sn))
1257  return
1258 
1259  def scheduleSequenceAtEnd(self,seq,prefix):
1260  self.scheduleSequence(seq,prefix,what='EndPath')
1261  return
1262 
1263  def prepare_ALCAPRODUCER(self, sequence = None):
1264  self.prepare_ALCA(sequence, workflow = "producers")
1265 
1266  def prepare_ALCAOUTPUT(self, sequence = None):
1267  self.prepare_ALCA(sequence, workflow = "output")
1268 
1269  def prepare_ALCA(self, sequence = None, workflow = 'full'):
1270  """ Enrich the process with alca streams """
1271  alcaConfig=self.loadDefaultOrSpecifiedCFF(sequence,self.ALCADefaultCFF)
1272  sequence = sequence.split('.')[-1]
1273 
1274  # decide which ALCA paths to use
1275  alcaList = sequence.split("+")
1276  maxLevel=0
1277  from Configuration.AlCa.autoAlca import autoAlca
1278  # support @X from autoAlca.py, and recursion support: i.e T0:@Mu+@EG+...
1279  self.expandMapping(alcaList,autoAlca)
1280  self.AlCaPaths=[]
1281  for name in alcaConfig.__dict__:
1282  alcastream = getattr(alcaConfig,name)
1283  shortName = name.replace('ALCARECOStream','')
1284  if shortName in alcaList and isinstance(alcastream,cms.FilteredStream):
1285  output = self.addExtraStream(name,alcastream, workflow = workflow)
1286  self.executeAndRemember('process.ALCARECOEventContent.outputCommands.extend(process.OutALCARECO'+shortName+'_noDrop.outputCommands)')
1287  self.AlCaPaths.append(shortName)
1288  if 'DQM' in alcaList:
1289  if not self._options.inlineEventContent and hasattr(self.process,name):
1290  self.executeAndRemember('process.' + name + '.outputCommands.append("keep *_MEtoEDMConverter_*_*")')
1291  else:
1292  output.outputCommands.append("keep *_MEtoEDMConverter_*_*")
1293 
1294  #rename the HLT process name in the alca modules
1295  if self._options.hltProcess or 'HLT' in self.stepMap:
1296  if isinstance(alcastream.paths,tuple):
1297  for path in alcastream.paths:
1298  self.renameHLTprocessInSequence(path.label())
1299  else:
1300  self.renameHLTprocessInSequence(alcastream.paths.label())
1301 
1302  for i in range(alcaList.count(shortName)):
1303  alcaList.remove(shortName)
1304 
1305  # DQM needs a special handling
1306  elif name == 'pathALCARECODQM' and 'DQM' in alcaList:
1307  path = getattr(alcaConfig,name)
1308  self.schedule.append(path)
1309  alcaList.remove('DQM')
1310 
1311  if isinstance(alcastream,cms.Path):
1312  #black list the alca path so that they do not appear in the cfg
1313  self.blacklist_paths.append(alcastream)
1314 
1315 
1316  if len(alcaList) != 0:
1317  available=[]
1318  for name in alcaConfig.__dict__:
1319  alcastream = getattr(alcaConfig,name)
1320  if isinstance(alcastream,cms.FilteredStream):
1321  available.append(name.replace('ALCARECOStream',''))
1322  print("The following alcas could not be found "+str(alcaList))
1323  print("available ",available)
1324  #print "verify your configuration, ignoring for now"
1325  raise Exception("The following alcas could not be found "+str(alcaList))
1326 
1327  def prepare_LHE(self, sequence = None):
1328  #load the fragment
1329 
1330  loadFragment = self._options.evt_type.replace('.py','',).replace('.','_').replace('python/','').replace('/','.')
1331  print("Loading lhe fragment from",loadFragment)
1332  __import__(loadFragment)
1333  self.process.load(loadFragment)
1334 
1335  self._options.inlineObjets+=','+sequence
1336 
1337  getattr(self.process,sequence).nEvents = int(self._options.number)
1338 
1339  #schedule it
1340  self.process.lhe_step = cms.Path( getattr( self.process,sequence) )
1341  self.excludedPaths.append("lhe_step")
1342  self.schedule.append( self.process.lhe_step )
1343 
1344  def prepare_GEN(self, sequence = None):
1345  """ load the fragment of generator configuration """
1346  loadFailure=False
1347  #remove trailing .py
1348  #support old style .cfi by changing into something.cfi into something_cfi
1349  #remove python/ from the name
1350  loadFragment = self._options.evt_type.replace('.py','',).replace('.','_').replace('python/','')
1351  #standard location of fragments
1352  if not '/' in loadFragment:
1353  loadFragment='Configuration.Generator.'+loadFragment
1354  else:
1355  loadFragment=loadFragment.replace('/','.')
1356  try:
1357  print("Loading generator fragment from",loadFragment)
1358  __import__(loadFragment)
1359  except:
1360  loadFailure=True
1361  #if self.process.source and self.process.source.type_()=='EmptySource':
1362  if not (self._options.filein or self._options.dasquery):
1363  raise Exception("Neither gen fragment of input files provided: this is an inconsistent GEN step configuration")
1364 
1365  if not loadFailure:
1366  generatorModule=sys.modules[loadFragment]
1367  genModules=generatorModule.__dict__
1368  #remove lhe producer module since this should have been
1369  #imported instead in the LHE step
1370  if self.LHEDefaultSeq in genModules:
1371  del genModules[self.LHEDefaultSeq]
1372 
1373  if self._options.hideGen:
1374  self.loadAndRemember(loadFragment)
1375  else:
1376  self.process.load(loadFragment)
1377  # expose the objects from that fragment to the configuration
1378  import FWCore.ParameterSet.Modules as cmstypes
1379  for name in genModules:
1380  theObject = getattr(generatorModule,name)
1381  if isinstance(theObject, cmstypes._Module):
1382  self._options.inlineObjets=name+','+self._options.inlineObjets
1383  elif isinstance(theObject, cms.Sequence) or isinstance(theObject, cmstypes.ESProducer):
1384  self._options.inlineObjets+=','+name
1385 
1386  if sequence == self.GENDefaultSeq or sequence == 'pgen_genonly':
1387  if 'ProductionFilterSequence' in genModules and ('generator' in genModules):
1388  self.productionFilterSequence = 'ProductionFilterSequence'
1389  elif 'generator' in genModules:
1390  self.productionFilterSequence = 'generator'
1391 
1392  """ Enrich the schedule with the rest of the generation step """
1393  self.loadDefaultOrSpecifiedCFF(sequence,self.GENDefaultCFF)
1394  genSeqName=sequence.split('.')[-1]
1395 
1396  if True:
1397  try:
1398  from Configuration.StandardSequences.VtxSmeared import VtxSmeared
1399  cffToBeLoaded=VtxSmeared[self._options.beamspot]
1400  self.loadAndRemember(cffToBeLoaded)
1401  except ImportError:
1402  raise Exception("VertexSmearing type or beamspot "+self._options.beamspot+" unknown.")
1403 
1404  if self._options.scenario == 'HeavyIons':
1405  if self._options.pileup=='HiMixGEN':
1406  self.loadAndRemember("Configuration/StandardSequences/GeneratorMix_cff")
1407  elif self._options.pileup=='HiMixEmbGEN':
1408  self.loadAndRemember("Configuration/StandardSequences/GeneratorEmbMix_cff")
1409  else:
1410  self.loadAndRemember("Configuration/StandardSequences/GeneratorHI_cff")
1411 
1412  self.process.generation_step = cms.Path( getattr(self.process,genSeqName) )
1413  self.schedule.append(self.process.generation_step)
1414 
1415  #register to the genstepfilter the name of the path (static right now, but might evolve)
1416  self.executeAndRemember('process.genstepfilter.triggerConditions=cms.vstring("generation_step")')
1417 
1418  if 'reGEN' in self.stepMap:
1419  #stop here
1420  return
1421 
1422  """ Enrich the schedule with the summary of the filter step """
1423  #the gen filter in the endpath
1424  self.loadAndRemember("GeneratorInterface/Core/genFilterSummary_cff")
1425  self.scheduleSequenceAtEnd('genFilterSummary','genfiltersummary_step')
1426  return
1427 
1428  def prepare_SIM(self, sequence = None):
1429  """ Enrich the schedule with the simulation step"""
1430  self.loadDefaultOrSpecifiedCFF(sequence,self.SIMDefaultCFF)
1431  if not self._options.fast:
1432  if self._options.gflash==True:
1433  self.loadAndRemember("Configuration/StandardSequences/GFlashSIM_cff")
1434 
1435  if self._options.magField=='0T':
1436  self.executeAndRemember("process.g4SimHits.UseMagneticField = cms.bool(False)")
1437  else:
1438  if self._options.magField=='0T':
1439  self.executeAndRemember("process.fastSimProducer.detectorDefinition.magneticFieldZ = cms.untracked.double(0.)")
1440 
1441  self.scheduleSequence(sequence.split('.')[-1],'simulation_step')
1442  return
1443 
1444  def prepare_DIGI(self, sequence = None):
1445  """ Enrich the schedule with the digitisation step"""
1446  self.loadDefaultOrSpecifiedCFF(sequence,self.DIGIDefaultCFF)
1447 
1448  if self._options.gflash==True:
1449  self.loadAndRemember("Configuration/StandardSequences/GFlashDIGI_cff")
1450 
1451  if sequence == 'pdigi_valid' or sequence == 'pdigi_hi':
1452  self.executeAndRemember("process.mix.digitizers = cms.PSet(process.theDigitizersValid)")
1453 
1454  if sequence != 'pdigi_nogen' and sequence != 'pdigi_valid_nogen' and sequence != 'pdigi_hi_nogen' and not self.process.source.type_()=='EmptySource' and not self._options.filetype == "LHE":
1455  if self._options.inputEventContent=='':
1456  self._options.inputEventContent='REGEN'
1457  else:
1458  self._options.inputEventContent=self._options.inputEventContent+',REGEN'
1459 
1460 
1461  self.scheduleSequence(sequence.split('.')[-1],'digitisation_step')
1462  return
1463 
1464  def prepare_CFWRITER(self, sequence = None):
1465  """ Enrich the schedule with the crossing frame writer step"""
1467  self.scheduleSequence('pcfw','cfwriter_step')
1468  return
1469 
1470  def prepare_DATAMIX(self, sequence = None):
1471  """ Enrich the schedule with the digitisation step"""
1473  self.scheduleSequence('pdatamix','datamixing_step')
1474 
1475  if self._options.pileup_input:
1476  theFiles=''
1477  if self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:'):
1478  theFiles=filesFromDASQuery('file dataset = %s'%(self._options.pileup_input[4:],),self._options.pileup_dasoption)[0]
1479  elif self._options.pileup_input.startswith("filelist:"):
1480  theFiles= (filesFromList(self._options.pileup_input[9:]))[0]
1481  else:
1482  theFiles=self._options.pileup_input.split(',')
1483  #print theFiles
1484  self.executeAndRemember( "process.mixData.input.fileNames = cms.untracked.vstring(%s)"%( theFiles ) )
1485 
1486  return
1487 
1488  def prepare_DIGI2RAW(self, sequence = None):
1490  self.scheduleSequence(sequence.split('.')[-1],'digi2raw_step')
1491  return
1492 
1493  def prepare_REPACK(self, sequence = None):
1495  self.scheduleSequence(sequence.split('.')[-1],'digi2repack_step')
1496  return
1497 
1498  def prepare_L1(self, sequence = None):
1499  """ Enrich the schedule with the L1 simulation step"""
1500  assert(sequence == None)
1501  self.loadAndRemember(self.L1EMDefaultCFF)
1502  self.scheduleSequence('SimL1Emulator','L1simulation_step')
1503  return
1504 
1505  def prepare_L1REPACK(self, sequence = None):
1506  """ Enrich the schedule with the L1 simulation step, running the L1 emulator on data unpacked from the RAW collection, and repacking the result in a new RAW collection"""
1507  supported = ['GT','GT1','GT2','GCTGT','Full','FullSimTP','FullMC','Full2015Data','uGT','CalouGT']
1508  if sequence in supported:
1509  self.loadAndRemember('Configuration/StandardSequences/SimL1EmulatorRepack_%s_cff'%sequence)
1510  if self._options.scenario == 'HeavyIons':
1511  self.renameInputTagsInSequence("SimL1Emulator","rawDataCollector","rawDataRepacker")
1512  self.scheduleSequence('SimL1Emulator','L1RePack_step')
1513  else:
1514  print("L1REPACK with '",sequence,"' is not supported! Supported choices are: ",supported)
1515  raise Exception('unsupported feature')
1516 
1517 
1518  def prepare_HLT(self, sequence = None):
1519  """ Enrich the schedule with the HLT simulation step"""
1520  if not sequence:
1521  print("no specification of the hlt menu has been given, should never happen")
1522  raise Exception('no HLT sequence provided')
1523 
1524  if '@' in sequence:
1525  # case where HLT:@something was provided
1526  from Configuration.HLT.autoHLT import autoHLT
1527  key = sequence[1:]
1528  if key in autoHLT:
1529  sequence = autoHLT[key]
1530  else:
1531  raise ValueError('no HLT mapping key "%s" found in autoHLT' % key)
1532 
1533  if ',' in sequence:
1534  #case where HLT:something:something was provided
1535  self.executeAndRemember('import HLTrigger.Configuration.Utilities')
1536  optionsForHLT = {}
1537  if self._options.scenario == 'HeavyIons':
1538  optionsForHLT['type'] = 'HIon'
1539  else:
1540  optionsForHLT['type'] = 'GRun'
1541  optionsForHLTConfig = ', '.join('%s=%s' % (key, repr(val)) for (key, val) in optionsForHLT.items())
1542  if sequence == 'run,fromSource':
1543  if hasattr(self.process.source,'firstRun'):
1544  self.executeAndRemember('process.loadHltConfiguration("run:%%d"%%(process.source.firstRun.value()),%s)'%(optionsForHLTConfig))
1545  elif hasattr(self.process.source,'setRunNumber'):
1546  self.executeAndRemember('process.loadHltConfiguration("run:%%d"%%(process.source.setRunNumber.value()),%s)'%(optionsForHLTConfig))
1547  else:
1548  raise Exception('Cannot replace menu to load %s'%(sequence))
1549  else:
1550  self.executeAndRemember('process.loadHltConfiguration("%s",%s)'%(sequence.replace(',',':'),optionsForHLTConfig))
1551  else:
1552  self.loadAndRemember('HLTrigger/Configuration/HLT_%s_cff' % sequence)
1553 
1554  if self._options.isMC:
1555  self._options.customisation_file.append("HLTrigger/Configuration/customizeHLTforMC.customizeHLTforMC")
1556 
1557  if self._options.name != 'HLT':
1558  self.additionalCommands.append('from HLTrigger.Configuration.CustomConfigs import ProcessName')
1559  self.additionalCommands.append('process = ProcessName(process)')
1560  self.additionalCommands.append('')
1561  from HLTrigger.Configuration.CustomConfigs import ProcessName
1562  self.process = ProcessName(self.process)
1563 
1564  self.schedule.append(self.process.HLTSchedule)
1565  [self.blacklist_paths.append(path) for path in self.process.HLTSchedule if isinstance(path,(cms.Path,cms.EndPath))]
1566 
1567  #this is a fake, to be removed with fastim migration and HLT menu dump
1568  if self._options.fast:
1569  if not hasattr(self.process,'HLTEndSequence'):
1570  self.executeAndRemember("process.HLTEndSequence = cms.Sequence( process.dummyModule )")
1571 
1572 
1573  def prepare_RAW2RECO(self, sequence = None):
1574  if ','in sequence:
1575  seqReco=sequence.split(',')[1]
1576  seqDigi=sequence.split(',')[0]
1577  else:
1578  print("RAW2RECO requires two specifications",sequence,"insufficient")
1579 
1580  self.prepare_RAW2DIGI(seqDigi)
1581  self.prepare_RECO(seqReco)
1582  return
1583 
1584  def prepare_RAW2DIGI(self, sequence = "RawToDigi"):
1586  self.scheduleSequence(sequence,'raw2digi_step')
1587  # if self._options.isRepacked:
1588  #self.renameInputTagsInSequence(sequence)
1589  return
1590 
1591  def prepare_PATFILTER(self, sequence=None):
1592  self.loadAndRemember("PhysicsTools/PatAlgos/slimming/metFilterPaths_cff")
1593  from PhysicsTools.PatAlgos.slimming.metFilterPaths_cff import allMetFilterPaths
1594  for filt in allMetFilterPaths:
1595  self.schedule.append(getattr(self.process,'Flag_'+filt))
1596 
1597  def prepare_L1HwVal(self, sequence = 'L1HwVal'):
1598  ''' Enrich the schedule with L1 HW validation '''
1599  self.loadDefaultOrSpecifiedCFF(sequence,self.L1HwValDefaultCFF)
1600  #self.scheduleSequence(sequence.split('.')[-1],'l1hwval_step')
1601  print('\n\n\n DEPRECATED this has no action \n\n\n')
1602  return
1603 
1604  def prepare_L1Reco(self, sequence = "L1Reco"):
1605  ''' Enrich the schedule with L1 reconstruction '''
1606  self.loadDefaultOrSpecifiedCFF(sequence,self.L1RecoDefaultCFF)
1607  self.scheduleSequence(sequence.split('.')[-1],'L1Reco_step')
1608  return
1609 
1610  def prepare_L1TrackTrigger(self, sequence = "L1TrackTrigger"):
1611  ''' Enrich the schedule with L1 reconstruction '''
1613  self.scheduleSequence(sequence.split('.')[-1],'L1TrackTrigger_step')
1614  return
1615 
1616  def prepare_FILTER(self, sequence = None):
1617  ''' Enrich the schedule with a user defined filter sequence '''
1618 
1619  filterConfig=self.load(sequence.split('.')[0])
1620  filterSeq=sequence.split('.')[-1]
1621 
1622  class PrintAllModules(object):
1623  def __init__(self):
1624  self.inliner=''
1625  pass
1626  def enter(self,visitee):
1627  try:
1628  label=visitee.label()
1629 
1630  self.inliner=label+','+self.inliner
1631  except:
1632  pass
1633  def leave(self,v): pass
1634 
1635  expander=PrintAllModules()
1636  getattr(self.process,filterSeq).visit( expander )
1637  self._options.inlineObjets+=','+expander.inliner
1638  self._options.inlineObjets+=','+filterSeq
1639 
1640 
1641  self.scheduleSequence(filterSeq,'filtering_step')
1642  self.nextScheduleIsConditional=True
1643 
1644  self.productionFilterSequence = filterSeq
1645 
1646  return
1647 
1648  def prepare_RECO(self, sequence = "reconstruction"):
1649  ''' Enrich the schedule with reconstruction '''
1650  self.loadDefaultOrSpecifiedCFF(sequence,self.RECODefaultCFF)
1651  self.scheduleSequence(sequence.split('.')[-1],'reconstruction_step')
1652  return
1653 
1654  def prepare_RECOSIM(self, sequence = "recosim"):
1655  ''' Enrich the schedule with reconstruction '''
1656  self.loadDefaultOrSpecifiedCFF(sequence,self.RECOSIMDefaultCFF)
1657  self.scheduleSequence(sequence.split('.')[-1],'recosim_step')
1658  return
1659 
1660  def prepare_RECOBEFMIX(self, sequence = "reconstruction"):
1661  ''' Enrich the schedule with the part of reconstruction that is done before mixing in FastSim'''
1662  if not self._options.fast:
1663  print("ERROR: this step is only implemented for FastSim")
1664  sys.exit()
1666  self.scheduleSequence(sequence.split('.')[-1],'reconstruction_befmix_step')
1667  return
1668 
1669  def prepare_PAT(self, sequence = "miniAOD"):
1670  ''' Enrich the schedule with PAT '''
1671  self.prepare_PATFILTER(self)
1672  self.loadDefaultOrSpecifiedCFF(sequence,self.PATDefaultCFF)
1673  self.labelsToAssociate.append('patTask')
1674  if self._options.isData:
1675  self._options.customisation_file_unsch.insert(0,"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllData")
1676  else:
1677  if self._options.fast:
1678  self._options.customisation_file_unsch.insert(0,"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllMCFastSim")
1679  else:
1680  self._options.customisation_file_unsch.insert(0,"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllMC")
1681 
1682  if self._options.hltProcess:
1683  if len(self._options.customise_commands) > 1:
1684  self._options.customise_commands = self._options.customise_commands + " \n"
1685  self._options.customise_commands = self._options.customise_commands + "process.patTrigger.processName = \""+self._options.hltProcess+"\"\n"
1686  self._options.customise_commands = self._options.customise_commands + "process.slimmedPatTrigger.triggerResults= cms.InputTag( 'TriggerResults::"+self._options.hltProcess+"' )\n"
1687  self._options.customise_commands = self._options.customise_commands + "process.patMuons.triggerResults= cms.InputTag( 'TriggerResults::"+self._options.hltProcess+"' )\n"
1688 
1689 # self.renameHLTprocessInSequence(sequence)
1690 
1691  return
1692 
1693  def prepare_PATGEN(self, sequence = "miniGEN"):
1694  ''' Enrich the schedule with PATGEN '''
1695  self.loadDefaultOrSpecifiedCFF(sequence,self.PATGENDefaultCFF) #this is unscheduled
1696  self.labelsToAssociate.append('patGENTask')
1697  if self._options.isData:
1698  raise Exception("PATGEN step can only run on MC")
1699  return
1700 
1701  def prepare_NANO(self, sequence = "nanoAOD"):
1702  ''' Enrich the schedule with NANO '''
1703  self.loadDefaultOrSpecifiedCFF(sequence,self.NANODefaultCFF)
1704  self.scheduleSequence(sequence.split('.')[-1],'nanoAOD_step')
1705  custom = "nanoAOD_customizeData" if self._options.isData else "nanoAOD_customizeMC"
1706  self._options.customisation_file.insert(0,"PhysicsTools/NanoAOD/nano_cff."+custom)
1707  if self._options.hltProcess:
1708  if len(self._options.customise_commands) > 1:
1709  self._options.customise_commands = self._options.customise_commands + " \n"
1710  self._options.customise_commands = self._options.customise_commands + "process.unpackedPatTrigger.triggerResults= cms.InputTag( 'TriggerResults::"+self._options.hltProcess+"' )\n"
1711 
1712  def prepare_NANOGEN(self, sequence = "nanoAOD"):
1713  ''' Enrich the schedule with NANOGEN '''
1714  # TODO: Need to modify this based on the input file type
1715  fromGen = any([x in self.stepMap for x in ['LHE', 'GEN', 'AOD']])
1716  self.loadDefaultOrSpecifiedCFF(sequence,self.NANOGENDefaultCFF)
1717  self.scheduleSequence(sequence.split('.')[-1],'nanoAOD_step')
1718  custom = "customizeNanoGEN" if fromGen else "customizeNanoGENFromMini"
1719  if self._options.runUnscheduled:
1720  self._options.customisation_file_unsch.insert(0, '.'.join([self.NANOGENDefaultCFF, custom]))
1721  else:
1722  self._options.customisation_file.insert(0, '.'.join([self.NANOGENDefaultCFF, custom]))
1723 
1724  def prepare_EI(self, sequence = None):
1725  ''' Enrich the schedule with event interpretation '''
1726  from Configuration.StandardSequences.EventInterpretation import EventInterpretation
1727  if sequence in EventInterpretation:
1728  self.EIDefaultCFF = EventInterpretation[sequence]
1729  sequence = 'EIsequence'
1730  else:
1731  raise Exception('Cannot set %s event interpretation'%( sequence) )
1732  self.loadDefaultOrSpecifiedCFF(sequence,self.EIDefaultCFF)
1733  self.scheduleSequence(sequence.split('.')[-1],'eventinterpretaion_step')
1734  return
1735 
1736  def prepare_SKIM(self, sequence = "all"):
1737  ''' Enrich the schedule with skimming fragments'''
1738  skimConfig = self.loadDefaultOrSpecifiedCFF(sequence,self.SKIMDefaultCFF)
1739  sequence = sequence.split('.')[-1]
1740 
1741  skimlist=sequence.split('+')
1742 
1743  from Configuration.Skimming.autoSkim import autoSkim
1744  self.expandMapping(skimlist,autoSkim)
1745 
1746  #print "dictionnary for skims:",skimConfig.__dict__
1747  for skim in skimConfig.__dict__:
1748  skimstream = getattr(skimConfig,skim)
1749  if isinstance(skimstream,cms.Path):
1750  #black list the alca path so that they do not appear in the cfg
1751  self.blacklist_paths.append(skimstream)
1752  if (not isinstance(skimstream,cms.FilteredStream)):
1753  continue
1754  shortname = skim.replace('SKIMStream','')
1755  if (sequence=="all"):
1756  self.addExtraStream(skim,skimstream)
1757  elif (shortname in skimlist):
1758  self.addExtraStream(skim,skimstream)
1759  #add a DQM eventcontent for this guy
1760  if self._options.datatier=='DQM':
1761  self.process.load(self.EVTCONTDefaultCFF)
1762  skimstreamDQM = cms.FilteredStream(
1763  responsible = skimstream.responsible,
1764  name = skimstream.name+'DQM',
1765  paths = skimstream.paths,
1766  selectEvents = skimstream.selectEvents,
1767  content = self._options.datatier+'EventContent',
1768  dataTier = cms.untracked.string(self._options.datatier)
1769  )
1770  self.addExtraStream(skim+'DQM',skimstreamDQM)
1771  for i in range(skimlist.count(shortname)):
1772  skimlist.remove(shortname)
1773 
1774 
1775 
1776  if (skimlist.__len__()!=0 and sequence!="all"):
1777  print('WARNING, possible typo with SKIM:'+'+'.join(skimlist))
1778  raise Exception('WARNING, possible typo with SKIM:'+'+'.join(skimlist))
1779 
1780  def prepare_USER(self, sequence = None):
1781  ''' Enrich the schedule with a user defined sequence '''
1782  self.loadDefaultOrSpecifiedCFF(sequence,self.USERDefaultCFF)
1783  self.scheduleSequence(sequence.split('.')[-1],'user_step')
1784  return
1785 
1786  def prepare_POSTRECO(self, sequence = None):
1787  """ Enrich the schedule with the postreco step """
1789  self.scheduleSequence('postreco_generator','postreco_step')
1790  return
1791 
1792 
1793  def prepare_VALIDATION(self, sequence = 'validation'):
1794  print(sequence,"in preparing validation")
1796  from Validation.Configuration.autoValidation import autoValidation
1797  #in case VALIDATION:something:somethingelse -> something,somethingelse
1798  sequence=sequence.split('.')[-1]
1799  if sequence.find(',')!=-1:
1800  prevalSeqName=sequence.split(',')[0].split('+')
1801  valSeqName=sequence.split(',')[1].split('+')
1802  self.expandMapping(prevalSeqName,autoValidation,index=0)
1803  self.expandMapping(valSeqName,autoValidation,index=1)
1804  else:
1805  if '@' in sequence:
1806  prevalSeqName=sequence.split('+')
1807  valSeqName=sequence.split('+')
1808  self.expandMapping(prevalSeqName,autoValidation,index=0)
1809  self.expandMapping(valSeqName,autoValidation,index=1)
1810  else:
1811  postfix=''
1812  if sequence:
1813  postfix='_'+sequence
1814  prevalSeqName=['prevalidation'+postfix]
1815  valSeqName=['validation'+postfix]
1816  if not hasattr(self.process,valSeqName[0]):
1817  prevalSeqName=['']
1818  valSeqName=[sequence]
1819 
1820  def NFI(index):
1821 
1822  if index==0:
1823  return ''
1824  else:
1825  return '%s'%index
1826 
1827 
1828  #rename the HLT process in validation steps
1829  if ('HLT' in self.stepMap and not self._options.fast) or self._options.hltProcess:
1830  for s in valSeqName+prevalSeqName:
1831  if s:
1833  for (i,s) in enumerate(prevalSeqName):
1834  if s:
1835  setattr(self.process,'prevalidation_step%s'%NFI(i), cms.Path( getattr(self.process, s)) )
1836  self.schedule.append(getattr(self.process,'prevalidation_step%s'%NFI(i)))
1837 
1838  for (i,s) in enumerate(valSeqName):
1839  setattr(self.process,'validation_step%s'%NFI(i), cms.EndPath( getattr(self.process, s)))
1840  self.schedule.append(getattr(self.process,'validation_step%s'%NFI(i)))
1841 
1842  #needed in case the miniAODValidation sequence is run starting from AODSIM
1843  if 'PAT' in self.stepMap and not 'RECO' in self.stepMap:
1844  return
1845 
1846  if not 'DIGI' in self.stepMap and not self._options.fast and not any(map( lambda s : s.startswith('genvalid'), valSeqName)):
1847  if self._options.restoreRNDSeeds==False and not self._options.restoreRNDSeeds==True:
1848  self._options.restoreRNDSeeds=True
1849 
1850  if not 'DIGI' in self.stepMap and not self._options.fast:
1851  self.executeAndRemember("process.mix.playback = True")
1852  self.executeAndRemember("process.mix.digitizers = cms.PSet()")
1853  self.executeAndRemember("for a in process.aliases: delattr(process, a)")
1854  self._options.customisation_file.append("SimGeneral/MixingModule/fullMixCustomize_cff.setCrossingFrameOn")
1855 
1856  if hasattr(self.process,"genstepfilter") and len(self.process.genstepfilter.triggerConditions):
1857  #will get in the schedule, smoothly
1858  for (i,s) in enumerate(valSeqName):
1859  getattr(self.process,'validation_step%s'%NFI(i)).insert(0, self.process.genstepfilter)
1860 
1861  return
1862 
1863 
1865  """Visitor that travels within a cms.Sequence, looks for a parameter and replace its value
1866  It will climb down within PSets, VPSets and VInputTags to find its target"""
1867  def __init__(self, paramSearch, paramReplace, verbose=False, whitelist=()):
1868  self._paramReplace = paramReplace
1869  self._paramSearch = paramSearch
1870  self._verbose = verbose
1871  self._whitelist = whitelist
1873  def doIt(self,pset,base):
1874  if isinstance(pset, cms._Parameterizable):
1875  for name in pset.parameters_().keys():
1876  # skip whitelisted parameters
1877  if name in self._whitelist:
1878  continue
1879  # if I use pset.parameters_().items() I get copies of the parameter values
1880  # so I can't modify the nested pset
1881  value = getattr(pset,name)
1882  type = value.pythonTypeName()
1883  if type in ('cms.PSet', 'cms.untracked.PSet'):
1884  self.doIt(value,base+"."+name)
1885  elif type in ('cms.VPSet', 'cms.untracked.VPSet'):
1886  for (i,ps) in enumerate(value): self.doIt(ps, "%s.%s[%d]"%(base,name,i) )
1887  elif type in ('cms.string', 'cms.untracked.string'):
1888  if value.value() == self._paramSearch:
1889  if self._verbose: print("set string process name %s.%s %s ==> %s"% (base, name, value, self._paramReplace))
1890  setattr(pset, name,self._paramReplace)
1891  elif type in ('cms.VInputTag', 'cms.untracked.VInputTag'):
1892  for (i,n) in enumerate(value):
1893  if not isinstance(n, cms.InputTag):
1894  n=cms.InputTag(n)
1895  if n.processName == self._paramSearch:
1896  # VInputTag can be declared as a list of strings, so ensure that n is formatted correctly
1897  if self._verbose:print("set process name %s.%s[%d] %s ==> %s " % (base, name, i, n, self._paramReplace))
1898  setattr(n,"processName",self._paramReplace)
1899  value[i]=n
1900  elif type in ('cms.vstring', 'cms.untracked.vstring'):
1901  for (i,n) in enumerate(value):
1902  if n==self._paramSearch:
1903  getattr(pset,name)[i]=self._paramReplace
1904  elif type in ('cms.InputTag', 'cms.untracked.InputTag'):
1905  if value.processName == self._paramSearch:
1906  if self._verbose: print("set process name %s.%s %s ==> %s " % (base, name, value, self._paramReplace))
1907  setattr(getattr(pset, name),"processName",self._paramReplace)
1908 
1909  def enter(self,visitee):
1910  label = ''
1911  try:
1912  label = visitee.label()
1913  except AttributeError:
1914  label = '<Module not in a Process>'
1915  except:
1916  label = 'other execption'
1917  self.doIt(visitee, label)
1918 
1919  def leave(self,visitee):
1920  pass
1921 
1922  #visit a sequence to repalce all input tags
1923  def renameInputTagsInSequence(self,sequence,oldT="rawDataCollector",newT="rawDataRepacker"):
1924  print("Replacing all InputTag %s => %s"%(oldT,newT))
1925  from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
1926  massSearchReplaceAnyInputTag(getattr(self.process,sequence),oldT,newT)
1927  loadMe='from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag'
1928  if not loadMe in self.additionalCommands:
1929  self.additionalCommands.append(loadMe)
1930  self.additionalCommands.append('massSearchReplaceAnyInputTag(process.%s,"%s","%s",False,True)'%(sequence,oldT,newT))
1931 
1932  #change the process name used to address HLT results in any sequence
1933  def renameHLTprocessInSequence(self,sequence,proc=None,HLTprocess='HLT'):
1934  if self._options.hltProcess:
1935  proc=self._options.hltProcess
1936  else:
1937  proc=self.process.name_()
1938  if proc==HLTprocess: return
1939  # look up all module in dqm sequence
1940  print("replacing %s process name - sequence %s will use '%s'" % (HLTprocess,sequence, proc))
1941  getattr(self.process,sequence).visit(ConfigBuilder.MassSearchReplaceProcessNameVisitor(HLTprocess,proc,whitelist = ("subSystemFolder",)))
1942  if 'from Configuration.Applications.ConfigBuilder import ConfigBuilder' not in self.additionalCommands:
1943  self.additionalCommands.append('from Configuration.Applications.ConfigBuilder import ConfigBuilder')
1944  self.additionalCommands.append('process.%s.visit(ConfigBuilder.MassSearchReplaceProcessNameVisitor("%s", "%s", whitelist = ("subSystemFolder",)))'% (sequence,HLTprocess, proc))
1945 
1946 
1947  def expandMapping(self,seqList,mapping,index=None):
1948  maxLevel=30
1949  level=0
1950  while '@' in repr(seqList) and level<maxLevel:
1951  level+=1
1952  for specifiedCommand in seqList:
1953  if specifiedCommand.startswith('@'):
1954  location=specifiedCommand[1:]
1955  if not location in mapping:
1956  raise Exception("Impossible to map "+location+" from "+repr(mapping))
1957  mappedTo=mapping[location]
1958  if index!=None:
1959  mappedTo=mappedTo[index]
1960  seqList.remove(specifiedCommand)
1961  seqList.extend(mappedTo.split('+'))
1962  break;
1963  if level==maxLevel:
1964  raise Exception("Could not fully expand "+repr(seqList)+" from "+repr(mapping))
1965 
1966  def prepare_DQM(self, sequence = 'DQMOffline'):
1967  # this one needs replacement
1968 
1969  # any 'DQM' job should use DQMStore in non-legacy mode (but not HARVESTING)
1970  self.loadAndRemember("DQMServices/Core/DQMStoreNonLegacy_cff")
1972  sequenceList=sequence.split('.')[-1].split('+')
1973  postSequenceList=sequence.split('.')[-1].split('+')
1974  from DQMOffline.Configuration.autoDQM import autoDQM
1975  self.expandMapping(sequenceList,autoDQM,index=0)
1976  self.expandMapping(postSequenceList,autoDQM,index=1)
1977 
1978  if len(set(sequenceList))!=len(sequenceList):
1979  sequenceList=list(set(sequenceList))
1980  print("Duplicate entries for DQM:, using",sequenceList)
1981 
1982  pathName='dqmoffline_step'
1983  for (i,sequence) in enumerate(sequenceList):
1984  if (i!=0):
1985  pathName='dqmoffline_%d_step'%(i)
1986 
1987  if 'HLT' in self.stepMap.keys() or self._options.hltProcess:
1988  self.renameHLTprocessInSequence(sequence)
1989 
1990  setattr(self.process,pathName, cms.EndPath( getattr(self.process,sequence ) ) )
1991  self.schedule.append(getattr(self.process,pathName))
1992 
1993  if hasattr(self.process,"genstepfilter") and len(self.process.genstepfilter.triggerConditions):
1994  #will get in the schedule, smoothly
1995  getattr(self.process,pathName).insert(0,self.process.genstepfilter)
1996 
1997 
1998  pathName='dqmofflineOnPAT_step'
1999  for (i,sequence) in enumerate(postSequenceList):
2000  #Fix needed to avoid duplication of sequences not defined in autoDQM or without a PostDQM
2001  if (sequenceList[i]==postSequenceList[i]):
2002  continue
2003  if (i!=0):
2004  pathName='dqmofflineOnPAT_%d_step'%(i)
2005 
2006  setattr(self.process,pathName, cms.EndPath( getattr(self.process, sequence ) ) )
2007  self.schedule.append(getattr(self.process,pathName))
2008 
2009  def prepare_HARVESTING(self, sequence = None):
2010  """ Enrich the process with harvesting step """
2011  self.DQMSaverCFF='Configuration/StandardSequences/DQMSaver'+self._options.harvesting+'_cff'
2013 
2014  harvestingConfig = self.loadDefaultOrSpecifiedCFF(sequence,self.HARVESTINGDefaultCFF)
2015  sequence = sequence.split('.')[-1]
2016 
2017  # decide which HARVESTING paths to use
2018  harvestingList = sequence.split("+")
2019  from DQMOffline.Configuration.autoDQM import autoDQM
2020  from Validation.Configuration.autoValidation import autoValidation
2021  import copy
2022  combined_mapping = copy.deepcopy( autoDQM )
2023  combined_mapping.update( autoValidation )
2024  self.expandMapping(harvestingList,combined_mapping,index=-1)
2025 
2026  if len(set(harvestingList))!=len(harvestingList):
2027  harvestingList=list(set(harvestingList))
2028  print("Duplicate entries for HARVESTING, using",harvestingList)
2029 
2030  for name in harvestingList:
2031  if not name in harvestingConfig.__dict__:
2032  print(name,"is not a possible harvesting type. Available are",harvestingConfig.__dict__.keys())
2033  # trigger hard error, like for other sequence types
2034  getattr(self.process, name)
2035  continue
2036  harvestingstream = getattr(harvestingConfig,name)
2037  if isinstance(harvestingstream,cms.Path):
2038  self.schedule.append(harvestingstream)
2039  self.blacklist_paths.append(harvestingstream)
2040  if isinstance(harvestingstream,cms.Sequence):
2041  setattr(self.process,name+"_step",cms.Path(harvestingstream))
2042  self.schedule.append(getattr(self.process,name+"_step"))
2043 
2044  self.scheduleSequence('DQMSaver','dqmsave_step')
2045  return
2046 
2047  def prepare_ALCAHARVEST(self, sequence = None):
2048  """ Enrich the process with AlCaHarvesting step """
2049  harvestingConfig = self.loadAndRemember(self.ALCAHARVESTDefaultCFF)
2050  sequence=sequence.split(".")[-1]
2051 
2052  # decide which AlcaHARVESTING paths to use
2053  harvestingList = sequence.split("+")
2054 
2055 
2056 
2057  from Configuration.AlCa.autoPCL import autoPCL
2058  self.expandMapping(harvestingList,autoPCL)
2059 
2060  for name in harvestingConfig.__dict__:
2061  harvestingstream = getattr(harvestingConfig,name)
2062  if name in harvestingList and isinstance(harvestingstream,cms.Path):
2063  self.schedule.append(harvestingstream)
2064  if isinstance(getattr(harvestingConfig,"ALCAHARVEST" + name + "_dbOutput"), cms.VPSet) and \
2065  isinstance(getattr(harvestingConfig,"ALCAHARVEST" + name + "_metadata"), cms.VPSet):
2066  self.executeAndRemember("process.PoolDBOutputService.toPut.extend(process.ALCAHARVEST" + name + "_dbOutput)")
2067  self.executeAndRemember("process.pclMetadataWriter.recordsToMap.extend(process.ALCAHARVEST" + name + "_metadata)")
2068  else:
2069  self.executeAndRemember("process.PoolDBOutputService.toPut.append(process.ALCAHARVEST" + name + "_dbOutput)")
2070  self.executeAndRemember("process.pclMetadataWriter.recordsToMap.append(process.ALCAHARVEST" + name + "_metadata)")
2071  harvestingList.remove(name)
2072  # append the common part at the end of the sequence
2073  lastStep = getattr(harvestingConfig,"ALCAHARVESTDQMSaveAndMetadataWriter")
2074  self.schedule.append(lastStep)
2075 
2076  if len(harvestingList) != 0 and 'dummyHarvesting' not in harvestingList :
2077  print("The following harvesting could not be found : ", harvestingList)
2078  raise Exception("The following harvesting could not be found : "+str(harvestingList))
2079 
2080 
2081 
2082  def prepare_ENDJOB(self, sequence = 'endOfProcess'):
2084  self.scheduleSequenceAtEnd(sequence.split('.')[-1],'endjob_step')
2085  return
2086 
2087  def finalizeFastSimHLT(self):
2088  self.process.reconstruction = cms.Path(self.process.reconstructionWithFamos)
2089  self.schedule.append(self.process.reconstruction)
2090 
2091 
2092  def build_production_info(self, evt_type, evtnumber):
2093  """ Add useful info for the production. """
2094  self.process.configurationMetadata=cms.untracked.PSet\
2095  (version=cms.untracked.string("$Revision: 1.19 $"),
2096  name=cms.untracked.string("Applications"),
2097  annotation=cms.untracked.string(evt_type+ " nevts:"+str(evtnumber))
2098  )
2099 
2100  self.addedObjects.append(("Production Info","configurationMetadata"))
2101 
2102 
2103  def create_process(self):
2104  self.pythonCfgCode = "# Auto generated configuration file\n"
2105  self.pythonCfgCode += "# using: \n# "+__version__[1:-1]+"\n# "+__source__[1:-1]+'\n'
2106  self.pythonCfgCode += "# with command line options: "+self._options.arguments+'\n'
2107  self.pythonCfgCode += "import FWCore.ParameterSet.Config as cms\n\n"
2108 
2109  # now set up the modifies
2110  modifiers=[]
2111  modifierStrings=[]
2112  modifierImports=[]
2113 
2114  if hasattr(self._options,"era") and self._options.era :
2115  # Multiple eras can be specified in a comma seperated list
2116  from Configuration.StandardSequences.Eras import eras
2117  for requestedEra in self._options.era.split(",") :
2118  modifierStrings.append(requestedEra)
2119  modifierImports.append(eras.pythonCfgLines[requestedEra])
2120  modifiers.append(getattr(eras,requestedEra))
2121 
2122 
2123  if hasattr(self._options,"procModifiers") and self._options.procModifiers:
2124  import importlib
2125  thingsImported=[]
2126  for pm in self._options.procModifiers.split(','):
2127  modifierStrings.append(pm)
2128  modifierImports.append('from Configuration.ProcessModifiers.'+pm+'_cff import '+pm)
2129  modifiers.append(getattr(importlib.import_module('Configuration.ProcessModifiers.'+pm+'_cff'),pm))
2130 
2131  self.pythonCfgCode += '\n'.join(modifierImports)+'\n\n'
2132  self.pythonCfgCode += "process = cms.Process('"+self._options.name+"'" # Start of the line, finished after the loop
2133 
2134 
2135  if len(modifierStrings)>0:
2136  self.pythonCfgCode+= ','+','.join(modifierStrings)
2137  self.pythonCfgCode+=')\n\n'
2138 
2139  #yes, the cfg code gets out of sync here if a process is passed in. That could be fixed in the future
2140  #assuming there is some way for the fwk to get the list of modifiers (and their stringified name)
2141  if self.process == None:
2142  if len(modifiers)>0:
2143  self.process = cms.Process(self._options.name,*modifiers)
2144  else:
2145  self.process = cms.Process(self._options.name)
2146 
2147 
2148 
2149 
2150  def prepare(self, doChecking = False):
2151  """ Prepare the configuration string and add missing pieces."""
2152 
2153  self.loadAndRemember(self.EVTCONTDefaultCFF) #load the event contents regardless
2154  self.addMaxEvents()
2155  if self.with_input:
2156  self.addSource()
2157  self.addStandardSequences()
2158 
2159  self.completeInputCommand()
2160  self.addConditions()
2161 
2162 
2163  outputModuleCfgCode=""
2164  if not 'HARVESTING' in self.stepMap.keys() and not 'ALCAHARVEST' in self.stepMap.keys() and not 'ALCAOUTPUT' in self.stepMap.keys() and self.with_output:
2165  outputModuleCfgCode=self.addOutput()
2166 
2167  self.addCommon()
2168 
2169  self.pythonCfgCode += "# import of standard configurations\n"
2170  for module in self.imports:
2171  self.pythonCfgCode += ("process.load('"+module+"')\n")
2172 
2173  # production info
2174  if not hasattr(self.process,"configurationMetadata"):
2175  self.build_production_info(self._options.evt_type, self._options.number)
2176  else:
2177  #the PSet was added via a load
2178  self.addedObjects.append(("Production Info","configurationMetadata"))
2179 
2180  self.pythonCfgCode +="\n"
2181  for comment,object in self.addedObjects:
2182  if comment!="":
2183  self.pythonCfgCode += "\n# "+comment+"\n"
2184  self.pythonCfgCode += dumpPython(self.process,object)
2185 
2186  # dump the output definition
2187  self.pythonCfgCode += "\n# Output definition\n"
2188  self.pythonCfgCode += outputModuleCfgCode
2189 
2190  # dump all additional outputs (e.g. alca or skim streams)
2191  self.pythonCfgCode += "\n# Additional output definition\n"
2192  #I do not understand why the keys are not normally ordered.
2193  nl=sorted(self.additionalOutputs.keys())
2194  for name in nl:
2195  output = self.additionalOutputs[name]
2196  self.pythonCfgCode += "process.%s = %s" %(name, output.dumpPython())
2197  tmpOut = cms.EndPath(output)
2198  setattr(self.process,name+'OutPath',tmpOut)
2199  self.schedule.append(tmpOut)
2200 
2201  # dump all additional commands
2202  self.pythonCfgCode += "\n# Other statements\n"
2203  for command in self.additionalCommands:
2204  self.pythonCfgCode += command + "\n"
2205 
2206  #comma separated list of objects that deserve to be inlined in the configuration (typically from a modified config deep down)
2207  for object in self._options.inlineObjets.split(','):
2208  if not object:
2209  continue
2210  if not hasattr(self.process,object):
2211  print('cannot inline -'+object+'- : not known')
2212  else:
2213  self.pythonCfgCode +='\n'
2214  self.pythonCfgCode +=dumpPython(self.process,object)
2215 
2216  if self._options.pileup=='HiMixEmbGEN':
2217  self.pythonCfgCode += "\nprocess.generator.embeddingMode=cms.bool(True)\n"
2218 
2219  # dump all paths
2220  self.pythonCfgCode += "\n# Path and EndPath definitions\n"
2221  for path in self.process.paths:
2222  if getattr(self.process,path) not in self.blacklist_paths:
2223  self.pythonCfgCode += dumpPython(self.process,path)
2224 
2225  for endpath in self.process.endpaths:
2226  if getattr(self.process,endpath) not in self.blacklist_paths:
2227  self.pythonCfgCode += dumpPython(self.process,endpath)
2228 
2229  # dump the schedule
2230  self.pythonCfgCode += "\n# Schedule definition\n"
2231  result = "process.schedule = cms.Schedule("
2232 
2233  # handling of the schedule
2234  self.process.schedule = cms.Schedule()
2235  for item in self.schedule:
2236  if not isinstance(item, cms.Schedule):
2237  self.process.schedule.append(item)
2238  else:
2239  self.process.schedule.extend(item)
2240 
2241  if hasattr(self.process,"HLTSchedule"):
2242  beforeHLT = self.schedule[:self.schedule.index(self.process.HLTSchedule)]
2243  afterHLT = self.schedule[self.schedule.index(self.process.HLTSchedule)+1:]
2244  pathNames = ['process.'+p.label_() for p in beforeHLT]
2245  result += ','.join(pathNames)+')\n'
2246  result += 'process.schedule.extend(process.HLTSchedule)\n'
2247  pathNames = ['process.'+p.label_() for p in afterHLT]
2248  result += 'process.schedule.extend(['+','.join(pathNames)+'])\n'
2249  else:
2250  pathNames = ['process.'+p.label_() for p in self.schedule]
2251  result ='process.schedule = cms.Schedule('+','.join(pathNames)+')\n'
2252 
2253  self.pythonCfgCode += result
2254 
2255  for labelToAssociate in self.labelsToAssociate:
2256  self.process.schedule.associate(getattr(self.process, labelToAssociate))
2257  self.pythonCfgCode += 'process.schedule.associate(process.' + labelToAssociate + ')\n'
2258 
2259  from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask
2261  self.pythonCfgCode+="from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask\n"
2262  self.pythonCfgCode+="associatePatAlgosToolsTask(process)\n"
2263 
2264  if self._options.nThreads != "1":
2265  self.pythonCfgCode +="\n"
2266  self.pythonCfgCode +="#Setup FWK for multithreaded\n"
2267  self.pythonCfgCode +="process.options.numberOfThreads = "+self._options.nThreads+"\n"
2268  self.pythonCfgCode +="process.options.numberOfStreams = "+self._options.nStreams+"\n"
2269  self.pythonCfgCode +="process.options.numberOfConcurrentLuminosityBlocks = "+self._options.nConcurrentLumis+"\n"
2270  self.pythonCfgCode +="process.options.eventSetup.numberOfConcurrentIOVs = "+self._options.nConcurrentIOVs+"\n"
2271  if int(self._options.nConcurrentLumis) > 1:
2272  self.pythonCfgCode +="if hasattr(process, 'DQMStore'): process.DQMStore.assertLegacySafe=cms.untracked.bool(False)\n"
2273  self.process.options.numberOfThreads = int(self._options.nThreads)
2274  self.process.options.numberOfStreams = int(self._options.nStreams)
2275  self.process.options.numberOfConcurrentLuminosityBlocks = int(self._options.nConcurrentLumis)
2276  self.process.options.eventSetup.numberOfConcurrentIOVs = int(self._options.nConcurrentIOVs)
2277  #repacked version
2278  if self._options.isRepacked:
2279  self.pythonCfgCode +="\n"
2280  self.pythonCfgCode +="from Configuration.Applications.ConfigBuilder import MassReplaceInputTag\n"
2281  self.pythonCfgCode +="MassReplaceInputTag(process, new=\"rawDataMapperByLabel\", old=\"rawDataCollector\")\n"
2282  MassReplaceInputTag(self.process, new="rawDataMapperByLabel", old="rawDataCollector")
2283 
2284  # special treatment in case of production filter sequence 2/2
2285  if self.productionFilterSequence and not (self._options.pileup=='HiMixEmbGEN'):
2286  self.pythonCfgCode +='# filter all path with the production filter sequence\n'
2287  self.pythonCfgCode +='for path in process.paths:\n'
2288  if len(self.conditionalPaths):
2289  self.pythonCfgCode +='\tif not path in %s: continue\n'%str(self.conditionalPaths)
2290  if len(self.excludedPaths):
2291  self.pythonCfgCode +='\tif path in %s: continue\n'%str(self.excludedPaths)
2292  self.pythonCfgCode +='\tgetattr(process,path).insert(0, process.%s)\n'%(self.productionFilterSequence,)
2293  pfs = getattr(self.process,self.productionFilterSequence)
2294  for path in self.process.paths:
2295  if not path in self.conditionalPaths: continue
2296  if path in self.excludedPaths: continue
2297  getattr(self.process,path).insert(0, pfs)
2298 
2299 
2300  # dump customise fragment
2301  self.pythonCfgCode += self.addCustomise()
2302 
2303  if self._options.runUnscheduled:
2304  print("--runUnscheduled is deprecated and not necessary anymore, and will be removed soon. Please update your command line.")
2305  # Keep the "unscheduled customise functions" separate for now,
2306  # there are customize functions given by users (in our unit
2307  # tests) that need to be run before the "unscheduled customise
2308  # functions"
2309  self.pythonCfgCode += self.addCustomise(1)
2310 
2311  self.pythonCfgCode += self.addCustomiseCmdLine()
2312 
2313  if hasattr(self.process,"logErrorHarvester"):
2314  #configure logErrorHarvester to wait for same EDProducers to finish as the OutputModules
2315  self.pythonCfgCode +="\n#Have logErrorHarvester wait for the same EDProducers to finish as those providing data for the OutputModule\n"
2316  self.pythonCfgCode +="from FWCore.Modules.logErrorHarvester_cff import customiseLogErrorHarvesterUsingOutputCommands\n"
2317  self.pythonCfgCode +="process = customiseLogErrorHarvesterUsingOutputCommands(process)\n"
2318  from FWCore.Modules.logErrorHarvester_cff import customiseLogErrorHarvesterUsingOutputCommands
2320 
2321  # Temporary hack to put the early delete customization after
2322  # everything else
2323  #
2324  # FIXME: remove when no longer needed
2325  self.pythonCfgCode += "\n# Add early deletion of temporary data products to reduce peak memory need\n"
2326  self.pythonCfgCode += "from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete\n"
2327  self.pythonCfgCode += "process = customiseEarlyDelete(process)\n"
2328  self.pythonCfgCode += "# End adding early deletion\n"
2329  from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete
2330  self.process = customiseEarlyDelete(self.process)
2331 
2332  imports = cms.specialImportRegistry.getSpecialImports()
2333  if len(imports) > 0:
2334  #need to inject this at the top
2335  index = self.pythonCfgCode.find("import FWCore.ParameterSet.Config")
2336  #now find the end of line
2337  index = self.pythonCfgCode.find("\n",index)
2338  self.pythonCfgCode = self.pythonCfgCode[:index]+ "\n" + "\n".join(imports)+"\n" +self.pythonCfgCode[index:]
2339 
2340 
2341  # make the .io file
2342 
2343  if self._options.io:
2344  #io=open(self._options.python_filename.replace('.py','.io'),'w')
2345  if not self._options.io.endswith('.io'): self._option.io+='.io'
2346  io=open(self._options.io,'w')
2347  ioJson={}
2348  if hasattr(self.process.source,"fileNames"):
2349  if len(self.process.source.fileNames.value()):
2350  ioJson['primary']=self.process.source.fileNames.value()
2351  if hasattr(self.process.source,"secondaryFileNames"):
2352  if len(self.process.source.secondaryFileNames.value()):
2353  ioJson['secondary']=self.process.source.secondaryFileNames.value()
2354  if self._options.pileup_input and (self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:')):
2355  ioJson['pileup']=self._options.pileup_input[4:]
2356  for (o,om) in self.process.outputModules_().items():
2357  ioJson[o]=om.fileName.value()
2358  ioJson['GT']=self.process.GlobalTag.globaltag.value()
2359  if self.productionFilterSequence:
2360  ioJson['filter']=self.productionFilterSequence
2361  import json
2362  io.write(json.dumps(ioJson))
2363  return
2364 
2365 
ConfigBuilder.ConfigBuilder.GENDefaultSeq
GENDefaultSeq
Definition: ConfigBuilder.py:989
helpers.associatePatAlgosToolsTask
def associatePatAlgosToolsTask(process)
Definition: helpers.py:24
ConfigBuilder.ConfigBuilder.RECODefaultSeq
RECODefaultSeq
Definition: ConfigBuilder.py:1004
LumiList.LumiList
Definition: LumiList.py:22
ConfigBuilder.ConfigBuilder.DIGIDefaultSeq
DIGIDefaultSeq
Definition: ConfigBuilder.py:991
ConfigBuilder.ConfigBuilder.prepare_GEN
def prepare_GEN(self, sequence=None)
Definition: ConfigBuilder.py:1345
ConfigBuilder.ConfigBuilder.VALIDATIONDefaultSeq
VALIDATIONDefaultSeq
Definition: ConfigBuilder.py:1012
ConfigBuilder.ConfigBuilder.prepare_CFWRITER
def prepare_CFWRITER(self, sequence=None)
Definition: ConfigBuilder.py:1465
ConfigBuilder.ConfigBuilder.RECODefaultCFF
RECODefaultCFF
Definition: ConfigBuilder.py:963
FastTimerService_cff.range
range
Definition: FastTimerService_cff.py:34
ConfigBuilder.ConfigBuilder.prepare_L1Reco
def prepare_L1Reco(self, sequence="L1Reco")
Definition: ConfigBuilder.py:1605
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.enter
def enter(self, visitee)
Definition: ConfigBuilder.py:1910
logErrorHarvester_cff.customiseLogErrorHarvesterUsingOutputCommands
def customiseLogErrorHarvesterUsingOutputCommands(process)
Definition: logErrorHarvester_cff.py:4
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._whitelist
_whitelist
Definition: ConfigBuilder.py:1872
ConfigBuilder.ConfigBuilder.prepare_EI
def prepare_EI(self, sequence=None)
Definition: ConfigBuilder.py:1725
ConfigBuilder.ConfigBuilder.finalizeFastSimHLT
def finalizeFastSimHLT(self)
Definition: ConfigBuilder.py:2088
ConfigBuilder.ConfigBuilder.NANODefaultCFF
NANODefaultCFF
Definition: ConfigBuilder.py:966
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
ConfigBuilder.ConfigBuilder.EVTCONTDefaultCFF
EVTCONTDefaultCFF
Definition: ConfigBuilder.py:1021
ConfigBuilder.ConfigBuilder.REPACKDefaultSeq
REPACKDefaultSeq
Definition: ConfigBuilder.py:1014
ConfigBuilder.ConfigBuilder.prepare_NANOGEN
def prepare_NANOGEN(self, sequence="nanoAOD")
Definition: ConfigBuilder.py:1713
ConfigBuilder.ConfigBuilder.addMaxEvents
def addMaxEvents(self)
Definition: ConfigBuilder.py:367
ConfigBuilder.ConfigBuilder.LHEDefaultSeq
LHEDefaultSeq
Definition: ConfigBuilder.py:988
ConfigBuilder.ConfigBuilder.additionalOutputs
additionalOutputs
Definition: ConfigBuilder.py:264
ConfigBuilder.ConfigBuilder.productionFilterSequence
productionFilterSequence
put it before all the other paths
Definition: ConfigBuilder.py:266
ConfigBuilder.ConfigBuilder.DQMDefaultSeq
DQMDefaultSeq
Definition: ConfigBuilder.py:1011
ConfigBuilder.ConfigBuilder.prepare_RECOSIM
def prepare_RECOSIM(self, sequence="recosim")
Definition: ConfigBuilder.py:1655
ConfigBuilder.ConfigBuilder.prepare_VALIDATION
def prepare_VALIDATION(self, sequence='validation')
Definition: ConfigBuilder.py:1794
ConfigBuilder.ConfigBuilder.VALIDATIONDefaultCFF
VALIDATIONDefaultCFF
Definition: ConfigBuilder.py:971
ConfigBuilder.ConfigBuilder.prepare_LHE
def prepare_LHE(self, sequence=None)
Definition: ConfigBuilder.py:1328
ConfigBuilder.ConfigBuilder.prepare_REPACK
def prepare_REPACK(self, sequence=None)
Definition: ConfigBuilder.py:1494
ConfigBuilder.ConfigBuilder.HARVESTINGDefaultCFF
HARVESTINGDefaultCFF
Definition: ConfigBuilder.py:974
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.__init__
def __init__(self, paramSearch, paramReplace, verbose=False, whitelist=())
Definition: ConfigBuilder.py:1868
ConfigBuilder.ConfigBuilder.GENDefaultCFF
GENDefaultCFF
Definition: ConfigBuilder.py:952
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.doIt
def doIt(self, pset, base)
Definition: ConfigBuilder.py:1874
ConfigBuilder.ConfigBuilder.prepare_DIGI2RAW
def prepare_DIGI2RAW(self, sequence=None)
Definition: ConfigBuilder.py:1489
ConfigBuilder.ConfigBuilder.addCommon
def addCommon(self)
Definition: ConfigBuilder.py:339
ConfigBuilder.ConfigBuilder.stepMap
stepMap
Definition: ConfigBuilder.py:225
ConfigBuilder.ConfigBuilder.L1TrackTriggerDefaultSeq
L1TrackTriggerDefaultSeq
Definition: ConfigBuilder.py:1002
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._paramSearch
_paramSearch
Definition: ConfigBuilder.py:1870
ConfigBuilder.ConfigBuilder.SIMDefaultSeq
SIMDefaultSeq
Definition: ConfigBuilder.py:990
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
ConfigBuilder.ConfigBuilder
Definition: ConfigBuilder.py:195
ConfigBuilder.ConfigBuilder.geometryDBLabel
geometryDBLabel
Definition: ConfigBuilder.py:1085
cms::cuda::assert
assert(be >=bs)
ConfigBuilder.ConfigBuilder.NANOGENDefaultCFF
NANOGENDefaultCFF
Definition: ConfigBuilder.py:967
ConfigBuilder.ConfigBuilder.RAW2DIGIDefaultSeq
RAW2DIGIDefaultSeq
Definition: ConfigBuilder.py:1000
ConfigBuilder.ConfigBuilder.ALCAHARVESTDefaultSeq
ALCAHARVESTDefaultSeq
Definition: ConfigBuilder.py:998
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
ConfigBuilder.ConfigBuilder.pythonCfgCode
pythonCfgCode
Definition: ConfigBuilder.py:2105
ConfigBuilder.ConfigBuilder.PATGENDefaultCFF
PATGENDefaultCFF
Definition: ConfigBuilder.py:1031
earlyDeleteSettings_cff.customiseEarlyDelete
def customiseEarlyDelete(process)
Definition: earlyDeleteSettings_cff.py:40
ConfigBuilder.ConfigBuilder.with_input
with_input
Definition: ConfigBuilder.py:250
ConfigBuilder.ConfigBuilder.build_production_info
def build_production_info(self, evt_type, evtnumber)
Definition: ConfigBuilder.py:2093
ConfigBuilder.ConfigBuilder.executeAndRemember
def executeAndRemember(self, command)
Definition: ConfigBuilder.py:330
ConfigBuilder.ConfigBuilder.renameHLTprocessInSequence
def renameHLTprocessInSequence(self, sequence, proc=None, HLTprocess='HLT')
Definition: ConfigBuilder.py:1934
spr::find
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
ConfigBuilder.filesFromList
def filesFromList(fileName, s=None)
Definition: ConfigBuilder.py:102
ConfigBuilder.filesFromDASQuery
def filesFromDASQuery(query, option="", s=None)
Definition: ConfigBuilder.py:136
ConfigBuilder.ConfigBuilder.runsAndWeightsInt
runsAndWeightsInt
Definition: ConfigBuilder.py:501
ConfigBuilder.ConfigBuilder.RECOBEFMIXDefaultCFF
RECOBEFMIXDefaultCFF
Definition: ConfigBuilder.py:1135
mps_monitormerge.items
list items
Definition: mps_monitormerge.py:29
ConfigBuilder.ConfigBuilder.expandMapping
def expandMapping(self, seqList, mapping, index=None)
Definition: ConfigBuilder.py:1948
any
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:37
ConfigBuilder.ConfigBuilder.prepare_FILTER
def prepare_FILTER(self, sequence=None)
Definition: ConfigBuilder.py:1617
ConfigBuilder.ConfigBuilder.PATDefaultCFF
PATDefaultCFF
Definition: ConfigBuilder.py:965
ConfigBuilder.ConfigBuilder.NANODefaultSeq
NANODefaultSeq
Definition: ConfigBuilder.py:1019
ConfigBuilder.ConfigBuilder.prepare_PATGEN
def prepare_PATGEN(self, sequence="miniGEN")
Definition: ConfigBuilder.py:1694
ConfigBuilder.ConfigBuilder.scheduleSequence
def scheduleSequence(self, seq, prefix, what='Path')
Definition: ConfigBuilder.py:1231
ConfigBuilder.ConfigBuilder.conditionalPaths
conditionalPaths
Definition: ConfigBuilder.py:269
ConfigBuilder.ConfigBuilder.PATGENDefaultSeq
PATGENDefaultSeq
Definition: ConfigBuilder.py:1016
ConfigBuilder.ConfigBuilder.RECOSIMDefaultSeq
RECOSIMDefaultSeq
Definition: ConfigBuilder.py:1007
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._verbose
_verbose
Definition: ConfigBuilder.py:1871
ConfigBuilder.ConfigBuilder.addedObjects
addedObjects
Definition: ConfigBuilder.py:263
ConfigBuilder.ConfigBuilder.L1DefaultSeq
L1DefaultSeq
Definition: ConfigBuilder.py:995
CustomConfigs.ProcessName
def ProcessName(process)
Definition: CustomConfigs.py:8
ConfigBuilder.ConfigBuilder.create_process
def create_process(self)
Definition: ConfigBuilder.py:2104
ConfigBuilder.ConfigBuilder.__init__
def __init__(self, options, process=None, with_output=False, with_input=False)
Definition: ConfigBuilder.py:198
ConfigBuilder.Options
Definition: ConfigBuilder.py:19
ConfigBuilder.ConfigBuilder.prepare_ENDJOB
def prepare_ENDJOB(self, sequence='endOfProcess')
Definition: ConfigBuilder.py:2083
ConfigBuilder.ConfigBuilder.CFWRITERDefaultCFF
CFWRITERDefaultCFF
Definition: ConfigBuilder.py:978
submitPVValidationJobs.split
def split(sequence, size)
Definition: submitPVValidationJobs.py:352
ConfigBuilder.ConfigBuilder.ALCAHARVESTDefaultCFF
ALCAHARVESTDefaultCFF
Definition: ConfigBuilder.py:975
ConfigBuilder.ConfigBuilder.magFieldCFF
magFieldCFF
Definition: ConfigBuilder.py:1080
ConfigBuilder.ConfigBuilder.POSTRECODefaultCFF
POSTRECODefaultCFF
Definition: ConfigBuilder.py:970
ConfigBuilder.ConfigBuilder.imports
imports
Definition: ConfigBuilder.py:251
ConfigBuilder.ConfigBuilder.DQMSaverCFF
DQMSaverCFF
Definition: ConfigBuilder.py:2012
ConfigBuilder.ConfigBuilder.prepare_SIM
def prepare_SIM(self, sequence=None)
Definition: ConfigBuilder.py:1429
ConfigBuilder.ConfigBuilder.NANOGENDefaultSeq
NANOGENDefaultSeq
Definition: ConfigBuilder.py:1018
str
#define str(s)
Definition: TestProcessor.cc:53
ConfigBuilder.ConfigBuilder.loadAndRemember
def loadAndRemember(self, includeFile)
Definition: ConfigBuilder.py:321
ConfigBuilder.ConfigBuilder.ALCADefaultSeq
ALCADefaultSeq
Definition: ConfigBuilder.py:987
ConfigBuilder.ConfigBuilder.ENDJOBDefaultCFF
ENDJOBDefaultCFF
Definition: ConfigBuilder.py:976
ConfigBuilder.ConfigBuilder.L1TrackTriggerDefaultCFF
L1TrackTriggerDefaultCFF
Definition: ConfigBuilder.py:962
ConfigBuilder.ConfigBuilder.addSource
def addSource(self)
Definition: ConfigBuilder.py:374
ConfigBuilder.ConfigBuilder.L1RecoDefaultSeq
L1RecoDefaultSeq
Definition: ConfigBuilder.py:1001
ConfigBuilder.ConfigBuilder.prepare_ALCA
def prepare_ALCA(self, sequence=None, workflow='full')
Definition: ConfigBuilder.py:1270
ConfigBuilder.ConfigBuilder.prepare_RECOBEFMIX
def prepare_RECOBEFMIX(self, sequence="reconstruction")
Definition: ConfigBuilder.py:1661
ConfigBuilder.ConfigBuilder.L1REPACKDefaultSeq
L1REPACKDefaultSeq
Definition: ConfigBuilder.py:996
ConfigBuilder.ConfigBuilder.prepare_DIGI
def prepare_DIGI(self, sequence=None)
Definition: ConfigBuilder.py:1445
ConfigBuilder.ConfigBuilder.DIGI2RAWDefaultSeq
DIGI2RAWDefaultSeq
Definition: ConfigBuilder.py:993
ConfigBuilder.ConfigBuilder.ConditionsDefaultCFF
ConditionsDefaultCFF
Definition: ConfigBuilder.py:977
ConfigBuilder.ConfigBuilder.HLTDefaultSeq
HLTDefaultSeq
Definition: ConfigBuilder.py:994
geometryDiff.file
file
Definition: geometryDiff.py:13
ConfigBuilder.ConfigBuilder.prepare_SKIM
def prepare_SKIM(self, sequence="all")
Definition: ConfigBuilder.py:1737
ConfigBuilder.ConfigBuilder.L1EMDefaultCFF
L1EMDefaultCFF
Definition: ConfigBuilder.py:956
GlobalTag
Definition: GlobalTag.h:4
ConfigBuilder.ConfigBuilder.addOutput
def addOutput(self)
Definition: ConfigBuilder.py:526
DictTypes.SortedKeysDict
Definition: DictTypes.py:2
ConfigBuilder.ConfigBuilder.prepare_RECO
def prepare_RECO(self, sequence="reconstruction")
Definition: ConfigBuilder.py:1649
ConfigBuilder.ConfigBuilder.prepare_L1HwVal
def prepare_L1HwVal(self, sequence='L1HwVal')
Definition: ConfigBuilder.py:1598
ConfigBuilder.ConfigBuilder.excludedPaths
excludedPaths
Definition: ConfigBuilder.py:270
ConfigBuilder.ConfigBuilder.prepare_L1
def prepare_L1(self, sequence=None)
Definition: ConfigBuilder.py:1499
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
LumiToRun.lumi_to_run
def lumi_to_run(runs, events_in_sample, events_per_job)
Definition: LumiToRun.py:1
ConfigBuilder.ConfigBuilder.RECOBEFMIXDefaultSeq
RECOBEFMIXDefaultSeq
Definition: ConfigBuilder.py:1136
Mixing.defineMixing
def defineMixing(dict)
Definition: Mixing.py:189
Exception
mps_setup.append
append
Definition: mps_setup.py:85
ConfigBuilder.ConfigBuilder.EIDefaultCFF
EIDefaultCFF
Definition: ConfigBuilder.py:968
ConfigBuilder.ConfigBuilder.with_output
with_output
Definition: ConfigBuilder.py:245
ConfigBuilder.ConfigBuilder.define_Configs
def define_Configs(self)
Definition: ConfigBuilder.py:938
ConfigBuilder.ConfigBuilder.loadDefaultOrSpecifiedCFF
def loadDefaultOrSpecifiedCFF(self, sequence, defaultCFF)
Definition: ConfigBuilder.py:1219
ConfigBuilder.ConfigBuilder.profileOptions
def profileOptions(self)
Definition: ConfigBuilder.py:272
createfilelist.int
int
Definition: createfilelist.py:10
metFilterPaths_cff
ConfigBuilder.ConfigBuilder.L1RecoDefaultCFF
L1RecoDefaultCFF
Definition: ConfigBuilder.py:961
ConfigBuilder.ConfigBuilder.prepare_ALCAOUTPUT
def prepare_ALCAOUTPUT(self, sequence=None)
Definition: ConfigBuilder.py:1267
ConfigBuilder.ConfigBuilder.scheduleSequenceAtEnd
def scheduleSequenceAtEnd(self, seq, prefix)
Definition: ConfigBuilder.py:1260
ConfigBuilder.ConfigBuilder.addCustomiseCmdLine
def addCustomiseCmdLine(self)
Definition: ConfigBuilder.py:923
ConfigBuilder.ConfigBuilder.prepare_HLT
def prepare_HLT(self, sequence=None)
Definition: ConfigBuilder.py:1519
helpers
ConfigBuilder.anyOf
def anyOf(listOfKeys, dict, opt=None)
Definition: ConfigBuilder.py:184
ConfigBuilder.ConfigBuilder.DATAMIXDefaultSeq
DATAMIXDefaultSeq
Definition: ConfigBuilder.py:992
ConfigBuilder.ConfigBuilder.POSTRECODefaultSeq
POSTRECODefaultSeq
Definition: ConfigBuilder.py:1009
ConfigBuilder.ConfigBuilder.prepare_POSTRECO
def prepare_POSTRECO(self, sequence=None)
Definition: ConfigBuilder.py:1787
ConfigBuilder.ConfigBuilder.HLTDefaultCFF
HLTDefaultCFF
Definition: ConfigBuilder.py:958
TriggerAnalyzer.__str__
def __str__(self)
Definition: TriggerAnalyzer.py:103
ConfigBuilder.ConfigBuilder.SKIMDefaultCFF
SKIMDefaultCFF
Definition: ConfigBuilder.py:969
ConfigBuilder.ConfigBuilder.prepare_ALCAPRODUCER
def prepare_ALCAPRODUCER(self, sequence=None)
Definition: ConfigBuilder.py:1264
ConfigBuilder.ConfigBuilder.RAW2DIGIDefaultCFF
RAW2DIGIDefaultCFF
Definition: ConfigBuilder.py:959
ConfigBuilder.ConfigBuilder.EIDefaultSeq
EIDefaultSeq
Definition: ConfigBuilder.py:1008
ConfigBuilder.ConfigBuilder.stepKeys
stepKeys
Definition: ConfigBuilder.py:226
ConfigBuilder.ConfigBuilder.prepare_DQM
def prepare_DQM(self, sequence='DQMOffline')
Definition: ConfigBuilder.py:1967
ConfigBuilder.ConfigBuilder.DQMOFFLINEDefaultCFF
DQMOFFLINEDefaultCFF
Definition: ConfigBuilder.py:973
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor
Definition: ConfigBuilder.py:1865
ConfigBuilder.ConfigBuilder.labelsToAssociate
labelsToAssociate
Definition: ConfigBuilder.py:267
ConfigBuilder.ConfigBuilder.renameInputTagsInSequence
def renameInputTagsInSequence(self, sequence, oldT="rawDataCollector", newT="rawDataRepacker")
Definition: ConfigBuilder.py:1924
ConfigBuilder.ConfigBuilder.RAW2RECODefaultSeq
RAW2RECODefaultSeq
Definition: ConfigBuilder.py:1074
ComparisonHelper::zip
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
Definition: L1TStage2CaloLayer1.h:41
ConfigBuilder.ConfigBuilder.USERDefaultSeq
USERDefaultSeq
Definition: ConfigBuilder.py:1076
ConfigBuilder.ConfigBuilder.DIGIDefaultCFF
DIGIDefaultCFF
Definition: ConfigBuilder.py:954
ConfigBuilder.ConfigBuilder.L1MENUDefaultCFF
L1MENUDefaultCFF
Definition: ConfigBuilder.py:957
miniAOD_tools.miniAOD_customizeOutput
def miniAOD_customizeOutput(out)
Definition: miniAOD_tools.py:608
ConfigBuilder.ConfigBuilder.additionalCommands
additionalCommands
Definition: ConfigBuilder.py:260
ConfigBuilder.ConfigBuilder.load
def load(self, includeFile)
Definition: ConfigBuilder.py:316
ConfigBuilder.ConfigBuilder.REDIGIDefaultSeq
REDIGIDefaultSeq
Definition: ConfigBuilder.py:1151
ConfigBuilder.ConfigBuilder.HARVESTINGDefaultSeq
HARVESTINGDefaultSeq
Definition: ConfigBuilder.py:997
ConfigBuilder.ConfigBuilder.PATDefaultSeq
PATDefaultSeq
Definition: ConfigBuilder.py:1015
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.leave
def leave(self, visitee)
Definition: ConfigBuilder.py:1920
ConfigBuilder.ConfigBuilder.SimGeometryCFF
SimGeometryCFF
Definition: ConfigBuilder.py:1110
ConfigBuilder.ConfigBuilder.prepare_HARVESTING
def prepare_HARVESTING(self, sequence=None)
Definition: ConfigBuilder.py:2010
ConfigBuilder.ConfigBuilder.L1HwValDefaultSeq
L1HwValDefaultSeq
Definition: ConfigBuilder.py:1010
alcaDQMUpload.encode
def encode(args, files)
Definition: alcaDQMUpload.py:32
ConfigBuilder.dumpPython
def dumpPython(process, name)
Definition: ConfigBuilder.py:94
ConfigBuilder.ConfigBuilder.runsAndWeights
runsAndWeights
drop LHEXMLStringProduct on input to save memory if appropriate
Definition: ConfigBuilder.py:480
ConfigBuilder.ConfigBuilder._options
_options
Definition: ConfigBuilder.py:203
ThrowAndSetRandomRun.throwAndSetRandomRun
def throwAndSetRandomRun(source, runsAndProbs)
Definition: ThrowAndSetRandomRun.py:7
ConfigBuilder.ConfigBuilder.L1HwValDefaultCFF
L1HwValDefaultCFF
Definition: ConfigBuilder.py:972
ConfigBuilder.ConfigBuilder.ALCADefaultCFF
ALCADefaultCFF
Definition: ConfigBuilder.py:951
edm::eventsetup::heterocontainer::insert
bool insert(Storage &iStorage, ItemType *iItem, const IdTag &iIdTag)
Definition: HCMethods.h:50
ConfigBuilder.ConfigBuilder.prepare_PAT
def prepare_PAT(self, sequence="miniAOD")
Definition: ConfigBuilder.py:1670
ConfigBuilder.ConfigBuilder.blacklist_paths
blacklist_paths
Definition: ConfigBuilder.py:262
MassReplace.massSearchReplaceAnyInputTag
def massSearchReplaceAnyInputTag(sequence, oldInputTag, newInputTag, verbose=False, moduleLabelOnly=False, skipLabelTest=False)
Definition: MassReplace.py:79
ConfigBuilder.ConfigBuilder.USERDefaultCFF
USERDefaultCFF
Definition: ConfigBuilder.py:1077
ConfigBuilder.ConfigBuilder.addCustomise
def addCustomise(self, unsch=0)
Definition: ConfigBuilder.py:850
ConfigBuilder.ConfigBuilder.prepare_ALCAHARVEST
def prepare_ALCAHARVEST(self, sequence=None)
Definition: ConfigBuilder.py:2048
ConfigBuilder.ConfigBuilder.completeInputCommand
def completeInputCommand(self)
Definition: ConfigBuilder.py:805
ConfigBuilder.ConfigBuilder.nextScheduleIsConditional
nextScheduleIsConditional
put the filtering path in the schedule
Definition: ConfigBuilder.py:268
AlignmentPI::index
index
Definition: AlignmentPayloadInspectorHelper.h:46
ConfigBuilder.ConfigBuilder.RECOSIMDefaultCFF
RECOSIMDefaultCFF
Definition: ConfigBuilder.py:964
ConfigBuilder.ConfigBuilder.prepare
def prepare(self, doChecking=False)
Definition: ConfigBuilder.py:2151
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._paramReplace
_paramReplace
Definition: ConfigBuilder.py:1869
ConfigBuilder.ConfigBuilder.addExtraStream
def addExtraStream(self, name, stream, workflow='full')
Definition: ConfigBuilder.py:1154
ConfigBuilder.ConfigBuilder.process
process
adding standard sequences might change the inputEventContent option and therefore needs to be finaliz...
Definition: ConfigBuilder.py:246
ConfigBuilder.ConfigBuilder.addStandardSequences
def addStandardSequences(self)
Definition: ConfigBuilder.py:708
genParticles_cff.map
map
Definition: genParticles_cff.py:11
ConfigBuilder.ConfigBuilder.prepare_NANO
def prepare_NANO(self, sequence="nanoAOD")
Definition: ConfigBuilder.py:1702
ConfigBuilder.ConfigBuilder.prepare_RAW2RECO
def prepare_RAW2RECO(self, sequence=None)
Definition: ConfigBuilder.py:1574
ConfigBuilder.ConfigBuilder.prepare_DATAMIX
def prepare_DATAMIX(self, sequence=None)
Definition: ConfigBuilder.py:1471
ConfigBuilder.ConfigBuilder.REPACKDefaultCFF
REPACKDefaultCFF
Definition: ConfigBuilder.py:979
ConfigBuilder.ConfigBuilder.DATAMIXDefaultCFF
DATAMIXDefaultCFF
Definition: ConfigBuilder.py:982
ConfigBuilder.ConfigBuilder.prepare_L1REPACK
def prepare_L1REPACK(self, sequence=None)
Definition: ConfigBuilder.py:1506
ConfigBuilder.ConfigBuilder.GeometryCFF
GeometryCFF
Definition: ConfigBuilder.py:1084
ConfigBuilder.ConfigBuilder.inliner
inliner
load the relevant part
Definition: ConfigBuilder.py:1625
ConfigBuilder.ConfigBuilder.CFWRITERDefaultSeq
CFWRITERDefaultSeq
Definition: ConfigBuilder.py:999
ConfigBuilder.ConfigBuilder.DIGI2RAWDefaultCFF
DIGI2RAWDefaultCFF
Definition: ConfigBuilder.py:955
ConfigBuilder.ConfigBuilder.AlCaPaths
AlCaPaths
Definition: ConfigBuilder.py:1281
ConfigBuilder.ConfigBuilder.SIMDefaultCFF
SIMDefaultCFF
Definition: ConfigBuilder.py:953
ConfigBuilder.ConfigBuilder.prepare_L1TrackTrigger
def prepare_L1TrackTrigger(self, sequence="L1TrackTrigger")
Definition: ConfigBuilder.py:1611
ConfigBuilder.ConfigBuilder.schedule
schedule
Definition: ConfigBuilder.py:254
ConfigBuilder.ConfigBuilder.prepare_RAW2DIGI
def prepare_RAW2DIGI(self, sequence="RawToDigi")
Definition: ConfigBuilder.py:1585
ConfigBuilder.ConfigBuilder.prepare_PATFILTER
def prepare_PATFILTER(self, sequence=None)
Definition: ConfigBuilder.py:1592
ConfigBuilder.ConfigBuilder.ENDJOBDefaultSeq
ENDJOBDefaultSeq
Definition: ConfigBuilder.py:1013
python.rootplot.root2matplotlib.replace
def replace(string, replacements)
Definition: root2matplotlib.py:444
ConfigBuilder.ConfigBuilder.prepare_USER
def prepare_USER(self, sequence=None)
Definition: ConfigBuilder.py:1781
ConfigBuilder.ConfigBuilder.addConditions
def addConditions(self)
Definition: ConfigBuilder.py:835