CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
trackselectionRefitting.py
Go to the documentation of this file.
1 from __future__ import print_function
2 import sys
3 import FWCore.ParameterSet.Config as cms
4 
5 
6 
7 def getSequence(process, collection,
8  saveCPU = False,
9  TTRHBuilder = "WithAngleAndTemplate",
10  usePixelQualityFlag = None,
11  openMassWindow = False,
12  cosmicsDecoMode = False,
13  cosmicsZeroTesla = True,
14  momentumConstraint = None,
15  cosmicTrackSplitting = False,
16  isPVValidation = False,
17  use_d0cut = True):
18  """This function returns a cms.Sequence containing as last element the
19  module 'FinalTrackRefitter', which can be used as cms.InputTag for
20  subsequent processing steps.
21  The modules in the sequence are already attached to the given `process`
22  object using the given track collection `collection` and the given
23  optional arguments.
24 
25  Arguments:
26  - `process`: 'cms.Process' object to which the modules of the sequence will
27  be attached.
28  - `collection`: String indicating the input track collection.
29  - `saveCPU`: If set to 'True', some steps are merged to reduce CPU time.
30  Reduces a little the accuracy of the results.
31  This option is currently not recommended.
32  - `TTRHBuilder`: Option used for the Track(Re)Fitter modules.
33  - `usePixelQualityFlag`: Option used for the TrackHitFilter module.
34  Defaults to 'True' but is automatically set to
35  'False' if a `TTRHBuilder` without templates is
36  used.
37  If this is still wanted for some reason, one can
38  explicitely specify it as 'True'.
39  - `openMassWindow`: Used to configure the TwoBodyDecaySelector for ZMuMu.
40  - `cosmicsDecoMode`: If set to 'True' a lower Signal/Noise cut is used.
41  - `cosmicsZeroTesla`: If set to 'True' a 0T-specific selection is used.
42  - `momentumConstraint`: If you want to apply a momentum constraint for the
43  track refitting, e.g. for CRUZET data, you need
44  to provide here the name of the constraint module.
45  - `cosmicTrackSplitting`: If set to 'True' cosmic tracks are split before the
46  second track refitter.
47  - `isPVValidation`: If set to 'True' most of the selection cuts are overridden
48  to allow unbiased selection of tracks for vertex refitting
49  - `use_d0cut`: If 'True' (default), apply a cut |d0| < 50.
50  """
51 
52  ###################################################
53  # resolve default values incl. consistency checks #
54  ###################################################
55 
56  if usePixelQualityFlag is None:
57  if "Template" not in TTRHBuilder:
58  usePixelQualityFlag = False # not defined without templates
59  print("Using 'TTRHBuilder' without templates:", TTRHBuilder)
60  print(" --> Turning off pixel quality flag in hit filter.")
61  else:
62  usePixelQualityFlag = True # default for usage with templates
63 
64 
65  #############################
66  ## setting general options ##
67  #############################
68 
69  options = {"TrackHitFilter": {},
70  "TrackFitter": {},
71  "TrackRefitter": {},
72  "TrackSelector": {}}
73 
74  options["TrackSelector"]["HighPurity"] = {
75  "trackQualities": ["highPurity"],
76  "filter": True,
77  "etaMin": -3.0,
78  "etaMax": 3.0,
79  "pMin": 8.0
80  }
81  options["TrackSelector"]["Alignment"] = {
82  "filter": True,
83  "pMin": 3.0,
84  "nHitMin2D": 2,
85  "d0Min": -50.0,
86  "d0Max": 50.0,
87  "etaMin": -3.0,
88  "etaMax": 3.0,
89  "nHitMin": 8,
90  "chi2nMax": 9999.0
91  }
92  options["TrackRefitter"]["First"] = {
93  "NavigationSchool": "",
94  "TTRHBuilder": TTRHBuilder,
95  }
96  options["TrackRefitter"]["Second"] = {
97  "NavigationSchool": "",
98  "TTRHBuilder": TTRHBuilder,
99  }
100  options["TrackHitFilter"]["Tracker"] = {
101  "useTrajectories": True,
102  "minimumHits": 8,
103  "commands": cms.vstring("keep PXB", "keep PXE", "keep TIB", "keep TID",
104  "keep TOB", "keep TEC"),
105  "replaceWithInactiveHits": True,
106  "rejectBadStoNHits": True,
107  "rejectLowAngleHits": True,
108  "usePixelQualityFlag": usePixelQualityFlag,
109  "StoNcommands": cms.vstring("ALL 12.0"),
110  "TrackAngleCut": 0.087,
111  }
112  options["TrackFitter"]["HitFilteredTracks"] = {
113  "NavigationSchool": "",
114  "TTRHBuilder": TTRHBuilder,
115  }
116 
117 
118  #########################################
119  ## setting collection specific options ##
120  #########################################
121  isCosmics = False
122 
123  if collection in ("ALCARECOTkAlMinBias", "generalTracks",
124  "ALCARECOTkAlMinBiasHI", "hiGeneralTracks"):
125  options["TrackSelector"]["Alignment"].update({
126  "ptMin": 1.0,
127  "pMin": 8.,
128  })
129  options["TrackHitFilter"]["Tracker"].update({
130  "minimumHits": 10,
131  })
132  elif collection in ("ALCARECOTkAlCosmicsCTF0T",
133  "ALCARECOTkAlCosmicsCosmicTF0T",
134  "ALCARECOTkAlCosmicsInCollisions"):
135  isCosmics = True
136  options["TrackSelector"]["HighPurity"] = {} # drop high purity cut
137  if not cosmicsDecoMode:
138  options["TrackHitFilter"]["Tracker"].update({
139  "StoNcommands": cms.vstring("ALL 18.0")
140  })
141  if cosmicsZeroTesla:
142  options["TrackHitFilter"]["Tracker"].update({
143  "TrackAngleCut": 0.1 # Run-I: 0.087 for 0T
144  })
145  else:
146  options["TrackHitFilter"]["Tracker"].update({
147  "TrackAngleCut": 0.1 # Run-I: 0.35 for 3.8T
148  })
149  options["TrackSelector"]["Alignment"].update({
150  "pMin": 4.0,
151  "etaMin": -99.0,
152  "etaMax": 99.0,
153  "applyMultiplicityFilter": True,
154  "maxMultiplicity": 1
155  })
156  if cosmicTrackSplitting:
157  options["TrackSplitting"] = {}
158  options["TrackSplitting"]["TrackSplitting"] = {}
159  if not use_d0cut:
160  options["TrackSelector"]["Alignment"].update({
161  "d0Min": -99999.0,
162  "d0Max": 99999.0,
163  })
164  elif collection in ("ALCARECOTkAlMuonIsolated",
165  "ALCARECOTkAlMuonIsolatedHI",
166  "ALCARECOTkAlMuonIsolatedPA"):
167  options["TrackSelector"]["Alignment"].update({
168  ("minHitsPerSubDet", "inPIXEL"): 1,
169  "ptMin": 5.0,
170  "nHitMin": 10,
171  "applyMultiplicityFilter": True,
172  "maxMultiplicity": 1,
173  })
174  elif collection in ("ALCARECOTkAlZMuMu",
175  "ALCARECOTkAlZMuMuHI",
176  "ALCARECOTkAlZMuMuPA"):
177  options["TrackSelector"]["Alignment"].update({
178  "ptMin": 15.0,
179  "etaMin": -3.0,
180  "etaMax": 3.0,
181  "nHitMin": 10,
182  "applyMultiplicityFilter": True,
183  "minMultiplicity": 2,
184  "maxMultiplicity": 2,
185  ("minHitsPerSubDet", "inPIXEL"): 1,
186  ("TwoBodyDecaySelector", "applyChargeFilter"): True,
187  ("TwoBodyDecaySelector", "charge"): 0,
188  ("TwoBodyDecaySelector",
189  "applyMassrangeFilter"): not openMassWindow,
190  ("TwoBodyDecaySelector", "minXMass"): 85.8,
191  ("TwoBodyDecaySelector", "maxXMass"): 95.8,
192  ("TwoBodyDecaySelector", "daughterMass"): 0.105
193  })
194  options["TrackHitFilter"]["Tracker"].update({
195  "minimumHits": 10,
196  })
197  elif collection == "ALCARECOTkAlUpsilonMuMu":
198  options["TrackSelector"]["Alignment"].update({
199  "ptMin": 3.0,
200  "etaMin": -2.4,
201  "etaMax": 2.4,
202  "nHitMin": 10,
203  "applyMultiplicityFilter": True,
204  "minMultiplicity": 2,
205  "maxMultiplicity": 2,
206  ("minHitsPerSubDet", "inPIXEL"): 1,
207  ("TwoBodyDecaySelector", "applyChargeFilter"): True,
208  ("TwoBodyDecaySelector", "charge"): 0,
209  ("TwoBodyDecaySelector",
210  "applyMassrangeFilter"): not openMassWindow,
211  ("TwoBodyDecaySelector", "minXMass"): 9.2,
212  ("TwoBodyDecaySelector", "maxXMass"): 9.7,
213  ("TwoBodyDecaySelector", "daughterMass"): 0.105
214  })
215  options["TrackHitFilter"]["Tracker"].update({
216  "minimumHits": 10,
217  })
218  elif collection == "ALCARECOTkAlJpsiMuMu":
219  options["TrackSelector"]["Alignment"].update({
220  "ptMin": 1.0,
221  "etaMin": -2.4,
222  "etaMax": 2.4,
223  "nHitMin": 10,
224  "applyMultiplicityFilter": True,
225  "minMultiplicity": 2,
226  "maxMultiplicity": 2,
227  ("minHitsPerSubDet", "inPIXEL"): 1,
228  ("TwoBodyDecaySelector", "applyChargeFilter"): True,
229  ("TwoBodyDecaySelector", "charge"): 0,
230  ("TwoBodyDecaySelector",
231  "applyMassrangeFilter"): not openMassWindow,
232  ("TwoBodyDecaySelector", "minXMass"): 2.7,
233  ("TwoBodyDecaySelector", "maxXMass"): 3.4,
234  ("TwoBodyDecaySelector", "daughterMass"): 0.105
235  })
236  options["TrackHitFilter"]["Tracker"].update({
237  "minimumHits": 10,
238  })
239  else:
240  raise ValueError("Unknown input track collection: {}".format(collection))
241 
242  if cosmicTrackSplitting and not isCosmics:
243  raise ValueError("Can only do cosmic track splitting for cosmics.")
244 
245 
246 
247  ####################
248  ## save CPU time? ##
249  ####################
250 
251  if saveCPU:
252  if cosmicTrackSplitting:
253  raise ValueError("Can't turn on both saveCPU and cosmicTrackSplitting at the same time")
254  mods = [("TrackSelector", "Alignment", {"method": "load"}),
255  ("TrackRefitter", "First", {"method": "load",
256  "clone": True}),
257  ("TrackHitFilter", "Tracker", {"method": "load"}),
258  ("TrackFitter", "HitFilteredTracks", {"method": "import"})]
259  options["TrackSelector"]["Alignment"].update(
260  options["TrackSelector"]["HighPurity"])
261  elif cosmicTrackSplitting:
262  mods = [("TrackRefitter", "First", {"method": "load",
263  "clone": True}),
264  ("TrackSelector", "Alignment", {"method": "load"}),
265  ("TrackSplitting", "TrackSplitting", {"method": "load"}),
266  ("TrackFitter", "HitFilteredTracks", {"method": "import"}),
267  ("TrackRefitter", "Second", {"method": "load",
268  "clone": True})]
269  else:
270  mods = [("TrackSelector", "HighPurity", {"method": "import"}),
271  ("TrackRefitter", "First", {"method": "load",
272  "clone": True}),
273  ("TrackHitFilter", "Tracker", {"method": "load"}),
274  ("TrackFitter", "HitFilteredTracks", {"method": "import"}),
275  ("TrackSelector", "Alignment", {"method": "load"}),
276  ("TrackRefitter", "Second", {"method": "load",
277  "clone": True})]
278  if isCosmics: mods = mods[1:] # skip high purity selector for cosmics
279 
280  #############################
281  ## PV Validation cuts tune ##
282  #############################
283 
284  if isPVValidation:
285  options["TrackSelector"]["HighPurity"].update({
286  "trackQualities": [],
287  "pMin": 0.
288  })
289  options["TrackSelector"]["Alignment"].update({
290  "pMin" : 0.,
291  "ptMin" : 0.,
292  "nHitMin2D" : 0,
293  "nHitMin" : 0,
294  "d0Min" : -999999.0,
295  "d0Max" : 999999.0,
296  "dzMin" : -999999.0,
297  "dzMax" : 999999.0
298  })
299 
300  ################################
301  ## apply momentum constraint? ##
302  ################################
303 
304  if momentumConstraint is not None:
305  for mod in options["TrackRefitter"]:
306  momconstrspecs = momentumConstraint.split(',')
307  if len(momconstrspecs)==1:
308  options["TrackRefitter"][mod].update({
309  "constraint": "momentum",
310  "srcConstr": momconstrspecs[0]
311  })
312  else:
313  options["TrackRefitter"][mod].update({
314  "constraint": momconstrspecs[1],
315  "srcConstr": momconstrspecs[0]
316  })
317 
318 
319 
320  #######################################################
321  # load offline beam spot module required by the refit #
322  #######################################################
323  process.load("RecoVertex.BeamSpotProducer.BeamSpot_cff")
324 
325 
326 
327  ###############################
328  ## put the sequence together ##
329  ###############################
330 
331  modules = []
332  src = collection
333  prevsrc = None
334  for mod in mods[:-1]:
335  src, prevsrc = _getModule(process, src, mod[0], "".join(reversed(mod[:-1])),
336  options[mod[0]][mod[1]], isCosmics = isCosmics, prevsrc = prevsrc,
337  **(mod[2])), src
338  modules.append(getattr(process, src))
339  else:
340  if mods[-1][-1]["method"] == "load" and \
341  not mods[-1][-1].get("clone", False):
342  print("Name of the last module needs to be modifiable.")
343  sys.exit(1)
344  src = _getModule(process, src, mods[-1][0], "FinalTrackRefitter",
345  options[mods[-1][0]][mods[-1][1]],
346  isCosmics = isCosmics, **(mods[-1][2]))
347  modules.append(getattr(process, src))
348 
349  moduleSum = process.offlineBeamSpot # first element of the sequence
350  for module in modules:
351  # Spply srcConstr fix here
352  if hasattr(module,"srcConstr"):
353  strSrcConstr = module.srcConstr.getModuleLabel()
354  if strSrcConstr:
355  procsrcconstr = getattr(process,strSrcConstr)
356  if hasattr(procsrcconstr,"src"): # Momentum or track parameter constraints
357  if procsrcconstr.src != module.src:
358  module.srcConstr=''
359  module.constraint=''
360  else:
361  moduleSum += procsrcconstr # Add constraint
362  elif hasattr(procsrcconstr,"srcTrk"): # Vertex constraint
363  if procsrcconstr.srcTrk != module.src:
364  module.srcConstr=''
365  module.constraint=''
366  else:
367  procsrcconstrsrcvtx = getattr(process,procsrcconstr.srcVtx.getModuleLabel())
368  if type(procsrcconstrsrcvtx) is cms.EDFilter: # If source of vertices is itself a filter (e.g. good PVs)
369  procsrcconstrsrcvtxprefilter = getattr(process,procsrcconstrsrcvtx.src.getModuleLabel())
370  moduleSum += procsrcconstrsrcvtxprefilter # Add vertex source to constraint before filter
371  moduleSum += procsrcconstrsrcvtx # Add vertex source to constraint
372  moduleSum += procsrcconstr # Add constraint
373 
374  moduleSum += module # append the other modules
375 
376  return cms.Sequence(moduleSum)
377 
378 
379 
380 
381 
382 ###############################
383 ###############################
384 ### ###
385 ### Auxiliary functions ###
386 ### ###
387 ###############################
388 ###############################
389 
390 
391 def _getModule(process, src, modType, moduleName, options, **kwargs):
392  """General function for attaching the module of type `modType` to the
393  cms.Process `process` using `options` for customization and `moduleName` as
394  the name of the new attribute of `process`.
395 
396  Arguments:
397  - `process`: 'cms.Process' object to which the module is attached.
398  - `src`: cms.InputTag for this module.
399  - `modType`: Type of the requested module.
400  - `options`: Dictionary with customized values for the module's options.
401  - `**kwargs`: Used to supply options at construction time of the module.
402  """
403 
404  objTuple = globals()["_"+modType](kwargs)
405  method = kwargs.get("method")
406  if method == "import":
407  __import__(objTuple[0])
408  obj = getattr(sys.modules[objTuple[0]], objTuple[1]).clone()
409  elif method == "load":
410  process.load(objTuple[0])
411  if kwargs.get("clone", False):
412  obj = getattr(process, objTuple[1]).clone(src=src)
413  else:
414  obj = getattr(process, objTuple[1])
415  moduleName = objTuple[1]
416  else:
417  print("Unknown method:", method)
418  sys.exit(1)
419 
420  if modType == "TrackSplitting":
421  #track splitting takes the TrackSelector as tracks
422  # and the first TrackRefitter as tjTkAssociationMapTag
423  _customSetattr(obj, "tracks", src)
424  _customSetattr(obj, "tjTkAssociationMapTag", kwargs["prevsrc"])
425  else:
426  obj.src = src
427 
428  for option in options:
429  _customSetattr(obj, option, options[option])
430 
431  if moduleName is not objTuple[1]:
432  setattr(process, moduleName, obj)
433  return moduleName
434 
435 
436 def _TrackHitFilter(kwargs):
437  """Returns TrackHitFilter module name.
438 
439  Arguments:
440  - `kwargs`: Not used in this function.
441  """
442 
443  return ("RecoTracker.FinalTrackSelectors.TrackerTrackHitFilter_cff",
444  "TrackerTrackHitFilter")
445 
446 
447 def _TrackSelector(kwargs):
448  """Returns TrackSelector module name.
449 
450  Arguments:
451  - `kwargs`: Not used in this function.
452  """
453 
454  return ("Alignment.CommonAlignmentProducer.AlignmentTrackSelector_cfi",
455  "AlignmentTrackSelector")
456 
457 
458 def _TrackFitter(kwargs):
459  """Returns TrackFitter module name.
460 
461  Arguments:
462  - `kwargs`: Used to supply options at construction time of the object.
463  """
464 
465  isCosmics = kwargs.get("isCosmics", False)
466  if isCosmics:
467  return ("RecoTracker.TrackProducer.CTFFinalFitWithMaterialP5_cff",
468  "ctfWithMaterialTracksCosmics")
469  else:
470  return ("RecoTracker.TrackProducer.CTFFinalFitWithMaterial_cff",
471  "ctfWithMaterialTracks")
472 
473 
474 def _TrackRefitter(kwargs):
475  """Returns TrackRefitter module name.
476 
477  Arguments:
478  - `kwargs`: Used to supply options at construction time of the object.
479  """
480 
481  isCosmics = kwargs.get("isCosmics", False)
482  if isCosmics:
483  return ("RecoTracker.TrackProducer.TrackRefitters_cff",
484  "TrackRefitterP5")
485  else:
486  return ("RecoTracker.TrackProducer.TrackRefitters_cff",
487  "TrackRefitter")
488 
489 def _TrackSplitting(kwargs):
490  return ("RecoTracker.FinalTrackSelectors.cosmicTrackSplitter_cfi",
491  "cosmicTrackSplitter")
492 
493 
494 def _customSetattr(obj, attr, val):
495  """Sets the attribute `attr` of the object `obj` using the value `val`.
496  `attr` can be a string or a tuple of strings, if one wants to set an
497  attribute of an attribute, etc.
498 
499  Arguments:
500  - `obj`: Object, which must have a '__dict__' attribute.
501  - `attr`: String or tuple of strings describing the attribute's name.
502  - `val`: value of the attribute.
503  """
504 
505  if isinstance(attr, tuple) and len(attr) > 1:
506  _customSetattr(getattr(obj, attr[0]), attr[1:], val)
507  else:
508  if isinstance(attr, tuple): attr = attr[0]
509  setattr(obj, attr, val)
510 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
TEveGeoShape * clone(const TEveElement *element, TEveElement *parent)
Definition: eve_macros.cc:135
#define update(a, b)
def _getModule
### Auxiliary functions ###