CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_8_patch3/src/HLTrigger/Configuration/python/Tools/confdb.py

Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 import sys
00004 import re
00005 import os
00006 from pipe import pipe as _pipe
00007 from options import globalTag
00008 from itertools import islice
00009 
00010 def splitter(iterator, n):
00011   i = iterator.__iter__()
00012   while True:
00013     l = list(islice(i, n))
00014     if l:
00015       yield l
00016     else:
00017       break
00018 
00019 
00020 class HLTProcess(object):
00021   # paths not supported by FastSim
00022   fastsimUnsupportedPaths = (
00023 
00024   # paths for which a recovery is not foreseen/possible
00025     "AlCa_EcalEta_v*",
00026     "AlCa_EcalPhiSym_v*",
00027     "AlCa_EcalPi0_v*",
00028     "AlCa_EcalPi0EBonly_v*",
00029     "AlCa_EcalPi0EEonly_v*",
00030     "AlCa_EcalEtaEBonly_v*",
00031     "AlCa_EcalEtaEEonly_v*",
00032     "AlCa_RPCMuonNoHits_v*",
00033     "AlCa_RPCMuonNoTriggers_v*",
00034     "AlCa_RPCMuonNormalisation_v*",
00035     "AlCa_LumiPixels_v*",
00036     "AlCa_LumiPixels_Random_v*",
00037     "AlCa_LumiPixels_ZeroBias_v*",
00038     "DQM_FEDIntegrity_v*",
00039     "DQM_HcalEmptyEvents_v*",
00040     "HLT_Calibration_v*",
00041     "HLT_EcalCalibration_v*",
00042     "HLT_HcalCalibration_v*",
00043     "HLT_TrackerCalibration_v*",
00044     "HLT_DTErrors_v*",
00045     "HLT_DTCalibration_v*",
00046     "HLT_Random_v*",
00047     "HLT_HcalNZS_v*",
00048     "HLT_HcalPhiSym_v*",
00049     "HLT_IsoTrackHB_v*",
00050     "HLT_IsoTrackHE_v*",
00051     "HLT_L1SingleMuOpen_AntiBPTX_v*",
00052     "HLT_JetE30_NoBPTX*_v*",
00053     "HLT_JetE50_NoBPTX*_v*",
00054     "HLT_JetE50_NoBPTX3BX_NoHalo_v*",
00055     "HLT_JetE70_NoBPTX3BX_NoHalo_v*",
00056     "HLT_L2Mu10_NoVertex_NoBPTX3BX_NoHalo_v*",
00057     "HLT_L2Mu20_NoVertex_NoBPTX3BX_NoHalo_v*",
00058     "HLT_L2Mu30_NoVertex_NoBPTX3BX_NoHalo_v*",
00059     "HLT_JetE30_NoBPTX3BX_v*",
00060     "HLT_JetE50_NoBPTX3BX_v*",
00061     "HLT_JetE70_NoBPTX3BX_v*",
00062     "HLT_L2Mu10_NoVertex_NoBPTX3BX_v*",
00063     "HLT_L2Mu10_NoVertex_NoBPTX3BX_v*",
00064     "HLT_L2Mu10_NoVertex_NoBPTX3BX_v*",
00065     "HLT_L2Mu20_NoVertex_NoBPTX3BX_v*",
00066     "HLT_L2Mu30_NoVertex_NoBPTX3BX_v*",
00067     "HLT_L2Mu20_NoVertex_2Cha_NoBPTX3BX_NoHalo_v*",
00068     "HLT_L2Mu30_NoVertex_2Cha_NoBPTX3BX_NoHalo_v*",
00069     "HLT_PixelTracks_Multiplicity70_v*",
00070     "HLT_PixelTracks_Multiplicity80_v*",
00071     "HLT_PixelTracks_Multiplicity90_v*",
00072     "HLT_BeamGas_HF_Beam1_v*",
00073     "HLT_BeamGas_HF_Beam2_v*",
00074     "HLT_BeamHalo_v*",
00075     "HLT_L1Tech_CASTOR_HaloMuon_v*",
00076     "HLT_L1Tech_DT_GlobalOR_v*",
00077     "HLT_GlobalRunHPDNoise_v*",
00078     "HLT_L1Tech_HBHEHO_totalOR_v*",
00079     "HLT_L1Tech_HCAL_HF_single_channel_v*",
00080     "HLT_L1TrackerCosmics_v*",
00081     "HLT_HcalUTCA_v*",
00082     
00083 # TODO: paths not supported by FastSim, but for which a recovery should be attempted
00084     
00085     "HLT_DoubleMediumIsoPFTau30_Trk1_eta2p1_Reg_Jet30_v*", 
00086     "HLT_DoubleMediumIsoPFTau30_Trk1_eta2p1_Reg_v*",
00087     "HLT_DoubleMediumIsoPFTau35_Trk1_eta2p1_Prong1_Reg_v*",
00088     "HLT_DoubleMediumIsoPFTau35_Trk1_eta2p1_Reg_v*",
00089     "HLT_IsoMu18_eta2p1_MediumIsoPFTau25_Trk1_eta2p1_Reg_v*",
00090 # (not really needed for the five above, because the corresponding paths without regional
00091 #  tracking are already in the HLT menu)
00092   
00093     )
00094 
00095   def __init__(self, configuration):
00096     self.config = configuration
00097     self.data   = None
00098     self.source = None
00099     self.parent = None
00100 
00101     self.options = {
00102       'essources' : [],
00103       'esmodules' : [],
00104       'modules'   : [],
00105       'sequences' : [],
00106       'services'  : [],
00107       'paths'     : [],
00108       'psets'     : [],
00109       'blocks'    : [],
00110     }
00111 
00112     self.labels = {}
00113     if self.config.fragment:
00114       self.labels['process'] = ''
00115       self.labels['dict']    = 'locals()'
00116     else:
00117       self.labels['process'] = 'process.'
00118       self.labels['dict']    = 'process.__dict__'
00119 
00120     if self.config.online:
00121       self.labels['connect'] = 'frontier://(proxyurl=https://localhost:3128)(serverurl=https://localhost:8000/FrontierOnProd)(serverurl=https://localhost:8000/FrontierOnProd)(retrieve-ziplevel=0)'
00122     else:
00123       self.labels['connect'] = 'frontier://FrontierProd'
00124 
00125     # get the configuration from ConfdB
00126     self.buildPathList()
00127     self.buildOptions()
00128     self.getRawConfigurationFromDB()
00129     self.customize()
00130 
00131 
00132   def _build_query(self):
00133     if self.config.menu.run:
00134       return '--runNumber %s' % self.config.menu.run
00135     else:
00136       return '--%s --configName %s' % (self.config.menu.db, self.config.menu.name)
00137 
00138   def _build_options(self):
00139     return ' '.join(['--%s %s' % (key, ','.join(vals)) for key, vals in self.options.iteritems() if vals])
00140 
00141   def _build_cmdline(self):
00142     if not self.config.fragment:
00143       return 'edmConfigFromDB       %s --noedsources %s' % (self._build_query(), self._build_options())
00144     else:
00145       return 'edmConfigFromDB --cff %s --noedsources %s' % (self._build_query(), self._build_options())
00146 
00147 
00148   def getRawConfigurationFromDB(self):
00149     cmdline = self._build_cmdline()
00150     data = _pipe(cmdline)
00151     if 'Exhausted Resultset' in data or 'CONFIG_NOT_FOUND' in data:
00152       raise ImportError('%s is not a valid HLT menu' % self.config.menuConfig.value)
00153     self.data = data
00154 
00155 
00156   def getPathList(self):
00157     cmdline = 'edmConfigFromDB --cff %s --noedsources --noes --noservices --nosequences --nomodules' % self._build_query()
00158     data = _pipe(cmdline)
00159     if 'Exhausted Resultset' in data or 'CONFIG_NOT_FOUND' in data:
00160       raise ImportError('%s is not a valid HLT menu' % self.config.menuConfig.value)
00161     filter = re.compile(r' *= *cms.(End)?Path.*')
00162     paths  = [ filter.sub('', line) for line in data.splitlines() if filter.search(line) ]
00163     return paths
00164 
00165 
00166   @staticmethod
00167   def expandWildcards(globs, collection):
00168     # expand a list of unix-style wildcards matching a given collection
00169     # wildcards with no matches are silently discarded
00170     matches = []
00171     for glob in globs:
00172       negate = ''
00173       if glob[0] == '-':
00174         negate = '-'
00175         glob   = glob[1:]
00176       # translate a unix-style glob expression into a regular expression
00177       filter = re.compile(r'^' + glob.replace('?', '.').replace('*', '.*').replace('[!', '[^') + r'$')
00178       matches.extend( negate + element for element in collection if filter.match(element) )
00179     return matches
00180 
00181 
00182   @staticmethod
00183   def consolidateNegativeList(elements):
00184     # consolidate a list of path exclusions and re-inclusions
00185     # the result is the list of paths to be removed from the dump
00186     result = set()
00187     for element in elements:
00188       if element[0] == '-':
00189         result.add( element )
00190       else:
00191         result.discard( '-' + element )
00192     return sorted( element for element in result )
00193 
00194   @staticmethod
00195   def consolidatePositiveList(elements):
00196     # consolidate a list of path selection and re-exclusions
00197     # the result is the list of paths to be included in the dump
00198     result = set()
00199     for element in elements:
00200       if element[0] == '-':
00201         result.discard( element[1:] )
00202       else:
00203         result.add( element )
00204     return sorted( element for element in result )
00205 
00206 
00207   # dump the final configuration
00208   def dump(self):
00209     return self.data % self.labels
00210 
00211 
00212   # add release-specific customizations
00213   def releaseSpecificCustomize(self):
00214     # version specific customizations
00215     self.data += """
00216 # CMSSW version specific customizations
00217 import os
00218 cmsswVersion = os.environ['CMSSW_VERSION']
00219 
00220 # customization for CMSSW_5_2_X
00221 if cmsswVersion.startswith('CMSSW_5_2_'):
00222 
00223     # force the use of the correct calo jet energy corrections
00224     if 'hltESPL1FastJetCorrectionESProducer' in %(dict)s:
00225         %(process)shltESPL1FastJetCorrectionESProducer.algorithm  = "AK5CaloHLT"
00226 
00227     if 'hltESPL2RelativeCorrectionESProducer' in %(dict)s:
00228         %(process)shltESPL2RelativeCorrectionESProducer.algorithm = "AK5CaloHLT"
00229 
00230     if 'hltESPL3AbsoluteCorrectionESProducer' in %(dict)s:
00231         %(process)shltESPL3AbsoluteCorrectionESProducer.algorithm = "AK5CaloHLT"
00232 
00233 
00234 # customization for CMSSW_5_3_X
00235 if cmsswVersion.startswith('CMSSW_5_3_'):
00236 
00237     # do not override the calo jet energy corrections in 5.3.x for consistency with the current MC samples
00238     pass
00239 
00240 
00241 # customization for CMSSW_6_1_X and 6_2_X
00242 if cmsswVersion.startswith('CMSSW_6_1_') or cmsswVersion.startswith('CMSSW_6_2_'):
00243 
00244     # force the use of the correct calo jet energy corrections
00245     if 'hltESPL1FastJetCorrectionESProducer' in %(dict)s:
00246         %(process)shltESPL1FastJetCorrectionESProducer.algorithm  = "AK5CaloHLT"
00247 
00248     if 'hltESPL2RelativeCorrectionESProducer' in %(dict)s:
00249         %(process)shltESPL2RelativeCorrectionESProducer.algorithm = "AK5CaloHLT"
00250 
00251     if 'hltESPL3AbsoluteCorrectionESProducer' in %(dict)s:
00252         %(process)shltESPL3AbsoluteCorrectionESProducer.algorithm = "AK5CaloHLT"
00253 
00254     # adapt the HLT menu to the "prototype for Event Interpretation" development
00255     if 'hltPFPileUp' in %(dict)s:
00256         # define new PFCandidateFwdPtrProducer module
00257         %(process)shltParticleFlowPtrs = cms.EDProducer("PFCandidateFwdPtrProducer",
00258             src = cms.InputTag('hltParticleFlow')
00259         )
00260         # add the new module before the hltPFPileUp module
00261         _sequence = None
00262         for _sequence in [ _sequence for _sequence in %(dict)s.itervalues() if isinstance(_sequence, cms._ModuleSequenceType)]:
00263             try:
00264                 _sequence.insert( _sequence.index(%(process)shltPFPileUp), %(process)shltParticleFlowPtrs )
00265             except ValueError:
00266                 pass
00267         # reconfigure hltPFPileUp and hltPFNoPileUp to use the new module
00268         %(process)shltPFPileUp.PFCandidates       = cms.InputTag( "hltParticleFlowPtrs" )
00269         %(process)shltPFNoPileUp.bottomCollection = cms.InputTag( "hltParticleFlowPtrs" )
00270 
00271 
00272 # customization for CMSSW_6_2_X only
00273 if cmsswVersion.startswith('CMSSW_6_2_'):
00274     # /Geometry/TrackerNumberingBuilder/trackerTopologyConstants_cfi.py
00275     %(process)strackerTopologyConstants = cms.ESProducer('TrackerTopologyEP',
00276       pxb_layerStartBit = cms.uint32(16),
00277       pxb_ladderStartBit = cms.uint32(8),
00278       pxb_moduleStartBit = cms.uint32(2),
00279       pxb_layerMask = cms.uint32(15),
00280       pxb_ladderMask = cms.uint32(255),
00281       pxb_moduleMask = cms.uint32(63),
00282       pxf_sideStartBit = cms.uint32(23),
00283       pxf_diskStartBit = cms.uint32(16),
00284       pxf_bladeStartBit = cms.uint32(10),
00285       pxf_panelStartBit = cms.uint32(8),
00286       pxf_moduleStartBit = cms.uint32(2),
00287       pxf_sideMask = cms.uint32(3),
00288       pxf_diskMask = cms.uint32(15),
00289       pxf_bladeMask = cms.uint32(63),
00290       pxf_panelMask = cms.uint32(3),
00291       pxf_moduleMask = cms.uint32(63),
00292       tec_sideStartBit = cms.uint32(18),
00293       tec_wheelStartBit = cms.uint32(14),
00294       tec_petal_fw_bwStartBit = cms.uint32(12),
00295       tec_petalStartBit = cms.uint32(8),
00296       tec_ringStartBit = cms.uint32(5),
00297       tec_moduleStartBit = cms.uint32(2),
00298       tec_sterStartBit = cms.uint32(0),
00299       tec_sideMask = cms.uint32(3),
00300       tec_wheelMask = cms.uint32(15),
00301       tec_petal_fw_bwMask = cms.uint32(3),
00302       tec_petalMask = cms.uint32(15),
00303       tec_ringMask = cms.uint32(7),
00304       tec_moduleMask = cms.uint32(7),
00305       tec_sterMask = cms.uint32(3),
00306       tib_layerStartBit = cms.uint32(14),
00307       tib_str_fw_bwStartBit = cms.uint32(12),
00308       tib_str_int_extStartBit = cms.uint32(10),
00309       tib_strStartBit = cms.uint32(4),
00310       tib_moduleStartBit = cms.uint32(2),
00311       tib_sterStartBit = cms.uint32(0),
00312       tib_layerMask = cms.uint32(7),
00313       tib_str_fw_bwMask = cms.uint32(3),
00314       tib_str_int_extMask = cms.uint32(3),
00315       tib_strMask = cms.uint32(63),
00316       tib_moduleMask = cms.uint32(3),
00317       tib_sterMask = cms.uint32(3),
00318       tid_sideStartBit = cms.uint32(13),
00319       tid_wheelStartBit = cms.uint32(11),
00320       tid_ringStartBit = cms.uint32(9),
00321       tid_module_fw_bwStartBit = cms.uint32(7),
00322       tid_moduleStartBit = cms.uint32(2),
00323       tid_sterStartBit = cms.uint32(0),
00324       tid_sideMask = cms.uint32(3),
00325       tid_wheelMask = cms.uint32(3),
00326       tid_ringMask = cms.uint32(3),
00327       tid_module_fw_bwMask = cms.uint32(3),
00328       tid_moduleMask = cms.uint32(31),
00329       tid_sterMask = cms.uint32(3),
00330       tob_layerStartBit = cms.uint32(14),
00331       tob_rod_fw_bwStartBit = cms.uint32(12),
00332       tob_rodStartBit = cms.uint32(5),
00333       tob_moduleStartBit = cms.uint32(2),
00334       tob_sterStartBit = cms.uint32(0),
00335       tob_layerMask = cms.uint32(7),
00336       tob_rod_fw_bwMask = cms.uint32(3),
00337       tob_rodMask = cms.uint32(127),
00338       tob_moduleMask = cms.uint32(7),
00339       tob_sterMask = cms.uint32(3),
00340       appendToDataLabel = cms.string('')
00341     )
00342 
00343 """
00344 
00345   # customize the configuration according to the options
00346   def customize(self):
00347 
00348     # adapt the source to the current scenario
00349     if not self.config.fragment:
00350       self.build_source()
00351 
00352     # manual override some parameters
00353     if self.config.type in ('GRun', ):
00354       self.data += """
00355 # Enable HF Noise filters in GRun menu
00356 if 'hltHfreco' in %(dict)s:
00357     %(process)shltHfreco.setNoiseFlags = cms.bool( True )
00358 """
00359     if self.config.type in ('HIon', ):
00360       self.data += """
00361 # Disable HF Noise filters in HIon menu
00362 if 'hltHfreco' in %(dict)s:
00363     %(process)shltHfreco.setNoiseFlags = cms.bool( False )
00364 """
00365 
00366 #    self.data += """
00367 ## untracked parameters with NO default in the code
00368 #if 'hltHcalDataIntegrityMonitor' in %(dict)s:
00369 #    %(process)shltHcalDataIntegrityMonitor.RawDataLabel = cms.untracked.InputTag("rawDataCollector")
00370 #if 'hltDt4DSegments' in %(dict)s:
00371 #    %(process)shltDt4DSegments.debug = cms.untracked.bool( False )
00372 #"""
00373 
00374     # if requested, override the L1 self from the GlobalTag (Xml)
00375     self.overrideL1MenuXml()
00376 
00377     # if running on MC, adapt the configuration accordingly
00378     self.fixForMC()
00379 
00380     # if requested, remove the HLT prescales
00381     self.fixPrescales()
00382 
00383     # if requested, override all ED/HLTfilters to always pass ("open" mode)
00384     self.instrumentOpenMode()
00385 
00386     # if requested, change all HLTTriggerTypeFilter EDFilters to accept only error events (SelectedTriggerType = 0)
00387     self.instrumentErrorEventType()
00388 
00389     # if requested, instrument the self with the modules and EndPath needed for timing studies
00390     self.instrumentTiming()
00391 
00392     # add version-specific customisations
00393     self.releaseSpecificCustomize()
00394 
00395     if self.config.fragment:
00396       
00397 #      self.data += """
00398 ## dummyfy hltGetConditions in cff's
00399 #if 'hltGetConditions' in %(dict)s and 'HLTriggerFirstPath' in %(dict)s :
00400 #    %(process)shltDummyConditions = cms.EDFilter( "HLTBool",
00401 #        result = cms.bool( True )
00402 #    )
00403 #    %(process)sHLTriggerFirstPath.replace(%(process)shltGetConditions,%(process)shltDummyConditions)
00404 #"""
00405 
00406       # if requested, adapt the configuration for FastSim
00407       self.fixForFastSim()
00408 
00409     else:
00410 
00411       # override the process name and adapt the relevant filters
00412       self.overrideProcessName()
00413 
00414       # override the output modules to output root files
00415       self.overrideOutput()
00416 
00417       # add global options
00418       self.addGlobalOptions()
00419 
00420       # if requested or necessary, override the GlobalTag and connection strings (incl. L1!)
00421       self.overrideGlobalTag()
00422 
00423       # if requested, run (part of) the L1 emulator
00424       self.runL1Emulator()
00425 
00426       # request summary informations from the MessageLogger
00427       self.updateMessageLogger()
00428 
00429       # load 5.2.x JECs, until they are in the GlobalTag
00430 #      self.loadAdditionalConditions('load 5.2.x JECs',
00431 #        {
00432 #          'record'  : 'JetCorrectionsRecord',
00433 #          'tag'     : 'JetCorrectorParametersCollection_AK5Calo_2012_V8_hlt_mc',
00434 #          'label'   : 'AK5CaloHLT',
00435 #          'connect' : '%(connect)s/CMS_COND_31X_PHYSICSTOOLS'
00436 #        }, {
00437 #          'record'  : 'JetCorrectionsRecord',
00438 #          'tag'     : 'JetCorrectorParametersCollection_AK5PF_2012_V8_hlt_mc',
00439 #          'label'   : 'AK5PFHLT',
00440 #          'connect' : '%(connect)s/CMS_COND_31X_PHYSICSTOOLS'
00441 #        }, {
00442 #          'record'  : 'JetCorrectionsRecord',
00443 #          'tag'     : 'JetCorrectorParametersCollection_AK5PFchs_2012_V8_hlt_mc',
00444 #          'label'   : 'AK5PFchsHLT',
00445 #          'connect' : '%(connect)s/CMS_COND_31X_PHYSICSTOOLS'
00446 #        }
00447 #      )
00448 
00449 
00450   def addGlobalOptions(self):
00451     # add global options
00452     self.data += """
00453 # limit the number of events to be processed
00454 %%(process)smaxEvents = cms.untracked.PSet(
00455     input = cms.untracked.int32( %d )
00456 )
00457 """ % self.config.events
00458 
00459     if not self.config.profiling:
00460       self.data += """
00461 # enable the TrigReport and TimeReport
00462 %(process)soptions = cms.untracked.PSet(
00463     wantSummary = cms.untracked.bool( True )
00464 )
00465 """
00466 
00467 
00468   def _fix_parameter(self, **args):
00469     """arguments:
00470         name:     parameter name (optional)
00471         type:     parameter type (look for tracked and untracked variants)
00472         value:    original value
00473         replace:  replacement value
00474     """
00475     if 'name' in args:
00476       self.data = re.sub(
00477           r'%(name)s = cms(?P<tracked>(?:\.untracked)?)\.%(type)s\( (?P<quote>["\']?)%(value)s(?P=quote)' % args,
00478           r'%(name)s = cms\g<tracked>.%(type)s( \g<quote>%(replace)s\g<quote>' % args,
00479           self.data)
00480     else:
00481       self.data = re.sub(
00482           r'cms(?P<tracked>(?:\.untracked)?)\.%(type)s\( (?P<quote>["\']?)%(value)s(?P=quote)' % args,
00483           r'cms\g<tracked>.%(type)s( \g<quote>%(replace)s\g<quote>' % args,
00484           self.data)
00485 
00486 
00487   def fixForMC(self):
00488     if not self.config.data:
00489       # customise the HLT menu for running on MC
00490       if not self.config.fragment:
00491         self.data += """
00492 # customise the HLT menu for running on MC
00493 from HLTrigger.Configuration.customizeHLTforMC import customizeHLTforMC
00494 process = customizeHLTforMC(process)
00495 """
00496 
00497 
00498   def fixForFastSim(self):
00499     if self.config.fastsim:
00500       # adapt the hle configuration (fragment) to run under fastsim
00501       self.data = re.sub( r'import FWCore.ParameterSet.Config as cms', r'\g<0>\nfrom FastSimulation.HighLevelTrigger.HLTSetup_cff import *', self.data)
00502 
00503       # remove the definition of streams and datasets
00504       self.data = re.compile( r'^streams.*\n(.*\n)*?^\)\s*\n',  re.MULTILINE ).sub( '', self.data )
00505       self.data = re.compile( r'^datasets.*\n(.*\n)*?^\)\s*\n', re.MULTILINE ).sub( '', self.data )
00506 
00507       # fix the definition of module
00508       # FIXME: this should be updated to take into accout the --l1-emulator option
00509       self._fix_parameter(                               type = 'InputTag', value = 'hltL1extraParticles',  replace = 'l1extraParticles')
00510       self._fix_parameter(name = 'GMTReadoutCollection', type = 'InputTag', value = 'hltGtDigis',           replace = 'gmtDigis')
00511       self._fix_parameter(                               type = 'InputTag', value = 'hltGtDigis',           replace = 'gtDigis')
00512       self._fix_parameter(                               type = 'InputTag', value = 'hltL1GtObjectMap',     replace = 'gtDigis')
00513       self._fix_parameter(name = 'initialSeeds',         type = 'InputTag', value = 'noSeedsHere',          replace = 'globalPixelSeeds:GlobalPixel')
00514       self._fix_parameter(name = 'preFilteredSeeds',     type = 'bool',     value = 'True',                 replace = 'False')
00515       self._fix_parameter(                               type = 'InputTag', value = 'hltOfflineBeamSpot',   replace = 'offlineBeamSpot')
00516       self._fix_parameter(                               type = 'InputTag', value = 'hltOnlineBeamSpot',    replace = 'offlineBeamSpot')
00517       self._fix_parameter(                               type = 'InputTag', value = 'hltMuonCSCDigis',      replace = 'simMuonCSCDigis')
00518       self._fix_parameter(                               type = 'InputTag', value = 'hltMuonDTDigis',       replace = 'simMuonDTDigis')
00519       self._fix_parameter(                               type = 'InputTag', value = 'hltMuonRPCDigis',      replace = 'simMuonRPCDigis')
00520       self._fix_parameter(                               type = 'InputTag', value = 'hltRegionalTracksForL3MuonIsolation', replace = 'hltPixelTracks')
00521       self._fix_parameter(name = 'src',                  type = 'InputTag', value = 'hltHcalTowerNoiseCleaner', replace = 'hltTowerMakerForAll')
00522       self._fix_parameter(name = 'src',                  type = 'InputTag', value = 'hltIter4Tau3MuMerged', replace = 'hltIter4Merged')
00523 
00524       # fix the definition of sequences and paths
00525       self.data = re.sub( r'hltMuonCSCDigis', r'cms.SequencePlaceholder( "simMuonCSCDigis" )',  self.data )
00526       self.data = re.sub( r'hltMuonDTDigis',  r'cms.SequencePlaceholder( "simMuonDTDigis" )',   self.data )
00527       self.data = re.sub( r'hltMuonRPCDigis', r'cms.SequencePlaceholder( "simMuonRPCDigis" )',  self.data )
00528       self.data = re.sub( r'HLTEndSequence',  r'cms.SequencePlaceholder( "HLTEndSequence" )',   self.data )
00529       self.data = re.sub( r'hltGtDigis',      r'HLTBeginSequence',                              self.data )
00530 
00531 
00532   def fixPrescales(self):
00533     # update the PrescaleService to match the new list of paths
00534     if self.options['paths']:
00535       if self.options['paths'][0][0] == '-':
00536         # drop requested paths
00537         for minuspath in self.options['paths']:
00538           path = minuspath[1:]
00539           self.data = re.sub(r'      cms.PSet\(  pathName = cms.string\( "%s" \),\n        prescales = cms.vuint32\( .* \)\n      \),?\n' % path, '', self.data)
00540       else:
00541         # keep requested paths
00542         for path in self.all_paths:
00543           if path not in self.options['paths']:
00544             self.data = re.sub(r'      cms.PSet\(  pathName = cms.string\( "%s" \),\n        prescales = cms.vuint32\( .* \)\n      \),?\n' % path, '', self.data)
00545 
00546     if self.config.unprescale:
00547       self.data += """
00548 # remove the HLT prescales
00549 if 'PrescaleService' in %(dict)s:
00550     %(process)sPrescaleService.lvl1DefaultLabel = cms.string( '0' )
00551     %(process)sPrescaleService.lvl1Labels       = cms.vstring( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' )
00552     %(process)sPrescaleService.prescaleTable    = cms.VPSet( )
00553 """
00554 
00555 
00556   def instrumentOpenMode(self):
00557     if self.config.open:
00558       # find all EDfilters
00559       filters = [ match[1] for match in re.findall(r'(process\.)?\b(\w+) = cms.EDFilter', self.data) ]
00560       re_sequence = re.compile( r'cms\.(Path|Sequence)\((.*)\)' )
00561       # remove existing 'cms.ingore' and '~' modifiers
00562       self.data = re_sequence.sub( lambda line: re.sub( r'cms\.ignore *\( *((process\.)?\b(\w+)) *\)', r'\1', line.group(0) ), self.data )
00563       self.data = re_sequence.sub( lambda line: re.sub( r'~', '', line.group(0) ), self.data )
00564       # wrap all EDfilters with "cms.ignore( ... )", 1000 at a time (python 2.6 complains for too-big regular expressions)
00565       for some in splitter(filters, 1000):
00566         re_filters  = re.compile( r'\b((process\.)?(' + r'|'.join(some) + r'))\b' )
00567         self.data = re_sequence.sub( lambda line: re_filters.sub( r'cms.ignore( \1 )', line.group(0) ), self.data )
00568 
00569 
00570   def instrumentErrorEventType(self):
00571     if self.config.errortype:
00572       # change all HLTTriggerTypeFilter EDFilters to accept only error events (SelectedTriggerType = 0)
00573       self._fix_parameter(name = 'SelectedTriggerType', type ='int32', value = '1', replace = '0')
00574       self._fix_parameter(name = 'SelectedTriggerType', type ='int32', value = '2', replace = '0')
00575       self._fix_parameter(name = 'SelectedTriggerType', type ='int32', value = '3', replace = '0')
00576 
00577 
00578   def overrideGlobalTag(self):
00579     # overwrite GlobalTag
00580     # the logic is:
00581     #   - always set the correct connection string and pfnPrefix
00582     #   - if a GlobalTag is specified on the command line:
00583     #      - override the global tag
00584     #      - if the GT is "auto:...", insert the code to read it from Configuration.AlCa.autoCond
00585     #   - if a GlobalTag is NOT  specified on the command line:
00586     #      - when running on data, do nothing, and keep the global tag in the menu
00587     #      - when running on mc, take the GT from the configuration.type
00588 
00589     # override the GlobalTag connection string and pfnPrefix
00590     text = """
00591 # override the GlobalTag, connection string and pfnPrefix
00592 if 'GlobalTag' in %(dict)s:
00593     %(process)sGlobalTag.connect   = '%(connect)s/CMS_COND_31X_GLOBALTAG'
00594     %(process)sGlobalTag.pfnPrefix = cms.untracked.string('%(connect)s/')
00595 """
00596 
00597     # when running on MC, override the global tag even if not specified on the command line
00598     if not self.config.data and not self.config.globaltag:
00599       if self.config.type in globalTag:
00600         self.config.globaltag = globalTag[self.config.type]
00601       else:
00602         self.config.globaltag = globalTag['GRun']
00603 
00604     # if requested, override the L1 menu from the GlobalTag (using the same connect as the GlobalTag itself)
00605     if self.config.l1.override:
00606       self.config.l1.record = 'L1GtTriggerMenuRcd'
00607       self.config.l1.label  = ''
00608       self.config.l1.tag    = self.config.l1.override
00609       if not self.config.l1.connect:
00610         self.config.l1.connect = '%(connect)s/CMS_COND_31X_L1T'
00611       self.config.l1cond = '%(tag)s,%(record)s,%(connect)s' % self.config.l1.__dict__
00612     else:
00613       self.config.l1cond = None
00614 
00615     if self.config.globaltag or self.config.l1cond:
00616       text += "    from Configuration.AlCa.GlobalTag import GlobalTag as customiseGlobalTag\n"
00617       text += "    %(process)sGlobalTag = customiseGlobalTag(%(process)sGlobalTag"
00618       if self.config.globaltag:
00619         text += ", globaltag = %s"  % repr(self.config.globaltag)
00620       if self.config.l1cond:
00621         text += ", conditions = %s" % repr(self.config.l1cond)
00622       text += ")\n"
00623 
00624     self.data += text
00625 
00626   def overrideL1MenuXml(self):
00627     # if requested, override the L1 menu from the GlobalTag (Xml file)
00628     if self.config.l1Xml.XmlFile:
00629       text = """
00630 # override the L1 menu from an Xml file
00631 %%(process)sl1GtTriggerMenuXml = cms.ESProducer("L1GtTriggerMenuXmlProducer",
00632   TriggerMenuLuminosity = cms.string('%(LumiDir)s'),
00633   DefXmlFile = cms.string('%(XmlFile)s'),
00634   VmeXmlFile = cms.string('')
00635 )
00636 %%(process)sL1GtTriggerMenuRcdSource = cms.ESSource("EmptyESSource",
00637   recordName = cms.string('L1GtTriggerMenuRcd'),
00638   iovIsRunNotTime = cms.bool(True),
00639   firstValid = cms.vuint32(1)
00640 )
00641 %%(process)ses_prefer_l1GtParameters = cms.ESPrefer('L1GtTriggerMenuXmlProducer','l1GtTriggerMenuXml') 
00642 """
00643       self.data += text % self.config.l1Xml.__dict__
00644 
00645   def runL1EmulatorGT(self):
00646     # if requested, run (part of) the L1 emulator, then repack the data into a new RAW collection, to be used by the HLT
00647     if not self.config.emulator:
00648       return
00649 
00650     if self.config.emulator != 'gt':
00651       # only the GT emulator is currently supported
00652       return
00653 
00654     # run the L1 GT emulator, then repack the data into a new RAW collection, to be used by the HLT
00655     text = """
00656 # run the L1 GT emulator, then repack the data into a new RAW collection, to be used by the HLT
00657 """
00658     if self.config.fragment:
00659       # FIXME in a cff, should also update the HLTSchedule
00660       text += "import Configuration.StandardSequences.SimL1EmulatorRepack_GT_cff\n"
00661     else:
00662       text += "process.load( 'Configuration.StandardSequences.SimL1EmulatorRepack_GT_cff' )\n"
00663 
00664     if not 'hltBoolFalse' in self.data:
00665       # add hltBoolFalse
00666       text += """
00667 %(process)shltBoolFalse = cms.EDFilter( "HLTBool",
00668     result = cms.bool( False )
00669 )
00670 """
00671     text += "process.L1Emulator = cms.Path( process.SimL1Emulator + process.hltBoolFalse )\n\n"
00672 
00673     self.data = re.sub(r'.*cms\.(End)?Path.*', text + r'\g<0>', self.data, 1)
00674 
00675 
00676   def runL1Emulator(self):
00677     # if requested, run (part of) the L1 emulator
00678     if self.config.emulator:
00679       # FIXME this fragment used "process" explicitly
00680       emulator = {
00681         'RawToDigi': '',
00682         'CustomL1T': '',
00683         'CustomHLT': ''
00684       }
00685 
00686       if self.config.data:
00687         emulator['RawToDigi'] = 'RawToDigi_Data_cff'
00688       else:
00689         emulator['RawToDigi'] = 'RawToDigi_cff'
00690 
00691       if self.config.emulator == 'gt':
00692         emulator['CustomL1T'] = 'customiseL1GtEmulatorFromRaw'
00693         emulator['CustomHLT'] = 'switchToSimGtDigis'
00694       elif self.config.emulator == 'gct,gt':
00695         emulator['CustomL1T'] = 'customiseL1CaloAndGtEmulatorsFromRaw'
00696         emulator['CustomHLT'] = 'switchToSimGctGtDigis'
00697       elif self.config.emulator == 'gmt,gt':
00698         # XXX currently unsupported
00699         emulator['CustomL1T'] = 'customiseL1MuonAndGtEmulatorsFromRaw'
00700         emulator['CustomHLT'] = 'switchToSimGmtGtDigis'
00701       elif self.config.emulator in ('gmt,gct,gt', 'gct,gmt,gt', 'all'):
00702         emulator['CustomL1T'] = 'customiseL1EmulatorFromRaw'
00703         emulator['CustomHLT'] = 'switchToSimGmtGctGtDigis'
00704       else:
00705         # unsupported argument, default to running the whole emulator
00706         emulator['CustomL1T'] = 'customiseL1EmulatorFromRaw'
00707         emulator['CustomHLT'] = 'switchToSimGmtGctGtDigis'
00708 
00709       self.data += """
00710 # customize the L1 emulator to run %(CustomL1T)s with HLT to %(CustomHLT)s
00711 process.load( 'Configuration.StandardSequences.%(RawToDigi)s' )
00712 process.load( 'Configuration.StandardSequences.SimL1Emulator_cff' )
00713 import L1Trigger.Configuration.L1Trigger_custom
00714 process = L1Trigger.Configuration.L1Trigger_custom.%(CustomL1T)s( process )
00715 process = L1Trigger.Configuration.L1Trigger_custom.customiseResetPrescalesAndMasks( process )
00716 
00717 # customize the HLT to use the emulated results
00718 import HLTrigger.Configuration.customizeHLTforL1Emulator
00719 process = HLTrigger.Configuration.customizeHLTforL1Emulator.switchToL1Emulator( process )
00720 process = HLTrigger.Configuration.customizeHLTforL1Emulator.%(CustomHLT)s( process )
00721 """ % emulator
00722 
00723 
00724   def overrideOutput(self):
00725     # override the "online" ShmStreamConsumer output modules with "offline" PoolOutputModule's
00726     self.data = re.sub(
00727       r'\b(process\.)?hltOutput(\w+) *= *cms\.OutputModule\( *"ShmStreamConsumer" *,',
00728       r'%(process)shltOutput\2 = cms.OutputModule( "PoolOutputModule",\n    fileName = cms.untracked.string( "output\2.root" ),\n    fastCloning = cms.untracked.bool( False ),\n    dataset = cms.untracked.PSet(\n        filterName = cms.untracked.string( "" ),\n        dataTier = cms.untracked.string( "RAW" )\n    ),',
00729       self.data
00730     )
00731 
00732     if not self.config.fragment and self.config.output == 'full':
00733       # add a single "keep *" output
00734       self.data += """
00735 # add a single "keep *" output
00736 %(process)shltOutputFULL = cms.OutputModule( "PoolOutputModule",
00737     fileName = cms.untracked.string( "outputFULL.root" ),
00738     fastCloning = cms.untracked.bool( False ),
00739     dataset = cms.untracked.PSet(
00740         dataTier = cms.untracked.string( 'RECO' ),
00741         filterName = cms.untracked.string( '' )
00742     ),
00743     outputCommands = cms.untracked.vstring( 'keep *' )
00744 )
00745 %(process)sFULLOutput = cms.EndPath( %(process)shltOutputFULL )
00746 """
00747 
00748 
00749   # override the process name and adapt the relevant filters
00750   def overrideProcessName(self):
00751     if self.config.name is None:
00752       return
00753 
00754     # override the process name
00755     quote = '[\'\"]'
00756     self.data = re.compile(r'^(process\s*=\s*cms\.Process\(\s*' + quote + r')\w+(' + quote + r'\s*\).*)$', re.MULTILINE).sub(r'\1%s\2' % self.config.name, self.data, 1)
00757 
00758     # the following was stolen and adapted from HLTrigger.Configuration.customL1THLT_Options
00759     self.data += """
00760 # adapt HLT modules to the correct process name
00761 if 'hltTrigReport' in %%(dict)s:
00762     %%(process)shltTrigReport.HLTriggerResults                    = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00763 
00764 if 'hltPreExpressCosmicsOutputSmart' in %%(dict)s:
00765     %%(process)shltPreExpressCosmicsOutputSmart.TriggerResultsTag = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00766 
00767 if 'hltPreExpressOutputSmart' in %%(dict)s:
00768     %%(process)shltPreExpressOutputSmart.TriggerResultsTag        = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00769 
00770 if 'hltPreDQMForHIOutputSmart' in %%(dict)s:
00771     %%(process)shltPreDQMForHIOutputSmart.TriggerResultsTag       = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00772 
00773 if 'hltPreDQMForPPOutputSmart' in %%(dict)s:
00774     %%(process)shltPreDQMForPPOutputSmart.TriggerResultsTag       = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00775 
00776 if 'hltPreHLTDQMResultsOutputSmart' in %%(dict)s:
00777     %%(process)shltPreHLTDQMResultsOutputSmart.TriggerResultsTag  = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00778 
00779 if 'hltPreHLTDQMOutputSmart' in %%(dict)s:
00780     %%(process)shltPreHLTDQMOutputSmart.TriggerResultsTag         = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00781 
00782 if 'hltPreHLTMONOutputSmart' in %%(dict)s:
00783     %%(process)shltPreHLTMONOutputSmart.TriggerResultsTag         = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00784 
00785 if 'hltDQMHLTScalers' in %%(dict)s:
00786     %%(process)shltDQMHLTScalers.triggerResults                   = cms.InputTag( 'TriggerResults', '', '%(name)s' )
00787     %%(process)shltDQMHLTScalers.processname                      = '%(name)s'
00788 
00789 if 'hltDQML1SeedLogicScalers' in %%(dict)s:
00790     %%(process)shltDQML1SeedLogicScalers.processname              = '%(name)s'
00791 """ % self.config.__dict__
00792 
00793 
00794   def updateMessageLogger(self):
00795     # request summary informations from the MessageLogger
00796     self.data += """
00797 if 'MessageLogger' in %(dict)s:
00798     %(process)sMessageLogger.categories.append('TriggerSummaryProducerAOD')
00799     %(process)sMessageLogger.categories.append('L1GtTrigReport')
00800     %(process)sMessageLogger.categories.append('HLTrigReport')
00801     %(process)sMessageLogger.categories.append('FastReport')
00802 """
00803 
00804 
00805   def loadAdditionalConditions(self, comment, *conditions):
00806     # load additional conditions
00807     self.data += """
00808 # %s
00809 if 'GlobalTag' in %%(dict)s:
00810 """ % comment
00811     for condition in conditions:
00812       self.data += """    %%(process)sGlobalTag.toGet.append(
00813         cms.PSet(
00814             record  = cms.string( '%(record)s' ),
00815             tag     = cms.string( '%(tag)s' ),
00816             label   = cms.untracked.string( '%(label)s' ),
00817             connect = cms.untracked.string( '%(connect)s' )
00818         )
00819     )
00820 """ % condition
00821 
00822 
00823   def loadCff(self, module):
00824     # load a cfi or cff module
00825     if self.config.fragment:
00826       self.data += 'from %s import *\n' % module
00827     else:
00828       self.data += 'process.load( "%s" )\n' % module
00829 
00830 
00831   def overrideParameters(self, module, parameters):
00832     # override a module's parameter if the module is present in the configuration
00833     self.data += "if '%s' in %%(dict)s:\n" % module
00834     for (parameter, value) in parameters:
00835       self.data += "    %%(process)s%s.%s = %s\n" % (module, parameter, value)
00836     self.data += "\n"
00837 
00838 
00839   def instrumentTiming(self):
00840     if self.config.profiling:
00841       # instrument the menu for profiling: remove the HLTAnalyzerEndpath, add/override the HLTriggerFirstPath, with hltGetRaw and hltGetConditions
00842       text = ''
00843 
00844       if not 'hltGetRaw' in self.data:
00845         # add hltGetRaw
00846         text += """
00847 %(process)shltGetRaw = cms.EDAnalyzer( "HLTGetRaw",
00848     RawDataCollection = cms.InputTag( "rawDataCollector" )
00849 )
00850 """
00851 
00852       if not 'hltGetConditions' in self.data:
00853         # add hltGetConditions
00854         text += """
00855 %(process)shltGetConditions = cms.EDAnalyzer( 'EventSetupRecordDataGetter',
00856     verbose = cms.untracked.bool( False ),
00857     toGet = cms.VPSet( )
00858 )
00859 """
00860 
00861       if not 'hltBoolFalse' in self.data:
00862         # add hltBoolFalse
00863         text += """
00864 %(process)shltBoolFalse = cms.EDFilter( "HLTBool",
00865     result = cms.bool( False )
00866 )
00867 """
00868 
00869       # add the definition of HLTriggerFirstPath
00870       # FIXME in a cff, should also update the HLTSchedule
00871       text += """
00872 %(process)sHLTriggerFirstPath = cms.Path( %(process)shltGetRaw + %(process)shltGetConditions + %(process)shltBoolFalse )
00873 """
00874       self.data = re.sub(r'.*cms\.(End)?Path.*', text + r'\g<0>', self.data, 1)
00875 
00876 
00877     # instrument the menu with the Service, EDProducer and EndPath needed for timing studies
00878     # FIXME in a cff, should also update the HLTSchedule
00879     if self.config.timing:
00880       self.data += """
00881 # instrument the menu with the modules and EndPath needed for timing studies
00882 """
00883 
00884       hasFST = False
00885       if 'FastTimerService' in self.data:
00886         hasFST = True
00887 
00888       self.data += '\n# configure the FastTimerService\n'
00889       if not hasFST:
00890         self.loadCff('HLTrigger.Timer.FastTimerService_cfi')
00891       self.data += """%(process)sFastTimerService.useRealTimeClock          = False
00892 %(process)sFastTimerService.enableTimingPaths         = True
00893 %(process)sFastTimerService.enableTimingModules       = True
00894 %(process)sFastTimerService.enableTimingExclusive     = True
00895 %(process)sFastTimerService.enableTimingSummary       = True
00896 %(process)sFastTimerService.skipFirstPath             = True
00897 %(process)sFastTimerService.enableDQM                 = True
00898 %(process)sFastTimerService.enableDQMbyPathActive     = True
00899 %(process)sFastTimerService.enableDQMbyPathTotal      = True
00900 %(process)sFastTimerService.enableDQMbyPathOverhead   = True
00901 %(process)sFastTimerService.enableDQMbyPathDetails    = True
00902 %(process)sFastTimerService.enableDQMbyPathCounters   = True
00903 %(process)sFastTimerService.enableDQMbyPathExclusive  = True
00904 %(process)sFastTimerService.enableDQMbyModule         = True
00905 %(process)sFastTimerService.enableDQMSummary          = True
00906 %(process)sFastTimerService.enableDQMbyLuminosity     = True
00907 %(process)sFastTimerService.enableDQMbyLumiSection    = True
00908 %(process)sFastTimerService.enableDQMbyProcesses      = False
00909 %(process)sFastTimerService.dqmTimeRange              =  1000. 
00910 %(process)sFastTimerService.dqmTimeResolution         =     5. 
00911 %(process)sFastTimerService.dqmPathTimeRange          =   100. 
00912 %(process)sFastTimerService.dqmPathTimeResolution     =     0.5
00913 %(process)sFastTimerService.dqmModuleTimeRange        =    40. 
00914 %(process)sFastTimerService.dqmModuleTimeResolution   =     0.2
00915 %(process)sFastTimerService.dqmLuminosityRange        = 1e+34
00916 %(process)sFastTimerService.dqmLuminosityResolution   = 1e+31
00917 %(process)sFastTimerService.dqmLumiSectionsRange      =  2500
00918 %(process)sFastTimerService.dqmPath                   = 'HLT/TimerService'
00919 %(process)sFastTimerService.luminosityProduct         = cms.untracked.InputTag( 'hltScalersRawToDigi' )
00920 %(process)sFastTimerService.supportedProcesses        = cms.untracked.vuint32( )
00921 """
00922 
00923       self.data += """
00924 # FastTimerServiceClient
00925 %(process)sfastTimerServiceClient = cms.EDAnalyzer( "FastTimerServiceClient",
00926     dqmPath = cms.untracked.string( "HLT/TimerService" )
00927 )
00928 
00929 # DQM file saver
00930 %(process)sdqmFileSaver = cms.EDAnalyzer( "DQMFileSaver",
00931     convention        = cms.untracked.string( "Offline" ),
00932     workflow          = cms.untracked.string( "/HLT/FastTimerService/All" ),
00933     dirName           = cms.untracked.string( "." ),
00934     saveByRun         = cms.untracked.int32(1),
00935     saveByLumiSection = cms.untracked.int32(-1),
00936     saveByEvent       = cms.untracked.int32(-1),
00937     saveByTime        = cms.untracked.int32(-1),
00938     saveByMinute      = cms.untracked.int32(-1),
00939     saveAtJobEnd      = cms.untracked.bool(False),
00940     forceRunNumber    = cms.untracked.int32(-1),
00941 )
00942 
00943 %(process)sTimingOutput = cms.EndPath( %(process)sfastTimerServiceClient + %(process)sdqmFileSaver )
00944 """
00945 
00946   @staticmethod
00947   def dumppaths(paths):
00948     sys.stderr.write('Path selection:\n')
00949     for path in paths:
00950       sys.stderr.write('\t%s\n' % path)
00951     sys.stderr.write('\n\n')
00952 
00953   def buildPathList(self):
00954     self.all_paths = self.getPathList()
00955 
00956     if self.config.paths:
00957       # no path list was requested, dump the full table, minus unsupported / unwanted paths
00958       paths = self.config.paths.split(',')
00959     else:
00960       # dump only the requested paths, plus the eventual output endpaths
00961       paths = []
00962 
00963     if self.config.fragment or self.config.output in ('none', 'full'):
00964       # 'full' removes all outputs (same as 'none') and then adds a single "keep *" output (see the overrideOutput method)
00965       if self.config.paths:
00966         # paths are removed by default
00967         pass    
00968       else:
00969         # drop all output endpaths
00970         paths.append( "-*Output" )
00971     elif self.config.output == 'minimal':
00972       # drop all output endpaths but HLTDQMResultsOutput
00973       if self.config.paths:
00974         paths.append( "HLTDQMResultsOutput" )
00975       else:
00976         paths.append( "-*Output" )
00977         paths.append( "HLTDQMResultsOutput" )
00978     else:
00979       # keep / add back all output endpaths
00980       if self.config.paths:
00981         paths.append( "*Output" )
00982       else:
00983         pass    # paths are kepy by default
00984 
00985     # drop paths unsupported by fastsim
00986     if self.config.fastsim:
00987       paths.extend( "-%s" % path for path in self.fastsimUnsupportedPaths )
00988 
00989     # drop unwanted paths for profiling (and timing studies)
00990     if self.config.profiling:
00991       paths.append( "-HLTriggerFirstPath" )
00992       paths.append( "-HLTAnalyzerEndpath" )
00993 
00994     # this should never be in any dump (nor online menu)
00995     paths.append( "-OfflineOutput" )
00996 
00997     # expand all wildcards
00998     paths = self.expandWildcards(paths, self.all_paths)
00999 
01000     if self.config.paths:
01001       # do an "additive" consolidation
01002       self.options['paths'] = self.consolidatePositiveList(paths)
01003       if not self.options['paths']:
01004         raise RuntimeError('Error: option "--paths %s" does not select any valid paths' % self.config.paths)
01005     else:
01006       # do a "subtractive" consolidation
01007       self.options['paths'] = self.consolidateNegativeList(paths)
01008 
01009 
01010   def buildOptions(self):
01011     # common configuration for all scenarios
01012     self.options['services'].append( "-FUShmDQMOutputService" )
01013 
01014     if self.config.fragment:
01015       # extract a configuration file fragment
01016       self.options['essources'].append( "-GlobalTag" )
01017       self.options['essources'].append( "-HepPDTESSource" )
01018       self.options['essources'].append( "-XMLIdealGeometryESSource" )
01019       self.options['essources'].append( "-eegeom" )
01020       self.options['essources'].append( "-es_hardcode" )
01021       self.options['essources'].append( "-magfield" )
01022 
01023       self.options['esmodules'].append( "-AutoMagneticFieldESProducer" )
01024       self.options['esmodules'].append( "-SlaveField0" )
01025       self.options['esmodules'].append( "-SlaveField20" )
01026       self.options['esmodules'].append( "-SlaveField30" )
01027       self.options['esmodules'].append( "-SlaveField35" )
01028       self.options['esmodules'].append( "-SlaveField38" )
01029       self.options['esmodules'].append( "-SlaveField40" )
01030       self.options['esmodules'].append( "-VBF0" )
01031       self.options['esmodules'].append( "-VBF20" )
01032       self.options['esmodules'].append( "-VBF30" )
01033       self.options['esmodules'].append( "-VBF35" )
01034       self.options['esmodules'].append( "-VBF38" )
01035       self.options['esmodules'].append( "-VBF40" )
01036       self.options['esmodules'].append( "-CSCGeometryESModule" )
01037       self.options['esmodules'].append( "-CaloGeometryBuilder" )
01038       self.options['esmodules'].append( "-CaloTowerHardcodeGeometryEP" )
01039       self.options['esmodules'].append( "-CastorHardcodeGeometryEP" )
01040       self.options['esmodules'].append( "-DTGeometryESModule" )
01041       self.options['esmodules'].append( "-EcalBarrelGeometryEP" )
01042       self.options['esmodules'].append( "-EcalElectronicsMappingBuilder" )
01043       self.options['esmodules'].append( "-EcalEndcapGeometryEP" )
01044       self.options['esmodules'].append( "-EcalLaserCorrectionService" )
01045       self.options['esmodules'].append( "-EcalPreshowerGeometryEP" )
01046       self.options['esmodules'].append( "-HcalHardcodeGeometryEP" )
01047       self.options['esmodules'].append( "-HcalTopologyIdealEP" )
01048       self.options['esmodules'].append( "-MuonNumberingInitialization" )
01049       self.options['esmodules'].append( "-ParametrizedMagneticFieldProducer" )
01050       self.options['esmodules'].append( "-RPCGeometryESModule" )
01051       self.options['esmodules'].append( "-SiStripGainESProducer" )
01052       self.options['esmodules'].append( "-SiStripRecHitMatcherESProducer" )
01053       self.options['esmodules'].append( "-SiStripQualityESProducer" )
01054       self.options['esmodules'].append( "-StripCPEfromTrackAngleESProducer" )
01055       self.options['esmodules'].append( "-TrackerDigiGeometryESModule" )
01056       self.options['esmodules'].append( "-TrackerGeometricDetESModule" )
01057       self.options['esmodules'].append( "-VolumeBasedMagneticFieldESProducer" )
01058       self.options['esmodules'].append( "-ZdcHardcodeGeometryEP" )
01059       self.options['esmodules'].append( "-hcal_db_producer" )
01060       self.options['esmodules'].append( "-L1GtTriggerMaskAlgoTrigTrivialProducer" )
01061       self.options['esmodules'].append( "-L1GtTriggerMaskTechTrigTrivialProducer" )
01062       self.options['esmodules'].append( "-hltESPEcalTrigTowerConstituentsMapBuilder" )
01063       self.options['esmodules'].append( "-hltESPGlobalTrackingGeometryESProducer" )
01064       self.options['esmodules'].append( "-hltESPMuonDetLayerGeometryESProducer" )
01065       self.options['esmodules'].append( "-hltESPTrackerRecoGeometryESProducer" )
01066       if not self.config.fastsim:
01067         self.options['esmodules'].append( "-CaloTowerGeometryFromDBEP" )
01068         self.options['esmodules'].append( "-CastorGeometryFromDBEP" )
01069         self.options['esmodules'].append( "-EcalBarrelGeometryFromDBEP" )
01070         self.options['esmodules'].append( "-EcalEndcapGeometryFromDBEP" )
01071         self.options['esmodules'].append( "-EcalPreshowerGeometryFromDBEP" )
01072         self.options['esmodules'].append( "-HcalGeometryFromDBEP" )
01073         self.options['esmodules'].append( "-ZdcGeometryFromDBEP" )
01074         self.options['esmodules'].append( "-XMLFromDBSource" )
01075         self.options['esmodules'].append( "-sistripconn" )
01076 
01077       self.options['services'].append( "-PrescaleService" )
01078       self.options['services'].append( "-MessageLogger" )
01079       self.options['services'].append( "-DQM" )
01080       self.options['services'].append( "-DQMStore" )
01081       self.options['services'].append( "-MicroStateService" )
01082       self.options['services'].append( "-ModuleWebRegistry" )
01083       self.options['services'].append( "-TimeProfilerService" )
01084       self.options['services'].append( "-FastTimerService" )
01085 
01086       self.options['psets'].append( "-maxEvents" )
01087       self.options['psets'].append( "-options" )
01088 
01089     if self.config.fastsim:
01090       # remove components not supported or needed by fastsim
01091       self.options['esmodules'].append( "-navigationSchoolESProducer" )
01092       self.options['esmodules'].append( "-TransientTrackBuilderESProducer" )
01093       self.options['esmodules'].append( "-SteppingHelixPropagatorAny" )
01094       self.options['esmodules'].append( "-OppositeMaterialPropagator" )
01095       self.options['esmodules'].append( "-MaterialPropagator" )
01096       self.options['esmodules'].append( "-CaloTowerConstituentsMapBuilder" )
01097       self.options['esmodules'].append( "-CaloTopologyBuilder" )
01098 
01099       self.options['services'].append( "-UpdaterService" )
01100 
01101       self.options['modules'].append( "hltL3MuonIsolations" )
01102       self.options['modules'].append( "hltPixelVertices" )
01103       self.options['modules'].append( "-hltCkfL1SeededTrackCandidates" )
01104       self.options['modules'].append( "-hltCtfL1SeededithMaterialTracks" )
01105       self.options['modules'].append( "-hltCkf3HitL1SeededTrackCandidates" )
01106       self.options['modules'].append( "-hltCtf3HitL1SeededWithMaterialTracks" )
01107       self.options['modules'].append( "-hltCkf3HitActivityTrackCandidates" )
01108       self.options['modules'].append( "-hltCtf3HitActivityWithMaterialTracks" )
01109       self.options['modules'].append( "-hltActivityCkfTrackCandidatesForGSF" )
01110       self.options['modules'].append( "-hltL1SeededCkfTrackCandidatesForGSF" )
01111       self.options['modules'].append( "-hltMuCkfTrackCandidates" )
01112       self.options['modules'].append( "-hltMuCtfTracks" )
01113       self.options['modules'].append( "-hltTau3MuCkfTrackCandidates" )
01114       self.options['modules'].append( "-hltTau3MuCtfWithMaterialTracks" )
01115       self.options['modules'].append( "-hltMuTrackJpsiCkfTrackCandidates" )
01116       self.options['modules'].append( "-hltMuTrackJpsiCtfTracks" )
01117       self.options['modules'].append( "-hltMuTrackJpsiEffCkfTrackCandidates" )
01118       self.options['modules'].append( "-hltMuTrackJpsiEffCtfTracks" )
01119       self.options['modules'].append( "-hltJpsiTkPixelSeedFromL3Candidate" )
01120       self.options['modules'].append( "-hltCkfTrackCandidatesJpsiTk" )
01121       self.options['modules'].append( "-hltCtfWithMaterialTracksJpsiTk" )
01122       self.options['modules'].append( "-hltMuTrackCkfTrackCandidatesOnia" )
01123       self.options['modules'].append( "-hltMuTrackCtfTracksOnia" )
01124       
01125       self.options['modules'].append( "-hltESRegionalEgammaRecHit" )
01126       self.options['modules'].append( "-hltEcalRegionalJetsFEDs" )
01127       self.options['modules'].append( "-hltEcalRegionalMuonsFEDs" )
01128       self.options['modules'].append( "-hltEcalRegionalEgammaFEDs" )
01129       self.options['modules'].append( "-hltFEDSelector" )
01130       self.options['modules'].append( "-hltL3TrajSeedOIHit" )
01131       self.options['modules'].append( "-hltL3TrajSeedIOHit" )
01132       self.options['modules'].append( "-hltL3TrackCandidateFromL2OIState" )
01133       self.options['modules'].append( "-hltL3TrackCandidateFromL2OIHit" )
01134       self.options['modules'].append( "-hltL3TrackCandidateFromL2IOHit" )
01135       self.options['modules'].append( "-hltL3TrackCandidateFromL2NoVtx" )
01136       self.options['modules'].append( "-hltHcalDigis" )
01137       self.options['modules'].append( "-hltHoreco" )
01138       self.options['modules'].append( "-hltHfreco" )
01139       self.options['modules'].append( "-hltHbhereco" )
01140       self.options['modules'].append( "-hltEcalRegionalRestFEDs" )
01141       self.options['modules'].append( "-hltEcalRegionalESRestFEDs" )
01142       self.options['modules'].append( "-hltEcalRawToRecHitFacility" )
01143       self.options['modules'].append( "-hltESRawToRecHitFacility" )
01144       self.options['modules'].append( "-hltEcalRegionalJetsRecHit" )
01145       self.options['modules'].append( "-hltEcalRegionalMuonsRecHit" )
01146       self.options['modules'].append( "-hltEcalRegionalEgammaRecHit" )
01147       self.options['modules'].append( "-hltEcalRecHitAll" )
01148       self.options['modules'].append( "-hltESRecHitAll" )
01149       # === hltPF
01150       self.options['modules'].append( "-hltPFJetCkfTrackCandidates" )
01151       self.options['modules'].append( "-hltPFJetCtfWithMaterialTracks" )
01152       self.options['modules'].append( "-hltPFlowTrackSelectionHighPurity" )
01153       # === hltFastJet
01154       self.options['modules'].append( "-hltDisplacedHT250L1FastJetRegionalPixelSeedGenerator" )
01155       self.options['modules'].append( "-hltDisplacedHT250L1FastJetRegionalCkfTrackCandidates" )
01156       self.options['modules'].append( "-hltDisplacedHT250L1FastJetRegionalCtfWithMaterialTracks" )     
01157       self.options['modules'].append( "-hltDisplacedHT300L1FastJetRegionalPixelSeedGenerator" )
01158       self.options['modules'].append( "-hltDisplacedHT300L1FastJetRegionalCkfTrackCandidates" )
01159       self.options['modules'].append( "-hltDisplacedHT300L1FastJetRegionalCtfWithMaterialTracks" )     
01160       self.options['modules'].append( "-hltBLifetimeRegionalPixelSeedGeneratorbbPhiL1FastJet" )
01161       self.options['modules'].append( "-hltBLifetimeRegionalCkfTrackCandidatesbbPhiL1FastJet" )
01162       self.options['modules'].append( "-hltBLifetimeRegionalCtfWithMaterialTracksbbPhiL1FastJet" )     
01163       self.options['modules'].append( "-hltBLifetimeRegionalPixelSeedGeneratorHbbVBF" )
01164       self.options['modules'].append( "-hltBLifetimeRegionalCkfTrackCandidatesHbbVBF" )
01165       self.options['modules'].append( "-hltBLifetimeRegionalCtfWithMaterialTracksHbbVBF" )
01166       self.options['modules'].append( "-hltBLifetimeBTagIP3D1stTrkRegionalPixelSeedGeneratorJet20HbbL1FastJet" )
01167       self.options['modules'].append( "-hltBLifetimeBTagIP3D1stTrkRegionalCkfTrackCandidatesJet20HbbL1FastJet" )
01168       self.options['modules'].append( "-hltBLifetimeBTagIP3D1stTrkRegionalCtfWithMaterialTracksJet20HbbL1FastJet" )
01169       self.options['modules'].append( "-hltBLifetimeDiBTagIP3D1stTrkRegionalPixelSeedGeneratorJet20HbbL1FastJet" )
01170       self.options['modules'].append( "-hltBLifetimeDiBTagIP3D1stTrkRegionalCkfTrackCandidatesJet20HbbL1FastJet" )
01171       self.options['modules'].append( "-hltBLifetimeDiBTagIP3D1stTrkRegionalCtfWithMaterialTracksJet20HbbL1FastJet" )
01172       # === hltBLifetimeRegional
01173       self.options['modules'].append( "-hltBLifetimeRegionalPixelSeedGeneratorHbb" )
01174       self.options['modules'].append( "-hltBLifetimeRegionalCkfTrackCandidatesHbb" )
01175       self.options['modules'].append( "-hltBLifetimeRegionalCtfWithMaterialTracksHbb" )
01176       self.options['modules'].append( "-hltBLifetimeRegionalPixelSeedGeneratorbbPhi" )
01177       self.options['modules'].append( "-hltBLifetimeRegionalCkfTrackCandidatesbbPhi" )
01178       self.options['modules'].append( "-hltBLifetimeRegionalCtfWithMaterialTracksbbPhi" )
01179       self.options['modules'].append( "-hltBLifetimeBTagIP3D1stTrkRegionalPixelSeedGeneratorJet20Hbb" )
01180       self.options['modules'].append( "-hltBLifetimeBTagIP3D1stTrkRegionalCkfTrackCandidatesJet20Hbb" )
01181       self.options['modules'].append( "-hltBLifetimeBTagIP3D1stTrkRegionalCtfWithMaterialTracksJet20Hbb" )
01182       self.options['modules'].append( "-hltBLifetimeDiBTagIP3D1stTrkRegionalPixelSeedGeneratorJet20Hbb" )
01183       self.options['modules'].append( "-hltBLifetimeDiBTagIP3D1stTrkRegionalCkfTrackCandidatesJet20Hbb" )
01184       self.options['modules'].append( "-hltBLifetimeDiBTagIP3D1stTrkRegionalCtfWithMaterialTracksJet20Hbb" )
01185       self.options['modules'].append( "-hltBLifetimeFastRegionalPixelSeedGeneratorHbbVBF" )
01186       self.options['modules'].append( "-hltBLifetimeFastRegionalCkfTrackCandidatesHbbVBF" )
01187       self.options['modules'].append( "-hltBLifetimeFastRegionalCtfWithMaterialTracksHbbVBF" )
01188       self.options['modules'].append( "-hltBLifetimeRegionalPixelSeedGeneratorbbPhiL1FastJetFastPV" )
01189       self.options['modules'].append( "-hltBLifetimeRegionalCkfTrackCandidatesbbPhiL1FastJetFastPV" )
01190       self.options['modules'].append( "-hltBLifetimeRegionalCtfWithMaterialTracksbbPhiL1FastJetFastPV" )
01191       self.options['modules'].append( "-hltFastPixelBLifetimeRegionalPixelSeedGeneratorHbb" )
01192       self.options['modules'].append( "-hltFastPixelBLifetimeRegionalCkfTrackCandidatesHbb" )
01193       self.options['modules'].append( "-hltFastPixelBLifetimeRegionalCtfWithMaterialTracksHbb" )
01194      
01195       self.options['modules'].append( "-hltPixelTracksForMinBias" )
01196       self.options['modules'].append( "-hltPixelTracksForHighMult" )
01197       self.options['modules'].append( "-hltRegionalPixelTracks" )
01198       self.options['modules'].append( "-hltPixelTracksReg" )
01199       self.options['modules'].append( "-hltIter4Merged" )
01200       self.options['modules'].append( "-hltFastPixelHitsVertex" )
01201       self.options['modules'].append( "-hltFastPixelTracks")
01202       self.options['modules'].append( "-hltFastPixelTracksRecover")
01203       
01204       self.options['modules'].append( "-hltFastPrimaryVertexbbPhi")
01205       self.options['modules'].append( "-hltPixelTracksFastPVbbPhi")
01206       self.options['modules'].append( "-hltPixelTracksRecoverbbPhi" )
01207       self.options['modules'].append( "-hltFastPixelHitsVertexVHbb" )
01208       self.options['modules'].append( "-hltFastPixelTracksVHbb" )
01209       self.options['modules'].append( "-hltFastPixelTracksRecoverVHbb" )
01210 
01211       self.options['modules'].append( "-hltFastPrimaryVertex")
01212       self.options['modules'].append( "-hltFastPVPixelTracks")
01213       self.options['modules'].append( "-hltFastPVPixelTracksRecover" )
01214 
01215       self.options['modules'].append( "-hltIter4Tau3MuMerged" )
01216       self.options['modules'].append( "hltPixelMatchElectronsActivity" )
01217 
01218       self.options['modules'].append( "-hltMuonCSCDigis" )
01219       self.options['modules'].append( "-hltMuonDTDigis" )
01220       self.options['modules'].append( "-hltMuonRPCDigis" )
01221       self.options['modules'].append( "-hltGtDigis" )
01222       self.options['modules'].append( "-hltL1GtTrigReport" )
01223       self.options['modules'].append( "hltCsc2DRecHits" )
01224       self.options['modules'].append( "hltDt1DRecHits" )
01225       self.options['modules'].append( "hltRpcRecHits" )
01226       self.options['modules'].append( "-hltScalersRawToDigi" )
01227 
01228       self.options['sequences'].append( "-HLTL1SeededEgammaRegionalRecoTrackerSequence" )
01229       self.options['sequences'].append( "-HLTEcalActivityEgammaRegionalRecoTrackerSequence" )
01230       self.options['sequences'].append( "-HLTPixelMatchElectronActivityTrackingSequence" )
01231       self.options['sequences'].append( "-HLTDoLocalStripSequence" )
01232       self.options['sequences'].append( "-HLTDoLocalPixelSequence" )
01233       self.options['sequences'].append( "-HLTDoLocalPixelSequenceRegL2Tau" )
01234       self.options['sequences'].append( "-hltSiPixelDigis" )
01235       self.options['sequences'].append( "-hltSiPixelClusters" )
01236       self.options['sequences'].append( "-hltSiPixelRecHits" )
01237       self.options['sequences'].append( "-HLTRecopixelvertexingSequence" )
01238       self.options['sequences'].append( "-HLTEndSequence" )
01239       self.options['sequences'].append( "-HLTBeginSequence" )
01240       self.options['sequences'].append( "-HLTBeginSequenceNZS" )
01241       self.options['sequences'].append( "-HLTBeginSequenceBPTX" )
01242       self.options['sequences'].append( "-HLTBeginSequenceAntiBPTX" )
01243       self.options['sequences'].append( "-HLTHBHENoiseSequence" )
01244       self.options['sequences'].append( "-HLTIterativeTracking" )
01245       self.options['sequences'].append( "-HLTIterativeTrackingTau3Mu" )
01246       self.options['sequences'].append( "-HLTRegionalCKFTracksForL3Isolation" )
01247       self.options['sequences'].append( "-HLTHBHENoiseCleanerSequence" )
01248 
01249       # remove HLTAnalyzerEndpath from fastsim cff's
01250       if self.config.fragment:
01251         self.options['paths'].append( "-HLTAnalyzerEndpath" )
01252 
01253 
01254   def build_source(self):
01255     if self.config.input:
01256       # if a dataset or a list of input files was given, use it
01257       if self.config.input[0:8] == 'dataset:':
01258         from dbsFileQuery import dbsFileQuery
01259         # extract the dataset name, and use DBS to fine the list of LFNs
01260         dataset = self.config.input[8:]
01261         query   = 'find file where dataset=' + dataset
01262         files   = dbsFileQuery(query)
01263         self.source = files
01264       else:
01265         # assume a list of input files
01266         self.source = self.config.input.split(',')
01267     elif self.config.online:
01268       # online we always run on data
01269       self.source = [ "file:/tmp/InputCollection.root" ]
01270     elif self.config.data:
01271       # offline we can run on data...
01272       self.source = [ "file:RelVal_Raw_%s_DATA.root" % self.config.type ]
01273     else:
01274       # ...or on mc
01275       self.source = [ "file:RelVal_Raw_%s_STARTUP.root" % self.config.type ]
01276 
01277     self.data += """
01278 %(process)ssource = cms.Source( "PoolSource",
01279     fileNames = cms.untracked.vstring(
01280 """
01281     if self.source: 
01282       for line in self.source:
01283         self.data += "        '%s',\n" % line
01284     self.data += """    ),
01285     secondaryFileNames = cms.untracked.vstring(
01286 """
01287     if self.parent: 
01288       for line in self.parent:
01289         self.data += "        '%s',\n" % line
01290     self.data += """    ),
01291     inputCommands = cms.untracked.vstring(
01292         'keep *'
01293     )
01294 )
01295 """