CMS 3D CMS Logo

Classes | Functions
helpers Namespace Reference

Classes

class  CloneSequenceVisitor
 
struct  CompositeCandidateMaker
 
struct  CompositePtrCandidateMaker
 
class  GatherAllModulesVisitor
 
struct  MCTruthPairSelector
 
struct  NamedCompositeCandidateMaker
 
class  TestModuleCommand
 

Functions

def __labelsInSequence (process, sequenceLabel, postfix="", keepPostFix=False)
 
def addESProducers (process, config)
 
def addKeepStatement (process, oldKeep, newKeeps, verbose=False)
 
def addToProcessAndTask (label, module, process, task)
 
def addToTask (loadedProducersAndFilters, module)
 
def applyPostfix (process, label, postfix)
 
def associatePatAlgosToolsTask (process)
 
def cloneProcessingSnippet (process, sequence, postfix, removePostfix="", noClones=[], addToTask=False)
 
def contains (sequence, moduleName)
 
def extendWithPrePostfix (process, other, prefix, postfix, loadedProducersAndFilters=None)
 
def get_path (file_in_path)
 
def get_vars (xml_path, useFileInPath=True)
 
def getPatAlgosToolsTask (process)
 
def jetCollectionString (prefix='', algo='', type='')
 
def listDependencyChain (process, module, sources, verbose=False)
 
def listModules (sequence)
 
def listSequences (sequence)
 
def loadWithPostfix (process, moduleName, postfix='', loadedProducersAndFilters=None)
 
def loadWithPrefix (process, moduleName, prefix='', loadedProducersAndFilters=None)
 
def loadWithPrePostfix (process, moduleName, prefix='', postfix='', loadedProducersAndFilters=None)
 
def removeIfInSequence (process, target, sequenceLabel, postfix="")
 
def testContains (self)
 
def testJetCollectionString (self)
 
def testListModules (self)
 

Function Documentation

def helpers.__labelsInSequence (   process,
  sequenceLabel,
  postfix = "",
  keepPostFix = False 
)
private

Definition at line 130 of file helpers.py.

References listModules(), and listSequences().

Referenced by removeIfInSequence().

130 def __labelsInSequence(process, sequenceLabel, postfix="", keepPostFix=False):
131  position = -len(postfix)
132  if keepPostFix:
133  position = None
134 
135  result = [ m.label()[:position] for m in listModules( getattr(process,sequenceLabel+postfix))]
136  result.extend([ m.label()[:position] for m in listSequences( getattr(process,sequenceLabel+postfix))] )
137  if postfix == "":
138  result = [ m.label() for m in listModules( getattr(process,sequenceLabel+postfix))]
139  result.extend([ m.label() for m in listSequences( getattr(process,sequenceLabel+postfix))] )
140  return result
141 
142 #FIXME name is not generic enough now
def listModules(sequence)
Definition: helpers.py:207
def listSequences(sequence)
Definition: helpers.py:212
def __labelsInSequence(process, sequenceLabel, postfix="", keepPostFix=False)
Definition: helpers.py:130
def helpers.addESProducers (   process,
  config 
)

Definition at line 33 of file helpers.py.

References dir.

33 def addESProducers(process,config):
34  config = config.replace("/",".")
35  #import RecoBTag.Configuration.RecoBTag_cff as btag
36  #print btag
37  module = __import__(config)
38  for name in dir(sys.modules[config]):
39  item = getattr(sys.modules[config],name)
40  if isinstance(item,cms._Labelable) and not isinstance(item,cms._ModuleSequenceType) and not name.startswith('_') and not (name == "source" or name == "looper" or name == "subProcess") and not isinstance(item, cms.PSet):
41  if 'ESProducer' in item.type_():
42  setattr(process,name,item)
43 
def addESProducers(process, config)
Definition: helpers.py:33
dbl *** dir
Definition: mlp_gen.cc:35
def helpers.addKeepStatement (   process,
  oldKeep,
  newKeeps,
  verbose = False 
)
Add new keep statements to any PoolOutputModule of the process that has the old keep statements

Definition at line 354 of file helpers.py.

References edm.print().

Referenced by customizeMiniAOD_MuEGFixMoriond2017.addDiscardedPFCandidates(), customizeMiniAOD_HcalFixLegacy2016.addDiscardedPFCandidates(), extraSlimmedMETs_MuEGFixMoriond2017.addExtraMETCollections(), extraSlimmedMETs_MuEGFixMoriond2017.addExtraPuppiMETCorrections(), extraJets_MuEGFixMoriond2017.backupJetsSecondStep(), and customizeMiniAOD_MuEGFixMoriond2017.customizeAll().

354 def addKeepStatement(process, oldKeep, newKeeps, verbose=False):
355  """Add new keep statements to any PoolOutputModule of the process that has the old keep statements"""
356  for name,out in six.iteritems(process.outputModules):
357  if out.type_() == 'PoolOutputModule' and hasattr(out, "outputCommands"):
358  if oldKeep in out.outputCommands:
359  out.outputCommands += newKeeps
360  if verbose:
361  print("Adding the following keep statements to output module %s: " % name)
362  for k in newKeeps: print("\t'%s'," % k)
363 
364 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def addKeepStatement(process, oldKeep, newKeeps, verbose=False)
Definition: helpers.py:354
def helpers.addToProcessAndTask (   label,
  module,
  process,
  task 
)

Definition at line 29 of file helpers.py.

Referenced by pfTools.addPFCandidates(), jetCollectionTools.GenJetAdder.addProcessAndTask(), jetCollectionTools.RecoJetAdder.addProcessAndTask(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.ak4JetReclustering(), applyDeepBtagging_cff.applyDeepBtagging(), applySubstructure_cff.applySubstructure(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.createShiftedModules(), eGammaCorrection.eGammaCorrection(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.extractMET(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.getCorrectedMET(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.getJetCollectionForCorsAndUncs(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.getMETUncertainties(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.jetCleaning(), egmIsolationsPUPPI_cfi.makeInputForPUPPIIsolationEgm(), muonIsolationsPUPPI_cfi.makeInputForPUPPIIsolationMuon(), puppiForMET_cff.makePuppies(), puppiForMET_cff.makePuppiesFromMiniAOD(), extraJets_MuEGFixMoriond2017.makeRecoJetCollection(), miniAOD_tools.miniAOD_customizeCommon(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.miniAODConfiguration(), muonRecoMitigation.muonRecoMitigation(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.produceMET(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.recomputeRawMetFromPfcs(), pfTools.reconfigurePF2PATTaus(), extraJets_MuEGFixMoriond2017.reduceFinalJetCollection(), extraJets_MuEGFixMoriond2017.reduceInputJetCollection(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.runFixEE2017(), jetTools.setupBTagging(), jetTools.setupJetCorrections(), pfTools.switchToPFJets(), trackTools.MakeAODTrackCandidates.toolCode(), metTools.AddMETCollection.toolCode(), trigTools.SwitchOnTrigger.toolCode(), trackTools.MakePATTrackCandidates.toolCode(), trigTools.SwitchOnTriggerStandAlone.toolCode(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.toolCode(), trigTools.SwitchOnTriggerMatchEmbedding.toolCode(), jetTools.AddJetCollection.toolCode(), jetTools.UpdateJetCollection.toolCode(), jetTools.AddJetID.toolCode(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.updateJECs(), and customizePuppiTune_cff.UpdatePuppiTuneV15().

29 def addToProcessAndTask(label, module, process, task):
30  setattr(process, label, module)
31  task.add(getattr(process, label))
32 
def addToProcessAndTask(label, module, process, task)
Definition: helpers.py:29
def helpers.addToTask (   loadedProducersAndFilters,
  module 
)

Definition at line 56 of file helpers.py.

Referenced by extendWithPrePostfix().

56 def addToTask(loadedProducersAndFilters, module):
57  if loadedProducersAndFilters:
58  if isinstance(module, cms.EDProducer) or isinstance(module, cms.EDFilter):
59  loadedProducersAndFilters.add(module)
60 
def addToTask(loadedProducersAndFilters, module)
Definition: helpers.py:56
def helpers.applyPostfix (   process,
  label,
  postfix 
)

Definition at line 115 of file helpers.py.

Referenced by pfTools.adaptPFMuons(), pfTools.addPFCandidates(), pfTools.reconfigurePF2PATTaus(), pfTools.switchToPFJets(), pfTools.switchToPFMET(), pfTools.tauTypeInPF2PAT(), HiCoreTools.RemoveMCMatching.toolCode(), HiCoreTools.RemoveSpecificPATObjects.toolCode(), HiCoreTools.RemoveCleaning.toolCode(), and pfTools.usePF2PAT().

115 def applyPostfix(process, label, postfix):
116  result = None
117  if hasattr(process, label+postfix):
118  result = getattr(process, label + postfix)
119  else:
120  raise ValueError("Error in <applyPostfix>: No module of name = %s attached to process !!" % (label + postfix))
121  return result
122 
def applyPostfix(process, label, postfix)
Definition: helpers.py:115
def helpers.associatePatAlgosToolsTask (   process)

Definition at line 25 of file helpers.py.

References getPatAlgosToolsTask().

Referenced by ConfigBuilder.ConfigBuilder.prepare().

26  task = getPatAlgosToolsTask(process)
27  process.schedule.associate(task)
28 
def associatePatAlgosToolsTask(process)
Definition: helpers.py:25
def getPatAlgosToolsTask(process)
Definition: helpers.py:14
def helpers.cloneProcessingSnippet (   process,
  sequence,
  postfix,
  removePostfix = "",
  noClones = [],
  addToTask = False 
)
------------------------------------------------------------------
copy a sequence plus the modules and sequences therein
both are renamed by getting a postfix
input tags are automatically adjusted
------------------------------------------------------------------

Definition at line 257 of file helpers.py.

Referenced by boostedHPSPFTaus_cfi.addBoostedTaus(), extraSlimmedMETs_MuEGFixMoriond2017.addExtraMETCollections(), extraJets_MuEGFixMoriond2017.backupJetsFirstStep(), extraJets_MuEGFixMoriond2017.makeRecoJetCollection(), pfIsolation.setupPFIso(), and pfIsolation.setupPFIsoPhoton().

257 def cloneProcessingSnippet(process, sequence, postfix, removePostfix="", noClones = [], addToTask = False):
258  """
259  ------------------------------------------------------------------
260  copy a sequence plus the modules and sequences therein
261  both are renamed by getting a postfix
262  input tags are automatically adjusted
263  ------------------------------------------------------------------
264  """
265  result = sequence
266  if not postfix == "":
267  visitor = CloneSequenceVisitor(process, sequence.label(), postfix, removePostfix, noClones, addToTask)
268  sequence.visit(visitor)
269  result = visitor.clonedSequence()
270  return result
271 
def cloneProcessingSnippet(process, sequence, postfix, removePostfix="", noClones=[], addToTask=False)
Definition: helpers.py:257
def helpers.contains (   sequence,
  moduleName 
)
------------------------------------------------------------------
return True if a module with name 'module' is contained in the
sequence with name 'sequence' and False otherwise. This version
is not so nice as it also returns True for any substr of the name
of a contained module.

sequence : sequence [e.g. process.patDefaultSequence]
module   : module name as a string
------------------------------------------------------------------

Definition at line 241 of file helpers.py.

References spr.find().

Referenced by testContains().

241 def contains(sequence, moduleName):
242  """
243  ------------------------------------------------------------------
244  return True if a module with name 'module' is contained in the
245  sequence with name 'sequence' and False otherwise. This version
246  is not so nice as it also returns True for any substr of the name
247  of a contained module.
248 
249  sequence : sequence [e.g. process.patDefaultSequence]
250  module : module name as a string
251  ------------------------------------------------------------------
252  """
253  return not sequence.__str__().find(moduleName)==-1
254 
255 
256 
def contains(sequence, moduleName)
Definition: helpers.py:241
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:20
def helpers.extendWithPrePostfix (   process,
  other,
  prefix,
  postfix,
  loadedProducersAndFilters = None 
)
Look in other and find types which we can use

Definition at line 61 of file helpers.py.

References addToTask(), dir, and MassReplace.massSearchReplaceAnyInputTag().

Referenced by loadWithPrePostfix().

61 def extendWithPrePostfix(process,other,prefix,postfix,loadedProducersAndFilters=None):
62  """Look in other and find types which we can use"""
63  # enable explicit check to avoid overwriting of existing objects
64  #__dict__['_Process__InExtendCall'] = True
65 
66  if loadedProducersAndFilters:
67  task = getattr(process, loadedProducersAndFilters)
68  if not isinstance(task, cms.Task):
69  raise Exception("extendWithPrePostfix argument must be name of Task type object attached to the process or None")
70  else:
71  task = None
72 
73  sequence = cms.Sequence()
74  sequence._moduleLabels = []
75  for name in dir(other):
76  #'from XX import *' ignores these, and so should we.
77  if name.startswith('_'):
78  continue
79  item = getattr(other,name)
80  if name == "source" or name == "looper" or name == "subProcess":
81  continue
82  elif isinstance(item,cms._ModuleSequenceType):
83  continue
84  elif isinstance(item,cms.Task):
85  continue
86  elif isinstance(item,cms.Schedule):
87  continue
88  elif isinstance(item,cms.VPSet) or isinstance(item,cms.PSet):
89  continue
90  elif isinstance(item,cms._Labelable):
91  if not item.hasLabel_():
92  item.setLabel(name)
93  if prefix != '' or postfix != '':
94  newModule = item.clone()
95  if isinstance(item,cms.ESProducer):
96  newName =name
97  else:
98  if 'TauDiscrimination' in name:
99  process.__setattr__(name,item)
100  addToTask(task, item)
101  newName = prefix+name+postfix
102  process.__setattr__(newName,newModule)
103  addToTask(task, newModule)
104  if isinstance(newModule, cms._Sequenceable) and not newName == name:
105  sequence +=getattr(process,newName)
106  sequence._moduleLabels.append(item.label())
107  else:
108  process.__setattr__(name,item)
109  addToTask(task, item)
110 
111  if prefix != '' or postfix != '':
112  for label in sequence._moduleLabels:
113  massSearchReplaceAnyInputTag(sequence, label, prefix+label+postfix,verbose=False,moduleLabelOnly=True)
114 
def extendWithPrePostfix(process, other, prefix, postfix, loadedProducersAndFilters=None)
Definition: helpers.py:61
def massSearchReplaceAnyInputTag(sequence, oldInputTag, newInputTag, verbose=False, moduleLabelOnly=False, skipLabelTest=False)
Definition: MassReplace.py:73
def addToTask(loadedProducersAndFilters, module)
Definition: helpers.py:56
dbl *** dir
Definition: mlp_gen.cc:35
def helpers.get_path (   file_in_path)

Definition at line 6 of file helpers.py.

Referenced by get_vars().

6 def get_path(file_in_path):
7  'mimics edm.FileInPath behavior'
8  search_env = os.environ.get('CMSSW_SEARCH_PATH', '')
9  if not search_env:
10  raise RuntimeError('The environmental variable CMSSW_SEARCH_PATH must be set')
11  search_paths = search_env.split(':')
12  for spath in search_paths:
13  full_path = os.path.join(spath, file_in_path)
14  if os.path.isfile(full_path):
15  return full_path
16  raise RuntimeError('No suitable path found for %s' % file_in_path)
17 
def get_path(file_in_path)
Definition: helpers.py:6
def helpers.get_vars (   xml_path,
  useFileInPath = True 
)

Definition at line 18 of file helpers.py.

References get_path(), and trainingvars.get_var_pset().

18 def get_vars(xml_path, useFileInPath=True):
19  full_path = get_path(xml_path) if useFileInPath else xml_path
20  xml_tree = ET.parse(full_path)
21  root = xml_tree.getroot()
22  variables = None
23  for i in root:
24  if i.tag == 'Variables':
25  variables = i
26 
27  if i is None:
28  raise RuntimeError('Could not find Variables inside the xml weights')
29 
30  var_names = [i.attrib['Title'] for i in variables]
31  return [get_var_pset(i) for i in var_names]
32 
33 
def get_path(file_in_path)
Definition: helpers.py:6
def get_var_pset(mvaname)
def get_vars(xml_path, useFileInPath=True)
Definition: helpers.py:18
def helpers.getPatAlgosToolsTask (   process)

Definition at line 14 of file helpers.py.

Referenced by customizeMiniAOD_MuEGFixMoriond2017.addBadMuonFilters(), customizeMiniAOD_MuEGFixMoriond2017.addDiscardedPFCandidates(), customizeMiniAOD_HcalFixLegacy2016.addDiscardedPFCandidates(), extraSlimmedMETs_MuEGFixMoriond2017.addExtraMETCollections(), extraSlimmedMETs_MuEGFixMoriond2017.addExtraPuppiMETCorrections(), pfTools.addPFCandidates(), jetCollectionTools.GenJetAdder.addProcessAndTask(), jetCollectionTools.RecoJetAdder.addProcessAndTask(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.ak4JetReclustering(), applyDeepBtagging_cff.applyDeepBtagging(), applySubstructure_cff.applySubstructure(), associatePatAlgosToolsTask(), extraJets_MuEGFixMoriond2017.backupJetsFirstStep(), extraJets_MuEGFixMoriond2017.backupJetsSecondStep(), customizeMiniAOD_MuEGFixMoriond2017.cleanPFCandidates(), customizeMiniAOD_HcalFixLegacy2016.cleanPfCandidates(), CompactSkim_cff.CompactSkim(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.createMVAMETModule(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.createShiftedModules(), eGammaCorrection.eGammaCorrection(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.extractMET(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.getCorrectedMET(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.getJetCollectionForCorsAndUncs(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.getMETUncertainties(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.jetCleaning(), customizeMiniAOD_HcalFixLegacy2016.loadJetMETBTag(), customizeMiniAOD_MuEGFixMoriond2017.loadJetMETBTag(), egmIsolationsPUPPI_cfi.makeInputForPUPPIIsolationEgm(), muonIsolationsPUPPI_cfi.makeInputForPUPPIIsolationMuon(), puppiForMET_cff.makePuppies(), puppiForMET_cff.makePuppiesFromMiniAOD(), extraJets_MuEGFixMoriond2017.makeRecoJetCollection(), miniAOD_tools.miniAOD_customizeCommon(), miniAOD_tools.miniAOD_customizeData(), miniAOD_tools.miniAOD_customizeMC(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.miniAODConfiguration(), muonRecoMitigation.muonRecoMitigation(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.produceMET(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.recomputeRawMetFromPfcs(), pfTools.reconfigurePF2PATTaus(), extraJets_MuEGFixMoriond2017.reduceFinalJetCollection(), extraJets_MuEGFixMoriond2017.reduceInputJetCollection(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.runFixEE2017(), jetTools.setupBTagging(), jetTools.setupJetCorrections(), pfTools.switchToPFJets(), trackTools.MakeAODTrackCandidates.toolCode(), metTools.AddMETCollection.toolCode(), trigTools.SwitchOnTrigger.toolCode(), trackTools.MakePATTrackCandidates.toolCode(), trigTools.SwitchOnTriggerStandAlone.toolCode(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.toolCode(), trigTools.SwitchOnTriggerMatching.toolCode(), trigTools.SwitchOnTriggerMatchingStandAlone.toolCode(), trigTools.SwitchOnTriggerMatchEmbedding.toolCode(), jetTools.AddJetCollection.toolCode(), jetTools.UpdateJetCollection.toolCode(), jetTools.AddJetID.toolCode(), runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.updateJECs(), customizePuppiTune_cff.UpdatePuppiTuneV15(), and pfTools.usePF2PAT().

14 def getPatAlgosToolsTask(process):
15  taskName = "patAlgosToolsTask"
16  if hasattr(process, taskName):
17  task = getattr(process, taskName)
18  if not isinstance(task, cms.Task):
19  raise Exception("patAlgosToolsTask does not have type Task")
20  else:
21  setattr(process, taskName, cms.Task())
22  task = getattr(process, taskName)
23  return task
24 
def getPatAlgosToolsTask(process)
Definition: helpers.py:14
def helpers.jetCollectionString (   prefix = '',
  algo = '',
  type = '' 
)
------------------------------------------------------------------
return the string of the jet collection module depending on the
input vaules. The default return value will be 'patAK5CaloJets'.

algo   : indicating the algorithm type of the jet [expected are
         'AK5', 'IC5', 'SC7', ...]
type   : indicating the type of constituents of the jet [expec-
         ted are 'Calo', 'PFlow', 'JPT', ...]
prefix : prefix indicating the type of pat collection module (ex-
         pected are '', 'selected', 'clean').
------------------------------------------------------------------

Definition at line 217 of file helpers.py.

Referenced by testJetCollectionString(), heavyIonTools.ProductionDefaults.toolCode(), HiCoreTools.RemoveMCMatching.toolCode(), coreTools.RemoveMCMatching.toolCode(), heavyIonTools.SelectionDefaults.toolCode(), and HiCoreTools.RemoveSpecificPATObjects.toolCode().

217 def jetCollectionString(prefix='', algo='', type=''):
218  """
219  ------------------------------------------------------------------
220  return the string of the jet collection module depending on the
221  input vaules. The default return value will be 'patAK5CaloJets'.
222 
223  algo : indicating the algorithm type of the jet [expected are
224  'AK5', 'IC5', 'SC7', ...]
225  type : indicating the type of constituents of the jet [expec-
226  ted are 'Calo', 'PFlow', 'JPT', ...]
227  prefix : prefix indicating the type of pat collection module (ex-
228  pected are '', 'selected', 'clean').
229  ------------------------------------------------------------------
230  """
231  if(prefix==''):
232  jetCollectionString ='pat'
233  else:
234  jetCollectionString =prefix
235  jetCollectionString+='Pat'
236  jetCollectionString+='Jets'
237  jetCollectionString+=algo
238  jetCollectionString+=type
239  return jetCollectionString
240 
def jetCollectionString(prefix='', algo='', type='')
Definition: helpers.py:217
def helpers.listDependencyChain (   process,
  module,
  sources,
  verbose = False 
)
Walk up the dependencies of a module to find any that depend on any of the listed sources

Definition at line 272 of file helpers.py.

References mps_setup.append, and edm.print().

Referenced by extraJets_MuEGFixMoriond2017.backupJetsFirstStep().

272 def listDependencyChain(process, module, sources, verbose=False):
273  """
274  Walk up the dependencies of a module to find any that depend on any of the listed sources
275  """
276  def allDirectInputModules(moduleOrPSet,moduleName,attrName):
277  ret = set()
278  for name,value in six.iteritems(moduleOrPSet.parameters_()):
279  type = value.pythonTypeName()
280  if type == 'cms.PSet':
281  ret.update(allDirectInputModules(value,moduleName,moduleName+"."+name))
282  elif type == 'cms.VPSet':
283  for (i,ps) in enumerate(value):
284  ret.update(allDirectInputModules(ps,moduleName,"%s.%s[%d]"%(moduleName,name,i)))
285  elif type == 'cms.VInputTag':
286  inputs = [ MassSearchReplaceAnyInputTagVisitor.standardizeInputTagFmt(it) for it in value ]
287  inputLabels = [ tag.moduleLabel for tag in inputs if tag.processName == '' or tag.processName == process.name_() ]
288  ret.update(inputLabels)
289  if verbose and inputLabels: print("%s depends on %s via %s" % (moduleName, inputLabels, attrName+"."+name))
290  elif type.endswith('.InputTag'):
291  if value.processName == '' or value.processName == process.name_():
292  ret.add(value.moduleLabel)
293  if verbose: print("%s depends on %s via %s" % (moduleName, value.moduleLabel, attrName+"."+name))
294  ret.discard("")
295  return ret
296  def fillDirectDepGraphs(root,fwdepgraph,revdepgraph):
297  if root.label_() in fwdepgraph: return
298  deps = allDirectInputModules(root,root.label_(),root.label_())
299  fwdepgraph[root.label_()] = []
300  for d in deps:
301  fwdepgraph[root.label_()].append(d)
302  if d not in revdepgraph: revdepgraph[d] = []
303  revdepgraph[d].append(root.label_())
304  depmodule = getattr(process,d,None)
305  if depmodule:
306  fillDirectDepGraphs(depmodule,fwdepgraph,revdepgraph)
307  return (fwdepgraph,revdepgraph)
308  fwdepgraph, revdepgraph = fillDirectDepGraphs(module, {}, {})
309  def flattenRevDeps(flatgraph, revdepgraph, tip):
310  """Make a graph that for each module lists all the ones that depend on it, directly or indirectly"""
311  # don't do it multiple times for the same module
312  if tip in flatgraph: return
313  # if nobody depends on this module, there's nothing to do
314  if tip not in revdepgraph: return
315  # assemble my dependencies, in a depth-first approach
316  mydeps = set()
317  # start taking the direct dependencies of this module
318  for d in revdepgraph[tip]:
319  # process them
320  flattenRevDeps(flatgraph, revdepgraph, d)
321  # then add them and their processed dependencies to our deps
322  mydeps.add(d)
323  if d in flatgraph:
324  mydeps.update(flatgraph[d])
325  flatgraph[tip] = mydeps
326  flatdeps = {}
327  allmodules = set()
328  for s in sources:
329  flattenRevDeps(flatdeps, revdepgraph, s)
330  if s in flatdeps: allmodules.update(f for f in flatdeps[s])
331  livemodules = [ a for a in allmodules if hasattr(process,a) ]
332  if not livemodules: return None
333  modulelist = [livemodules.pop()]
334  for module in livemodules:
335  for i,m in enumerate(modulelist):
336  if module in flatdeps and m in flatdeps[module]:
337  modulelist.insert(i, module)
338  break
339  if module not in modulelist:
340  modulelist.append(module)
341  # Validate
342  for i,m1 in enumerate(modulelist):
343  for j,m2 in enumerate(modulelist):
344  if j <= i: continue
345  if m2 in flatdeps and m1 in flatdeps[m2]:
346  raise RuntimeError("BAD ORDER %s BEFORE %s" % (m1,m2))
347  modules = [ getattr(process,p) for p in modulelist ]
348  #return cms.Sequence(sum(modules[1:],modules[0]))
349  task = cms.Task()
350  for mod in modules:
351  task.add(mod)
352  return task,cms.Sequence(task)
353 
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def listDependencyChain(process, module, sources, verbose=False)
Definition: helpers.py:272
def helpers.listModules (   sequence)
def helpers.listSequences (   sequence)

Definition at line 212 of file helpers.py.

Referenced by __labelsInSequence(), and runMETCorrectionsAndUncertainties.RunMETCorrectionsAndUncertainties.labelsInSequence().

212 def listSequences(sequence):
213  visitor = GatherAllModulesVisitor(gatheredInstance=cms.Sequence)
214  sequence.visit(visitor)
215  return visitor.modules()
216 
def listSequences(sequence)
Definition: helpers.py:212
def helpers.loadWithPostfix (   process,
  moduleName,
  postfix = '',
  loadedProducersAndFilters = None 
)

Definition at line 47 of file helpers.py.

References loadWithPrePostfix().

Referenced by pfTools.usePF2PAT().

47 def loadWithPostfix(process,moduleName,postfix='',loadedProducersAndFilters=None):
48  loadWithPrePostfix(process,moduleName,'',postfix,loadedProducersAndFilters)
49 
def loadWithPrePostfix(process, moduleName, prefix='', postfix='', loadedProducersAndFilters=None)
Definition: helpers.py:50
def loadWithPostfix(process, moduleName, postfix='', loadedProducersAndFilters=None)
Definition: helpers.py:47
def helpers.loadWithPrefix (   process,
  moduleName,
  prefix = '',
  loadedProducersAndFilters = None 
)

Definition at line 44 of file helpers.py.

References loadWithPrePostfix().

Referenced by jetTools.setupBTagging().

44 def loadWithPrefix(process,moduleName,prefix='',loadedProducersAndFilters=None):
45  loadWithPrePostfix(process,moduleName,prefix,'',loadedProducersAndFilters)
46 
def loadWithPrePostfix(process, moduleName, prefix='', postfix='', loadedProducersAndFilters=None)
Definition: helpers.py:50
def loadWithPrefix(process, moduleName, prefix='', loadedProducersAndFilters=None)
Definition: helpers.py:44
def helpers.loadWithPrePostfix (   process,
  moduleName,
  prefix = '',
  postfix = '',
  loadedProducersAndFilters = None 
)

Definition at line 50 of file helpers.py.

References extendWithPrePostfix().

Referenced by loadWithPostfix(), and loadWithPrefix().

50 def loadWithPrePostfix(process,moduleName,prefix='',postfix='',loadedProducersAndFilters=None):
51  moduleName = moduleName.replace("/",".")
52  module = __import__(moduleName)
53  #print module.PatAlgos.patSequences_cff.patDefaultSequence
54  extendWithPrePostfix(process,sys.modules[moduleName],prefix,postfix,loadedProducersAndFilters)
55 
def extendWithPrePostfix(process, other, prefix, postfix, loadedProducersAndFilters=None)
Definition: helpers.py:61
def loadWithPrePostfix(process, moduleName, prefix='', postfix='', loadedProducersAndFilters=None)
Definition: helpers.py:50
def helpers.removeIfInSequence (   process,
  target,
  sequenceLabel,
  postfix = "" 
)

Definition at line 123 of file helpers.py.

References __labelsInSequence(), and MatrixUtil.remove().

Referenced by HiCoreTools.RemoveSpecificPATObjects.toolCode().

123 def removeIfInSequence(process, target, sequenceLabel, postfix=""):
124  labels = __labelsInSequence(process, sequenceLabel, postfix, True)
125  if target+postfix in labels:
126  getattr(process, sequenceLabel+postfix).remove(
127  getattr(process, target+postfix)
128  )
129 
def removeIfInSequence(process, target, sequenceLabel, postfix="")
Definition: helpers.py:123
def __labelsInSequence(process, sequenceLabel, postfix="", keepPostFix=False)
Definition: helpers.py:130
def remove(d, key, TELL=False)
Definition: MatrixUtil.py:212
def helpers.testContains (   self)

Definition at line 423 of file helpers.py.

References contains().

423  def testContains(self):
424  p = cms.Process("test")
425  p.a = cms.EDProducer("a", src=cms.InputTag("gen"))
426  p.b = cms.EDProducer("ab", src=cms.InputTag("a"))
427  p.c = cms.EDProducer("ac", src=cms.InputTag("b"))
428  p.s1 = cms.Sequence(p.a*p.b*p.c)
429  p.s2 = cms.Sequence(p.b*p.c)
430  self.assert_( contains(p.s1, "a") )
431  self.assert_( not contains(p.s2, "a") )
def contains(sequence, moduleName)
Definition: helpers.py:241
def testContains(self)
Definition: helpers.py:423
def helpers.testJetCollectionString (   self)

Definition at line 432 of file helpers.py.

References jetCollectionString().

433  self.assertEqual(jetCollectionString(algo = 'Foo', type = 'Bar'), 'patJetsFooBar')
434  self.assertEqual(jetCollectionString(prefix = 'prefix', algo = 'Foo', type = 'Bar'), 'prefixPatJetsFooBar')
def testJetCollectionString(self)
Definition: helpers.py:432
def jetCollectionString(prefix='', algo='', type='')
Definition: helpers.py:217
def helpers.testListModules (   self)

Definition at line 435 of file helpers.py.

References listModules().

435  def testListModules(self):
436  p = cms.Process("test")
437  p.a = cms.EDProducer("a", src=cms.InputTag("gen"))
438  p.b = cms.EDProducer("ab", src=cms.InputTag("a"))
439  p.c = cms.EDProducer("ac", src=cms.InputTag("b"))
440  p.s = cms.Sequence(p.a*p.b*p.c)
441  self.assertEqual([p.a,p.b,p.c], listModules(p.s))
442 
def testListModules(self)
Definition: helpers.py:435
def listModules(sequence)
Definition: helpers.py:207