CMS 3D CMS Logo

PATMuonProducer.cc
Go to the documentation of this file.
1 //
2 //
3 
5 
9 
13 
15 
19 
22 
24 
27 
31 
36 
37 #include "TMath.h"
38 
40 
45 
50 
53 
54 #include <vector>
55 #include <memory>
56 
57 using namespace pat;
58 using namespace std;
59 
61  if (iConfig.getParameter<bool>("computeMuonMVA")) {
62  edm::FileInPath mvaTrainingFile = iConfig.getParameter<edm::FileInPath>("mvaTrainingFile");
63  edm::FileInPath mvaLowPtTrainingFile = iConfig.getParameter<edm::FileInPath>("lowPtmvaTrainingFile");
64  float mvaDrMax = iConfig.getParameter<double>("mvaDrMax");
65  muonMvaEstimator_ = std::make_unique<MuonMvaEstimator>(mvaTrainingFile, mvaDrMax);
66  muonLowPtMvaEstimator_ = std::make_unique<MuonMvaEstimator>(mvaLowPtTrainingFile, mvaDrMax);
67  }
68 
69  if (iConfig.getParameter<bool>("computeSoftMuonMVA")) {
70  edm::FileInPath softMvaTrainingFile = iConfig.getParameter<edm::FileInPath>("softMvaTrainingFile");
71  softMuonMvaEstimator_ = std::make_unique<SoftMuonMvaEstimator>(softMvaTrainingFile);
72  }
73 }
74 
76  : relMiniIsoPUCorrected_(0),
77  useUserData_(iConfig.exists("userData")),
78  computeMuonMVA_(false),
79  computeSoftMuonMVA_(false),
80  recomputeBasicSelectors_(false),
81  mvaUseJec_(false),
82  isolator_(iConfig.exists("userIsolation") ? iConfig.getParameter<edm::ParameterSet>("userIsolation")
83  : edm::ParameterSet(),
84  consumesCollector(),
85  false) {
86  // input source
87  muonToken_ = consumes<edm::View<reco::Muon>>(iConfig.getParameter<edm::InputTag>("muonSource"));
88  // embedding of tracks
89  embedBestTrack_ = iConfig.getParameter<bool>("embedMuonBestTrack");
90  embedTunePBestTrack_ = iConfig.getParameter<bool>("embedTunePMuonBestTrack");
91  forceEmbedBestTrack_ = iConfig.getParameter<bool>("forceBestTrackEmbedding");
92  embedTrack_ = iConfig.getParameter<bool>("embedTrack");
93  embedCombinedMuon_ = iConfig.getParameter<bool>("embedCombinedMuon");
94  embedStandAloneMuon_ = iConfig.getParameter<bool>("embedStandAloneMuon");
95  // embedding of muon MET correction information
96  embedCaloMETMuonCorrs_ = iConfig.getParameter<bool>("embedCaloMETMuonCorrs");
97  embedTcMETMuonCorrs_ = iConfig.getParameter<bool>("embedTcMETMuonCorrs");
99  mayConsume<edm::ValueMap<reco::MuonMETCorrectionData>>(iConfig.getParameter<edm::InputTag>("caloMETMuonCorrs"));
101  mayConsume<edm::ValueMap<reco::MuonMETCorrectionData>>(iConfig.getParameter<edm::InputTag>("tcMETMuonCorrs"));
102  // pflow specific configurables
103  useParticleFlow_ = iConfig.getParameter<bool>("useParticleFlow");
104  embedPFCandidate_ = iConfig.getParameter<bool>("embedPFCandidate");
105  pfMuonToken_ = mayConsume<reco::PFCandidateCollection>(iConfig.getParameter<edm::InputTag>("pfMuonSource"));
106  embedPfEcalEnergy_ = iConfig.getParameter<bool>("embedPfEcalEnergy");
107  // embedding of tracks from TeV refit
108  embedPickyMuon_ = iConfig.getParameter<bool>("embedPickyMuon");
109  embedTpfmsMuon_ = iConfig.getParameter<bool>("embedTpfmsMuon");
110  embedDytMuon_ = iConfig.getParameter<bool>("embedDytMuon");
111  // embedding of inverse beta variable information
112  addInverseBeta_ = iConfig.getParameter<bool>("addInverseBeta");
113  if (addInverseBeta_) {
115  consumes<edm::ValueMap<reco::MuonTimeExtra>>(iConfig.getParameter<edm::InputTag>("sourceMuonTimeExtra"));
116  }
117  // Switch to get the dB from the track instead of using IPTools
118  getdBFromTrack_ = iConfig.getParameter<bool>("getdBFromTrack");
119  // Monte Carlo matching
120  addGenMatch_ = iConfig.getParameter<bool>("addGenMatch");
121  if (addGenMatch_) {
122  embedGenMatch_ = iConfig.getParameter<bool>("embedGenMatch");
123  if (iConfig.existsAs<edm::InputTag>("genParticleMatch")) {
125  iConfig.getParameter<edm::InputTag>("genParticleMatch")));
126  } else {
128  iConfig.getParameter<std::vector<edm::InputTag>>("genParticleMatch"),
129  [this](edm::InputTag const& tag) { return consumes<edm::Association<reco::GenParticleCollection>>(tag); });
130  }
131  }
132  // efficiencies
133  addEfficiencies_ = iConfig.getParameter<bool>("addEfficiencies");
134  if (addEfficiencies_) {
136  pat::helper::EfficiencyLoader(iConfig.getParameter<edm::ParameterSet>("efficiencies"), consumesCollector());
137  }
138  // resolutions
139  addResolutions_ = iConfig.getParameter<bool>("addResolutions");
140  if (addResolutions_) {
142  }
143  // puppi
144  addPuppiIsolation_ = iConfig.getParameter<bool>("addPuppiIsolation");
145  if (addPuppiIsolation_) {
147  consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("puppiIsolationChargedHadrons"));
149  consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("puppiIsolationNeutralHadrons"));
151  consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("puppiIsolationPhotons"));
152  //puppiNoLeptons
154  consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("puppiNoLeptonsIsolationChargedHadrons"));
156  consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("puppiNoLeptonsIsolationNeutralHadrons"));
158  consumes<edm::ValueMap<float>>(iConfig.getParameter<edm::InputTag>("puppiNoLeptonsIsolationPhotons"));
159  }
160  // read isoDeposit labels, for direct embedding
161  readIsolationLabels(iConfig, "isoDeposits", isoDepositLabels_, isoDepositTokens_);
162  // read isolation value labels, for direct embedding
164  // check to see if the user wants to add user data
165  if (useUserData_) {
166  userDataHelper_ = PATUserDataHelper<Muon>(iConfig.getParameter<edm::ParameterSet>("userData"), consumesCollector());
167  }
168  // embed high level selection variables
169  embedHighLevelSelection_ = iConfig.getParameter<bool>("embedHighLevelSelection");
170  if (embedHighLevelSelection_) {
171  beamLineToken_ = consumes<reco::BeamSpot>(iConfig.getParameter<edm::InputTag>("beamLineSrc"));
172  pvToken_ = consumes<std::vector<reco::Vertex>>(iConfig.getParameter<edm::InputTag>("pvSrc"));
173  }
174 
175  //for mini-isolation calculation
176  computeMiniIso_ = iConfig.getParameter<bool>("computeMiniIso");
177 
178  computePuppiCombinedIso_ = iConfig.getParameter<bool>("computePuppiCombinedIso");
179 
180  effectiveAreaVec_ = iConfig.getParameter<std::vector<double>>("effectiveAreaVec");
181 
182  miniIsoParams_ = iConfig.getParameter<std::vector<double>>("miniIsoParams");
183  if (computeMiniIso_ && miniIsoParams_.size() != 9) {
184  throw cms::Exception("ParameterError") << "miniIsoParams must have exactly 9 elements.\n";
185  }
186  if (computeMiniIso_ || computePuppiCombinedIso_)
187  pcToken_ = consumes<pat::PackedCandidateCollection>(iConfig.getParameter<edm::InputTag>("pfCandsForMiniIso"));
188 
189  // standard selectors
190  recomputeBasicSelectors_ = iConfig.getParameter<bool>("recomputeBasicSelectors");
191  computeMuonMVA_ = iConfig.getParameter<bool>("computeMuonMVA");
192  if (computeMuonMVA_ and not computeMiniIso_)
193  throw cms::Exception("ConfigurationError") << "MiniIso is needed for Muon MVA calculation.\n";
194 
195  if (computeMuonMVA_) {
196  // pfCombinedInclusiveSecondaryVertexV2BJetTags
197  mvaBTagCollectionTag_ = consumes<reco::JetTagCollection>(iConfig.getParameter<edm::InputTag>("mvaJetTag"));
198  mvaL1Corrector_ = consumes<reco::JetCorrector>(iConfig.getParameter<edm::InputTag>("mvaL1Corrector"));
199  mvaL1L2L3ResCorrector_ = consumes<reco::JetCorrector>(iConfig.getParameter<edm::InputTag>("mvaL1L2L3ResCorrector"));
200  rho_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho"));
201  mvaUseJec_ = iConfig.getParameter<bool>("mvaUseJec");
202  }
203 
204  computeSoftMuonMVA_ = iConfig.getParameter<bool>("computeSoftMuonMVA");
205 
206  // MC info
207  simInfo_ = consumes<edm::ValueMap<reco::MuonSimInfo>>(iConfig.getParameter<edm::InputTag>("muonSimInfo"));
208 
209  addTriggerMatching_ = iConfig.getParameter<bool>("addTriggerMatching");
210  if (addTriggerMatching_) {
212  consumes<std::vector<pat::TriggerObjectStandAlone>>(iConfig.getParameter<edm::InputTag>("triggerObjects"));
213  triggerResults_ = consumes<edm::TriggerResults>(iConfig.getParameter<edm::InputTag>("triggerResults"));
214  }
215  hltCollectionFilters_ = iConfig.getParameter<std::vector<std::string>>("hltCollectionFilters");
216 
217  // produces vector of muons
218  produces<std::vector<Muon>>();
219 }
220 
222 
223 std::optional<GlobalPoint> PATMuonProducer::getMuonDirection(const reco::MuonChamberMatch& chamberMatch,
225  const DetId& chamberId) {
226  const GeomDet* chamberGeometry = geometry->idToDet(chamberId);
227  if (chamberGeometry) {
228  LocalPoint localPosition(chamberMatch.x, chamberMatch.y, 0);
229  return std::optional<GlobalPoint>(std::in_place, chamberGeometry->toGlobal(localPosition));
230  }
231  return std::optional<GlobalPoint>();
232 }
233 
235  edm::Handle<std::vector<pat::TriggerObjectStandAlone>>& triggerObjects,
236  const edm::TriggerNames& names,
238  // L1 trigger object parameters are defined at MB2/ME2. Use the muon
239  // chamber matching information to get the local direction of the
240  // muon trajectory and convert it to a global direction to match the
241  // trigger objects
242 
243  std::optional<GlobalPoint> muonPosition;
244  // Loop over chambers
245  // initialize muonPosition with any available match, just in case
246  // the second station is missing - it's better folling back to
247  // dR matching at IP
248  for (const auto& chamberMatch : aMuon.matches()) {
249  if (chamberMatch.id.subdetId() == MuonSubdetId::DT) {
250  DTChamberId detId(chamberMatch.id.rawId());
251  if (abs(detId.station()) > 3)
252  continue;
253  muonPosition = getMuonDirection(chamberMatch, geometry, detId);
254  if (abs(detId.station()) == 2)
255  break;
256  }
257  if (chamberMatch.id.subdetId() == MuonSubdetId::CSC) {
258  CSCDetId detId(chamberMatch.id.rawId());
259  if (abs(detId.station()) > 3)
260  continue;
261  muonPosition = getMuonDirection(chamberMatch, geometry, detId);
262  if (abs(detId.station()) == 2)
263  break;
264  }
265  }
266  if (not muonPosition)
267  return;
268  for (const auto& triggerObject : *triggerObjects) {
269  if (triggerObject.hasTriggerObjectType(trigger::TriggerL1Mu)) {
270  if (fabs(triggerObject.eta()) < 0.001) {
271  // L1 is defined in X-Y plain
272  if (deltaPhi(triggerObject.phi(), muonPosition->phi()) > 0.1)
273  continue;
274  } else {
275  // 3D L1
276  if (deltaR(triggerObject.p4(), *muonPosition) > 0.15)
277  continue;
278  }
279  pat::TriggerObjectStandAlone obj(triggerObject);
280  obj.unpackPathNames(names);
281  aMuon.addTriggerObjectMatch(obj);
282  }
283  }
284 }
285 
287  edm::Handle<std::vector<pat::TriggerObjectStandAlone>>& triggerObjects,
288  const edm::TriggerNames& names,
289  const std::vector<std::string>& collection_filter_names) {
290  // WARNING: in a case of close-by muons the dR matching may select both muons.
291  // It's better to select the best match for a given collection.
292  for (const auto& triggerObject : *triggerObjects) {
293  if (triggerObject.hasTriggerObjectType(trigger::TriggerMuon)) {
294  bool keepIt = false;
295  for (const auto& name : collection_filter_names) {
296  if (triggerObject.hasCollection(name)) {
297  keepIt = true;
298  break;
299  }
300  }
301  if (not keepIt)
302  continue;
303  if (deltaR(triggerObject.p4(), muon) > 0.1)
304  continue;
305  pat::TriggerObjectStandAlone obj(triggerObject);
306  obj.unpackPathNames(names);
307  muon.addTriggerObjectMatch(obj);
308  }
309  }
310 }
311 
313  // get the tracking Geometry
315  iSetup.get<GlobalTrackingGeometryRecord>().get(geometry);
316  if (!geometry.isValid())
317  throw cms::Exception("FatalError") << "Unable to find GlobalTrackingGeometryRecord in event!\n";
318 
319  // switch off embedding (in unschedules mode)
320  if (iEvent.isRealData()) {
321  addGenMatch_ = false;
322  embedGenMatch_ = false;
323  }
324 
326  iEvent.getByToken(muonToken_, muons);
327 
330  iEvent.getByToken(pcToken_, pc);
331 
332  // get the ESHandle for the transient track builder,
333  // if needed for high level selection embedding
335 
336  if (isolator_.enabled())
337  isolator_.beginEvent(iEvent, iSetup);
339  efficiencyLoader_.newEvent(iEvent);
341  resolutionLoader_.newEvent(iEvent, iSetup);
342 
344  for (size_t j = 0; j < isoDepositTokens_.size(); ++j) {
345  iEvent.getByToken(isoDepositTokens_[j], deposits[j]);
346  }
347 
349  for (size_t j = 0; j < isolationValueTokens_.size(); ++j) {
351  }
352 
353  //value maps for puppi isolation
354  edm::Handle<edm::ValueMap<float>> PUPPIIsolation_charged_hadrons;
355  edm::Handle<edm::ValueMap<float>> PUPPIIsolation_neutral_hadrons;
356  edm::Handle<edm::ValueMap<float>> PUPPIIsolation_photons;
357  //value maps for puppiNoLeptons isolation
358  edm::Handle<edm::ValueMap<float>> PUPPINoLeptonsIsolation_charged_hadrons;
359  edm::Handle<edm::ValueMap<float>> PUPPINoLeptonsIsolation_neutral_hadrons;
360  edm::Handle<edm::ValueMap<float>> PUPPINoLeptonsIsolation_photons;
361  if (addPuppiIsolation_) {
362  //puppi
363  iEvent.getByToken(PUPPIIsolation_charged_hadrons_, PUPPIIsolation_charged_hadrons);
364  iEvent.getByToken(PUPPIIsolation_neutral_hadrons_, PUPPIIsolation_neutral_hadrons);
365  iEvent.getByToken(PUPPIIsolation_photons_, PUPPIIsolation_photons);
366  //puppiNoLeptons
367  iEvent.getByToken(PUPPINoLeptonsIsolation_charged_hadrons_, PUPPINoLeptonsIsolation_charged_hadrons);
368  iEvent.getByToken(PUPPINoLeptonsIsolation_neutral_hadrons_, PUPPINoLeptonsIsolation_neutral_hadrons);
369  iEvent.getByToken(PUPPINoLeptonsIsolation_photons_, PUPPINoLeptonsIsolation_photons);
370  }
371 
372  // inputs for muon mva
373  edm::Handle<reco::JetTagCollection> mvaBTagCollectionTag;
376  if (computeMuonMVA_) {
377  iEvent.getByToken(mvaBTagCollectionTag_, mvaBTagCollectionTag);
378  iEvent.getByToken(mvaL1Corrector_, mvaL1Corrector);
379  iEvent.getByToken(mvaL1L2L3ResCorrector_, mvaL1L2L3ResCorrector);
380  }
381 
382  // prepare the MC genMatchTokens_
383  GenAssociations genMatches(genMatchTokens_.size());
384  if (addGenMatch_) {
385  for (size_t j = 0, nd = genMatchTokens_.size(); j < nd; ++j) {
386  iEvent.getByToken(genMatchTokens_[j], genMatches[j]);
387  }
388  }
389 
390  // prepare the high level selection: needs beamline
391  // OR primary vertex, depending on user selection
394  bool beamSpotIsValid = false;
395  bool primaryVertexIsValid = false;
397  // get the beamspot
398  edm::Handle<reco::BeamSpot> beamSpotHandle;
399  iEvent.getByToken(beamLineToken_, beamSpotHandle);
400 
401  // get the primary vertex
403  iEvent.getByToken(pvToken_, pvHandle);
404 
405  if (beamSpotHandle.isValid()) {
406  beamSpot = *beamSpotHandle;
407  beamSpotIsValid = true;
408  } else {
409  edm::LogError("DataNotAvailable") << "No beam spot available from EventSetup, not adding high level selection \n";
410  }
411  if (pvHandle.isValid() && !pvHandle->empty()) {
412  primaryVertex = pvHandle->at(0);
413  primaryVertexIsValid = true;
414  } else {
415  edm::LogError("DataNotAvailable")
416  << "No primary vertex available from EventSetup, not adding high level selection \n";
417  }
418  // this is needed by the IPTools methods from the tracking group
419  iSetup.get<TransientTrackRecord>().get("TransientTrackBuilder", trackBuilder);
420  }
421 
422  // MC info
424  bool simInfoIsAvailalbe = iEvent.getByToken(simInfo_, simInfo);
425 
426  // this will be the new object collection
427  std::vector<Muon>* patMuons = new std::vector<Muon>();
428 
430  if (useParticleFlow_) {
431  // get the PFCandidates of type muons
432  iEvent.getByToken(pfMuonToken_, pfMuons);
433 
434  unsigned index = 0;
435  for (reco::PFCandidateConstIterator i = pfMuons->begin(); i != pfMuons->end(); ++i, ++index) {
436  const reco::PFCandidate& pfmu = *i;
437  //const reco::IsolaPFCandidate& pfmu = *i;
438  const reco::MuonRef& muonRef = pfmu.muonRef();
439  assert(muonRef.isNonnull());
440 
441  MuonBaseRef muonBaseRef(muonRef);
442  Muon aMuon(muonBaseRef);
443 
444  if (useUserData_) {
445  userDataHelper_.add(aMuon, iEvent, iSetup);
446  }
447 
448  // embed high level selection
450  // get the tracks
451  reco::TrackRef innerTrack = muonBaseRef->innerTrack();
452  reco::TrackRef globalTrack = muonBaseRef->globalTrack();
453  reco::TrackRef bestTrack = muonBaseRef->muonBestTrack();
454  reco::TrackRef chosenTrack = innerTrack;
455  // Make sure the collection it points to is there
456  if (bestTrack.isNonnull() && bestTrack.isAvailable())
457  chosenTrack = bestTrack;
458 
459  if (chosenTrack.isNonnull() && chosenTrack.isAvailable()) {
460  unsigned int nhits = chosenTrack->numberOfValidHits(); // ????
461  aMuon.setNumberOfValidHits(nhits);
462 
463  reco::TransientTrack tt = trackBuilder->build(chosenTrack);
464  embedHighLevel(aMuon, chosenTrack, tt, primaryVertex, primaryVertexIsValid, beamSpot, beamSpotIsValid);
465  }
466 
467  if (globalTrack.isNonnull() && globalTrack.isAvailable() && !embedCombinedMuon_) {
468  double norm_chi2 = globalTrack->chi2() / globalTrack->ndof();
469  aMuon.setNormChi2(norm_chi2);
470  }
471  }
472  reco::PFCandidateRef pfRef(pfMuons, index);
473  //reco::PFCandidatePtr ptrToMother(pfMuons,index);
474  reco::CandidateBaseRef pfBaseRef(pfRef);
475 
476  aMuon.setPFCandidateRef(pfRef);
477  if (embedPFCandidate_)
478  aMuon.embedPFCandidate();
479  fillMuon(aMuon, muonBaseRef, pfBaseRef, genMatches, deposits, isolationValues);
480 
481  if (computeMiniIso_)
482  setMuonMiniIso(aMuon, pc.product());
483 
484  if (addPuppiIsolation_) {
485  aMuon.setIsolationPUPPI((*PUPPIIsolation_charged_hadrons)[muonBaseRef],
486  (*PUPPIIsolation_neutral_hadrons)[muonBaseRef],
487  (*PUPPIIsolation_photons)[muonBaseRef]);
488 
489  aMuon.setIsolationPUPPINoLeptons((*PUPPINoLeptonsIsolation_charged_hadrons)[muonBaseRef],
490  (*PUPPINoLeptonsIsolation_neutral_hadrons)[muonBaseRef],
491  (*PUPPINoLeptonsIsolation_photons)[muonBaseRef]);
492  } else {
493  aMuon.setIsolationPUPPI(-999., -999., -999.);
494  aMuon.setIsolationPUPPINoLeptons(-999., -999., -999.);
495  }
496 
497  if (embedPfEcalEnergy_) {
498  aMuon.setPfEcalEnergy(pfmu.ecalEnergy());
499  }
500 
501  patMuons->push_back(aMuon);
502  }
503  } else {
505  iEvent.getByToken(muonToken_, muons);
506 
507  // embedding of muon MET corrections
509  //edm::ValueMap<reco::MuonMETCorrectionData> caloMETmuCorValueMap;
511  iEvent.getByToken(caloMETMuonCorrsToken_, caloMETMuonCorrs);
512  //caloMETmuCorValueMap = *caloMETmuCorValueMap_h;
513  }
515  //edm::ValueMap<reco::MuonMETCorrectionData> tcMETmuCorValueMap;
516  if (embedTcMETMuonCorrs_) {
517  iEvent.getByToken(tcMETMuonCorrsToken_, tcMETMuonCorrs);
518  //tcMETmuCorValueMap = *tcMETmuCorValueMap_h;
519  }
520 
521  if (embedPfEcalEnergy_) {
522  // get the PFCandidates of type muons
523  iEvent.getByToken(pfMuonToken_, pfMuons);
524  }
525 
527  if (addInverseBeta_) {
528  // get MuonTimerExtra value map
529  iEvent.getByToken(muonTimeExtraToken_, muonsTimeExtra);
530  }
531 
532  for (edm::View<reco::Muon>::const_iterator itMuon = muons->begin(); itMuon != muons->end(); ++itMuon) {
533  // construct the Muon from the ref -> save ref to original object
534  unsigned int idx = itMuon - muons->begin();
535  MuonBaseRef muonRef = muons->refAt(idx);
536  reco::CandidateBaseRef muonBaseRef(muonRef);
537 
538  Muon aMuon(muonRef);
539  fillMuon(aMuon, muonRef, muonBaseRef, genMatches, deposits, isolationValues);
540  if (computeMiniIso_)
541  setMuonMiniIso(aMuon, pc.product());
542  if (addPuppiIsolation_) {
543  aMuon.setIsolationPUPPI((*PUPPIIsolation_charged_hadrons)[muonRef],
544  (*PUPPIIsolation_neutral_hadrons)[muonRef],
545  (*PUPPIIsolation_photons)[muonRef]);
546  aMuon.setIsolationPUPPINoLeptons((*PUPPINoLeptonsIsolation_charged_hadrons)[muonRef],
547  (*PUPPINoLeptonsIsolation_neutral_hadrons)[muonRef],
548  (*PUPPINoLeptonsIsolation_photons)[muonRef]);
549  } else {
550  aMuon.setIsolationPUPPI(-999., -999., -999.);
551  aMuon.setIsolationPUPPINoLeptons(-999., -999., -999.);
552  }
553 
554  // Isolation
555  if (isolator_.enabled()) {
556  //reco::CandidatePtr mother = ptrToMother->sourceCandidatePtr(0);
557  isolator_.fill(*muons, idx, isolatorTmpStorage_);
558  typedef pat::helper::MultiIsolator::IsolationValuePairs IsolationValuePairs;
559  // better to loop backwards, so the vector is resized less times
560  for (IsolationValuePairs::const_reverse_iterator it = isolatorTmpStorage_.rbegin(),
561  ed = isolatorTmpStorage_.rend();
562  it != ed;
563  ++it) {
564  aMuon.setIsolation(it->first, it->second);
565  }
566  }
567 
568  // for (size_t j = 0, nd = deposits.size(); j < nd; ++j) {
569  // aMuon.setIsoDeposit(isoDepositLabels_[j].first,
570  // (*deposits[j])[muonRef]);
571  // }
572 
573  // add sel to selected
574  edm::Ptr<reco::Muon> muonsPtr = muons->ptrAt(idx);
575  if (useUserData_) {
576  userDataHelper_.add(aMuon, iEvent, iSetup);
577  }
578 
579  // embed high level selection
581  // get the tracks
582  reco::TrackRef innerTrack = itMuon->innerTrack();
583  reco::TrackRef globalTrack = itMuon->globalTrack();
584  reco::TrackRef bestTrack = itMuon->muonBestTrack();
585  reco::TrackRef chosenTrack = innerTrack;
586  // Make sure the collection it points to is there
587  if (bestTrack.isNonnull() && bestTrack.isAvailable())
588  chosenTrack = bestTrack;
589  if (chosenTrack.isNonnull() && chosenTrack.isAvailable()) {
590  unsigned int nhits = chosenTrack->numberOfValidHits(); // ????
591  aMuon.setNumberOfValidHits(nhits);
592 
593  reco::TransientTrack tt = trackBuilder->build(chosenTrack);
594  embedHighLevel(aMuon, chosenTrack, tt, primaryVertex, primaryVertexIsValid, beamSpot, beamSpotIsValid);
595  }
596 
597  if (globalTrack.isNonnull() && globalTrack.isAvailable()) {
598  double norm_chi2 = globalTrack->chi2() / globalTrack->ndof();
599  aMuon.setNormChi2(norm_chi2);
600  }
601  }
602 
603  // embed MET muon corrections
605  aMuon.embedCaloMETMuonCorrs((*caloMETMuonCorrs)[muonRef]);
607  aMuon.embedTcMETMuonCorrs((*tcMETMuonCorrs)[muonRef]);
608 
609  if (embedPfEcalEnergy_) {
610  aMuon.setPfEcalEnergy(-99.0);
611  for (const reco::PFCandidate& pfmu : *pfMuons) {
612  if (pfmu.muonRef().isNonnull()) {
613  if (pfmu.muonRef().id() != muonRef.id())
614  throw cms::Exception("Configuration")
615  << "Muon reference within PF candidates does not point to the muon collection." << std::endl;
616  if (pfmu.muonRef().key() == muonRef.key()) {
617  aMuon.setPfEcalEnergy(pfmu.ecalEnergy());
618  }
619  }
620  }
621  }
622  if (addInverseBeta_) {
623  aMuon.readTimeExtra((*muonsTimeExtra)[muonRef]);
624  }
625  // MC info
626  aMuon.initSimInfo();
627  if (simInfoIsAvailalbe) {
628  const auto& msi = (*simInfo)[muonBaseRef];
629  aMuon.setSimType(msi.primaryClass);
630  aMuon.setExtSimType(msi.extendedClass);
631  aMuon.setSimFlavour(msi.flavour);
632  aMuon.setSimHeaviestMotherFlavour(msi.heaviestMotherFlavour);
633  aMuon.setSimPdgId(msi.pdgId);
634  aMuon.setSimMotherPdgId(msi.motherPdgId);
635  aMuon.setSimBX(msi.tpBX);
636  aMuon.setSimTpEvent(msi.tpEvent);
637  aMuon.setSimProdRho(msi.vertex.Rho());
638  aMuon.setSimProdZ(msi.vertex.Z());
639  aMuon.setSimPt(msi.p4.pt());
640  aMuon.setSimEta(msi.p4.eta());
641  aMuon.setSimPhi(msi.p4.phi());
642  aMuon.setSimMatchQuality(msi.tpAssoQuality);
643  }
644  patMuons->push_back(aMuon);
645  }
646  }
647 
648  // sort muons in pt
649  std::sort(patMuons->begin(), patMuons->end(), pTComparator_);
650 
651  // Store standard muon selection decisions and jet related
652  // quantaties.
653  // Need a separate loop over muons to have all inputs properly
654  // computed and stored in the object.
656  if (computeMuonMVA_)
657  iEvent.getByToken(rho_, rho);
658  const reco::Vertex* pv(nullptr);
659  if (primaryVertexIsValid)
660  pv = &primaryVertex;
661 
664  bool triggerObjectsAvailable = false;
665  bool triggerResultsAvailable = false;
666  if (addTriggerMatching_) {
667  triggerObjectsAvailable = iEvent.getByToken(triggerObjects_, triggerObjects);
668  triggerResultsAvailable = iEvent.getByToken(triggerResults_, triggerResults);
669  }
670 
671  for (auto& muon : *patMuons) {
672  // trigger info
673  if (addTriggerMatching_ and triggerObjectsAvailable and triggerResultsAvailable) {
674  const edm::TriggerNames& triggerNames(iEvent.triggerNames(*triggerResults));
675  fillL1TriggerInfo(muon, triggerObjects, triggerNames, geometry);
676  fillHltTriggerInfo(muon, triggerObjects, triggerNames, hltCollectionFilters_);
677  }
678 
680  muon.setSelectors(0);
681  bool isRun2016BCDEF = (272728 <= iEvent.run() && iEvent.run() <= 278808);
682  muon.setSelectors(muon::makeSelectorBitset(muon, pv, isRun2016BCDEF));
683  }
684  float miniIsoValue = -1;
685  if (computeMiniIso_) {
686  // MiniIsolation working points
687 
688  miniIsoValue = getRelMiniIsoPUCorrected(muon, *rho, effectiveAreaVec_);
689 
690  muon.setSelector(reco::Muon::MiniIsoLoose, miniIsoValue < 0.40);
691  muon.setSelector(reco::Muon::MiniIsoMedium, miniIsoValue < 0.20);
692  muon.setSelector(reco::Muon::MiniIsoTight, miniIsoValue < 0.10);
693  muon.setSelector(reco::Muon::MiniIsoVeryTight, miniIsoValue < 0.05);
694  }
695 
696  double puppiCombinedIsolationPAT = -1;
698  puppiCombinedIsolationPAT = puppiCombinedIsolation(muon, pc.product());
699  muon.setSelector(reco::Muon::PuppiIsoLoose, puppiCombinedIsolationPAT < 0.27);
700  muon.setSelector(reco::Muon::PuppiIsoMedium, puppiCombinedIsolationPAT < 0.22);
701  muon.setSelector(reco::Muon::PuppiIsoTight, puppiCombinedIsolationPAT < 0.12);
702  }
703 
704  float jetPtRatio = 0.0;
705  float jetPtRel = 0.0;
706  float mva = 0.0;
707  float mva_lowpt = 0.0;
708  if (computeMuonMVA_ && primaryVertexIsValid && computeMiniIso_) {
709  if (mvaUseJec_) {
710  mva = globalCache()->muonMvaEstimator()->computeMva(muon,
711  primaryVertex,
712  *(mvaBTagCollectionTag.product()),
713  jetPtRatio,
714  jetPtRel,
715  miniIsoValue,
716  &*mvaL1Corrector,
717  &*mvaL1L2L3ResCorrector);
718  mva_lowpt = globalCache()->muonLowPtMvaEstimator()->computeMva(muon,
719  primaryVertex,
720  *(mvaBTagCollectionTag.product()),
721  jetPtRatio,
722  jetPtRel,
723  miniIsoValue,
724  &*mvaL1Corrector,
725  &*mvaL1L2L3ResCorrector);
726 
727  } else {
728  mva = globalCache()->muonMvaEstimator()->computeMva(
729  muon, primaryVertex, *(mvaBTagCollectionTag.product()), jetPtRatio, jetPtRel, miniIsoValue);
730  mva_lowpt = globalCache()->muonLowPtMvaEstimator()->computeMva(
731  muon, primaryVertex, *(mvaBTagCollectionTag.product()), jetPtRatio, jetPtRel, miniIsoValue);
732  }
733 
734  muon.setMvaValue(mva);
735  muon.setLowPtMvaValue(mva_lowpt);
736  muon.setJetPtRatio(jetPtRatio);
737  muon.setJetPtRel(jetPtRel);
738 
739  // multi-isolation
740  if (computeMiniIso_) {
741  muon.setSelector(reco::Muon::MultiIsoMedium,
742  miniIsoValue < 0.11 && (muon.jetPtRatio() > 0.74 || muon.jetPtRel() > 6.8));
743  }
744 
745  // MVA working points
746  // https://twiki.cern.ch/twiki/bin/viewauth/CMS/LeptonMVA
747  double dB2D = fabs(muon.dB(pat::Muon::PV2D));
748  double dB3D = fabs(muon.dB(pat::Muon::PV3D));
749  double edB3D = fabs(muon.edB(pat::Muon::PV3D));
750  double sip3D = edB3D > 0 ? dB3D / edB3D : 0.0;
751  double dz = fabs(muon.muonBestTrack()->dz(primaryVertex.position()));
752 
753  // muon preselection
754  if (muon.pt() > 5 and muon.isLooseMuon() and muon.passed(reco::Muon::MiniIsoLoose) and sip3D < 8.0 and
755  dB2D < 0.05 and dz < 0.1) {
756  muon.setSelector(reco::Muon::MvaLoose, muon.mvaValue() > -0.60);
757  muon.setSelector(reco::Muon::MvaMedium, muon.mvaValue() > -0.20);
758  muon.setSelector(reco::Muon::MvaTight, muon.mvaValue() > 0.15);
759  muon.setSelector(reco::Muon::MvaVTight, muon.mvaValue() > 0.45);
760  muon.setSelector(reco::Muon::MvaVVTight, muon.mvaValue() > 0.9);
761  }
762  if (muon.pt() > 5 and muon.isLooseMuon() and sip3D < 4 and dB2D < 0.5 and dz < 1) {
763  muon.setSelector(reco::Muon::LowPtMvaLoose, muon.lowptMvaValue() > -0.60);
764  muon.setSelector(reco::Muon::LowPtMvaMedium, muon.lowptMvaValue() > -0.20);
765  }
766  }
767 
768  //SOFT MVA
769  if (computeSoftMuonMVA_) {
770  float mva = globalCache()->softMuonMvaEstimator()->computeMva(muon);
771  muon.setSoftMvaValue(mva);
772  //preselection in SoftMuonMvaEstimator.cc
773  muon.setSelector(reco::Muon::SoftMvaId, muon.softMvaValue() > 0.58); //WP choose for bmm4
774  }
775  }
776 
777  // put products in Event
778  std::unique_ptr<std::vector<Muon>> ptr(patMuons);
779  iEvent.put(std::move(ptr));
780 
781  if (isolator_.enabled())
783 }
784 
786  const MuonBaseRef& muonRef,
787  const reco::CandidateBaseRef& baseRef,
788  const GenAssociations& genMatches,
789  const IsoDepositMaps& deposits,
790  const IsolationValueMaps& isolationValues) const {
791  // in the particle flow algorithm,
792  // the muon momentum is recomputed.
793  // the new value is stored as the momentum of the
794  // resulting PFCandidate of type Muon, and choosen
795  // as the pat::Muon momentum
796  if (useParticleFlow_)
797  aMuon.setP4(aMuon.pfCandidateRef()->p4());
798  if (embedTrack_)
799  aMuon.embedTrack();
801  aMuon.embedStandAloneMuon();
802  if (embedCombinedMuon_)
803  aMuon.embedCombinedMuon();
804 
805  // embed the TeV refit track refs (only available for globalMuons)
806  if (aMuon.isGlobalMuon()) {
808  aMuon.embedPickyMuon();
810  aMuon.embedTpfmsMuon();
812  aMuon.embedDytMuon();
813  }
814 
815  // embed best tracks (at the end, so unless forceEmbedBestTrack_ is true we can save some space not embedding them twice)
816  if (embedBestTrack_)
820 
821  // store the match to the generated final state muons
822  if (addGenMatch_) {
823  for (size_t i = 0, n = genMatches.size(); i < n; ++i) {
824  reco::GenParticleRef genMuon = (*genMatches[i])[baseRef];
825  aMuon.addGenParticleRef(genMuon);
826  }
827  if (embedGenMatch_)
828  aMuon.embedGenParticle();
829  }
830  if (efficiencyLoader_.enabled()) {
831  efficiencyLoader_.setEfficiencies(aMuon, muonRef);
832  }
833 
834  for (size_t j = 0, nd = deposits.size(); j < nd; ++j) {
835  if (useParticleFlow_) {
836  if (deposits[j]->contains(baseRef.id())) {
837  aMuon.setIsoDeposit(isoDepositLabels_[j].first, (*deposits[j])[baseRef]);
838  } else if (deposits[j]->contains(muonRef.id())) {
839  aMuon.setIsoDeposit(isoDepositLabels_[j].first, (*deposits[j])[muonRef]);
840  } else {
841  reco::CandidatePtr source = aMuon.pfCandidateRef()->sourceCandidatePtr(0);
842  aMuon.setIsoDeposit(isoDepositLabels_[j].first, (*deposits[j])[source]);
843  }
844  } else {
845  aMuon.setIsoDeposit(isoDepositLabels_[j].first, (*deposits[j])[muonRef]);
846  }
847  }
848 
849  for (size_t j = 0; j < isolationValues.size(); ++j) {
850  if (useParticleFlow_) {
851  if (isolationValues[j]->contains(baseRef.id())) {
852  aMuon.setIsolation(isolationValueLabels_[j].first, (*isolationValues[j])[baseRef]);
853  } else if (isolationValues[j]->contains(muonRef.id())) {
854  aMuon.setIsolation(isolationValueLabels_[j].first, (*isolationValues[j])[muonRef]);
855  } else {
856  reco::CandidatePtr source = aMuon.pfCandidateRef()->sourceCandidatePtr(0);
857  aMuon.setIsolation(isolationValueLabels_[j].first, (*isolationValues[j])[source]);
858  }
859  } else {
860  aMuon.setIsolation(isolationValueLabels_[j].first, (*isolationValues[j])[muonRef]);
861  }
862  }
863 
864  if (resolutionLoader_.enabled()) {
866  }
867 }
868 
871  aMuon.polarP4(),
872  miniIsoParams_[0],
873  miniIsoParams_[1],
874  miniIsoParams_[2],
875  miniIsoParams_[3],
876  miniIsoParams_[4],
877  miniIsoParams_[5],
878  miniIsoParams_[6],
879  miniIsoParams_[7],
880  miniIsoParams_[8]);
881  aMuon.setMiniPFIsolation(miniiso);
882 }
883 
884 double PATMuonProducer::getRelMiniIsoPUCorrected(const pat::Muon& muon, double rho, const std::vector<double>& area) {
885  double mindr(miniIsoParams_[0]);
886  double maxdr(miniIsoParams_[1]);
887  double kt_scale(miniIsoParams_[2]);
888  double drcut = pat::miniIsoDr(muon.polarP4(), mindr, maxdr, kt_scale);
889  return pat::muonRelMiniIsoPUCorrected(muon.miniPFIsolation(), muon.polarP4(), drcut, rho, area);
890 }
891 
893  double dR_threshold = 0.4;
894  double dR2_threshold = dR_threshold * dR_threshold;
895  double mix_fraction = 0.5;
896  enum particleType { CH = 0, NH = 1, PH = 2, OTHER = 100000 };
897  double val_PuppiWithLep = 0.0;
898  double val_PuppiWithoutLep = 0.0;
899 
900  for (const auto& cand : *pc) { //pat::pat::PackedCandidate loop start
901 
902  const particleType pType =
903  isChargedHadron(cand.pdgId()) ? CH : isNeutralHadron(cand.pdgId()) ? NH : isPhoton(cand.pdgId()) ? PH : OTHER;
904  if (pType == OTHER) {
905  if (cand.pdgId() != 1 && cand.pdgId() != 2 && abs(cand.pdgId()) != 11 && abs(cand.pdgId()) != 13) {
906  LogTrace("PATMuonProducer") << "candidate with PDGID = " << cand.pdgId()
907  << " is not CH/NH/PH/e/mu or 1/2 (and this is removed from isolation calculation)"
908  << std::endl;
909  }
910  continue;
911  }
912  double d_eta = std::abs(cand.eta() - muon.eta());
913  if (d_eta > dR_threshold)
914  continue;
915 
916  double d_phi = std::abs(reco::deltaPhi(cand.phi(), muon.phi()));
917  if (d_phi > dR_threshold)
918  continue;
919 
920  double dR2 = reco::deltaR2(cand, muon);
921  if (dR2 > dR2_threshold)
922  continue;
923  if (pType == CH && dR2 < 0.0001 * 0.0001)
924  continue;
925  if (pType == NH && dR2 < 0.01 * 0.01)
926  continue;
927  if (pType == PH && dR2 < 0.01 * 0.01)
928  continue;
929  val_PuppiWithLep += cand.pt() * cand.puppiWeight();
930  val_PuppiWithoutLep += cand.pt() * cand.puppiWeightNoLep();
931 
932  } //pat::pat::PackedCandidate loop end
933 
934  double reliso_Puppi_withLep = val_PuppiWithLep / muon.pt();
935  double reliso_Puppi_withoutlep = val_PuppiWithoutLep / muon.pt();
936  double reliso_Puppi_combined = mix_fraction * reliso_Puppi_withLep + (1.0 - mix_fraction) * reliso_Puppi_withoutlep;
937  return reliso_Puppi_combined;
938 }
939 
940 bool PATMuonProducer::isNeutralHadron(long pdgid) { return std::abs(pdgid) == 130; }
941 
942 bool PATMuonProducer::isChargedHadron(long pdgid) { return std::abs(pdgid) == 211; }
943 
944 bool PATMuonProducer::isPhoton(long pdgid) { return pdgid == 22; }
945 
946 // ParameterSet description for module
949  iDesc.setComment("PAT muon producer module");
950 
951  // input source
952  iDesc.add<edm::InputTag>("muonSource", edm::InputTag("no default"))->setComment("input collection");
953 
954  // embedding
955  iDesc.add<bool>("embedMuonBestTrack", true)->setComment("embed muon best track (global pflow)");
956  iDesc.add<bool>("embedTunePMuonBestTrack", true)->setComment("embed muon best track (muon only)");
957  iDesc.add<bool>("forceBestTrackEmbedding", true)
958  ->setComment(
959  "force embedding separately the best tracks even if they're already embedded e.g. as tracker or global "
960  "tracks");
961  iDesc.add<bool>("embedTrack", true)->setComment("embed external track");
962  iDesc.add<bool>("embedStandAloneMuon", true)->setComment("embed external stand-alone muon");
963  iDesc.add<bool>("embedCombinedMuon", false)->setComment("embed external combined muon");
964  iDesc.add<bool>("embedPickyMuon", false)->setComment("embed external picky track");
965  iDesc.add<bool>("embedTpfmsMuon", false)->setComment("embed external tpfms track");
966  iDesc.add<bool>("embedDytMuon", false)->setComment("embed external dyt track ");
967 
968  // embedding of MET muon corrections
969  iDesc.add<bool>("embedCaloMETMuonCorrs", true)->setComment("whether to add MET muon correction for caloMET or not");
970  iDesc.add<edm::InputTag>("caloMETMuonCorrs", edm::InputTag("muonMETValueMapProducer", "muCorrData"))
971  ->setComment("source of MET muon corrections for caloMET");
972  iDesc.add<bool>("embedTcMETMuonCorrs", true)->setComment("whether to add MET muon correction for tcMET or not");
973  iDesc.add<edm::InputTag>("tcMETMuonCorrs", edm::InputTag("muonTCMETValueMapProducer", "muCorrData"))
974  ->setComment("source of MET muon corrections for tcMET");
975 
976  // pf specific parameters
977  iDesc.add<edm::InputTag>("pfMuonSource", edm::InputTag("pfMuons"))->setComment("particle flow input collection");
978  iDesc.add<bool>("useParticleFlow", false)->setComment("whether to use particle flow or not");
979  iDesc.add<bool>("embedPFCandidate", false)->setComment("embed external particle flow object");
980  iDesc.add<bool>("embedPfEcalEnergy", true)->setComment("add ecal energy as reconstructed by PF");
981 
982  // inverse beta computation
983  iDesc.add<bool>("addInverseBeta", true)->setComment("add combined inverse beta");
984  iDesc.add<edm::InputTag>("sourceInverseBeta", edm::InputTag("muons", "combined"))
985  ->setComment("source of inverse beta values");
986 
987  // switch to get the IP from the best track instead of running IPTools
988  iDesc.add<bool>("getdBFromTrack", false)->setComment("switch IP2D computation to use the best track one");
989 
990  // MC matching configurables
991  iDesc.add<bool>("addGenMatch", true)->setComment("add MC matching");
992  iDesc.add<bool>("embedGenMatch", false)->setComment("embed MC matched MC information");
993  std::vector<edm::InputTag> emptySourceVector;
994  iDesc
995  .addNode(edm::ParameterDescription<edm::InputTag>("genParticleMatch", edm::InputTag(), true) xor
996  edm::ParameterDescription<std::vector<edm::InputTag>>("genParticleMatch", emptySourceVector, true))
997  ->setComment("input with MC match information");
998 
999  // mini-iso
1000  iDesc.add<bool>("computeMiniIso", false)->setComment("whether or not to compute and store electron mini-isolation");
1001  iDesc.add<bool>("computePuppiCombinedIso", false)
1002  ->setComment("whether or not to compute and store puppi combined isolation");
1003 
1004  iDesc.add<edm::InputTag>("pfCandsForMiniIso", edm::InputTag("packedPFCandidates"))
1005  ->setComment("collection to use to compute mini-iso");
1006  iDesc.add<std::vector<double>>("miniIsoParams", std::vector<double>())
1007  ->setComment("mini-iso parameters to use for muons");
1008 
1009  iDesc.add<bool>("addTriggerMatching", false)->setComment("add L1 and HLT matching to offline muon");
1010 
1012 
1013  // IsoDeposit configurables
1014  edm::ParameterSetDescription isoDepositsPSet;
1015  isoDepositsPSet.addOptional<edm::InputTag>("tracker");
1016  isoDepositsPSet.addOptional<edm::InputTag>("ecal");
1017  isoDepositsPSet.addOptional<edm::InputTag>("hcal");
1018  isoDepositsPSet.addOptional<edm::InputTag>("particle");
1019  isoDepositsPSet.addOptional<edm::InputTag>("pfChargedHadrons");
1020  isoDepositsPSet.addOptional<edm::InputTag>("pfChargedAll");
1021  isoDepositsPSet.addOptional<edm::InputTag>("pfPUChargedHadrons");
1022  isoDepositsPSet.addOptional<edm::InputTag>("pfNeutralHadrons");
1023  isoDepositsPSet.addOptional<edm::InputTag>("pfPhotons");
1024  isoDepositsPSet.addOptional<std::vector<edm::InputTag>>("user");
1025  iDesc.addOptional("isoDeposits", isoDepositsPSet);
1026 
1027  // isolation values configurables
1028  edm::ParameterSetDescription isolationValuesPSet;
1029  isolationValuesPSet.addOptional<edm::InputTag>("tracker");
1030  isolationValuesPSet.addOptional<edm::InputTag>("ecal");
1031  isolationValuesPSet.addOptional<edm::InputTag>("hcal");
1032  isolationValuesPSet.addOptional<edm::InputTag>("particle");
1033  isolationValuesPSet.addOptional<edm::InputTag>("pfChargedHadrons");
1034  isolationValuesPSet.addOptional<edm::InputTag>("pfChargedAll");
1035  isolationValuesPSet.addOptional<edm::InputTag>("pfPUChargedHadrons");
1036  isolationValuesPSet.addOptional<edm::InputTag>("pfNeutralHadrons");
1037  isolationValuesPSet.addOptional<edm::InputTag>("pfPhotons");
1038  iDesc.addOptional("isolationValues", isolationValuesPSet);
1039 
1040  iDesc.ifValue(edm::ParameterDescription<bool>("addPuppiIsolation", false, true),
1042  "puppiIsolationChargedHadrons",
1043  edm::InputTag("muonPUPPIIsolation", "h+-DR030-ThresholdVeto000-ConeVeto000"),
1044  true) and
1046  "puppiIsolationNeutralHadrons",
1047  edm::InputTag("muonPUPPIIsolation", "h0-DR030-ThresholdVeto000-ConeVeto001"),
1048  true) and
1050  "puppiIsolationPhotons",
1051  edm::InputTag("muonPUPPIIsolation", "gamma-DR030-ThresholdVeto000-ConeVeto001"),
1052  true) and
1054  "puppiNoLeptonsIsolationChargedHadrons",
1055  edm::InputTag("muonPUPPINoLeptonsIsolation", "h+-DR030-ThresholdVeto000-ConeVeto000"),
1056  true) and
1058  "puppiNoLeptonsIsolationNeutralHadrons",
1059  edm::InputTag("muonPUPPINoLeptonsIsolation", "h0-DR030-ThresholdVeto000-ConeVeto001"),
1060  true) and
1062  "puppiNoLeptonsIsolationPhotons",
1063  edm::InputTag("muonPUPPINoLeptonsIsolation", "gamma-DR030-ThresholdVeto000-ConeVeto001"),
1064  true)) or
1065  false >> edm::EmptyGroupDescription());
1066 
1067  // Efficiency configurables
1068  edm::ParameterSetDescription efficienciesPSet;
1069  efficienciesPSet.setAllowAnything(); // TODO: the pat helper needs to implement a description.
1070  iDesc.add("efficiencies", efficienciesPSet);
1071  iDesc.add<bool>("addEfficiencies", false);
1072 
1073  // Check to see if the user wants to add user data
1074  edm::ParameterSetDescription userDataPSet;
1076  iDesc.addOptional("userData", userDataPSet);
1077 
1078  edm::ParameterSetDescription isolationPSet;
1079  isolationPSet.setAllowAnything(); // TODO: the pat helper needs to implement a description.
1080  iDesc.add("userIsolation", isolationPSet);
1081 
1082  iDesc.add<bool>("embedHighLevelSelection", true)->setComment("embed high level selection");
1083  edm::ParameterSetDescription highLevelPSet;
1084  highLevelPSet.setAllowAnything();
1085  iDesc.addNode(edm::ParameterDescription<edm::InputTag>("beamLineSrc", edm::InputTag(), true))
1086  ->setComment("input with high level selection");
1088  ->setComment("input with high level selection");
1089 
1090  //descriptions.add("PATMuonProducer", iDesc);
1091 }
1092 
1093 // embed various impact parameters with errors
1094 // embed high level selection
1099  bool primaryVertexIsValid,
1101  bool beamspotIsValid) {
1102  // Generic variable to store measurements
1103  std::pair<bool,Measurement1D> result;
1104  double d0_corr;
1105  double d0_err;
1106 
1107  // Correct to PV
1108 
1109  // PV2D
1110  if (getdBFromTrack_){
1111  aMuon.setDB(track->dxy(primaryVertex.position()),
1112  track->dxyError(primaryVertex.position(), primaryVertex.covariance()),
1113  pat::Muon::PV2D);
1114  } else{
1115  result =
1116  IPTools::signedTransverseImpactParameter(tt, GlobalVector(track->px(), track->py(), track->pz()), primaryVertex);
1117  d0_corr = result.second.value();
1118  d0_err = primaryVertexIsValid ? result.second.error() : -1.0;
1119  aMuon.setDB( d0_corr, d0_err, pat::Muon::PV2D);
1120  }
1121 
1122  // PV3D
1123  result = IPTools::signedImpactParameter3D(tt, GlobalVector(track->px(), track->py(), track->pz()), primaryVertex);
1124  d0_corr = result.second.value();
1125  d0_err = primaryVertexIsValid ? result.second.error() : -1.0;
1126  aMuon.setDB(d0_corr, d0_err, pat::Muon::PV3D);
1127 
1128  // Correct to beam spot
1129 
1130  // BS2D
1131  // make a fake vertex out of beam spot
1132  reco::Vertex vBeamspot(beamspot.position(), beamspot.rotatedCovariance3D());
1133  if (getdBFromTrack_){
1134  aMuon.setDB(track->dxy(beamspot), track->dxyError(beamspot), pat::Muon::BS2D);
1135  } else{
1136  result = IPTools::signedTransverseImpactParameter(tt, GlobalVector(track->px(), track->py(), track->pz()), vBeamspot);
1137  d0_corr = result.second.value();
1138  d0_err = beamspotIsValid ? result.second.error() : -1.0;
1139  aMuon.setDB( d0_corr, d0_err, pat::Muon::BS2D);
1140  }
1141 
1142  // BS3D
1143  result = IPTools::signedImpactParameter3D(tt, GlobalVector(track->px(), track->py(), track->pz()), vBeamspot);
1144  d0_corr = result.second.value();
1145  d0_err = beamspotIsValid ? result.second.error() : -1.0;
1146  aMuon.setDB(d0_corr, d0_err, pat::Muon::BS3D);
1147 
1148  // PVDZ
1149  aMuon.setDB(
1150  track->dz(primaryVertex.position()), std::hypot(track->dzError(), primaryVertex.zError()), pat::Muon::PVDZ);
1151 }
1152 
1154 
bool embedTpfmsMuon_
embed track from tpfms muon fit into the muon
edm::EDGetTokenT< edm::ValueMap< float > > PUPPIIsolation_charged_hadrons_
bool enabled() const
&#39;true&#39; if this there is at least one efficiency configured
bool useUserData_
add user data to the muon (this will be data members of th muon even w/o embedding) ...
void readIsolationLabels(const edm::ParameterSet &iConfig, const char *psetName, IsolationLabels &labels, std::vector< edm::EDGetTokenT< edm::ValueMap< T >>> &tokens)
constexpr double deltaPhi(double phi1, double phi2)
Definition: deltaPhi.h:22
bool isAvailable() const
Definition: Ref.h:575
edm::EDGetTokenT< edm::ValueMap< float > > PUPPIIsolation_photons_
T getParameter(std::string const &) const
double ecalEnergy() const
return corrected Ecal energy
Definition: PFCandidate.h:222
void setComment(std::string const &value)
Assists in assimilating all pat::UserData into pat objects.
ParameterDescriptionNode * ifValue(ParameterDescription< T > const &switchParameter, std::unique_ptr< ParameterDescriptionCases< T >> cases)
void newEvent(const edm::Event &event)
To be called for each new event, reads in the ValueMaps for efficiencies.
bool addPuppiIsolation_
add puppi isolation
void embedDytMuon()
embed reference to the above dyt Track
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:125
ParameterDescriptionBase * addOptional(U const &iLabel, T const &value)
bool isNonnull() const
Checks for non-null.
Definition: Ref.h:251
void embedTpfmsMuon()
embed reference to the above tpfms Track
edm::EDGetTokenT< edm::ValueMap< reco::MuonMETCorrectionData > > tcMETMuonCorrsToken_
source of tcMET muon corrections
double eta() const final
momentum pseudorapidity
void setIsolation(IsolationKeys key, float value)
Definition: Lepton.h:99
bool embedTcMETMuonCorrs_
embed muon MET correction info for tcMET into the muon
const PolarLorentzVector & polarP4() const final
four-momentum Lorentz vector
class definition
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:161
void embedTcMETMuonCorrs(const reco::MuonMETCorrectionData &t)
edm::EDGetTokenT< std::vector< reco::Vertex > > pvToken_
input source of the primary vertex
bool contains(EventRange const &lh, EventID const &rh)
Definition: EventRange.cc:38
static const int OTHER
edm::EDGetTokenT< edm::ValueMap< reco::MuonTimeExtra > > muonTimeExtraToken_
input tag for reading inverse beta
edm::EDGetTokenT< edm::ValueMap< float > > PUPPINoLeptonsIsolation_photons_
void embedCombinedMuon()
set reference to Track reconstructed in both tracked and muon detector (reimplemented from reco::Muon...
edm::EDGetTokenT< double > rho_
edm::EDGetTokenT< edm::View< reco::Muon > > muonToken_
input source
void embedTunePMuonBestTrack(bool force=false)
bool addEfficiencies_
add efficiencies to the muon (this will be data members of th muon even w/o embedding) ...
edm::EDGetTokenT< edm::ValueMap< reco::MuonMETCorrectionData > > caloMETMuonCorrsToken_
source of caloMET muon corrections
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:517
enum start value shifted to 81 so as to avoid clashes with PDG codes
void setAllowAnything()
allow any parameter label/value pairs
double zError() const
error on z
Definition: Vertex.h:123
void setSimFlavour(int f)
Definition: Muon.h:325
GlobalPoint toGlobal(const Local2DPoint &lp) const
Conversion to the global R.F. from the R.F. of the GeomDet.
Definition: GeomDet.h:54
bool embedCaloMETMuonCorrs_
embed muon MET correction info for caloMET into the muon
bool isChargedHadron(long pdgid)
std::pair< bool, Measurement1D > signedTransverseImpactParameter(const reco::TransientTrack &track, const GlobalVector &direction, const reco::Vertex &vertex)
Definition: IPTools.cc:50
~PATMuonProducer() override
default destructur
edm::EDGetTokenT< edm::ValueMap< reco::MuonSimInfo > > simInfo_
MC info.
void embedMuonBestTrack(bool force=false)
std::vector< pat::PackedCandidate > PackedCandidateCollection
void setIsolationPUPPINoLeptons(float chargedhadrons, float neutralhadrons, float photons)
sets PUPPINoLeptons isolations
Definition: Muon.h:207
void setMuonMiniIso(pat::Muon &aMuon, const pat::PackedCandidateCollection *pc)
reco::TransientTrack build(const reco::Track *p) const
PATMuonProducer(const edm::ParameterSet &iConfig, PATMuonHeavyObjectCache const *)
default constructir
bool addTriggerMatching_
Trigger.
void setSimBX(int bx)
Definition: Muon.h:329
ParameterDescriptionNode * addNode(ParameterDescriptionNode const &node)
bool embedBestTrack_
embed the track from best muon measurement (global pflow)
edm::EDGetTokenT< reco::JetCorrector > mvaL1Corrector_
std::pair< bool, Measurement1D > signedImpactParameter3D(const reco::TransientTrack &track, const GlobalVector &direction, const reco::Vertex &vertex)
Definition: IPTools.cc:71
double pt() const final
transverse momentum
bool addResolutions_
add resolutions to the muon (this will be data members of th muon even w/o embedding) ...
double covariance(int i, int j) const
(i, j)-th element of error matrix, i, j = 0, ... 2
Definition: Vertex.h:130
void unpackPathNames(const edm::TriggerNames &names)
unpack trigger names into indices
edm::EDGetTokenT< edm::ValueMap< float > > PUPPINoLeptonsIsolation_charged_hadrons_
std::vector< double > miniIsoParams_
void setSimPhi(float phi)
Definition: Muon.h:335
PFCandidateCollection::const_iterator PFCandidateConstIterator
iterator
void setResolutions(pat::PATObject< T > &obj) const
Sets the efficiencies for this object, using the reference to the original objects.
void setSimProdRho(float rho)
Definition: Muon.h:331
void setSimHeaviestMotherFlavour(int id)
Definition: Muon.h:326
void setPFCandidateRef(const reco::PFCandidateRef &ref)
add a reference to the source IsolatedPFCandidate
Definition: Muon.h:141
bool isRealData() const
Definition: EventBase.h:62
const Point & position() const
position
Definition: Vertex.h:109
void embedHighLevel(pat::Muon &aMuon, reco::TrackRef track, reco::TransientTrack &tt, reco::Vertex &primaryVertex, bool primaryVertexIsValid, reco::BeamSpot &beamspot, bool beamspotIsValid)
std::vector< double > effectiveAreaVec_
ProductID id() const
Definition: RefToBase.h:242
const std::string names[nVars_]
edm::EDGetTokenT< edm::ValueMap< float > > PUPPINoLeptonsIsolation_neutral_hadrons_
void setSimType(reco::MuonSimType type)
Definition: Muon.h:323
void embedStandAloneMuon()
set reference to Track reconstructed in the muon detector only (reimplemented from reco::Muon) ...
edm::EDGetTokenT< reco::JetTagCollection > mvaBTagCollectionTag_
edm::EDGetTokenT< reco::PFCandidateCollection > pfMuonToken_
input source pfCandidates that will be to be transformed into pat::Muons, when using PF2PAT ...
void setIsolationPUPPI(float chargedhadrons, float neutralhadrons, float photons)
sets PUPPI isolations
Definition: Muon.h:201
pat::helper::MultiIsolator isolator_
helper class to add userdefined isolation values to the muon
std::vector< edm::EDGetTokenT< edm::ValueMap< IsoDeposit > > > isoDepositTokens_
bool enabled() const
&#39;true&#39; if this there is at least one efficiency configured
void setIsoDeposit(IsolationKeys key, const IsoDeposit &dep)
Sets the IsoDeposit associated with some key; if it is already existent, it is overwritten.
Definition: Lepton.h:176
Definition: HeavyIon.h:7
void embedTrack()
set reference to Track reconstructed in the tracker only (reimplemented from reco::Muon) ...
static void fillDescription(edm::ParameterSetDescription &iDesc)
const PFIsolation & miniPFIsolation() const
Definition: Lepton.h:196
edm::EDGetTokenT< reco::BeamSpot > beamLineToken_
input source of the primary vertex/beamspot
bool addInverseBeta_
add combined inverse beta measurement into the muon
bool useParticleFlow_
switch to use particle flow (PF2PAT) or not
pat::PATUserDataHelper< pat::Muon > userDataHelper_
helper class to add userData to the muon
bool enabled() const
True if it has a non null configuration.
Definition: MultiIsolator.h:50
std::vector< edm::Handle< edm::ValueMap< IsoDeposit > > > IsoDepositMaps
bool embedStandAloneMuon_
embed track from muon system into the muon
void setComment(std::string const &value)
edm::EDGetTokenT< edm::TriggerResults > triggerResults_
int iEvent
Definition: GenABIO.cc:224
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
void beginEvent(const edm::Event &event, const edm::EventSetup &eventSetup)
GreaterByPt< Muon > pTComparator_
bool embedTrack_
embed the track from inner tracker into the muon
void setDB(double dB, double edB, IPTYPE type=PV2D)
Definition: Muon.h:247
bool addGenMatch_
add generator match information
PATMuonHeavyObjectCache(const edm::ParameterSet &)
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
description of config file parameters
Definition: Muon.py:1
void fillL1TriggerInfo(pat::Muon &muon, edm::Handle< std::vector< pat::TriggerObjectStandAlone >> &triggerObjects, const edm::TriggerNames &names, const edm::ESHandle< GlobalTrackingGeometry > &geometry)
double muonRelMiniIsoPUCorrected(const PFIsolation &iso, const reco::Candidate::PolarLorentzVector &p4, double dr, double rho, const std::vector< double > &area)
bool isGlobalMuon() const override
Definition: Muon.h:291
bool embedPfEcalEnergy_
add ecal PF energy
void embedGenParticle()
Definition: PATObject.h:694
void newEvent(const edm::Event &event, const edm::EventSetup &setup)
To be called for each new event, reads in the EventSetup object.
void embedPFCandidate()
embed the IsolatedPFCandidate pointed to by pfCandidateRef_
bool getdBFromTrack_
switch on reading the dB information from the track
The Signals That Services Can Subscribe To This is based on ActivityRegistry and is current per Services can connect to the signals distributed by the ActivityRegistry in order to monitor the activity of the application Each possible callback has some defined which we here list in angle e< void, edm::EventID const &, edm::Timestamp const & > We also list in braces which AR_WATCH_USING_METHOD_ is used for those or
Definition: Activities.doc:12
void produce(edm::Event &iEvent, const edm::EventSetup &iSetup) override
everything that needs to be done during the event loop
reco::PFCandidateRef pfCandidateRef() const
RunNumber_t run() const
Definition: Event.h:101
def pv(vc)
Definition: MetAnalyzer.py:7
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
edm::EDGetTokenT< pat::PackedCandidateCollection > pcToken_
static std::string const triggerResults
Definition: EdmProvDump.cc:45
ParameterDescriptionBase * add(U const &iLabel, T const &value)
bool isValid() const
Definition: HandleBase.h:74
double puppiCombinedIsolation(const pat::Muon &muon, const pat::PackedCandidateCollection *pc)
#define LogTrace(id)
void readTimeExtra(const reco::MuonTimeExtra &t)
std::vector< std::string > hltCollectionFilters_
float miniIsoDr(const reco::Candidate::PolarLorentzVector &p4, float mindr, float maxdr, float kt_scale)
reco::MuonRef muonRef() const
Definition: PFCandidate.cc:459
void fillHltTriggerInfo(pat::Muon &muon, edm::Handle< std::vector< pat::TriggerObjectStandAlone >> &triggerObjects, const edm::TriggerNames &names, const std::vector< std::string > &collection_names)
reco::Muon::Selector makeSelectorBitset(reco::Muon const &muon, reco::Vertex const *vertex=0, bool run2016_hip_mitigation=false)
Definition: DetId.h:18
bool isAValidMuonTrack(const MuonTrackType &type) const
void initSimInfo(void)
constexpr auto deltaR2(const T1 &t1, const T2 &t2) -> decltype(t1.eta())
Definition: deltaR.h:16
void addGenParticleRef(const reco::GenParticleRef &ref)
Definition: PATObject.h:678
auto vector_transform(std::vector< InputType > const &input, Function predicate) -> std::vector< typename std::remove_cv< typename std::remove_reference< decltype(predicate(input.front()))>::type >::type >
Definition: transform.h:11
void setPfEcalEnergy(float pfEcalEnergy)
Definition: Muon.h:277
bool embedTunePBestTrack_
embed the track from best muon measurement (muon only)
T const * product() const
Definition: Handle.h:74
static void fillDescription(edm::ParameterSetDescription &iDesc)
Method for documentation and validation of PSet.
double getRelMiniIsoPUCorrected(const pat::Muon &muon, double rho, const std::vector< double > &area)
void setSimMotherPdgId(int id)
Definition: Muon.h:328
void setEfficiencies(pat::PATObject< T > &obj, const R &originalRef) const
Sets the efficiencies for this object, using the reference to the original objects.
void addTriggerObjectMatch(const TriggerObjectStandAlone &trigObj)
add a trigger match
Definition: PATObject.h:204
void setExtSimType(reco::ExtendedMuonSimType type)
Definition: Muon.h:324
std::vector< MuonChamberMatch > & matches()
get muon matching information
Definition: Muon.h:144
void setMiniPFIsolation(PFIsolation const &iso)
Definition: Lepton.h:197
std::vector< edm::Handle< edm::Association< reco::GenParticleCollection > > > GenAssociations
edm::EDGetTokenT< reco::JetCorrector > mvaL1L2L3ResCorrector_
void fillMuon(Muon &aMuon, const MuonBaseRef &muonRef, const reco::CandidateBaseRef &baseRef, const GenAssociations &genMatches, const IsoDepositMaps &deposits, const IsolationValueMaps &isolationValues) const
common muon filling, for both the standard and PF2PAT case
ESHandle< TrackerGeometry > geometry
std::vector< std::pair< pat::IsolationKeys, float > > IsolationValuePairs
Definition: MultiIsolator.h:16
void setSimProdZ(float z)
Definition: Muon.h:332
Particle reconstructed by the particle flow algorithm.
Definition: PFCandidate.h:40
std::vector< edm::Handle< edm::ValueMap< double > > > IsolationValueMaps
pat::helper::EfficiencyLoader efficiencyLoader_
helper class to add efficiencies to the muon
HLT enums.
bool embedPickyMuon_
embed track from picky muon fit into the muon
void setNormChi2(double normChi2)
Definition: Muon.h:262
boost::indirect_iterator< typename seq_t::const_iterator > const_iterator
Definition: View.h:86
bool embedDytMuon_
embed track from DYT muon fit into the muon
void embedCaloMETMuonCorrs(const reco::MuonMETCorrectionData &t)
void setSimPdgId(int id)
Definition: Muon.h:327
T get() const
Definition: EventSetup.h:71
void setSimPt(float pt)
Definition: Muon.h:333
const GeomDet * idToDet(DetId) const override
bool isPhoton(long pdgid)
pat::helper::MultiIsolator::IsolationValuePairs isolatorTmpStorage_
isolation value pair for temporary storage before being folded into the muon
edm::EDGetTokenT< std::vector< pat::TriggerObjectStandAlone > > triggerObjects_
bool embedGenMatch_
embed the gen match information into the muon
const Point & position() const
position
Definition: BeamSpot.h:62
IsolationLabels isoDepositLabels_
input source for isoDeposits
std::vector< edm::EDGetTokenT< edm::Association< reco::GenParticleCollection > > > genMatchTokens_
input tags for generator match information
PFIsolation getMiniPFIsolation(const pat::PackedCandidateCollection *pfcands, const reco::Candidate::PolarLorentzVector &p4, float mindr=0.05, float maxdr=0.2, float kt_scale=10.0, float ptthresh=0.5, float deadcone_ch=0.0001, float deadcone_pu=0.01, float deadcone_ph=0.01, float deadcone_nh=0.01, float dZ_cut=0.0)
Covariance3DMatrix rotatedCovariance3D() const
Definition: BeamSpot.cc:78
static constexpr int DT
Definition: MuonSubdetId.h:12
IsolationLabels isolationValueLabels_
input source isolation value maps
bool isValid() const
Definition: ESHandle.h:44
void embedPickyMuon()
embed reference to the above picky Track
static constexpr int CSC
Definition: MuonSubdetId.h:13
bool forceEmbedBestTrack_
force separate embed of the best track even if already embedded
bool embedPFCandidate_
embed pfCandidates into the muon
double phi() const final
momentum azimuthal angle
std::vector< edm::EDGetTokenT< edm::ValueMap< double > > > isolationValueTokens_
void setNumberOfValidHits(unsigned int numberOfValidHits)
Definition: Muon.h:255
bool computeMuonMVA_
standard muon selectors
void setSimEta(float eta)
Definition: Muon.h:334
bool embedCombinedMuon_
embed track of the combined fit into the muon
Analysis-level muon class.
Definition: Muon.h:51
pat::helper::KinResolutionsLoader resolutionLoader_
helper class to add resolutions to the muon
static std::string const source
Definition: EdmProvDump.cc:47
void setP4(const LorentzVector &p4) final
set 4-momentum
edm::TriggerNames const & triggerNames(edm::TriggerResults const &triggerResults) const override
Definition: Event.cc:256
edm::EDGetTokenT< edm::ValueMap< float > > PUPPIIsolation_neutral_hadrons_
def move(src, dest)
Definition: eostools.py:511
std::optional< GlobalPoint > getMuonDirection(const reco::MuonChamberMatch &chamberMatch, const edm::ESHandle< GlobalTrackingGeometry > &geometry, const DetId &chamberId)
bool isNeutralHadron(long pdgid)
Global3DVector GlobalVector
Definition: GlobalVector.h:10
Analysis-level trigger object class (stand-alone)
void setSimMatchQuality(float quality)
Definition: Muon.h:336
void fill(const edm::View< T > &coll, int idx, IsolationValuePairs &isolations) const
Definition: MultiIsolator.h:82
void setSimTpEvent(int tpEvent)
Definition: Muon.h:330
bool embedHighLevelSelection_
embed high level selection variables