CMS 3D CMS Logo

HLTMuonMatchAndPlot.cc
Go to the documentation of this file.
1 
6 
15 #include <boost/algorithm/string/replace.hpp>
16 
17 #include <iostream>
18 #include <string>
19 #include <utility>
20 #include <utility>
21 
24 
25 using namespace std;
26 using namespace edm;
27 using namespace reco;
28 using namespace trigger;
29 using namespace l1extra;
30 
31 using vstring = std::vector<std::string>;
32 
35 
38  : hltProcessName_(pset.getParameter<string>("hltProcessName")),
39  destination_(pset.getUntrackedParameter<string>("destination")),
40  requiredTriggers_(pset.getUntrackedParameter<vstring>("requiredTriggers")),
41  targetParams_(pset.getParameterSet("targetParams")),
42  probeParams_(pset.getParameterSet("probeParams")),
43  hltPath_(std::move(hltPath)),
44  moduleLabel_(std::move(moduleLabel)),
45  isLastFilter_(islastfilter),
46  hasTargetRecoCuts(targetParams_.exists("recoCuts")),
47  hasProbeRecoCuts(probeParams_.exists("recoCuts")),
48  targetMuonSelector_(targetParams_.getUntrackedParameter<string>("recoCuts", "")),
49  targetZ0Cut_(targetParams_.getUntrackedParameter<double>("z0Cut", 0.)),
50  targetD0Cut_(targetParams_.getUntrackedParameter<double>("d0Cut", 0.)),
51  targetptCutZ_(targetParams_.getUntrackedParameter<double>("ptCut_Z", 20.)),
52  targetptCutJpsi_(targetParams_.getUntrackedParameter<double>("ptCut_Jpsi", 20.)),
53  probeMuonSelector_(probeParams_.getUntrackedParameter<string>("recoCuts", "")),
54  probeZ0Cut_(probeParams_.getUntrackedParameter<double>("z0Cut", 0.)),
55  probeD0Cut_(probeParams_.getUntrackedParameter<double>("d0Cut", 0.)),
56  triggerSelector_(targetParams_.getUntrackedParameter<string>("hltCuts", "")),
57  hasTriggerCuts_(targetParams_.exists("hltCuts")) {
58  // Create std::map<string, T> from ParameterSets.
59  fillMapFromPSet(binParams_, pset, "binParams");
60  fillMapFromPSet(plotCuts_, pset, "plotCuts");
61 
62  // Get the trigger level.
63  triggerLevel_ = "L3";
64  TPRegexp levelRegexp("L[1-3]");
65  // size_t nModules = moduleLabels_.size();
66  // cout << moduleLabel_ << " " << hltPath_ << endl;
67  TObjArray* levelArray = levelRegexp.MatchS(moduleLabel_);
68  if (levelArray->GetEntriesFast() > 0) {
69  triggerLevel_ = static_cast<const char*>(((TObjString*)levelArray->At(0))->GetString());
70  }
71  delete levelArray;
72 
73  // Get the pT cut by parsing the name of the HLT path.
74  cutMinPt_ = 3;
75  TPRegexp ptRegexp("Mu([0-9]*)");
76  TObjArray* objArray = ptRegexp.MatchS(hltPath_);
77  if (objArray->GetEntriesFast() >= 2) {
78  auto* ptCutString = (TObjString*)objArray->At(1);
79  cutMinPt_ = atoi(ptCutString->GetString());
80  cutMinPt_ = ceil(cutMinPt_ * plotCuts_["minPtFactor"]);
81  }
82  delete objArray;
83 }
84 
85 void HLTMuonMatchAndPlot::beginRun(DQMStore::IBooker& iBooker, const edm::Run& iRun, const edm::EventSetup& iSetup) {
86  TPRegexp suffixPtCut("Mu[0-9]+$");
87 
88  string baseDir = destination_;
89  if (baseDir[baseDir.size() - 1] != '/')
90  baseDir += '/';
91  string pathSansSuffix = hltPath_;
92  if (hltPath_.rfind("_v") < hltPath_.length())
93  pathSansSuffix = hltPath_.substr(0, hltPath_.rfind("_v"));
94 
95  if (isLastFilter_)
96  iBooker.setCurrentFolder(baseDir + pathSansSuffix);
97  else
98  iBooker.setCurrentFolder(baseDir + pathSansSuffix + "/" + moduleLabel_);
99 
100  // Form is book1D(name, binningType, title) where 'binningType' is used
101  // to fetch the bin settings from binParams_.
102 
103  for (const auto& suffix : EFFICIENCY_SUFFIXES) {
104  if (isLastFilter_)
105  iBooker.setCurrentFolder(baseDir + pathSansSuffix);
106  else
107  iBooker.setCurrentFolder(baseDir + pathSansSuffix + "/" + moduleLabel_);
108 
109  book1D(iBooker, "efficiencyEta_" + suffix, "eta", ";#eta;");
110  book1D(iBooker, "efficiencyPhi_" + suffix, "phi", ";#phi;");
111  book1D(iBooker, "efficiencyTurnOn_" + suffix, "pt", ";p_{T};");
112  book1D(iBooker, "efficiencyNVertex_" + suffix, "NVertex", ";NVertex;");
113 
114  if (isLastFilter_)
115  iBooker.setCurrentFolder(baseDir + pathSansSuffix);
116  else
117  iBooker.setCurrentFolder(baseDir + pathSansSuffix + "/" + moduleLabel_);
118 
119  if (!isLastFilter_)
120  continue; //this will be plotted only for the last filter
121 
122  book1D(iBooker, "efficiencyCharge_" + suffix, "charge", ";charge;");
123  book1D(iBooker, "efficiencyZ0_" + suffix, "z0", ";z0;");
124  book1D(iBooker, "efficiency_DZ_Mu_" + suffix, "z0", ";z0;");
125  }
126 }
127 
128 void HLTMuonMatchAndPlot::endRun(const edm::Run& iRun, const edm::EventSetup& iSetup) {}
129 
135  const edm::TriggerNames& trigNames) {
136  /*
137  if(gen != 0) {
138  for(g_part = gen->begin(); g_part != gen->end(); g_part++){
139  if( abs(g_part->pdgId()) == 13) {
140  if(!( g_part->status() ==1 || (g_part->status() ==2 && abs(g_part->pdgId())==5))) continue;
141  bool GenMomExists (true);
142  bool GenGrMomExists(true);
143  if( g_part->pt() < 10.0 ) continue;
144  if( fabs(g_part->eta()) > 2.4 ) continue;
145  int gen_id= g_part->pdgId();
146  const GenParticle* gen_lept = &(*g_part);
147  // get mother of gen_lept
148  const GenParticle* gen_mom = static_cast<const GenParticle*> (gen_lept->mother());
149  if(gen_mom==NULL) GenMomExists=false;
150  int m_id=-999;
151  if(GenMomExists) m_id = gen_mom->pdgId();
152  if(m_id != gen_id || !GenMomExists);
153  else{
154  int id= m_id;
155  while(id == gen_id && GenMomExists){
156  gen_mom = static_cast<const GenParticle*> (gen_mom->mother());
157  if(gen_mom==NULL){
158  GenMomExists=false;
159  }
160  if(GenMomExists) id=gen_mom->pdgId();
161  }
162  }
163  if(GenMomExists) m_id = gen_mom->pdgId();
164  gen_leptsp.push_back(gen_lept);
165  gen_momsp.push_back(gen_mom);
166  }
167  }
168  }
169  std::vector<GenParticle> gen_lepts;
170  for(size_t i = 0; i < gen_leptsp.size(); i++) {
171  gen_lepts.push_back(*gen_leptsp[i]);
172  }
173  */
174 
175  // Select objects based on the configuration.
176  MuonCollection targetMuons =
178  MuonCollection probeMuons =
180  TriggerObjectCollection allTriggerObjects = triggerSummary->getObjects();
183  // Fill plots for HLT muons.
184 
185  // Find the best trigger object matches for the targetMuons.
186  vector<size_t> matches = matchByDeltaR(targetMuons, hltMuons, plotCuts_[triggerLevel_ + "DeltaR"]);
187 
188  // Fill plots for matched muons.
189  for (size_t i = 0; i < targetMuons.size(); i++) {
190  Muon& muon = targetMuons[i];
191 
192  // Fill numerators and denominators for efficiency plots.
193  for (const auto& suffix : EFFICIENCY_SUFFIXES) {
194  // If no match was found, then the numerator plots don't get filled.
195  if (suffix == "numer" && matches[i] >= targetMuons.size())
196  continue;
197 
198  if (muon.pt() > cutMinPt_) {
199  hists_["efficiencyEta_" + suffix]->Fill(muon.eta());
200  }
201 
202  if (fabs(muon.eta()) < plotCuts_["maxEta"]) {
203  hists_["efficiencyTurnOn_" + suffix]->Fill(muon.pt());
204  }
205 
206  if (muon.pt() > cutMinPt_ && fabs(muon.eta()) < plotCuts_["maxEta"]) {
207  const Track* track = nullptr;
208  if (muon.isTrackerMuon())
209  track = &*muon.innerTrack();
210  else if (muon.isStandAloneMuon())
211  track = &*muon.outerTrack();
212  if (track) {
213  hists_["efficiencyNVertex_" + suffix]->Fill(vertices->size());
214  hists_["efficiencyPhi_" + suffix]->Fill(muon.phi());
215 
216  if (isLastFilter_) {
217  hists_["efficiencyZ0_" + suffix]->Fill(track->dz(beamSpot->position()));
218  hists_["efficiencyCharge_" + suffix]->Fill(muon.charge());
219  }
220  }
221  }
222  } // finish loop numerator / denominator...
223 
224  if (!isLastFilter_)
225  continue;
226  // Fill plots for tag and probe
227  // Muon cannot be a tag because doesn't match an hlt muon
228  if (matches[i] >= targetMuons.size())
229  continue;
230  } // End loop over targetMuons.
231 
232  // fill eff histograms for reference trigger method
233  // Denominator: events passing reference trigger and two target muons
234  // Numerator: events in the denominator with two target muons
235  // matched to hlt muons
236  if (!isLastFilter_)
237  return;
238  unsigned int numTriggers = trigNames.size();
239 
240  int nMatched = 0;
241  for (unsigned long matche : matches) {
242  if (matche < targetMuons.size())
243  nMatched++;
244  }
245 
246  string nonDZPath = hltPath_;
247  bool dzPath = false;
248  if (nonDZPath.rfind("_DZ") < nonDZPath.length()) {
249  dzPath = true;
250  nonDZPath = boost::replace_all_copy<string>(nonDZPath, "_DZ", "");
251  nonDZPath = nonDZPath.substr(0, nonDZPath.rfind("_v") + 2);
252  }
253  bool passTriggerDZ = false;
254 
255  if (dzPath) {
256  for (unsigned int hltIndex = 0; hltIndex < numTriggers; ++hltIndex) {
257  passTriggerDZ = passTriggerDZ || (trigNames.triggerName(hltIndex).find(nonDZPath) != std::string::npos &&
258  triggerResults->wasrun(hltIndex) && triggerResults->accept(hltIndex));
259  }
260  }
261  if (dzPath && targetMuons.size() > 1 && passTriggerDZ) {
262  const Track* track0 = nullptr;
263  const Track* track1 = nullptr;
264  if (targetMuons.at(0).isTrackerMuon())
265  track0 = &*targetMuons.at(0).innerTrack();
266  else if (targetMuons.at(0).isStandAloneMuon())
267  track0 = &*targetMuons.at(0).outerTrack();
268  if (targetMuons.at(1).isTrackerMuon())
269  track1 = &*targetMuons.at(1).innerTrack();
270  else if (targetMuons.at(1).isStandAloneMuon())
271  track1 = &*targetMuons.at(1).outerTrack();
272 
273  if (track0 && track1) {
274  hists_["efficiency_DZ_Mu_denom"]->Fill(track0->dz(beamSpot->position()) - track1->dz(beamSpot->position()));
275  if (nMatched > 1) {
276  hists_["efficiency_DZ_Mu_numer"]->Fill(track0->dz(beamSpot->position()) - track1->dz(beamSpot->position()));
277  }
278  }
279  }
280 
281 } // End analyze() method.
282 
283 // Method to fill binning parameters from a vector of doubles.
284 bool HLTMuonMatchAndPlot::fillEdges(size_t& nBins, float*& edges, const vector<double>& binning) {
285  if (binning.size() < 3) {
286  LogWarning("HLTMuonVal") << "Invalid binning parameters!";
287  return false;
288  }
289 
290  // Fixed-width binning.
291  if (binning.size() == 3) {
292  nBins = binning[0];
293  edges = new float[nBins + 1];
294  const double min = binning[1];
295  const double binwidth = (binning[2] - binning[1]) / nBins;
296  for (size_t i = 0; i <= nBins; i++)
297  edges[i] = min + (binwidth * i);
298  }
299 
300  // Variable-width binning.
301  else {
302  nBins = binning.size() - 1;
303  edges = new float[nBins + 1];
304  for (size_t i = 0; i <= nBins; i++)
305  edges[i] = binning[i];
306  }
307  return true;
308 }
309 
310 // This is an unorthodox method of getting parameters, but cleaner in my mind
311 // It looks for parameter 'target' in the pset, and assumes that all entries
312 // have the same class (T), filling the values into a std::map.
313 template <class T>
314 void HLTMuonMatchAndPlot::fillMapFromPSet(map<string, T>& m, const ParameterSet& pset, const string& target) {
315  // Get the ParameterSet with name 'target' from 'pset'
316  ParameterSet targetPset;
317  if (pset.existsAs<ParameterSet>(target, true)) // target is tracked
318  targetPset = pset.getParameterSet(target);
319  else if (pset.existsAs<ParameterSet>(target, false)) // target is untracked
320  targetPset = pset.getUntrackedParameterSet(target);
321 
322  // Get the parameter names from targetPset
323  vector<string> names = targetPset.getParameterNames();
324  vector<string>::const_iterator iter;
325 
326  for (iter = names.begin(); iter != names.end(); ++iter) {
327  if (targetPset.existsAs<T>(*iter, true)) // target is tracked
328  m[*iter] = targetPset.getParameter<T>(*iter);
329  else if (targetPset.existsAs<T>(*iter, false)) // target is untracked
330  m[*iter] = targetPset.getUntrackedParameter<T>(*iter);
331  }
332 }
333 
334 // A generic method to find the best deltaR matches from 2 collections.
335 template <class T1, class T2>
336 vector<size_t> HLTMuonMatchAndPlot::matchByDeltaR(const vector<T1>& collection1,
337  const vector<T2>& collection2,
338  const double maxDeltaR) {
339  const size_t n1 = collection1.size();
340  const size_t n2 = collection2.size();
341 
342  vector<size_t> result(n1, -1);
343  vector<vector<double> > deltaRMatrix(n1, vector<double>(n2, NOMATCH));
344 
345  for (size_t i = 0; i < n1; i++)
346  for (size_t j = 0; j < n2; j++) {
347  deltaRMatrix[i][j] = deltaR(collection1[i], collection2[j]);
348  }
349 
350  // Run through the matrix n1 times to make sure we've found all matches.
351  for (size_t k = 0; k < n1; k++) {
352  size_t i_min = -1;
353  size_t j_min = -1;
354  double minDeltaR = maxDeltaR;
355  // find the smallest deltaR
356  for (size_t i = 0; i < n1; i++)
357  for (size_t j = 0; j < n2; j++)
358  if (deltaRMatrix[i][j] < minDeltaR) {
359  i_min = i;
360  j_min = j;
361  minDeltaR = deltaRMatrix[i][j];
362  }
363  // If a match has been made, save it and make those candidates unavailable.
364  if (minDeltaR < maxDeltaR) {
365  result[i_min] = j_min;
366  deltaRMatrix[i_min] = vector<double>(n2, NOMATCH);
367  for (size_t i = 0; i < n1; i++)
368  deltaRMatrix[i][j_min] = NOMATCH;
369  }
370  }
371 
372  return result;
373 }
374 
376  const BeamSpot& beamSpot,
377  bool hasRecoCuts,
378  const StringCutObjectSelector<reco::Muon>& selector,
379  double d0Cut,
380  double z0Cut) {
381  // If there is no selector (recoCuts does not exists), return an empty collection.
382  if (!hasRecoCuts)
383  return MuonCollection();
384 
385  MuonCollection reducedMuons;
386  for (auto const& mu : allMuons) {
387  const Track* track = nullptr;
388  if (mu.isTrackerMuon())
389  track = &*mu.innerTrack();
390  else if (mu.isStandAloneMuon())
391  track = &*mu.outerTrack();
392  if (track && selector(mu) && fabs(track->dxy(beamSpot.position())) < d0Cut &&
393  fabs(track->dz(beamSpot.position())) < z0Cut)
394  reducedMuons.push_back(mu);
395  }
396 
397  return reducedMuons;
398 }
399 
403  bool hasTriggerCuts,
404  const StringCutObjectSelector<TriggerObject>& triggerSelector) {
405  if (!hasTriggerCuts)
406  return TriggerObjectCollection();
407 
408  InputTag filterTag(moduleLabel_, "", hltProcessName_);
409  size_t filterIndex = triggerSummary.filterIndex(filterTag);
410 
411  TriggerObjectCollection selectedObjects;
412 
413  if (filterIndex < triggerSummary.sizeFilters()) {
414  const Keys& keys = triggerSummary.filterKeys(filterIndex);
415  for (unsigned short key : keys) {
416  TriggerObject foundObject = triggerObjects[key];
417  if (triggerSelector(foundObject))
418  selectedObjects.push_back(foundObject);
419  }
420  }
421 
422  return selectedObjects;
423 }
424 
425 void HLTMuonMatchAndPlot::book1D(DQMStore::IBooker& iBooker, string name, const string& binningType, string title) {
426  /* Properly delete the array of floats that has been allocated on
427  * the heap by fillEdges. Avoid multiple copies and internal ROOT
428  * clones by simply creating the histograms directly in the DQMStore
429  * using the appropriate book1D method to handle the variable bins
430  * case. */
431 
432  size_t nBins;
433  float* edges = nullptr;
434  bool bookhist = fillEdges(nBins, edges, binParams_[binningType]);
435  if (bookhist) {
436  hists_[name] = iBooker.book1D(name, title, nBins, edges);
437  if (hists_[name]->getTH1F()->GetSumw2N())
438  hists_[name]->enableSumw2();
439 
440  delete[] edges;
441  }
442 }
443 
445  const string& name,
446  const string& binningTypeX,
447  const string& binningTypeY,
448  const string& title) {
449  /* Properly delete the arrays of floats that have been allocated on
450  * the heap by fillEdges. Avoid multiple copies and internal ROOT
451  * clones by simply creating the histograms directly in the DQMStore
452  * using the appropriate book2D method to handle the variable bins
453  * case. */
454 
455  size_t nBinsX;
456  float* edgesX = nullptr;
457  bool bookhist = fillEdges(nBinsX, edgesX, binParams_[binningTypeX]);
458 
459  size_t nBinsY;
460  float* edgesY = nullptr;
461  bookhist &= fillEdges(nBinsY, edgesY, binParams_[binningTypeY]);
462  if (bookhist) {
463  hists_[name] = iBooker.book2D(name.c_str(), title.c_str(), nBinsX, edgesX, nBinsY, edgesY);
464  if (hists_[name]->getTH2F()->GetSumw2N())
465  hists_[name]->enableSumw2();
466 
467  delete[] edgesX;
468  delete[] edgesY;
469  }
470 }
constexpr int32_t ceil(float num)
reco::MuonCollection selectedMuons(const reco::MuonCollection &, const reco::BeamSpot &, bool, const StringCutObjectSelector< reco::Muon > &, double, double)
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
StringCutObjectSelector< reco::Muon > probeMuonSelector_
The single EDProduct to be saved for each event (AOD case)
Definition: TriggerEvent.h:25
const std::string EFFICIENCY_SUFFIXES[2]
virtual void setCurrentFolder(std::string const &fullpath)
Definition: DQMStore.cc:36
vector< string > vstring
Definition: ExoticaDQM.cc:7
std::map< std::string, std::vector< double > > binParams_
std::map< std::string, MonitorElement * > hists_
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:171
const std::string names[nVars_]
std::vector< Muon > MuonCollection
collection of Muon objects
Definition: MuonFwd.h:9
HLTMuonMatchAndPlot(const edm::ParameterSet &, std::string, std::string, bool)
Constructor.
T getUntrackedParameter(std::string const &, T const &) const
const double NOMATCH
void book2D(DQMStore::IBooker &, const std::string &, const std::string &, const std::string &, const std::string &)
double dz() const
dz parameter (= dsz/cos(lambda)). This is the track z0 w.r.t (0,0,0) only if the refPoint is close to...
Definition: TrackBase.h:622
std::vector< size_t > matchByDeltaR(const std::vector< T1 > &, const std::vector< T2 > &, const double maxDeltaR=NOMATCH)
Definition: Muon.py:1
void fillMapFromPSet(std::map< std::string, T > &, const edm::ParameterSet &, const std::string &)
trigger::TriggerObjectCollection selectedTriggerObjects(const trigger::TriggerObjectCollection &, const trigger::TriggerEvent &, bool hasTriggerCuts, const StringCutObjectSelector< trigger::TriggerObject > &triggerSelector)
static std::string const triggerResults
Definition: EdmProvDump.cc:47
void book1D(DQMStore::IBooker &, std::string, const std::string &, std::string)
std::vector< TriggerObject > TriggerObjectCollection
collection of trigger physics objects (e.g., all isolated muons)
Definition: TriggerObject.h:75
static const char *const trigNames[]
Definition: EcalDumpRaw.cc:57
void analyze(edm::Handle< reco::MuonCollection > &, edm::Handle< reco::BeamSpot > &, edm::Handle< reco::VertexCollection > &, edm::Handle< trigger::TriggerEvent > &, edm::Handle< edm::TriggerResults > &, const edm::TriggerNames &)
StringCutObjectSelector< reco::Muon > targetMuonSelector_
std::vector< size_type > Keys
MonitorElement * book2D(TString const &name, TString const &title, int nchX, double lowX, double highX, int nchY, double lowY, double highY, FUNC onbooking=NOOP())
Definition: DQMStore.h:212
ParameterSet const & getParameterSet(ParameterSetID const &id)
fixed size matrix
HLT enums.
StringCutObjectSelector< trigger::TriggerObject > triggerSelector_
void endRun(const edm::Run &, const edm::EventSetup &)
Log< level::Warning, false > LogWarning
MonitorElement * book1D(TString const &name, TString const &title, int const nchX, double const lowX, double const highX, FUNC onbooking=NOOP())
Definition: DQMStore.h:98
long double T
std::vector< std::string > getParameterNames() const
std::map< std::string, double > plotCuts_
bool fillEdges(size_t &nBins, float *&edges, const std::vector< double > &binning)
def move(src, dest)
Definition: eostools.py:511
Definition: Run.h:45
void beginRun(DQMStore::IBooker &, const edm::Run &, const edm::EventSetup &)