Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2022-11-09 11:29:19

0001 import FWCore.ParameterSet.Config as cms
0002 import FWCore.PythonUtilities.LumiList as LumiList
0003 from Alignment.OfflineValidation.TkAlAllInOneTool.defaultInputFiles_cff import filesDefaultData_MinBias2018B
0004 
0005 from FWCore.ParameterSet.VarParsing import VarParsing
0006 
0007 from Alignment.OfflineValidation.TkAlAllInOneTool.utils import _byteify
0008 import json
0009 import os
0010 
0011 ##Define process
0012 process = cms.Process("PrimaryVertexValidation")
0013 
0014 ##Argument parsing
0015 options = VarParsing()
0016 options.register("config", "", VarParsing.multiplicity.singleton, VarParsing.varType.string , "AllInOne config")
0017 
0018 options.parseArguments()
0019 
0020 ##Read in AllInOne config in JSON format
0021 if options.config == "":
0022     config = {"validation": {},
0023               "alignment": {}}
0024 else:
0025     with open(options.config, "r") as configFile:
0026         config = json.load(configFile)
0027 
0028 isDA = config["validation"].get("isda", True)
0029 isMC = config["validation"].get("ismc", True)
0030 
0031 runboundary = config["validation"].get("runboundary", 1)
0032 
0033 ##Read filenames from given TXT file and define input source
0034 readFiles = []
0035 
0036 if "dataset" in config["validation"]:
0037     with open(config["validation"]["dataset"], "r") as datafiles:
0038         for fileName in datafiles.readlines():
0039             readFiles.append(fileName.replace("\n", ""))
0040 
0041     process.source = cms.Source("PoolSource",
0042                                 fileNames = cms.untracked.vstring(readFiles),
0043                                 skipEvents = cms.untracked.uint32(0)
0044                             )
0045 else:
0046     print(">>>>>>>>>> PV_cfg.py: msg%-i: config not specified! Loading default dataset -> filesDefaultData_MinBias2018B!")
0047     process.source = cms.Source("PoolSource",
0048                                 fileNames = filesDefaultData_MinBias2018B,
0049                                 skipEvents = cms.untracked.uint32(0)
0050                             )
0051 
0052 ##Get good lumi section and load data or handle MC
0053 if "goodlumi" in config["validation"]:
0054     if os.path.isfile(config["validation"]["goodlumi"]):
0055         goodLumiSecs = cms.untracked.VLuminosityBlockRange(LumiList.LumiList(filename = config["validation"]["goodlumi"]).getCMSSWString().split(','))
0056         
0057     else:
0058         print("Does not exist: {}. Continue without good lumi section file.")
0059         goodLumiSecs = cms.untracked.VLuminosityBlockRange()
0060 
0061 else:
0062     goodLumiSecs = cms.untracked.VLuminosityBlockRange()
0063 
0064 if isMC:
0065      print(">>>>>>>>>> PV_cfg.py: msg%-i: This is simulation!")
0066      runboundary = 1
0067 else:
0068      process.source.lumisToProcess = goodLumiSecs
0069 
0070 isMultipleRuns=False
0071 if(isinstance(runboundary, (list, tuple))):
0072      isMultipleRuns=True
0073      print("Multiple Runs are selected")       
0074 if(isMultipleRuns):
0075      process.source.firstRun = cms.untracked.uint32(runboundary[0])
0076 else:
0077      process.source.firstRun = cms.untracked.uint32(runboundary)
0078 
0079 ##default set to 1 for unit tests
0080 process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(config["validation"].get("maxevents", 1)))
0081 
0082 ##Bookeeping
0083 process.options = cms.untracked.PSet(
0084    wantSummary = cms.untracked.bool(False),
0085    Rethrow = cms.untracked.vstring("ProductNotFound"),
0086    fileMode  =  cms.untracked.string('NOMERGE'),
0087 )
0088 
0089 process.load("FWCore.MessageLogger.MessageLogger_cfi")
0090 process.MessageLogger = cms.Service("MessageLogger",
0091                                     destinations   = cms.untracked.vstring('cerr'),
0092                                     cerr       = cms.untracked.PSet(threshold = cms.untracked.string('INFO'))
0093                                    )
0094 
0095 ##Basic modules
0096 process.load("RecoVertex.BeamSpotProducer.BeamSpot_cff")
0097 process.load("Configuration.Geometry.GeometryRecoDB_cff") #or process.load("Configuration.Geometry.GeometryDB_cff")?????
0098 process.load('Configuration.StandardSequences.Services_cff')
0099 process.load("Configuration.StandardSequences.MagneticField_cff")
0100 
0101 ####################################################################
0102 # Produce the Transient Track Record in the event
0103 ####################################################################
0104 process.load("TrackingTools.TransientTrack.TransientTrackBuilder_cfi")
0105 
0106 ####################################################################
0107 # Load and Configure Common Track Selection and refitting sequence
0108 ####################################################################
0109 import Alignment.CommonAlignment.tools.trackselectionRefitting as trackselRefit
0110 process.seqTrackselRefit = trackselRefit.getSequence(process,
0111                                                      config["validation"].get("trackcollection", "ALCARECOTkAlMinBias"),
0112                                                      isPVValidation=True,
0113                                                      TTRHBuilder=config["validation"].get("tthrbuilder", "WithAngleAndTemplate"),
0114                                                      usePixelQualityFlag=config["validation"].get("usePixelQualityFlag", True),
0115                                                      openMassWindow=False,
0116                                                      cosmicsDecoMode=True,
0117                                                      cosmicsZeroTesla=config["validation"].get("cosmicsZeroTesla", False),                                                     
0118                                                      momentumConstraint=None,
0119                                                      cosmicTrackSplitting=False,
0120                                                      use_d0cut=False,
0121                                                      )
0122 
0123 #Global tag
0124 process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
0125 from Configuration.AlCa.GlobalTag import GlobalTag
0126 process.GlobalTag = GlobalTag(process.GlobalTag, config["alignment"].get("globaltag", "auto:phase1_2017_realistic"))
0127 
0128 ##Load conditions if wished
0129 if "conditions" in config["alignment"]:
0130     from CalibTracker.Configuration.Common.PoolDBESSource_cfi import poolDBESSource
0131 
0132     for condition in config["alignment"]["conditions"]:
0133         setattr(process, "conditionsIn{}".format(condition), poolDBESSource.clone(
0134              connect = cms.string(str(config["alignment"]["conditions"][condition]["connect"])),
0135              toGet = cms.VPSet(
0136                         cms.PSet(
0137                                  record = cms.string(str(condition)),
0138                                  tag = cms.string(str(config["alignment"]["conditions"][condition]["tag"]))
0139                         )
0140                      )
0141             )
0142         )
0143 
0144         setattr(process, "prefer_conditionsIn{}".format(condition), cms.ESPrefer("PoolDBESSource", "conditionsIn{}".format(condition)))
0145 
0146 ####################################################################
0147 # Load and Configure event selection
0148 ####################################################################
0149 process.primaryVertexFilter = cms.EDFilter("VertexSelector",
0150                                            src = cms.InputTag(config["validation"].get("vertexcollection", "offlinePrimaryVertices")),
0151                                            cut = cms.string("!isFake && ndof > 4 && abs(z) <= 24 && position.Rho <= 2"),
0152                                            filter = cms.bool(True)
0153                                            )
0154 
0155 process.noscraping = cms.EDFilter("FilterOutScraping",
0156                                   applyfilter = cms.untracked.bool(True),
0157                                   src = cms.untracked.InputTag(config["validation"].get("trackcollection", "ALCARECOTkAlMinBias")),
0158                                   debugOn = cms.untracked.bool(False),
0159                                   numtrack = cms.untracked.uint32(10),
0160                                   thresh = cms.untracked.double(0.25)
0161                                   )
0162 
0163 process.load("Alignment.CommonAlignment.filterOutLowPt_cfi")
0164 process.filterOutLowPt.src = cms.untracked.InputTag(config["validation"].get("trackcollection", "ALCARECOTkAlMinBias"))
0165 process.filterOutLowPt.ptmin = cms.untracked.double(config["validation"].get("ptCut", 3.))
0166 process.filterOutLowPt.runControl = False
0167 if(isMultipleRuns):
0168      process.filterOutLowPt.runControlNumber.extend((runboundary))
0169 else:
0170      process.filterOutLowPt.runControlNumber = [runboundary]
0171 
0172 if isMC:
0173      process.goodvertexSkim = cms.Sequence(process.noscraping + process.filterOutLowPt)
0174 else:
0175      process.goodvertexSkim = cms.Sequence(process.primaryVertexFilter + process.noscraping + process.filterOutLowPt)
0176 
0177 
0178 ####################################################################
0179 # Imports of parameters
0180 ####################################################################
0181 from RecoVertex.PrimaryVertexProducer.OfflinePrimaryVertices_cfi import offlinePrimaryVertices
0182 ## modify the parameters which differ
0183 FilteringParams = offlinePrimaryVertices.TkFilterParameters.clone(
0184      maxNormalizedChi2 = 5.0,  # chi2ndof < 5
0185      maxD0Significance = 5.0,  # fake cut (requiring 1 PXB hit)
0186      maxEta = 5.0,             # as per recommendation in PR #18330
0187 )
0188 
0189 ## MM 04.05.2017 (use settings as in: https://github.com/cms-sw/cmssw/pull/18330)
0190 from RecoVertex.PrimaryVertexProducer.TkClusParameters_cff import DA_vectParameters
0191 DAClusterizationParams = DA_vectParameters.clone()
0192 
0193 GapClusterizationParams = cms.PSet(algorithm   = cms.string('gap'),
0194                                    TkGapClusParameters = cms.PSet(zSeparation = cms.double(0.2))  # 0.2 cm max separation betw. clusters
0195                                    )
0196 
0197 ####################################################################
0198 # Deterministic annealing clustering or Gap clustering
0199 ####################################################################
0200 def switchClusterizerParameters(da):
0201      if da:
0202           print(">>>>>>>>>> testPVValidation_cfg.py: msg%-i: Running DA Algorithm!")
0203           return DAClusterizationParams
0204      else:
0205           print(">>>>>>>>>> testPVValidation_cfg.py: msg%-i: Running GAP Algorithm!")
0206           return GapClusterizationParams
0207 
0208 ####################################################################
0209 # Configure the PVValidation Analyzer module
0210 ####################################################################
0211 process.PVValidation = cms.EDAnalyzer("PrimaryVertexValidation",
0212                                       TrackCollectionTag = cms.InputTag("FinalTrackRefitter"),
0213                                       VertexCollectionTag = cms.InputTag(config["validation"].get("vertexcollection", "offlinePrimaryVertices")),
0214                                       Debug = cms.bool(False),
0215                                       storeNtuple = cms.bool(False),
0216                                       useTracksFromRecoVtx = cms.bool(False),
0217                                       isLightNtuple = cms.bool(True),
0218                                       askFirstLayerHit = cms.bool(False),
0219                                       forceBeamSpot = cms.untracked.bool(config["validation"].get("forceBeamSpot", False)),
0220                                       probePt  = cms.untracked.double(config["validation"].get("ptCut", 3)),
0221                                       probeEta  = cms.untracked.double(config["validation"].get("etaCut", 2.5)),
0222                                       minPt  = cms.untracked.double(config["validation"].get("minPt", 1.)),
0223                                       maxPt  = cms.untracked.double(config["validation"].get("maxPt", 30.)),
0224                                       doBPix   = cms.untracked.bool(config["validation"].get("doBPix", True)),
0225                                       doFPix   = cms.untracked.bool(config["validation"].get("doFPix", True)),
0226                                       numberOfBins = cms.untracked.int32(config["validation"].get("numberOfBins", 48)),
0227                                       runControl = cms.untracked.bool(config["validation"].get("runControl", False)),
0228                                       runControlNumber = cms.untracked.vuint32(runboundary),
0229                                       TkFilterParameters = FilteringParams,
0230                                       TkClusParameters = switchClusterizerParameters(isDA)
0231                                       )
0232 
0233 ####################################################################
0234 # Output file
0235 ####################################################################
0236 process.TFileService = cms.Service("TFileService",
0237             fileName = cms.string("{}/PVValidation_{}_{}.root".format(config.get("output", os.getcwd()), config["alignment"].get("name", ""), config["validation"].get("IOV", 1.))),
0238             closeFileFast = cms.untracked.bool(True),
0239     )
0240 
0241 ####################################################################
0242 # Path
0243 ####################################################################
0244 process.p = cms.Path(process.goodvertexSkim*process.seqTrackselRefit*process.PVValidation)
0245 
0246 print("Done")