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