CMS 3D CMS Logo

JetHT_cfg.py
Go to the documentation of this file.
1 '''
2 cfg to produce alignment validation plots from JetHT sample
3 here doing refit of tracks and vertices using latest alignment
4 '''
5 
6 # Define the process
7 import FWCore.ParameterSet.Config as cms
8 from Alignment.OfflineValidation.TkAlAllInOneTool.defaultInputFiles_cff import filesDefaultData_JetHTRun2018D
9 process = cms.Process("JetHTAnalyzer")
10 
11 # Choose whether to run with Monte Carlo or data settings based on command line argument
12 import FWCore.ParameterSet.VarParsing as VarParsing
13 
15 options.register ('config',
16  "", # Default file
17  VarParsing.VarParsing.multiplicity.singleton, # singleton or list
18  VarParsing.VarParsing.varType.string, # string, int, or float
19  "AllInOne config.")
20 options.register ('runType',
21  "condor", # Default type
22  VarParsing.VarParsing.multiplicity.singleton, # singleton or list
23  VarParsing.VarParsing.varType.string, # string, int, or float
24  "AllInOne config.")
25 options.register ('jobNumber',
26  -1, # Default value
27  VarParsing.VarParsing.multiplicity.singleton, # singleton or list
28  VarParsing.VarParsing.varType.int, # string, int, or float
29  "AllInOne config.")
30 options.parseArguments()
31 
32 #Read in AllInOne config in JSON format
33 import json
34 import os
35 import re
36 
37 if options.config == "":
38  configuration = {"validation": {},
39  "alignment": {}}
40 else:
41  with open(options.config, "r") as configFile:
42  configuration = json.load(configFile)
43 
44 # Read parameters from the configuration file
45 useMC = configuration["validation"].get("mc", False)
46 printTriggers = configuration["validation"].get("printTriggers", False)
47 triggerFilter = str(configuration["validation"].get("triggerFilter", "nothing"))
48 iovListFile = str(configuration["validation"].get("iovListFile", "nothing"))
49 iovListList = configuration["validation"].get("iovList", [0,500000])
50 ptBorders = configuration["validation"].get("profilePtBorders", [3,5,10,20,50,100])
51 trackCollection = str(configuration["validation"].get("trackCollection", "ALCARECOTkAlMinBias"))
52 maxEventsToRun = configuration["validation"].get("maxevents", 1)
53 filesPerJob = configuration["validation"].get("filesPerJob", 5)
54 runsInFiles = configuration.get("runsInFiles",[])
55 
56 # The default global tag is suiteble for the unit test file for data
57 globalTag = str(configuration["alignment"].get("globaltag", "auto:run2_data"))
58 
59 # Alignment conditions can be also loaded from a configuration file instead of database
60 alignmentFile = str(configuration["validation"].get("TrackerAlignmentRcdFile", "nothing"))
61 alignmentErrorFile = str(configuration["validation"].get("TrackerAlignmentErrorFile", "nothing"))
62 
63 
64 # If IOV list file is given, read the IOV:s from the file
65 if not (iovListFile == "nothing" or iovListFile == ""):
66 
67  # Expand CMSSW_BASE
68  iovListFile = iovListFile.replace("CMSSW_BASE", os.environ["CMSSW_BASE"])
69 
70  # Read the file
71  iovListList = []
72  iovReader = open(iovListFile,"r")
73  iovContents = iovReader.readlines()
74 
75  for line in iovContents:
76  lineContents = line.split()
77  iovListList.append(int(lineContents[0]))
78 
79  # Add a dummy run to the end of the list to make the last number its own IOV
80  iovListList.append(iovListList[-1]+100)
81 
82 
83 
86 process.load("FWCore.MessageService.MessageLogger_cfi")
87 process.MessageLogger.cerr.FwkReport.reportEvery = 1000
88 process.MessageLogger.cout.enableStatistics = cms.untracked.bool(True)
89 
90 # If maxEvents not specified, only do one event
91 process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(maxEventsToRun) )
92 
93 
96 process.load("RecoVertex.BeamSpotProducer.BeamSpot_cff")
97 process.load("Configuration.Geometry.GeometryDB_cff")
98 process.load('Configuration.StandardSequences.Services_cff')
99 process.load("Configuration.StandardSequences.MagneticField_cff")
100 
101 
102 readFiles = []
103 
104 if "dataset" in configuration["validation"]:
105 
106  # We have defined a CMS dataset
107  if re.match( r'^/[^/.]+/[^/.]+/[^/.]+$', configuration["validation"]["dataset"] ):
108 
109 
110  process.source = cms.Source("PoolSource",
111  fileNames = cms.untracked.vstring("dummy.dat"),
112  skipEvents = cms.untracked.uint32(0)
113  )
114 
115  # We are dealing with a filelist
116  else:
117  with open(configuration["validation"]["dataset"], "r") as datafiles:
118  for fileName in datafiles.readlines():
119  readFiles.append(fileName.replace("\n", ""))
120 
121  # If we do run number based splitting, only read the files that correspond to the current run number
122  if len(runsInFiles) > 0:
123  newFiles = []
124  for line in readFiles:
125  runAndFile = line.split()
126  if runsInFiles[options.jobNumber] == runAndFile[0]:
127  newFiles.append(runAndFile[1])
128  readFiles = newFiles
129 
130 
131  process.source = cms.Source("PoolSource",
132  fileNames = cms.untracked.vstring(readFiles),
133  eventsToProcess = cms.untracked.VEventRange("{}:1-{}:max".format(runsInFiles[options.jobNumber], runsInFiles[options.jobNumber]))
134  )
135 
136 
137  elif options.jobNumber >= 0:
138  newFiles = []
139  numberOfFiles = len(readFiles)
140  firstIndex = filesPerJob * options.jobNumber
141  for fileIndex in range(firstIndex, firstIndex+filesPerJob):
142  if fileIndex >= numberOfFiles:
143  break
144  newFiles.append(readFiles[fileIndex])
145  readFiles = newFiles
146 
147 
148  process.source = cms.Source("PoolSource",
149  fileNames = cms.untracked.vstring(readFiles),
150  skipEvents = cms.untracked.uint32(0)
151  )
152 
153 
154  else:
155 
156  process.source = cms.Source("PoolSource",
157  fileNames = cms.untracked.vstring(readFiles),
158  skipEvents = cms.untracked.uint32(0)
159  )
160 
161 # If no text file with dataset given, read default file
162 else:
163  print(">>>>>>>>>> JetHT_cfg.py: msg%-i: dataset not specified in configuration! Loading default file!")
164 
165  if useMC:
166  print(">>>>>>>>>> JetHT_cfg.py: msg%-i: Default file for 2018 MC from 170-300 pT hat bin.")
167  process.source = cms.Source("PoolSource",
168  fileNames = cms.untracked.vstring('root://xrootd-cms.infn.it//store/mc/RunIIWinter19PFCalibDRPremix/QCD_Pt_170to300_TuneCP5_13TeV_pythia8/ALCARECO/TkAlMinBias-2018Conditions_105X_upgrade2018_realistic_v4-v1/270000/C42688BC-7401-3A41-9008-7CD1CA4B09E1.root')
169  )
170  else:
171  print(">>>>>>>>>> JetHT_cfg.py: msg%-i: Default file read from 2018D JetHT dataset.")
172  process.source = cms.Source("PoolSource",
173  fileNames = filesDefaultData_JetHTRun2018D)
174 
175 
178 process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
179 from Configuration.AlCa.GlobalTag import GlobalTag
180 process.GlobalTag = GlobalTag(process.GlobalTag, globalTag)
181 
182 
185 
187 
188 # Determine tracker conditions if defined in the configuration
189 if "conditions" in configuration["alignment"]:
191 
192  for condition in configuration["alignment"]["conditions"]:
193  setattr(process, "conditionsIn{}".format(condition), poolDBESSource.clone(
194  connect = cms.string(str(configuration["alignment"]["conditions"][condition]["connect"])),
195  toGet = cms.VPSet(
196  cms.PSet(
197  record = cms.string(str(condition)),
198  tag = cms.string(str(configuration["alignment"]["conditions"][condition]["tag"]))
199  )
200  )
201  )
202  )
203 
204  setattr(process, "prefer_conditionsIn{}".format(condition), cms.ESPrefer("PoolDBESSource", "conditionsIn{}".format(condition)))
205 
206 # If the reference to the database is not provided, check if a database file is provided
207 if not (alignmentFile == "nothing" or alignmentFile == ""):
208  process.conditionsInTrackerAlignmentRcd = CalibTracker.Configuration.Common.PoolDBESSource_cfi.poolDBESSource.clone(
209  connect = cms.string("sqlite_file:" + alignmentFile),
210  toGet = cms.VPSet(cms.PSet(record = cms.string('TrackerAlignmentRcd'),
211  tag = cms.string('Alignments')
212  )
213  )
214  )
215  process.prefer_conditionsInTrackerAlignmentRcd = cms.ESPrefer("PoolDBESSource", "conditionsInTrackerAlignmentRcd")
216 
217 # If the reference to the database is not provided, check if a database file is provided
218 if not (alignmentErrorFile == "nothing" or alignmentErrorFile == ""):
219  process.conditionsInTrackerAlignmentErrorExtendedRcd = CalibTracker.Configuration.Common.PoolDBESSource_cfi.poolDBESSource.clone(
220  connect = cms.string("sqlite_file:" + alignmentErrorFile),
221  toGet = cms.VPSet(cms.PSet(record = cms.string('TrackerAlignmentErrorExtendedRcd'),
222  tag = cms.string('APEs')
223  )
224  )
225  )
226  process.prefer_conditionsInTrackerAlignmentErrorExtendedRcd = cms.ESPrefer("PoolDBESSource", "conditionsInTrackerAlignmentErrorExtendedRcd")
227 
228 
231 
232 
233 # Setup track refitter
234 process.load("RecoTracker.TrackProducer.TrackRefitters_cff")
235 # remove the following lines if you run on RECO files
236 process.TrackRefitter.src = trackCollection
237 process.TrackRefitter.NavigationSchool = ""
238 
239 
240 process.load("TrackingTools.TransientTrack.TransientTrackBuilder_cfi")
241 
242 from RecoVertex.PrimaryVertexProducer.OfflinePrimaryVertices_cfi import offlinePrimaryVertices
243 process.offlinePrimaryVerticesFromRefittedTrks = offlinePrimaryVertices.clone()
244 process.offlinePrimaryVerticesFromRefittedTrks.TrackLabel = cms.InputTag("TrackRefitter")
245 process.offlinePrimaryVerticesFromRefittedTrks.vertexCollections.maxDistanceToBeam = 1
246 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.maxNormalizedChi2 = 20
247 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.minSiliconLayersWithHits = 5
248 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.maxD0Significance = 5.0
249 process.offlinePrimaryVerticesFromRefittedTrks.TkFilterParameters.minPixelLayersWithHits = 2
250 
251 
255 if not (triggerFilter == "nothing" or triggerFilter == ""):
256  triggerPath = triggerFilter
257  process.HLTFilter = triggerResultsFilter.clone(
258  triggerConditions = cms.vstring(triggerPath),
259  hltResults = cms.InputTag( "TriggerResults", "", "HLT" ),
260  l1tResults = cms.InputTag( "" ),
261  throw = cms.bool(False)
262  )
263 
264 
267 from Alignment.OfflineValidation.jetHTAnalyzer_cfi import jetHTAnalyzer as _jetHTAnalyzer
268 process.jetHTAnalyzer = _jetHTAnalyzer.clone(
269  vtxCollection = "offlinePrimaryVerticesFromRefittedTrks",
270  trackCollection = "TrackRefitter",
271  triggerResults = ("TriggerResults","","HLT"),
272  printTriggerTable = printTriggers,
273  minVertexNdf = 10.,
274  minVertexMeanWeight = 0.5,
275  profilePtBorders = ptBorders,
276  iovList = iovListList)
277 
278 jobNumberString = ""
279 if options.jobNumber >= 0:
280  jobNumberString = "_{}".format(options.jobNumber)
281 
282 outputName = "{}/JetHTAnalysis{}.root".format(configuration.get("output", os.getcwd()), jobNumberString)
283 if options.runType == "crab":
284  outputName = "JetHTAnalysis.root"
285 
286 process.TFileService = cms.Service("TFileService",
287  fileName = cms.string(outputName),
288  closeFileFast = cms.untracked.bool(False)
289  )
290 
291 
292 if (triggerFilter == "nothing" or triggerFilter == ""):
293  process.p = cms.Path(process.offlineBeamSpot +
294  process.TrackRefitter +
295  process.offlinePrimaryVerticesFromRefittedTrks +
296  process.jetHTAnalyzer)
297 else:
298  process.p = cms.Path(process.HLTFilter +
299  process.offlineBeamSpot +
300  process.TrackRefitter +
301  process.offlinePrimaryVerticesFromRefittedTrks +
302  process.jetHTAnalyzer)
303 
304 
The trigger filter module.
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
#define str(s)