CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_0/src/PhysicsTools/PatAlgos/python/tools/cmsswVersionTools.py

Go to the documentation of this file.
00001 import FWCore.ParameterSet.Config as cms
00002 
00003 from FWCore.GuiBrowsers.ConfigToolBase import *
00004 from PhysicsTools.PatAlgos.tools.helpers import *
00005 from PhysicsTools.PatAlgos.tools.jetTools import *
00006 from Configuration.AlCa.autoCond import autoCond
00007 
00008 import os
00009 import socket
00010 from subprocess import *
00011 import json
00012 import das_client
00013 
00014 
00015 ## ------------------------------------------------------
00016 ## Deal with backweard incompatibilities of conditions
00017 ## ------------------------------------------------------
00018 
00019 def run42xOn3yzMcInput( process
00020                       , l1MenuTag    = 'L1GtTriggerMenu_L1Menu_Commissioning2010_v4_mc' # L1 menu for Fall10 REDIGI (CMSSW_3_8_7)
00021                       ):
00022   """
00023   """
00024   # Use correct L1 trigger menu
00025   import CondCore.DBCommon.CondDBCommon_cfi
00026   process.l1GtTriggerMenu = cms.ESSource( "PoolDBESSource"
00027   , CondCore.DBCommon.CondDBCommon_cfi.CondDBCommon
00028   , toGet   = cms.VPSet(
00029       cms.PSet(
00030         connect = cms.untracked.string( 'frontier://FrontierProd/CMS_COND_31X_L1T' )
00031       , record  = cms.string( 'L1GtTriggerMenuRcd' )
00032       , tag     = cms.string( l1MenuTag )
00033       )
00034     )
00035   )
00036   process.preferL1GtTriggerMenu = cms.ESPrefer( "PoolDBESSource", "l1GtTriggerMenu" )
00037 
00038 
00039 ## ------------------------------------------------------
00040 ## Re-configuration of PATJetProducer
00041 ## ------------------------------------------------------
00042 
00043 def run36xOn35xInput(process,
00044                      genJets = "",
00045                      postfix=""):
00046     """
00047     ------------------------------------------------------------------
00048     Reconfigure the PATJetProducer to be able to run the 36X version
00049     of PAT on 35X input samples.
00050 
00051     process : process
00052     ------------------------------------------------------------------
00053     """
00054     print "*********************************************************************"
00055     print "NOTE TO USER: when running on 35X sample with 36X s/w versions you   "
00056     print "              need to adapt for different event contents. The        "
00057     print "              adaptations need to be made:                           "
00058     print "                                                                     "
00059     print "               - re-configuration of secondary vertex tag discrimi-  "
00060     print "                 nator information.                                  "
00061     print "                                                                     "
00062     print "*********************************************************************"
00063     ## re-configure b-discriminator sources for pat jets
00064     process.patJets.discriminatorSources = cms.VInputTag(
00065         cms.InputTag("combinedSecondaryVertexBJetTags"),
00066         cms.InputTag("combinedSecondaryVertexMVABJetTags"),
00067         cms.InputTag("jetBProbabilityBJetTags"),
00068         cms.InputTag("jetProbabilityBJetTags"),
00069         cms.InputTag("simpleSecondaryVertexBJetTags"),
00070         cms.InputTag("softElectronByPtBJetTags"),
00071         cms.InputTag("softElectronByIP3dBJetTags"),
00072         cms.InputTag("softMuonBJetTags"),
00073         cms.InputTag("softMuonByPtBJetTags"),
00074         cms.InputTag("softMuonByIP3dBJetTags"),
00075         cms.InputTag("trackCountingHighEffBJetTags"),
00076         cms.InputTag("trackCountingHighPurBJetTags"),
00077     )
00078     if genJets != "" :
00079         print "*********************************************************************"
00080         print "NOTE TO USER: when running on 31X samples re-recoed in 3.5.x         "
00081         print "              with this CMSSW version of PAT                         "
00082         print "              it is required to re-run the GenJet production for     "
00083         print "              anti-kT since that is not part of the re-reco          "
00084         print "*********************************************************************"
00085         process.load("RecoJets.Configuration.GenJetParticles_cff")
00086         process.load("RecoJets.JetProducers." + genJets +"_cfi")
00087         process.patDefaultSequence.replace( getattr(process,"patCandidates"+postfix), process.genParticlesForJets+getattr(process,genJets)+getattr(process,"patCandidates"+postfix))
00088 
00089 
00090 
00091 ## ------------------------------------------------------
00092 ## Re-implementation of jetTools
00093 ## ------------------------------------------------------
00094 
00095 class RunBTagging35X(ConfigToolBase):
00096 
00097     """
00098     ------------------------------------------------------------------
00099     Define sequence to run b tagging on AOD input for a given jet
00100     collection including a JetTracksAssociatorAtVertex module with
00101     name 'jetTracksAssociatorAtVertex' + 'label'.
00102 
00103     Return value is a pair of (sequence, labels) where 'sequence'
00104     is the cms.Sequence, and 'labels' is a vector with the follow-
00105     ing entries:
00106 
00107      * labels['jta']      = the name of the JetTrackAssociator module
00108      * labels['tagInfos'] = a list of names of the TagInfo modules
00109      * labels['jetTags '] = a list of names of the JetTag modules
00110 
00111     This is a re-implementation to run the 36X version of PAT on 35X
00112     input samples.
00113     ------------------------------------------------------------------
00114     """
00115     _label='runBTagging35X'
00116     _defaultParameters=dicttypes.SortedKeysDict()
00117     def __init__(self):
00118         ConfigToolBase.__init__(self)
00119         self.addParameter(self._defaultParameters,'jetCollection',self._defaultValue, 'input jet collection',Type=cms.InputTag)
00120         self.addParameter(self._defaultParameters,'label',self._defaultValue, 'postfix label to identify new sequence/modules', Type=str)
00121         self.addParameter(self._defaultParameters,'postfix',"", "postfix of default sequence (do not confuse with 'label')")
00122         self._parameters=copy.deepcopy(self._defaultParameters)
00123         self._comment = ""
00124 
00125     def getDefaultParameters(self):
00126         return self._defaultParameters
00127 
00128     def __call__(self,process,
00129                  jetCollection     = None,
00130                  label             = None,
00131                  postfix           = None) :
00132         if  jetCollection is None:
00133             jetCollection=self._defaultParameters['jetCollection'].value
00134         if  label is None:
00135             label=self._defaultParameters['label'].value
00136         if postfix  is None:
00137             postfix=self._defaultParameters['postfix'].value
00138         self.setParameter('jetCollection',jetCollection)
00139         self.setParameter('label',label)
00140         self.setParameter('postfix',postfix)
00141 
00142         return self.apply(process)
00143 
00144     def apply(self, process):
00145         jetCollection=self._parameters['jetCollection'].value
00146         label=self._parameters['label'].value
00147         postfix=self._parameters['postfix'].value
00148 
00149         if hasattr(process, "addAction"):
00150             process.disableRecording()
00151 
00152         try:
00153             comment=inspect.stack(2)[2][4][0].rstrip("\n")
00154             if comment.startswith("#"):
00155                 self.setComment(comment.lstrip("#"))
00156         except:
00157             pass
00158 
00159         #############################
00160         ### TOOL CODE STARTS HERE ###
00161         #############################
00162         print "*********************************************************************"
00163         print "NOTE TO USER: when running on 35X sample with 36X s/w versions you   "
00164         print "              need to adapt for different event contents. The        "
00165         print "              adaptations need to be made:                           "
00166         print "                                                                     "
00167         print "               - re-configuration of secondary vertex tag discrimi-  "
00168         print "                 nator information.                                  "
00169         print "                                                                     "
00170         print "               - take out soft electron tagger information, which    "
00171         print "                 is not available on 35X.                            "
00172         print "*********************************************************************"
00173 
00174         if (label == ''):
00175         ## label is not allowed to be empty
00176             raise ValueError, "label for re-running b tagging is not allowed to be empty"
00177 
00178         ## import track associator & b tag configuration
00179         process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
00180         from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
00181         process.load("RecoBTag.Configuration.RecoBTag_cff")
00182         import RecoBTag.Configuration.RecoBTag_cff as btag
00183 
00184         # add negative tag infos
00185         import PhysicsTools.PatAlgos.recoLayer0.bTagging_cff as nbtag
00186 
00187         ## define jetTracksAssociator; for switchJetCollection
00188         ## the label is 'AOD' as empty labels will lead to crashes
00189         ## of crab. In this case the postfix label is skiped,
00190         ## otherwise a postfix label is added as for the other
00191         ## labels
00192         jtaLabel = 'jetTracksAssociatorAtVertex'+postfix
00193 
00194         if (not label == 'AOD'):
00195             jtaLabel  += label
00196         ## define tag info labels (compare with jetProducer_cfi.py)
00197         ipTILabel = 'impactParameterTagInfos'     + label
00198         svTILabel = 'secondaryVertexTagInfos'     + label
00199         smTILabel = 'softMuonTagInfos'            + label
00200 
00201         ## produce tag infos
00202         setattr( process, ipTILabel, btag.impactParameterTagInfos.clone(jetTracks = cms.InputTag(jtaLabel)) )
00203         setattr( process, svTILabel, btag.secondaryVertexTagInfos.clone(trackIPTagInfos = cms.InputTag(ipTILabel)) )
00204         setattr( process, smTILabel, btag.softMuonTagInfos.clone(jets = jetCollection) )
00205 
00206         ## make VInputTag from strings
00207         def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )
00208 
00209         ## produce btags
00210         setattr( process, 'jetBProbabilityBJetTags'+label, btag.jetBProbabilityBJetTags.clone(tagInfos = vit(ipTILabel)) )
00211         setattr( process, 'jetProbabilityBJetTags' +label, btag.jetProbabilityBJetTags.clone (tagInfos = vit(ipTILabel)) )
00212         setattr( process, 'trackCountingHighPurBJetTags'+label, btag.trackCountingHighPurBJetTags.clone(tagInfos = vit(ipTILabel)) )
00213         setattr( process, 'trackCountingHighEffBJetTags'+label, btag.trackCountingHighEffBJetTags.clone(tagInfos = vit(ipTILabel)) )
00214         setattr( process, 'simpleSecondaryVertexBJetTags'+label, btag.simpleSecondaryVertexBJetTags.clone(tagInfos = vit(svTILabel)) )
00215         setattr( process, 'combinedSecondaryVertexBJetTags'+label, btag.combinedSecondaryVertexBJetTags.clone(tagInfos = vit(ipTILabel, svTILabel)) )
00216         setattr( process, 'combinedSecondaryVertexMVABJetTags'+label, btag.combinedSecondaryVertexMVABJetTags.clone(tagInfos = vit(ipTILabel, svTILabel)) )
00217         setattr( process, 'softMuonBJetTags'+label, btag.softMuonBJetTags.clone(tagInfos = vit(smTILabel)) )
00218         setattr( process, 'softMuonByPtBJetTags'+label, btag.softMuonByPtBJetTags.clone(tagInfos = vit(smTILabel)) )
00219         setattr( process, 'softMuonByIP3dBJetTags'+label, btag.softMuonByIP3dBJetTags.clone(tagInfos = vit(smTILabel)) )
00220 
00221         ## define vector of (output) labels
00222         labels = { 'jta'      : jtaLabel,
00223                    'tagInfos' : (ipTILabel,svTILabel,smTILabel),
00224                    'jetTags'  : [ (x + label) for x in ('jetBProbabilityBJetTags',
00225                                                         'jetProbabilityBJetTags',
00226                                                         'trackCountingHighPurBJetTags',
00227                                                         'trackCountingHighEffBJetTags',
00228                                                         'simpleSecondaryVertexBJetTags',
00229                                                         'combinedSecondaryVertexBJetTags',
00230                                                         'combinedSecondaryVertexMVABJetTags',
00231                                                         'softMuonBJetTags',
00232                                                         'softMuonByPtBJetTags',
00233                                                         'softMuonByIP3dBJetTags'
00234                                                         )
00235                                   ]
00236                    }
00237 
00238         ## extend an existing sequence by otherLabels
00239         def mkseq(process, firstlabel, *otherlabels):
00240             seq = getattr(process, firstlabel)
00241             for x in otherlabels: seq += getattr(process, x)
00242             return cms.Sequence(seq)
00243 
00244         ## add tag infos to the process
00245         setattr( process, 'btaggingTagInfos'+label, mkseq(process, *(labels['tagInfos']) ) )
00246         ## add b tags to the process
00247         setattr( process, 'btaggingJetTags'+label,  mkseq(process, *(labels['jetTags'])  ) )
00248         ## add a combined sequence to the process
00249         seq = mkseq(process, 'btaggingTagInfos'+label, 'btaggingJetTags' + label)
00250         setattr( process, 'btagging'+label, seq )
00251         ## return the combined sequence and the labels defined above
00252 
00253         if hasattr(process, "addAction"):
00254             process.enableRecording()
00255             action=self.__copy__()
00256             process.addAction(action)
00257         return (seq, labels)
00258 
00259 
00260 runBTagging35X=RunBTagging35X()
00261 
00262 
00263 class AddJetCollection35X(ConfigToolBase):
00264 
00265     """
00266     ------------------------------------------------------------------
00267     Add a new collection of jets. Takes the configuration from the
00268     already configured standard jet collection as starting point;
00269     replaces before calling addJetCollection will also affect the
00270     new jet collections. This is a re-implementation to run the
00271     36X version of PAT on 35X input samples.
00272     ------------------------------------------------------------------
00273     """
00274     _label='addJetCollection35X'
00275     _defaultParameters=dicttypes.SortedKeysDict()
00276     def __init__(self):
00277         ConfigToolBase.__init__(self)
00278         self.addParameter(self._defaultParameters,'jetCollection',self._defaultValue,'Input jet collection', cms.InputTag)
00279         self.addParameter(self._defaultParameters,'algoLabel',self._defaultValue, "label to indicate the jet algorithm (e.g.'AK5')",str)
00280         self.addParameter(self._defaultParameters,'typeLabel',self._defaultValue, "label to indicate the type of constituents (e.g. 'Calo', 'Pflow', 'Jpt', ...)",str)
00281         self.addParameter(self._defaultParameters,'doJTA',True, "run b tagging sequence for new jet collection and add it to the new pat jet collection")
00282         self.addParameter(self._defaultParameters,'doBTagging',True, 'run JetTracksAssociation and JetCharge and add it to the new pat jet collection (will autom. be true if doBTagging is set to true)')
00283         self.addParameter(self._defaultParameters,'jetCorrLabel',None, "algorithm and type of JEC; use 'None' for no JEC; examples are ('AK5','Calo'), ('SC7','Calo'), ('KT4','PF')", tuple,acceptNoneValue=True)
00284         self.addParameter(self._defaultParameters,'doType1MET',True, "if jetCorrLabel is not 'None', set this to 'True' to redo the Type1 MET correction for the new jet colllection; at the moment it must be 'False' for non CaloJets otherwise the JetMET POG module crashes. ")
00285         self.addParameter(self._defaultParameters,'doL1Cleaning',True, "copy also the producer modules for cleanLayer1 will be set to 'True' automatically when doL1Counters is 'True'")
00286         self.addParameter(self._defaultParameters,'doL1Counters',False, "copy also the filter modules that accept/reject the event looking at the number of jets")
00287         self.addParameter(self._defaultParameters,'genJetCollection',cms.InputTag("ak5GenJets"), "GenJet collection to match to")
00288         self.addParameter(self._defaultParameters,'doJetID',True, "add jetId variables to the added jet collection?")
00289         self.addParameter(self._defaultParameters,'jetIdLabel',"ak5", " specify the label prefix of the xxxJetID object; in general it is the jet collection tag like ak5, kt4 sc5, aso. For more information have a look to SWGuidePATTools#add_JetCollection")
00290         self.addParameter(self._defaultParameters,'standardAlgo',"AK5", "standard algorithm label of the collection from which the clones for the new jet collection will be taken from (note that this jet collection has to be available in the event before hand)")
00291         self.addParameter(self._defaultParameters,'standardType',"Calo", "standard constituent type label of the collection from which the clones for the new jet collection will be taken from (note that this jet collection has to be available in the event before hand)")
00292 
00293         self._parameters=copy.deepcopy(self._defaultParameters)
00294         self._comment = ""
00295 
00296     def getDefaultParameters(self):
00297         return self._defaultParameters
00298 
00299     def __call__(self,process,
00300                  jetCollection      = None,
00301                  algoLabel          = None,
00302                  typeLabel          = None,
00303                  doJTA              = None,
00304                  doBTagging         = None,
00305                  jetCorrLabel       = None,
00306                  doType1MET         = None,
00307                  doL1Cleaning       = None,
00308                  doL1Counters       = None,
00309                  genJetCollection   = None,
00310                  doJetID            = None,
00311                  jetIdLabel         = None,
00312                  standardAlgo       = None,
00313                  standardType       = None):
00314 
00315         if jetCollection  is None:
00316             jetCollection=self._defaultParameters['jetCollection'].value
00317         if algoLabel is None:
00318             algoLabel=self._defaultParameters['algoLabel'].value
00319         if typeLabel is None:
00320             typeLabel=self._defaultParameters['typeLabel'].value
00321         if doJTA is None:
00322             doJTA=self._defaultParameters['doJTA'].value
00323         if doBTagging is None:
00324             doBTagging=self._defaultParameters['doBTagging'].value
00325         if jetCorrLabel  is None:
00326             jetCorrLabel=self._defaultParameters['jetCorrLabel'].value
00327         if doType1MET  is None:
00328             doType1MET=self._defaultParameters['doType1MET'].value
00329         if doL1Cleaning is None:
00330             doL1Cleaning=self._defaultParameters['doL1Cleaning'].value
00331         if doL1Counters  is None:
00332             doL1Counters=self._defaultParameters['doL1Counters'].value
00333         if genJetCollection  is None:
00334             genJetCollection=self._defaultParameters['genJetCollection'].value
00335         if doJetID  is None:
00336             doJetID=self._defaultParameters['doJetID'].value
00337         if jetIdLabel  is None:
00338             jetIdLabel=self._defaultParameters['jetIdLabel'].value
00339         if standardAlgo is None:
00340             standardAlgo=self._defaultParameters['standardAlgo'].value
00341         if standardType is None:
00342             standardType=self._defaultParameters['standardType'].value
00343 
00344         self.setParameter('jetCollection',jetCollection)
00345         self.setParameter('algoLabel',algoLabel)
00346         self.setParameter('typeLabel',typeLabel)
00347         self.setParameter('doJTA',doJTA)
00348         self.setParameter('doBTagging',doBTagging)
00349         self.setParameter('jetCorrLabel',jetCorrLabel)
00350         self.setParameter('doType1MET',doType1MET)
00351         self.setParameter('doL1Cleaning',doL1Cleaning)
00352         self.setParameter('doL1Counters',doL1Counters)
00353         self.setParameter('genJetCollection',genJetCollection)
00354         self.setParameter('doJetID',doJetID)
00355         self.setParameter('jetIdLabel',jetIdLabel)
00356         self.setParameter('standardAlgo',standardAlgo)
00357         self.setParameter('standardType',standardType)
00358 
00359         self.apply(process)
00360 
00361     def toolCode(self, process):
00362         jetCollection=self._parameters['jetCollection'].value
00363         algoLabel=self._parameters['algoLabel'].value
00364         typeLabel=self._parameters['typeLabel'].value
00365         doJTA=self._parameters['doJTA'].value
00366         doBTagging=self._parameters['doBTagging'].value
00367         jetCorrLabel=self._parameters['jetCorrLabel'].value
00368         doType1MET =self._parameters['doType1MET'].value
00369         doL1Cleaning=self._parameters['doL1Cleaning'].value
00370         doL1Counters=self._parameters['doL1Counters'].value
00371         genJetCollection=self._parameters['genJetCollection'].value
00372         doJetID=self._parameters['doJetID'].value
00373         jetIdLabel=self._parameters['jetIdLabel'].value
00374         standardAlgo=self._parameters['standardAlgo'].value
00375         standardType=self._parameters['standardType'].value
00376 
00377         ## define common label for pre pat jet
00378         ## creation steps in makePatJets
00379         #label=standardAlgo+standardType
00380 
00381         ## create old module label from standardAlgo
00382         ## and standardType and return
00383         def oldLabel(prefix=''):
00384             return jetCollectionString(prefix, '', '')
00385 
00386         ## create new module label from old module
00387         ## label and return
00388         def newLabel(oldLabel):
00389             newLabel=oldLabel
00390             if(oldLabel.find(standardAlgo)>=0 and oldLabel.find(standardType)>=0):
00391                 oldLabel=oldLabel.replace(standardAlgo, algoLabel).replace(standardType, typeLabel)
00392             else:
00393                 oldLabel=oldLabel+algoLabel+typeLabel
00394             return oldLabel
00395 
00396         ## clone module and add it to the patDefaultSequence
00397         def addClone(hook, **replaceStatements):
00398             ## create a clone of the hook with corresponding
00399             ## parameter replacements
00400             newModule = getattr(process, hook).clone(**replaceStatements)
00401             ## add the module to the sequence
00402             addModuleToSequence(hook, newModule)
00403 
00404         ## add module to the patDefaultSequence
00405         def addModuleToSequence(hook, newModule):
00406             hookModule = getattr(process, hook)
00407             ## add the new module with standardAlgo &
00408             ## standardType replaced in module label
00409             setattr( process, newLabel(hook), newModule)
00410             ## add new module to default sequence
00411             ## just behind the hookModule
00412             process.patDefaultSequence.replace( hookModule, hookModule*newModule )
00413 
00414         print "*********************************************************************"
00415         print "NOTE TO USER: when running on 35X sample with 36X s/w versions you   "
00416         print "              need to adapt for different event contents. The        "
00417         print "              adaptations need to be made:                           "
00418         print "                                                                     "
00419         print "               - re-configuration of secondary vertex tag discrimi-  "
00420         print "                 nator information.                                  "
00421         print "                                                                     "
00422         print "               - take out soft electron tagger information, which    "
00423         print "                 is not available on 35X.                            "
00424         print "*********************************************************************"
00425 
00426         ## add a clone of patJets
00427         addClone(oldLabel(), jetSource = jetCollection)
00428         ## add a clone of selectedPatJets
00429         addClone(oldLabel('selected'), src=cms.InputTag(newLabel(oldLabel())))
00430         ## add a clone of cleanPatJets
00431         if( doL1Cleaning ):
00432             addClone(oldLabel('clean'), src=cms.InputTag(newLabel(oldLabel('selected'))))
00433         ## add a clone of countPatJets
00434         if( doL1Counters ):
00435             if( doL1Cleaning ):
00436                 addClone(oldLabel('count'), src=cms.InputTag(newLabel(oldLabel('clean'))))
00437             else:
00438                 addClone(oldLabel('count'), src=cms.InputTag(newLabel(oldLabel('selected'))))
00439 
00440         ## get attributes of new module
00441         l1Jets = getattr(process, newLabel(oldLabel()))
00442 
00443         ## add a clone of gen jet matching
00444         addClone('patJetPartonMatch', src = jetCollection)
00445         addClone('patJetGenJetMatch', src = jetCollection, matched = genJetCollection)
00446 
00447         ## add a clone of parton and flavour associations
00448         addClone('patJetPartonAssociation', jets = jetCollection)
00449         addClone('patJetFlavourAssociation', srcByReference = cms.InputTag(newLabel('patJetPartonAssociation')))
00450 
00451         ## fix label for input tag
00452         def fixInputTag(x): x.setModuleLabel(newLabel(x.moduleLabel))
00453         ## fix label for vector of input tags
00454         def fixVInputTag(x): x[0].setModuleLabel(newLabel(x[0].moduleLabel))
00455 
00456         ## provide allLayer1Jet inputs with individual labels
00457         fixInputTag(l1Jets.genJetMatch)
00458         fixInputTag(l1Jets.genPartonMatch)
00459         fixInputTag(l1Jets.JetPartonMapSource)
00460 
00461         ## make VInputTag from strings
00462         def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )
00463 
00464         if (doJTA or doBTagging):
00465             ## add clone of jet track association
00466             process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
00467             from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
00468             ## add jet track association module to processes
00469             jtaLabel = 'jetTracksAssociatorAtVertex'+algoLabel+typeLabel
00470             setattr( process, jtaLabel, ak5JetTracksAssociatorAtVertex.clone(jets = jetCollection) )
00471             process.makePatJets.replace(process.patJetCharge, getattr(process,jtaLabel)+process.patJetCharge)
00472             l1Jets.trackAssociationSource = cms.InputTag(jtaLabel)
00473             addClone('patJetCharge', src=cms.InputTag(jtaLabel)),
00474             fixInputTag(l1Jets.jetChargeSource)
00475         else:
00476             ## switch embedding of track association and jet
00477             ## charge estimate to 'False'
00478             l1Jets.addAssociatedTracks = False
00479             l1Jets.addJetCharge = False
00480 
00481         if (doBTagging):
00482             ## define postfixLabel
00483             postfixLabel=algoLabel+typeLabel
00484             ## add b tagging sequence
00485             (btagSeq, btagLabels) = runBTagging35X(process, jetCollection, postfixLabel)
00486             ## add b tagging sequence before running the allLayer1Jets modules
00487             process.makePatJets.replace(getattr(process,jtaLabel), getattr(process,jtaLabel)+btagSeq)
00488             ## replace corresponding tags for pat jet production
00489             l1Jets.trackAssociationSource = cms.InputTag(btagLabels['jta'])
00490             l1Jets.tagInfoSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['tagInfos'] ] )
00491             l1Jets.discriminatorSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['jetTags']  ] )
00492         else:
00493             ## switch general b tagging info switch off
00494             l1Jets.addBTagInfo = False
00495 
00496         if (doJetID):
00497             l1Jets.addJetID = cms.bool(True)
00498             jetIdLabelNew = jetIdLabel + 'JetID'
00499             l1Jets.jetIDMap = cms.InputTag( jetIdLabelNew )
00500         else :
00501             l1Jets.addJetID = cms.bool(False)
00502 
00503         if (jetCorrLabel != None):
00504             ## add clone of jet energy corrections;
00505             ## catch a couple of exceptions first
00506             if (jetCorrLabel == False ):
00507                 raise ValueError, "In addJetCollection 'jetCorrLabel' must be set to 'None', not 'False'"
00508             if (jetCorrLabel == "None"):
00509                 raise ValueError, "In addJetCollection 'jetCorrLabel' must be set to 'None' (without quotes)"
00510             ## check for the correct format
00511             if type(jetCorrLabel) != type(('AK5','Calo')):
00512                 raise ValueError, "In addJetCollection 'jetCorrLabel' must be 'None', or of type ('Algo','Type')"
00513 
00514             ## add clone of jetCorrFactors
00515             addClone('patJetCorrFactors', jetSource = jetCollection)
00516             switchJECParameters( getattr(process,newLabel('patJetCorrFactors')), jetCorrLabel[0], jetCorrLabel[1], oldAlgo='AK5',oldType='Calo' )
00517             fixVInputTag(l1Jets.jetCorrFactorsSource)
00518 
00519             ## switch type1MET corrections off for PFJets
00520             if( jetCollection.__str__().find('PFJets')>=0 ):
00521                 print '================================================='
00522                 print 'Type1MET corrections are switched off for PFJets.'
00523                 print 'of type %s%s.' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1])
00524                 print 'Users are recommened to use pfMET together with  '
00525                 print 'PFJets.'
00526                 print '================================================='
00527                 doType1MET=False
00528 
00529             ## add a clone of the type1MET correction for the new jet collection
00530             if (doType1MET):
00531                 ## in case there is no jet correction service in the paths add it
00532                 ## as L2L3 if possible, as combined from L2 and L3 otherwise
00533                 if not hasattr( process, '%s%sL2L3' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]) ):
00534                     setattr( process, '%s%sL2L3' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]),
00535                              cms.ESProducer("JetCorrectionESChain",
00536                                           correctors = cms.vstring('%s%sL2Relative' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]),
00537                                                                    '%s%sL3Absolute' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1])
00538                                                                    )
00539                                           )
00540                              )
00541                 ## add a clone of the type1MET correction
00542                 ## and the following muonMET correction
00543                 addClone('metJESCorAK5CaloJet', inputUncorJetsLabel = jetCollection.value(),
00544                          corrector = cms.string('%s%sL2L3' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]))
00545                          )
00546                 addClone('metJESCorAK5CaloJetMuons', uncorMETInputTag = cms.InputTag(newLabel('metJESCorAK5CaloJet')))
00547                 addClone('patMETs', metSource = cms.InputTag(newLabel('metJESCorAK5CaloJetMuons')))
00548                 l1MET = getattr(process, newLabel('patMETs'))
00549                 ## add new met collections output to the pat summary
00550                 process.patCandidateSummary.candidates += [ cms.InputTag(newLabel('patMETs')) ]
00551         else:
00552             ## switch jetCorrFactors off
00553             l1Jets.addJetCorrFactors = False
00554 
00555 
00556 
00557 addJetCollection35X=AddJetCollection35X()
00558 
00559 
00560 class SwitchJetCollection35X(ConfigToolBase):
00561 
00562     """
00563     ------------------------------------------------------------------
00564     Switch the collection of jets in PAT from the default value to a
00565     new jet collection. This is a re-implementation to run the 36X
00566     version of PAT on 35X input samples.
00567     ------------------------------------------------------------------
00568     """
00569     _label='switchJetCollection35X'
00570     _defaultParameters=dicttypes.SortedKeysDict()
00571     def __init__(self):
00572         ConfigToolBase.__init__(self)
00573         self.addParameter(self._defaultParameters,'jetCollection',self._defaultValue,'Input jet collection', cms.InputTag)
00574         self.addParameter(self._defaultParameters,'doJTA',True, "run b tagging sequence for new jet collection and add it to the new pat jet collection")
00575         self.addParameter(self._defaultParameters,'doBTagging',True, 'run JetTracksAssociation and JetCharge and add it to the new pat jet collection (will autom. be true if doBTagging is set to true)')
00576         self.addParameter(self._defaultParameters,'jetCorrLabel',None, "algorithm and type of JEC; use 'None' for no JEC; examples are ('AK5','Calo'), ('SC7','Calo'), ('KT4','PF')", tuple,acceptNoneValue=True)
00577         self.addParameter(self._defaultParameters,'doType1MET',True, "if jetCorrLabel is not 'None', set this to 'True' to redo the Type1 MET correction for the new jet colleection; at the moment it must be 'False' for non CaloJets otherwise the JetMET POG module crashes. ")
00578         self.addParameter(self._defaultParameters,'genJetCollection',cms.InputTag("ak5GenJets"), "GenJet collection to match to")
00579         self.addParameter(self._defaultParameters,'doJetID',True, "add jetId variables to the added jet collection")
00580         self.addParameter(self._defaultParameters,'jetIdLabel',"ak5", " specify the label prefix of the xxxJetID object; in general it is the jet collection tag like ak5, kt4 sc5, aso. For more information have a look to SWGuidePATTools#add_JetCollection")
00581         self.addParameter(self._defaultParameters,'postfix',"", "postfix of default sequence")
00582 
00583         self._parameters=copy.deepcopy(self._defaultParameters)
00584         self._comment = ""
00585 
00586     def getDefaultParameters(self):
00587         return self._defaultParameters
00588 
00589     def __call__(self,process,
00590                  jetCollection      = None,
00591                  doJTA              = None,
00592                  doBTagging         = None,
00593                  jetCorrLabel       = None,
00594                  doType1MET         = None,
00595                  genJetCollection   = None,
00596                  doJetID            = None,
00597                  jetIdLabel         = None,
00598                  postfix            = None):
00599 
00600         if jetCollection  is None:
00601             jetCollection=self._defaultParameters['jetCollection'].value
00602         if doJTA is None:
00603             doJTA=self._defaultParameters['doJTA'].value
00604         if doBTagging is None:
00605             doBTagging=self._defaultParameters['doBTagging'].value
00606         if jetCorrLabel  is None:
00607             jetCorrLabel=self._defaultParameters['jetCorrLabel'].value
00608         if doType1MET  is None:
00609             doType1MET=self._defaultParameters['doType1MET'].value
00610         if genJetCollection  is None:
00611             genJetCollection=self._defaultParameters['genJetCollection'].value
00612         if doJetID  is None:
00613             doJetID=self._defaultParameters['doJetID'].value
00614         if jetIdLabel  is None:
00615             jetIdLabel=self._defaultParameters['jetIdLabel'].value
00616         if postfix  is None:
00617             postfix=self._defaultParameters['postfix'].value
00618 
00619         self.setParameter('jetCollection',jetCollection)
00620         self.setParameter('doJTA',doJTA)
00621         self.setParameter('doBTagging',doBTagging)
00622         self.setParameter('jetCorrLabel',jetCorrLabel)
00623         self.setParameter('doType1MET',doType1MET)
00624         self.setParameter('genJetCollection',genJetCollection)
00625         self.setParameter('doJetID',doJetID)
00626         self.setParameter('jetIdLabel',jetIdLabel)
00627         self.setParameter('postfix',postfix)
00628 
00629         self.apply(process)
00630 
00631     def toolCode(self, process):
00632         jetCollection=self._parameters['jetCollection'].value
00633         doJTA=self._parameters['doJTA'].value
00634         doBTagging=self._parameters['doBTagging'].value
00635         jetCorrLabel=self._parameters['jetCorrLabel'].value
00636         doType1MET =self._parameters['doType1MET'].value
00637         genJetCollection=self._parameters['genJetCollection'].value
00638         doJetID=self._parameters['doJetID'].value
00639         jetIdLabel=self._parameters['jetIdLabel'].value
00640         postfix=self._parameters['postfix'].value
00641 
00642 
00643         ## save label of old input jet collection
00644         oldLabel = applyPostfix(process, "patJets", postfix).jetSource;
00645 
00646         ## replace input jet collection for generator matches
00647         applyPostfix(process, "patJetPartonMatch", postfix).src = jetCollection
00648         applyPostfix(process, "patJetGenJetMatch", postfix).src = jetCollection
00649         applyPostfix(process, "patJetGenJetMatch", postfix).matched = genJetCollection
00650         applyPostfix(process, "patJetPartonAssociation", postfix).jets = jetCollection
00651         ## replace input jet collection for pat jet production
00652         applyPostfix(process, "patJets", postfix).jetSource = jetCollection
00653 
00654         ## make VInputTag from strings
00655         def vit(*args) : return cms.VInputTag( *[ cms.InputTag(x) for x in args ] )
00656 
00657         if (doJTA or doBTagging):
00658             ## replace jet track association
00659             process.load("RecoJets.JetAssociationProducers.ak5JTA_cff")
00660             from RecoJets.JetAssociationProducers.ak5JTA_cff import ak5JetTracksAssociatorAtVertex
00661             setattr(process, "jetTracksAssociatorAtVertex"+postfix, ak5JetTracksAssociatorAtVertex.clone(jets = jetCollection))
00662             getattr(process, "patDefaultSequence"+postfix).replace(
00663                 applyPostfix(process, "patJetCharge", postfix),
00664                 getattr(process, "jetTracksAssociatorAtVertex" + postfix) #module with postfix that is not n patDefaultSequence
00665                 + applyPostfix(process, "patJetCharge", postfix)
00666                 )
00667 
00668             applyPostfix(process, "patJetCharge", postfix).src = 'jetTracksAssociatorAtVertex'+postfix
00669             applyPostfix(process, "patJets", postfix).trackAssociationSource = 'jetTracksAssociatorAtVertex'+postfix
00670         else:
00671             ## remove the jet track association from the std
00672             ## sequence
00673             removeIfInSequence(process,  "patJetCharge",  "patDefaultSequence", postfix)
00674             ## switch embedding of track association and jet
00675             ## charge estimate to 'False'
00676             applyPostfix(process, "patJets", postfix).addAssociatedTracks = False
00677             applyPostfix(process, "patJets", postfix).addJetCharge = False
00678 
00679         if (doBTagging):
00680             ## replace b tagging sequence; add postfix label 'AOD' as crab will
00681             ## crash when confronted with empy labels
00682             (btagSeq, btagLabels) = runBTagging35X(process, jetCollection, 'AOD',postfix)
00683             ## add b tagging sequence before running the allLayer1Jets modules
00684             getattr(process, "patDefaultSequence"+postfix).replace(
00685                 getattr( process,"jetTracksAssociatorAtVertex"+postfix),
00686                 getattr( process,"jetTracksAssociatorAtVertex"+postfix) + btagSeq
00687                 )
00688 
00689             ## replace corresponding tags for pat jet production
00690             applyPostfix(process, "patJets", postfix).trackAssociationSource = btagLabels['jta']
00691             applyPostfix(process, "patJets", postfix).tagInfoSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['tagInfos'] ] )
00692             applyPostfix(process, "patJets", postfix).discriminatorSources = cms.VInputTag( *[ cms.InputTag(x) for x in btagLabels['jetTags']  ] )
00693         else:
00694             ## remove b tagging from the std sequence
00695             removeIfInSequence(process,  "secondaryVertexNegativeTagInfos",  "patDefaultSequence", postfix)
00696             removeIfInSequence(process,  "simpleSecondaryVertexNegativeBJetTags",  "patDefaultSequence", postfix)
00697 
00698             ## switch embedding of b tagging for pat
00699             ## jet production to 'False'
00700             applyPostfix(process, "patJets", postfix).addBTagInfo = False
00701 
00702         if (doJetID):
00703             jetIdLabelNew = jetIdLabel + 'JetID'
00704             applyPostfix(process, "patJets", postfix).jetIDMap = cms.InputTag( jetIdLabelNew )
00705         else:
00706             applyPostfix(process, "patJets", postfix).addJetID = cms.bool(False)
00707 
00708 
00709         if (jetCorrLabel!=None):
00710             ## replace jet energy corrections; catch
00711             ## a couple of exceptions first
00712             if (jetCorrLabel == False ):
00713                 raise ValueError, "In switchJetCollection 'jetCorrLabel' must be set to 'None', not 'False'"
00714             if (jetCorrLabel == "None"):
00715                 raise ValueError, "In switchJetCollection 'jetCorrLabel' must be set to 'None' (without quotes)"
00716             ## check for the correct format
00717             if (type(jetCorrLabel)!=type(('AK5','Calo'))):
00718                 raise ValueError, "In switchJetCollection 'jetCorrLabel' must be 'None', or of type ('Algo','Type')"
00719 
00720             ## switch JEC parameters to the new jet collection
00721             applyPostfix(process, "patJetCorrFactors", postfix).jetSource = jetCollection
00722             switchJECParameters(applyPostfix(process, "patJetCorrFactors", postfix), jetCorrLabel[0], jetCorrLabel[1], oldAlgo='AK5',oldType='Calo')
00723 
00724             ## switch type1MET corrections off for PFJets
00725             if( jetCollection.__str__().find('PFJets')>=0 ):
00726                 print '================================================='
00727                 print 'Type1MET corrections are switched off for PFJets.'
00728                 print 'of type %s%s.' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1])
00729                 print 'Users are recommened to use pfMET together with  '
00730                 print 'PFJets.'
00731                 print '================================================='
00732                 doType1MET=False
00733 
00734             ## redo the type1MET correction for the new jet collection
00735             if (doType1MET):
00736                 ## in case there is no jet correction service in the paths add it
00737                 ## as L2L3 if possible, as combined from L2 and L3 otherwise
00738                 if not hasattr( process, '%s%sL2L3' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]) ):
00739                     setattr( process, '%s%sL2L3' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]),
00740                              cms.ESProducer("JetCorrectionESChain",
00741                                           correctors = cms.vstring('%s%sL2Relative' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1]),
00742                                                                    '%s%sL3Absolute' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1])
00743                                                                    )
00744                                           )
00745                              )
00746                 ## configure the type1MET correction the following muonMET
00747                 ## corrections have the metJESCorAK5CaloJet as input and
00748                 ## are automatically correct
00749                 applyPostfix(process, "metJESCorAK5CaloJet", postfix).inputUncorJetsLabel = jetCollection.value()
00750                 applyPostfix(process, "metJESCorAK5CaloJet", postfix).corrector = '%s%sL2L3' % (jetCorrLabel[0].swapcase(), jetCorrLabel[1])
00751         else:
00752             ## remove the jetCorrFactors from the std sequence
00753             process.patJetMETCorrections.remove(process.patJetCorrFactors)
00754             ## switch embedding of jetCorrFactors off
00755             ## for pat jet production
00756             applyPostfix(process, "patJets", postfix).addJetCorrFactors = False
00757 
00758 
00759 switchJetCollection35X=SwitchJetCollection35X()
00760 
00761 
00762 ## ------------------------------------------------------
00763 ## Automatic pick-up of RelVal input files
00764 ## ------------------------------------------------------
00765 
00766 class PickRelValInputFiles( ConfigToolBase ):
00767     """  Picks up RelVal input files automatically and
00768   returns a vector of strings with the paths to be used in [PoolSource].fileNames
00769     PickRelValInputFiles( cmsswVersion, relVal, dataTier, condition, globalTag, maxVersions, skipFiles, numberOfFiles, debug )
00770     - useDAS       : switch to perform query in DAS rather than in DBS
00771                      optional; default: False
00772     - cmsswVersion : CMSSW release to pick up the RelVal files from
00773                      optional; default: the current release (determined automatically from environment)
00774     - formerVersion: use the last before the last valid CMSSW release to pick up the RelVal files from
00775                      applies also, if 'cmsswVersion' is set explicitly
00776                      optional; default: False
00777     - relVal       : RelVal sample to be used
00778                      optional; default: 'RelValTTbar'
00779     - dataTier     : data tier to be used
00780                      optional; default: 'GEN-SIM-RECO'
00781     - condition    : identifier of GlobalTag as defined in Configurations/PyReleaseValidation/python/autoCond.py
00782                      possibly overwritten, if 'globalTag' is set explicitly
00783                      optional; default: 'startup'
00784     - globalTag    : name of GlobalTag as it is used in the data path of the RelVals
00785                      optional; default: determined automatically as defined by 'condition' in Configurations/PyReleaseValidation/python/autoCond.py
00786       !!!            Determination is done for the release one runs in, not for the release the RelVals have been produced in.
00787       !!!            Example of deviation: data RelVals (CMSSW_4_1_X) might not only have the pure name of the GlobalTag 'GR_R_311_V2' in the full path,
00788                      but also an extension identifying the data: 'GR_R_311_V2_RelVal_wzMu2010B'
00789     - maxVersions  : max. versioning number of RelVal to check
00790                      optional; default: 9
00791     - skipFiles    : number of files to skip for a found RelVal sample
00792                      optional; default: 0
00793     - numberOfFiles: number of files to pick up
00794                      setting it to negative values, returns all found ('skipFiles' remains active though)
00795                      optional; default: -1
00796     - debug        : switch to enable enhanced messages in 'stdout'
00797                      optional; default: False
00798     """
00799 
00800     _label             = 'pickRelValInputFiles'
00801     _defaultParameters = dicttypes.SortedKeysDict()
00802 
00803     def getDefaultParameters( self ):
00804         return self._defaultParameters
00805 
00806     def __init__( self ):
00807         ConfigToolBase.__init__( self )
00808         self.addParameter( self._defaultParameters, 'useDAS'       , False                                                               , '' )
00809         self.addParameter( self._defaultParameters, 'cmsswVersion' , os.getenv( "CMSSW_VERSION" )                                        , 'auto from environment' )
00810         self.addParameter( self._defaultParameters, 'formerVersion', False                                                               , '' )
00811         self.addParameter( self._defaultParameters, 'relVal'       , 'RelValTTbar'                                                       , '' )
00812         self.addParameter( self._defaultParameters, 'dataTier'     , 'GEN-SIM-RECO'                                                      , '' )
00813         self.addParameter( self._defaultParameters, 'condition'    , 'startup'                                                           , '' )
00814         self.addParameter( self._defaultParameters, 'globalTag'    , autoCond[ self.getDefaultParameters()[ 'condition' ].value ][ : -5 ], 'auto from \'condition\'' )
00815         self.addParameter( self._defaultParameters, 'maxVersions'  , 3                                                                   , '' )
00816         self.addParameter( self._defaultParameters, 'skipFiles'    , 0                                                                   , '' )
00817         self.addParameter( self._defaultParameters, 'numberOfFiles', -1                                                                  , 'all' )
00818         self.addParameter( self._defaultParameters, 'debug'        , False                                                               , '' )
00819         self._parameters = copy.deepcopy( self._defaultParameters )
00820         self._comment = ""
00821 
00822     def __call__( self
00823                 , useDAS        = None
00824                 , cmsswVersion  = None
00825                 , formerVersion = None
00826                 , relVal        = None
00827                 , dataTier      = None
00828                 , condition     = None
00829                 , globalTag     = None
00830                 , maxVersions   = None
00831                 , skipFiles     = None
00832                 , numberOfFiles = None
00833                 , debug         = None
00834                 ):
00835         if useDAS is None:
00836             useDAS = self.getDefaultParameters()[ 'useDAS' ].value
00837         if cmsswVersion is None:
00838             cmsswVersion = self.getDefaultParameters()[ 'cmsswVersion' ].value
00839         if formerVersion is None:
00840             formerVersion = self.getDefaultParameters()[ 'formerVersion' ].value
00841         if relVal is None:
00842             relVal = self.getDefaultParameters()[ 'relVal' ].value
00843         if dataTier is None:
00844             dataTier = self.getDefaultParameters()[ 'dataTier' ].value
00845         if condition is None:
00846             condition = self.getDefaultParameters()[ 'condition' ].value
00847         if globalTag is None:
00848             globalTag = autoCond[ condition ][ : -5 ] # auto from 'condition'
00849         if maxVersions is None:
00850             maxVersions = self.getDefaultParameters()[ 'maxVersions' ].value
00851         if skipFiles is None:
00852             skipFiles = self.getDefaultParameters()[ 'skipFiles' ].value
00853         if numberOfFiles is None:
00854             numberOfFiles = self.getDefaultParameters()[ 'numberOfFiles' ].value
00855         if debug is None:
00856             debug = self.getDefaultParameters()[ 'debug' ].value
00857         self.setParameter( 'useDAS'       , useDAS )
00858         self.setParameter( 'cmsswVersion' , cmsswVersion )
00859         self.setParameter( 'formerVersion', formerVersion )
00860         self.setParameter( 'relVal'       , relVal )
00861         self.setParameter( 'dataTier'     , dataTier )
00862         self.setParameter( 'condition'    , condition )
00863         self.setParameter( 'globalTag'    , globalTag )
00864         self.setParameter( 'maxVersions'  , maxVersions )
00865         self.setParameter( 'skipFiles'    , skipFiles )
00866         self.setParameter( 'numberOfFiles', numberOfFiles )
00867         self.setParameter( 'debug'        , debug )
00868         return self.apply()
00869 
00870     def messageEmptyList( self ):
00871         print '%s DEBUG: Empty file list returned'%( self._label )
00872         print '    This might be overwritten by providing input files explicitly to the source module in the main configuration file.'
00873 
00874     def apply( self ):
00875         useDAS        = self._parameters[ 'useDAS'        ].value
00876         cmsswVersion  = self._parameters[ 'cmsswVersion'  ].value
00877         formerVersion = self._parameters[ 'formerVersion' ].value
00878         relVal        = self._parameters[ 'relVal'        ].value
00879         dataTier      = self._parameters[ 'dataTier'      ].value
00880         condition     = self._parameters[ 'condition'     ].value # only used for GT determination in initialization, if GT not explicitly given
00881         globalTag     = self._parameters[ 'globalTag'     ].value
00882         maxVersions   = self._parameters[ 'maxVersions'   ].value
00883         skipFiles     = self._parameters[ 'skipFiles'     ].value
00884         numberOfFiles = self._parameters[ 'numberOfFiles' ].value
00885         debug         = self._parameters[ 'debug'         ].value
00886 
00887         filePaths = []
00888 
00889         # Determine corresponding CMSSW version for RelVals
00890         preId      = '_pre'
00891         patchId    = '_patch'    # patch releases
00892         hltPatchId = '_hltpatch' # HLT patch releases
00893         dqmPatchId = '_dqmpatch' # DQM patch releases
00894         slhcId     = '_SLHC'     # SLHC releases
00895         rootId     = '_root'     # ROOT test releases
00896         ibId       = '_X_'       # IBs
00897         if patchId in cmsswVersion:
00898             cmsswVersion = cmsswVersion.split( patchId )[ 0 ]
00899         elif hltPatchId in cmsswVersion:
00900             cmsswVersion = cmsswVersion.split( hltPatchId )[ 0 ]
00901         elif dqmPatchId in cmsswVersion:
00902             cmsswVersion = cmsswVersion.split( dqmPatchId )[ 0 ]
00903         elif rootId in cmsswVersion:
00904             cmsswVersion = cmsswVersion.split( rootId )[ 0 ]
00905         elif slhcId in cmsswVersion:
00906             cmsswVersion = cmsswVersion.split( slhcId )[ 0 ]
00907         elif ibId in cmsswVersion or formerVersion:
00908             outputTuple = Popen( [ 'scram', 'l -c CMSSW' ], stdout = PIPE, stderr = PIPE ).communicate()
00909             if len( outputTuple[ 1 ] ) != 0:
00910                 print '%s INFO : SCRAM error'%( self._label )
00911                 if debug:
00912                     print '    from trying to determine last valid releases before \'%s\''%( cmsswVersion )
00913                     print
00914                     print outputTuple[ 1 ]
00915                     print
00916                     self.messageEmptyList()
00917                 return filePaths
00918             versions = { 'last'      :''
00919                        , 'lastToLast':''
00920                        }
00921             for line in outputTuple[ 0 ].splitlines():
00922                 version = line.split()[ 1 ]
00923                 if cmsswVersion.split( ibId )[ 0 ] in version or cmsswVersion.rpartition( '_' )[ 0 ] in version:
00924                     if not ( patchId in version or hltPatchId in version or dqmPatchId in version or slhcId in version or ibId in version or rootId in version ):
00925                         versions[ 'lastToLast' ] = versions[ 'last' ]
00926                         versions[ 'last' ]       = version
00927                         if version == cmsswVersion:
00928                             break
00929             # FIXME: ordering of output problematic ('XYZ_pre10' before 'XYZ_pre2', no "formerVersion" for 'XYZ_pre1')
00930             if formerVersion:
00931                 # Don't use pre-releases as "former version" for other releases than CMSSW_X_Y_0
00932                 if preId in versions[ 'lastToLast' ] and not preId in versions[ 'last' ] and not versions[ 'last' ].endswith( '_0' ):
00933                     versions[ 'lastToLast' ] = versions[ 'lastToLast' ].split( preId )[ 0 ] # works only, if 'CMSSW_X_Y_0' esists ;-)
00934                 # Use pre-release as "former version" for CMSSW_X_Y_0
00935                 elif versions[ 'last' ].endswith( '_0' ) and not ( preId in versions[ 'lastToLast' ] and versions[ 'lastToLast' ].startswith( versions[ 'last' ] ) ):
00936                     versions[ 'lastToLast' ] = ''
00937                     for line in outputTuple[ 0 ].splitlines():
00938                         version      = line.split()[ 1 ]
00939                         versionParts = version.partition( preId )
00940                         if versionParts[ 0 ] == versions[ 'last' ] and versionParts[ 1 ] == preId:
00941                             versions[ 'lastToLast' ] = version
00942                         elif versions[ 'lastToLast' ] != '':
00943                             break
00944                 # Don't use CMSSW_X_Y_0 as "former version" for pre-releases
00945                 elif preId in versions[ 'last' ] and not preId in versions[ 'lastToLast' ] and versions[ 'lastToLast' ].endswith( '_0' ):
00946                     versions[ 'lastToLast' ] = '' # no alternative :-(
00947                 cmsswVersion = versions[ 'lastToLast' ]
00948             else:
00949                 cmsswVersion = versions[ 'last' ]
00950 
00951         # Debugging output
00952         if debug:
00953             print '%s DEBUG: Called with...'%( self._label )
00954             for key in self._parameters.keys():
00955                print '    %s:\t'%( key ),
00956                print self._parameters[ key ].value,
00957                if self._parameters[ key ].value is self.getDefaultParameters()[ key ].value:
00958                    print ' (default)'
00959                else:
00960                    print
00961                if key == 'cmsswVersion' and cmsswVersion != self._parameters[ key ].value:
00962                    if formerVersion:
00963                        print '    ==> modified to last to last valid release %s (s. \'formerVersion\' parameter)'%( cmsswVersion )
00964                    else:
00965                        print '    ==> modified to last valid release %s'%( cmsswVersion )
00966 
00967         # Check domain
00968         domain = socket.getfqdn().split( '.' )
00969         domainSE = ''
00970         if len( domain ) == 0:
00971             print '%s INFO : Cannot determine domain of this computer'%( self._label )
00972             if debug:
00973                 self.messageEmptyList()
00974             return filePaths
00975         elif os.uname()[0] == "Darwin":
00976             print '%s INFO : Running on MacOSX without direct access to RelVal files.'%( self._label )
00977             if debug:
00978                 self.messageEmptyList()
00979             return filePaths
00980         elif len( domain ) == 1:
00981             print '%s INFO : Running on local host \'%s\' without direct access to RelVal files'%( self._label, domain[ 0 ] )
00982             if debug:
00983                 self.messageEmptyList()
00984             return filePaths
00985         if not ( ( domain[ -2 ] == 'cern' and domain[ -1 ] == 'ch' ) or ( domain[ -2 ] == 'fnal' and domain[ -1 ] == 'gov' ) ):
00986             print '%s INFO : Running on site \'%s.%s\' without direct access to RelVal files'%( self._label, domain[ -2 ], domain[ -1 ] )
00987             if debug:
00988                 self.messageEmptyList()
00989             return filePaths
00990         if domain[ -2 ] == 'cern':
00991             domainSE = 'T2_CH_CERN'
00992         elif domain[ -2 ] == 'fnal':
00993             domainSE = 'T1_US_FNAL_MSS'
00994         if debug:
00995             print '%s DEBUG: Running at site \'%s.%s\''%( self._label, domain[ -2 ], domain[ -1 ] )
00996             print '%s DEBUG: Looking for SE \'%s\''%( self._label, domainSE )
00997 
00998         # Find files
00999         validVersion = 0
01000         dataset    = ''
01001         datasetAll = '/%s/%s-%s-v*/%s'%( relVal, cmsswVersion, globalTag, dataTier )
01002         if useDAS:
01003             if debug:
01004                 print '%s DEBUG: Using DAS query'%( self._label )
01005             dasLimit = numberOfFiles
01006             if dasLimit <= 0:
01007                 dasLimit += 1
01008             for version in range( maxVersions, 0, -1 ):
01009                 filePaths    = []
01010                 filePathsTmp = []
01011                 fileCount    = 0
01012                 dataset = '/%s/%s-%s-v%i/%s'%( relVal, cmsswVersion, globalTag, version, dataTier )
01013                 dasQuery = 'file dataset=%s | grep file.name'%( dataset )
01014                 if debug:
01015                     print '%s DEBUG: Querying dataset \'%s\' with'%( self._label, dataset )
01016                     print '    \'%s\''%( dasQuery )
01017                 # partially stolen from das_client.py for option '--format=plain', needs filter ("grep") in the query
01018                 dasData     = das_client.get_data( 'https://cmsweb.cern.ch', dasQuery, 0, dasLimit, False )
01019                 jsondict    = json.loads( dasData )
01020                 if debug:
01021                     print '%s DEBUG: Received DAS data:'%( self._label )
01022                     print '    \'%s\''%( dasData )
01023                     print '%s DEBUG: Determined JSON dictionary:'%( self._label )
01024                     print '    \'%s\''%( jsondict )
01025                 if jsondict[ 'status' ] != 'ok':
01026                     print 'There was a problem while querying DAS with query \'%s\'. Server reply was:\n %s' % (dasQuery, dasData)
01027                     exit( 1 )
01028                 mongo_query = jsondict[ 'mongo_query' ]
01029                 filters     = mongo_query[ 'filters' ]
01030                 data        = jsondict[ 'data' ]
01031                 if debug:
01032                     print '%s DEBUG: Query in JSON dictionary:'%( self._label )
01033                     print '    \'%s\''%( mongo_query )
01034                     print '%s DEBUG: Filters in query:'%( self._label )
01035                     print '    \'%s\''%( filters )
01036                     print '%s DEBUG: Data in JSON dictionary:'%( self._label )
01037                     print '    \'%s\''%( data )
01038                 for row in data:
01039                     filePath = [ r for r in das_client.get_value( row, filters ) ][ 0 ]
01040                     if debug:
01041                         print '%s DEBUG: Testing file entry \'%s\''%( self._label, filePath )
01042                     if len( filePath ) > 0:
01043                         if validVersion != version:
01044                             dasTest         = das_client.get_data( 'https://cmsweb.cern.ch', 'site dataset=%s | grep site.name'%( dataset ), 0, 999, False )
01045                             jsontestdict    = json.loads( dasTest )
01046                             mongo_testquery = jsontestdict[ 'mongo_query' ]
01047                             testfilters = mongo_testquery[ 'filters' ]
01048                             testdata    = jsontestdict[ 'data' ]
01049                             if debug:
01050                                 print '%s DEBUG: Received DAS data (site test):'%( self._label )
01051                                 print '    \'%s\''%( dasTest )
01052                                 print '%s DEBUG: Determined JSON dictionary (site test):'%( self._label )
01053                                 print '    \'%s\''%( jsontestdict )
01054                                 print '%s DEBUG: Query in JSON dictionary (site test):'%( self._label )
01055                                 print '    \'%s\''%( mongo_testquery )
01056                                 print '%s DEBUG: Filters in query (site test):'%( self._label )
01057                                 print '    \'%s\''%( testfilters )
01058                                 print '%s DEBUG: Data in JSON dictionary (site test):'%( self._label )
01059                                 print '    \'%s\''%( testdata )
01060                             foundSE = False
01061                             for testrow in testdata:
01062                                 siteName = [ tr for tr in das_client.get_value( testrow, testfilters ) ][ 0 ]
01063                                 if siteName == domainSE:
01064                                     foundSE = True
01065                                     break
01066                             if not foundSE:
01067                                 if debug:
01068                                     print '%s DEBUG: Possible version \'v%s\' not available on SE \'%s\''%( self._label, version, domainSE )
01069                                 break
01070                             validVersion = version
01071                             if debug:
01072                                 print '%s DEBUG: Valid version set to \'v%i\''%( self._label, validVersion )
01073                         if numberOfFiles == 0:
01074                             break
01075                         # protect from double entries ( 'unique' flag in query does not work here)
01076                         if not filePath in filePathsTmp:
01077                             filePathsTmp.append( filePath )
01078                             if debug:
01079                                 print '%s DEBUG: File \'%s\' found'%( self._label, filePath )
01080                             fileCount += 1
01081                             # needed, since and "limit" overrides "idx" in 'get_data' (==> "idx" set to '0' rather than "skipFiles")
01082                             if fileCount > skipFiles:
01083                                 filePaths.append( filePath )
01084                         elif debug:
01085                             print '%s DEBUG: File \'%s\' found again'%( self._label, filePath )
01086                 if validVersion > 0:
01087                     if numberOfFiles == 0 and debug:
01088                         print '%s DEBUG: No files requested'%( self._label )
01089                     break
01090         else:
01091             if debug:
01092                 print '%s DEBUG: Using DBS query'%( self._label )
01093             for version in range( maxVersions, 0, -1 ):
01094                 filePaths = []
01095                 fileCount = 0
01096                 dataset = '/%s/%s-%s-v%i/%s'%( relVal, cmsswVersion, globalTag, version, dataTier )
01097                 dbsQuery = 'find file where dataset = %s'%( dataset )
01098                 if debug:
01099                     print '%s DEBUG: Querying dataset \'%s\' with'%( self._label, dataset )
01100                     print '    \'%s\''%( dbsQuery )
01101                 foundSE = False
01102                 for line in os.popen( 'dbs search --query="%s"'%( dbsQuery ) ):
01103                     if line.find( '.root' ) != -1:
01104                         if validVersion != version:
01105                             if not foundSE:
01106                                 dbsSiteQuery = 'find dataset where dataset = %s and site = %s'%( dataset, domainSE )
01107                                 if debug:
01108                                     print '%s DEBUG: Querying site \'%s\' with'%( self._label, domainSE )
01109                                     print '    \'%s\''%( dbsSiteQuery )
01110                                 for lineSite in os.popen( 'dbs search --query="%s"'%( dbsSiteQuery ) ):
01111                                     if lineSite.find( dataset ) != -1:
01112                                         foundSE = True
01113                                         break
01114                             if not foundSE:
01115                                 if debug:
01116                                     print '%s DEBUG: Possible version \'v%s\' not available on SE \'%s\''%( self._label, version, domainSE )
01117                                 break
01118                             validVersion = version
01119                             if debug:
01120                                 print '%s DEBUG: Valid version set to \'v%i\''%( self._label, validVersion )
01121                         if numberOfFiles == 0:
01122                             break
01123                         filePath = line.replace( '\n', '' )
01124                         if debug:
01125                             print '%s DEBUG: File \'%s\' found'%( self._label, filePath )
01126                         fileCount += 1
01127                         if fileCount > skipFiles:
01128                             filePaths.append( filePath )
01129                         if not numberOfFiles < 0:
01130                             if numberOfFiles <= len( filePaths ):
01131                                 break
01132                 if validVersion > 0:
01133                     if numberOfFiles == 0 and debug:
01134                         print '%s DEBUG: No files requested'%( self._label )
01135                     break
01136 
01137         # Check output and return
01138         if validVersion == 0:
01139             print '%s INFO : No RelVal file(s) found at all in datasets \'%s*\' on SE \'%s\''%( self._label, datasetAll, domainSE )
01140             if debug:
01141                 self.messageEmptyList()
01142         elif len( filePaths ) == 0:
01143             print '%s INFO : No RelVal file(s) picked up in dataset \'%s\''%( self._label, dataset )
01144             if debug:
01145                 self.messageEmptyList()
01146         elif len( filePaths ) < numberOfFiles:
01147             print '%s INFO : Only %i RelVal file(s) instead of %i picked up in dataset \'%s\''%( self._label, len( filePaths ), numberOfFiles, dataset )
01148 
01149         if debug:
01150             print '%s DEBUG: returning %i file(s):\n%s'%( self._label, len( filePaths ), filePaths )
01151         return filePaths
01152 
01153 pickRelValInputFiles = PickRelValInputFiles()