CMS 3D CMS Logo

TemplatedSecondaryVertexProducer.cc
Go to the documentation of this file.
1 #include <algorithm>
2 #include <cstddef>
3 #include <functional>
4 #include <iterator>
5 #include <map>
6 #include <memory>
7 #include <set>
8 #include <string>
9 #include <vector>
10 
11 #include <boost/iterator/transform_iterator.hpp>
12 
25 
29 
34 
39 
47 
52 
58 
60 
61 #include "fastjet/JetDefinition.hh"
62 #include "fastjet/ClusterSequence.hh"
63 #include "fastjet/PseudoJet.hh"
64 
65 //
66 // constants, enums and typedefs
67 //
68 typedef std::shared_ptr<fastjet::ClusterSequence> ClusterSequencePtr;
69 typedef std::shared_ptr<fastjet::JetDefinition> JetDefPtr;
70 
71 using namespace reco;
72 
73 namespace {
74  class VertexInfo : public fastjet::PseudoJet::UserInfoBase {
75  public:
76  VertexInfo(const int vertexIndex) : m_vertexIndex(vertexIndex) {}
77 
78  inline const int vertexIndex() const { return m_vertexIndex; }
79 
80  protected:
81  int m_vertexIndex;
82  };
83 
84  template <typename T>
85  struct RefToBaseLess {
86  inline bool operator()(const edm::RefToBase<T> &r1, const edm::RefToBase<T> &r2) const {
87  return r1.id() < r2.id() || (r1.id() == r2.id() && r1.key() < r2.key());
88  }
89  };
90 } // namespace
91 
93  return GlobalVector(sv.x() - pv.x(), sv.y() - pv.y(), sv.z() - pv.z());
94 }
96  return GlobalVector(sv.vertex().x() - pv.x(), sv.vertex().y() - pv.y(), sv.vertex().z() - pv.z());
97 }
98 const math::XYZPoint &position(const reco::Vertex &sv) { return sv.position(); }
99 const math::XYZPoint &position(const reco::VertexCompositePtrCandidate &sv) { return sv.vertex(); }
100 
101 template <class IPTI, class VTX>
103 public:
106  static void fillDescriptions(edm::ConfigurationDescriptions &descriptions);
107  typedef std::vector<TemplatedSecondaryVertexTagInfo<IPTI, VTX> > Product;
109  typedef typename IPTI::input_container input_container;
111  typedef typename std::vector<reco::btag::IndexedTrackData> TrackDataVector;
112  void produce(edm::Event &event, const edm::EventSetup &es) override;
113 
114 private:
115  template <class CONTAINER>
116  void matchReclusteredJets(const edm::Handle<CONTAINER> &jets,
117  const std::vector<fastjet::PseudoJet> &matchedJets,
118  std::vector<int> &matchedIndices,
119  const std::string &jetType = "");
120  void matchGroomedJets(const edm::Handle<edm::View<reco::Jet> > &jets,
121  const edm::Handle<edm::View<reco::Jet> > &matchedJets,
122  std::vector<int> &matchedIndices);
123  void matchSubjets(const std::vector<int> &groomedIndices,
124  const edm::Handle<edm::View<reco::Jet> > &groomedJets,
125  const edm::Handle<std::vector<IPTI> > &subjets,
126  std::vector<std::vector<int> > &matchedIndices);
127  void matchSubjets(const edm::Handle<edm::View<reco::Jet> > &fatJets,
128  const edm::Handle<std::vector<IPTI> > &subjets,
129  std::vector<std::vector<int> > &matchedIndices);
130 
131  const reco::Jet *toJet(const reco::Jet &j) { return &j; }
132  const reco::Jet *toJet(const IPTI &j) { return &(*(j.jet())); }
133 
135  CONSTRAINT_NONE = 0,
140  CONSTRAINT_PV_PRIMARIES_IN_FIT
141  };
142  static ConstraintType getConstraintType(const std::string &name);
143 
162  double rParam;
163  double jetPtMin;
172 
175 
176  void markUsedTracks(TrackDataVector &trackData,
177  const input_container &trackRefs,
178  const SecondaryVertex &sv,
179  size_t idx);
180 
181  struct SVBuilder {
182  SVBuilder(const reco::Vertex &pv, const GlobalVector &direction, bool withPVError, double minTrackWeight)
183  : pv(pv), direction(direction), withPVError(withPVError), minTrackWeight(minTrackWeight) {}
184  SecondaryVertex operator()(const TransientVertex &sv) const;
185 
186  SecondaryVertex operator()(const VTX &sv) const { return SecondaryVertex(pv, sv, direction, withPVError); }
187 
188  const Vertex &pv;
192  };
193 
194  struct SVFilter {
195  SVFilter(const VertexFilter &filter, const Vertex &pv, const GlobalVector &direction)
196  : filter(filter), pv(pv), direction(direction) {}
197 
198  inline bool operator()(const SecondaryVertex &sv) const { return !filter(pv, sv, direction); }
199 
201  const Vertex &pv;
203  };
204 };
205 template <class IPTI, class VTX>
208  if (name == "None")
209  return CONSTRAINT_NONE;
210  else if (name == "BeamSpot")
211  return CONSTRAINT_BEAMSPOT;
212  else if (name == "BeamSpot+PVPosition")
213  return CONSTRAINT_PV_BEAMSPOT_SIZE;
214  else if (name == "BeamSpotZ+PVErrorScaledXY")
215  return CONSTRAINT_PV_BS_Z_ERRORS_SCALED;
216  else if (name == "PVErrorScaled")
217  return CONSTRAINT_PV_ERROR_SCALED;
218  else if (name == "BeamSpot+PVTracksInFit")
219  return CONSTRAINT_PV_PRIMARIES_IN_FIT;
220  else
221  throw cms::Exception("InvalidArgument") << "TemplatedSecondaryVertexProducer: ``constraint'' parameter "
222  "value \""
223  << name << "\" not understood." << std::endl;
224 }
225 
227  if (name == "AlwaysWithGhostTrack")
229  else if (name == "SingleTracksWithGhostTrack")
231  else if (name == "RefitGhostTrackWithVertices")
233  else
234  throw cms::Exception("InvalidArgument") << "TemplatedSecondaryVertexProducer: ``fitType'' "
235  "parameter value \""
236  << name
237  << "\" for "
238  "GhostTrackVertexFinder settings not "
239  "understood."
240  << std::endl;
241 }
242 
243 template <class IPTI, class VTX>
245  : sortCriterium(TrackSorting::getCriterium(params.getParameter<std::string>("trackSort"))),
246  trackSelector(params.getParameter<edm::ParameterSet>("trackSelection")),
247  constraint(getConstraintType(params.getParameter<std::string>("constraint"))),
248  constraintScaling(1.0),
249  vtxRecoPSet(params.getParameter<edm::ParameterSet>("vertexReco")),
250  useGhostTrack(vtxRecoPSet.getParameter<std::string>("finder") == "gtvr"),
251  withPVError(params.getParameter<bool>("usePVError")),
252  minTrackWeight(params.getParameter<double>("minimumTrackWeight")),
253  vertexFilter(params.getParameter<edm::ParameterSet>("vertexCuts")),
254  vertexSorting(params.getParameter<edm::ParameterSet>("vertexSelection")) {
255  token_trackIPTagInfo = consumes<std::vector<IPTI> >(params.getParameter<edm::InputTag>("trackIPTagInfos"));
257  constraintScaling = params.getParameter<double>("pvErrorScaling");
258 
261  token_BeamSpot = consumes<reco::BeamSpot>(params.getParameter<edm::InputTag>("beamSpotTag"));
262  useExternalSV = params.getParameter<bool>("useExternalSV");
263  if (useExternalSV) {
264  token_extSVCollection = consumes<edm::View<VTX> >(params.getParameter<edm::InputTag>("extSVCollection"));
265  extSVDeltaRToJet = params.getParameter<double>("extSVDeltaRToJet");
266  }
267  useSVClustering = (params.existsAs<bool>("useSVClustering") ? params.getParameter<bool>("useSVClustering") : false);
268  useSVMomentum = (params.existsAs<bool>("useSVMomentum") ? params.getParameter<bool>("useSVMomentum") : false);
269  useFatJets = (useExternalSV && params.exists("fatJets"));
270  useGroomedFatJets = (useExternalSV && params.exists("groomedFatJets"));
271  if (useSVClustering) {
272  jetAlgorithm = params.getParameter<std::string>("jetAlgorithm");
273  rParam = params.getParameter<double>("rParam");
274  jetPtMin =
275  0.; // hardcoded to 0. since we simply want to recluster all input jets which already had some PtMin applied
277  (params.existsAs<double>("ghostRescaling") ? params.getParameter<double>("ghostRescaling") : 1e-18);
279  (params.existsAs<double>("relPtTolerance")
280  ? params.getParameter<double>("relPtTolerance")
281  : 1e-03); // 0.1% relative difference in Pt should be sufficient to detect possible misconfigurations
282 
283  // set jet algorithm
284  if (jetAlgorithm == "Kt")
285  fjJetDefinition = std::make_shared<fastjet::JetDefinition>(fastjet::kt_algorithm, rParam);
286  else if (jetAlgorithm == "CambridgeAachen")
287  fjJetDefinition = std::make_shared<fastjet::JetDefinition>(fastjet::cambridge_algorithm, rParam);
288  else if (jetAlgorithm == "AntiKt")
289  fjJetDefinition = std::make_shared<fastjet::JetDefinition>(fastjet::antikt_algorithm, rParam);
290  else
291  throw cms::Exception("InvalidJetAlgorithm") << "Jet clustering algorithm is invalid: " << jetAlgorithm
292  << ", use CambridgeAachen | Kt | AntiKt" << std::endl;
293  }
295  esConsumes<TransientTrackBuilder, TransientTrackRecord>(edm::ESInputTag("", "TransientTrackBuilder"));
296  if (useFatJets) {
297  token_fatJets = consumes<edm::View<reco::Jet> >(params.getParameter<edm::InputTag>("fatJets"));
298  }
299  edm::InputTag srcWeights = params.getParameter<edm::InputTag>("weights");
300  if (!srcWeights.label().empty())
302  if (useGroomedFatJets) {
303  token_groomedFatJets = consumes<edm::View<reco::Jet> >(params.getParameter<edm::InputTag>("groomedFatJets"));
304  }
305  if (useFatJets && !useSVClustering)
306  rParam = params.getParameter<double>("rParam"); // will be used later as a dR cut
307 
308  produces<Product>();
309 }
310 template <class IPTI, class VTX>
312 
313 template <class IPTI, class VTX>
315  // typedef std::map<TrackBaseRef, TransientTrack,
316  // RefToBaseLess<Track> > TransientTrackMap;
317  //How about good old pointers?
318  typedef std::map<const Track *, TransientTrack> TransientTrackMap;
319 
320  edm::ESHandle<TransientTrackBuilder> trackBuilder = es.getHandle(token_trackBuilder);
321 
323  event.getByToken(token_trackIPTagInfo, trackIPTagInfos);
324 
325  // External Sec Vertex collection (e.g. for IVF usage)
326  edm::Handle<edm::View<VTX> > extSecVertex;
327  if (useExternalSV)
328  event.getByToken(token_extSVCollection, extSecVertex);
329 
330  edm::Handle<edm::View<reco::Jet> > fatJetsHandle;
331  edm::Handle<edm::View<reco::Jet> > groomedFatJetsHandle;
332  if (useFatJets) {
333  event.getByToken(token_fatJets, fatJetsHandle);
334  if (useGroomedFatJets) {
335  event.getByToken(token_groomedFatJets, groomedFatJetsHandle);
336 
337  if (groomedFatJetsHandle->size() > fatJetsHandle->size())
338  edm::LogError("TooManyGroomedJets")
339  << "There are more groomed (" << groomedFatJetsHandle->size() << ") than original fat jets ("
340  << fatJetsHandle->size() << "). Please check that the two jet collections belong to each other.";
341  }
342  }
343  edm::Handle<edm::ValueMap<float> > weightsHandle;
344  if (!token_weights.isUninitialized())
345  event.getByToken(token_weights, weightsHandle);
346 
348  unsigned int bsCovSrc[7] = {
349  0,
350  };
351  double sigmaZ = 0.0, beamWidth = 0.0;
352  switch (constraint) {
353  case CONSTRAINT_PV_BEAMSPOT_SIZE:
354  event.getByToken(token_BeamSpot, beamSpot);
355  bsCovSrc[3] = bsCovSrc[4] = bsCovSrc[5] = bsCovSrc[6] = 1;
356  sigmaZ = beamSpot->sigmaZ();
357  beamWidth = beamSpot->BeamWidthX();
358  break;
359 
360  case CONSTRAINT_PV_BS_Z_ERRORS_SCALED:
361  event.getByToken(token_BeamSpot, beamSpot);
362  bsCovSrc[0] = bsCovSrc[1] = 2;
363  bsCovSrc[3] = bsCovSrc[4] = bsCovSrc[5] = 1;
364  sigmaZ = beamSpot->sigmaZ();
365  break;
366 
367  case CONSTRAINT_PV_ERROR_SCALED:
368  bsCovSrc[0] = bsCovSrc[1] = bsCovSrc[2] = 2;
369  break;
370 
371  case CONSTRAINT_BEAMSPOT:
372  case CONSTRAINT_PV_PRIMARIES_IN_FIT:
373  event.getByToken(token_BeamSpot, beamSpot);
374  break;
375 
376  default:
377  /* nothing */;
378  }
379 
380  // ------------------------------------ SV clustering START --------------------------------------------
381  std::vector<std::vector<int> > clusteredSVs(trackIPTagInfos->size(), std::vector<int>());
382  if (useExternalSV && useSVClustering && !trackIPTagInfos->empty()) {
383  // vector of constituents for reclustering jets and "ghost" SVs
384  std::vector<fastjet::PseudoJet> fjInputs;
385  // loop over all input jets and collect all their constituents
386  if (useFatJets) {
387  for (edm::View<reco::Jet>::const_iterator it = fatJetsHandle->begin(); it != fatJetsHandle->end(); ++it) {
388  std::vector<edm::Ptr<reco::Candidate> > constituents = it->getJetConstituents();
389  std::vector<edm::Ptr<reco::Candidate> >::const_iterator m;
390  for (m = constituents.begin(); m != constituents.end(); ++m) {
391  reco::CandidatePtr constit = *m;
392  if (constit.isNull() || constit->pt() <= std::numeric_limits<double>::epsilon()) {
393  edm::LogWarning("NullTransverseMomentum") << "dropping input candidate with pt=0";
394  continue;
395  }
396  if (it->isWeighted()) {
397  if (token_weights.isUninitialized())
398  throw cms::Exception("MissingConstituentWeight")
399  << "TemplatedSecondaryVertexProducer: No weights (e.g. PUPPI) given for weighted jet collection"
400  << std::endl;
401  float w = (*weightsHandle)[constit];
402  if (w > 0) {
403  fjInputs.push_back(
404  fastjet::PseudoJet(constit->px() * w, constit->py() * w, constit->pz() * w, constit->energy() * w));
405  }
406  } else {
407  fjInputs.push_back(fastjet::PseudoJet(constit->px(), constit->py(), constit->pz(), constit->energy()));
408  }
409  }
410  }
411  } else {
412  for (typename std::vector<IPTI>::const_iterator it = trackIPTagInfos->begin(); it != trackIPTagInfos->end();
413  ++it) {
414  std::vector<edm::Ptr<reco::Candidate> > constituents = it->jet()->getJetConstituents();
415  std::vector<edm::Ptr<reco::Candidate> >::const_iterator m;
416  for (m = constituents.begin(); m != constituents.end(); ++m) {
417  reco::CandidatePtr constit = *m;
418  if (constit.isNull() || constit->pt() <= std::numeric_limits<double>::epsilon()) {
419  edm::LogWarning("NullTransverseMomentum") << "dropping input candidate with pt=0";
420  continue;
421  }
422  if (it->jet()->isWeighted()) {
423  if (token_weights.isUninitialized())
424  throw cms::Exception("MissingConstituentWeight")
425  << "TemplatedSecondaryVertexProducer: No weights (e.g. PUPPI) given for weighted jet collection"
426  << std::endl;
427  float w = (*weightsHandle)[constit];
428  if (w > 0) {
429  fjInputs.push_back(
430  fastjet::PseudoJet(constit->px() * w, constit->py() * w, constit->pz() * w, constit->energy() * w));
431  }
432  } else {
433  fjInputs.push_back(fastjet::PseudoJet(constit->px(), constit->py(), constit->pz(), constit->energy()));
434  }
435  }
436  }
437  }
438  // insert "ghost" SVs in the vector of constituents
439  for (typename edm::View<VTX>::const_iterator it = extSecVertex->begin(); it != extSecVertex->end(); ++it) {
440  const reco::Vertex &pv = *(trackIPTagInfos->front().primaryVertex());
442  dir = dir.unit();
443  fastjet::PseudoJet p(
444  dir.x(), dir.y(), dir.z(), dir.mag()); // using SV flight direction so treating SV as massless
445  if (useSVMomentum)
446  p = fastjet::PseudoJet(it->p4().px(), it->p4().py(), it->p4().pz(), it->p4().energy());
447  p *= ghostRescaling; // rescale SV direction/momentum
448  p.set_user_info(new VertexInfo(it - extSecVertex->begin()));
449  fjInputs.push_back(p);
450  }
451 
452  // define jet clustering sequence
453  fjClusterSeq = std::make_shared<fastjet::ClusterSequence>(fjInputs, *fjJetDefinition);
454  // recluster jet constituents and inserted "ghosts"
455  std::vector<fastjet::PseudoJet> inclusiveJets = fastjet::sorted_by_pt(fjClusterSeq->inclusive_jets(jetPtMin));
456 
457  if (useFatJets) {
458  if (inclusiveJets.size() < fatJetsHandle->size())
459  edm::LogError("TooFewReclusteredJets")
460  << "There are fewer reclustered (" << inclusiveJets.size() << ") than original fat jets ("
461  << fatJetsHandle->size()
462  << "). Please check that the jet algorithm and jet size match those used for the original jet collection.";
463 
464  // match reclustered and original fat jets
465  std::vector<int> reclusteredIndices;
466  matchReclusteredJets<edm::View<reco::Jet> >(fatJetsHandle, inclusiveJets, reclusteredIndices, "fat");
467 
468  // match groomed and original fat jets
469  std::vector<int> groomedIndices;
470  if (useGroomedFatJets)
471  matchGroomedJets(fatJetsHandle, groomedFatJetsHandle, groomedIndices);
472 
473  // match subjets and original fat jets
474  std::vector<std::vector<int> > subjetIndices;
475  if (useGroomedFatJets)
476  matchSubjets(groomedIndices, groomedFatJetsHandle, trackIPTagInfos, subjetIndices);
477  else
478  matchSubjets(fatJetsHandle, trackIPTagInfos, subjetIndices);
479 
480  // collect clustered SVs
481  for (size_t i = 0; i < fatJetsHandle->size(); ++i) {
482  if (reclusteredIndices.at(i) < 0)
483  continue; // continue if matching reclustered to original jets failed
484 
485  if (fatJetsHandle->at(i).pt() == 0) // continue if the original jet has Pt=0
486  {
487  edm::LogWarning("NullTransverseMomentum")
488  << "The original fat jet " << i << " has Pt=0. This is not expected so the jet will be skipped.";
489  continue;
490  }
491 
492  if (subjetIndices.at(i).empty())
493  continue; // continue if the original jet does not have subjets assigned
494 
495  // since the "ghosts" are extremely soft, the configuration and ordering of the reclustered and original fat jets should in principle stay the same
496  if ((std::abs(inclusiveJets.at(reclusteredIndices.at(i)).pt() - fatJetsHandle->at(i).pt()) /
497  fatJetsHandle->at(i).pt()) > relPtTolerance) {
498  if (fatJetsHandle->at(i).pt() < 10.) // special handling for low-Pt jets (Pt<10 GeV)
499  edm::LogWarning("JetPtMismatchAtLowPt")
500  << "The reclustered and original fat jet " << i << " have different Pt's ("
501  << inclusiveJets.at(reclusteredIndices.at(i)).pt() << " vs " << fatJetsHandle->at(i).pt()
502  << " GeV, respectively).\n"
503  << "Please check that the jet algorithm and jet size match those used for the original fat jet "
504  "collection and also make sure the original fat jets are uncorrected. In addition, make sure you "
505  "are not using CaloJets which are presently not supported.\n"
506  << "Since the mismatch is at low Pt, it is ignored and only a warning is issued.\n"
507  << "\nIn extremely rare instances the mismatch could be caused by a difference in the machine "
508  "precision in which case make sure the original jet collection is produced and reclustering is "
509  "performed in the same job.";
510  else
511  edm::LogError("JetPtMismatch")
512  << "The reclustered and original fat jet " << i << " have different Pt's ("
513  << inclusiveJets.at(reclusteredIndices.at(i)).pt() << " vs " << fatJetsHandle->at(i).pt()
514  << " GeV, respectively).\n"
515  << "Please check that the jet algorithm and jet size match those used for the original fat jet "
516  "collection and also make sure the original fat jets are uncorrected. In addition, make sure you "
517  "are not using CaloJets which are presently not supported.\n"
518  << "\nIn extremely rare instances the mismatch could be caused by a difference in the machine "
519  "precision in which case make sure the original jet collection is produced and reclustering is "
520  "performed in the same job.";
521  }
522 
523  // get jet constituents
524  std::vector<fastjet::PseudoJet> constituents = inclusiveJets.at(reclusteredIndices.at(i)).constituents();
525 
526  std::vector<int> svIndices;
527  // loop over jet constituents and try to find "ghosts"
528  for (std::vector<fastjet::PseudoJet>::const_iterator it = constituents.begin(); it != constituents.end();
529  ++it) {
530  if (!it->has_user_info())
531  continue; // skip if not a "ghost"
532 
533  svIndices.push_back(it->user_info<VertexInfo>().vertexIndex());
534  }
535 
536  // loop over clustered SVs and assign them to different subjets based on smallest dR
537  for (size_t sv = 0; sv < svIndices.size(); ++sv) {
538  const reco::Vertex &pv = *(trackIPTagInfos->front().primaryVertex());
539  const VTX &extSV = (*extSecVertex)[svIndices.at(sv)];
541  dir = dir.unit();
542  fastjet::PseudoJet p(
543  dir.x(), dir.y(), dir.z(), dir.mag()); // using SV flight direction so treating SV as massless
544  if (useSVMomentum)
545  p = fastjet::PseudoJet(extSV.p4().px(), extSV.p4().py(), extSV.p4().pz(), extSV.p4().energy());
546 
547  std::vector<double> dR2toSubjets;
548 
549  for (size_t sj = 0; sj < subjetIndices.at(i).size(); ++sj)
550  dR2toSubjets.push_back(Geom::deltaR2(p.rapidity(),
551  p.phi_std(),
552  trackIPTagInfos->at(subjetIndices.at(i).at(sj)).jet()->rapidity(),
553  trackIPTagInfos->at(subjetIndices.at(i).at(sj)).jet()->phi()));
554 
555  // find the closest subjet
556  int closestSubjetIdx =
557  std::distance(dR2toSubjets.begin(), std::min_element(dR2toSubjets.begin(), dR2toSubjets.end()));
558 
559  clusteredSVs.at(subjetIndices.at(i).at(closestSubjetIdx)).push_back(svIndices.at(sv));
560  }
561  }
562  } else {
563  if (inclusiveJets.size() < trackIPTagInfos->size())
564  edm::LogError("TooFewReclusteredJets")
565  << "There are fewer reclustered (" << inclusiveJets.size() << ") than original jets ("
566  << trackIPTagInfos->size()
567  << "). Please check that the jet algorithm and jet size match those used for the original jet collection.";
568 
569  // match reclustered and original jets
570  std::vector<int> reclusteredIndices;
571  matchReclusteredJets<std::vector<IPTI> >(trackIPTagInfos, inclusiveJets, reclusteredIndices);
572 
573  // collect clustered SVs
574  for (size_t i = 0; i < trackIPTagInfos->size(); ++i) {
575  if (reclusteredIndices.at(i) < 0)
576  continue; // continue if matching reclustered to original jets failed
577 
578  if (trackIPTagInfos->at(i).jet()->pt() == 0) // continue if the original jet has Pt=0
579  {
580  edm::LogWarning("NullTransverseMomentum")
581  << "The original jet " << i << " has Pt=0. This is not expected so the jet will be skipped.";
582  continue;
583  }
584 
585  // since the "ghosts" are extremely soft, the configuration and ordering of the reclustered and original jets should in principle stay the same
586  if ((std::abs(inclusiveJets.at(reclusteredIndices.at(i)).pt() - trackIPTagInfos->at(i).jet()->pt()) /
587  trackIPTagInfos->at(i).jet()->pt()) > relPtTolerance) {
588  if (trackIPTagInfos->at(i).jet()->pt() < 10.) // special handling for low-Pt jets (Pt<10 GeV)
589  edm::LogWarning("JetPtMismatchAtLowPt")
590  << "The reclustered and original jet " << i << " have different Pt's ("
591  << inclusiveJets.at(reclusteredIndices.at(i)).pt() << " vs " << trackIPTagInfos->at(i).jet()->pt()
592  << " GeV, respectively).\n"
593  << "Please check that the jet algorithm and jet size match those used for the original jet collection "
594  "and also make sure the original jets are uncorrected. In addition, make sure you are not using "
595  "CaloJets which are presently not supported.\n"
596  << "Since the mismatch is at low Pt, it is ignored and only a warning is issued.\n"
597  << "\nIn extremely rare instances the mismatch could be caused by a difference in the machine "
598  "precision in which case make sure the original jet collection is produced and reclustering is "
599  "performed in the same job.";
600  else
601  edm::LogError("JetPtMismatch")
602  << "The reclustered and original jet " << i << " have different Pt's ("
603  << inclusiveJets.at(reclusteredIndices.at(i)).pt() << " vs " << trackIPTagInfos->at(i).jet()->pt()
604  << " GeV, respectively).\n"
605  << "Please check that the jet algorithm and jet size match those used for the original jet collection "
606  "and also make sure the original jets are uncorrected. In addition, make sure you are not using "
607  "CaloJets which are presently not supported.\n"
608  << "\nIn extremely rare instances the mismatch could be caused by a difference in the machine "
609  "precision in which case make sure the original jet collection is produced and reclustering is "
610  "performed in the same job.";
611  }
612 
613  // get jet constituents
614  std::vector<fastjet::PseudoJet> constituents = inclusiveJets.at(reclusteredIndices.at(i)).constituents();
615 
616  // loop over jet constituents and try to find "ghosts"
617  for (std::vector<fastjet::PseudoJet>::const_iterator it = constituents.begin(); it != constituents.end();
618  ++it) {
619  if (!it->has_user_info())
620  continue; // skip if not a "ghost"
621  // push back clustered SV indices
622  clusteredSVs.at(i).push_back(it->user_info<VertexInfo>().vertexIndex());
623  }
624  }
625  }
626  }
627  // case where fat jets are used to associate SVs to subjets but no SV clustering is performed
628  else if (useExternalSV && !useSVClustering && !trackIPTagInfos->empty() && useFatJets) {
629  // match groomed and original fat jets
630  std::vector<int> groomedIndices;
631  if (useGroomedFatJets)
632  matchGroomedJets(fatJetsHandle, groomedFatJetsHandle, groomedIndices);
633 
634  // match subjets and original fat jets
635  std::vector<std::vector<int> > subjetIndices;
636  if (useGroomedFatJets)
637  matchSubjets(groomedIndices, groomedFatJetsHandle, trackIPTagInfos, subjetIndices);
638  else
639  matchSubjets(fatJetsHandle, trackIPTagInfos, subjetIndices);
640 
641  // loop over fat jets
642  for (size_t i = 0; i < fatJetsHandle->size(); ++i) {
643  if (fatJetsHandle->at(i).pt() == 0) // continue if the original jet has Pt=0
644  {
645  edm::LogWarning("NullTransverseMomentum")
646  << "The original fat jet " << i << " has Pt=0. This is not expected so the jet will be skipped.";
647  continue;
648  }
649 
650  if (subjetIndices.at(i).empty())
651  continue; // continue if the original jet does not have subjets assigned
652 
653  // loop over SVs, associate them to fat jets based on dR cone and
654  // then assign them to the closets subjet in dR
655  for (typename edm::View<VTX>::const_iterator it = extSecVertex->begin(); it != extSecVertex->end(); ++it) {
656  size_t sv = (it - extSecVertex->begin());
657 
658  const reco::Vertex &pv = *(trackIPTagInfos->front().primaryVertex());
659  const VTX &extSV = (*extSecVertex)[sv];
661  GlobalVector jetDir(fatJetsHandle->at(i).px(), fatJetsHandle->at(i).py(), fatJetsHandle->at(i).pz());
662  // skip SVs outside the dR cone
663  if (Geom::deltaR2(dir, jetDir) > rParam * rParam) // here using the jet clustering rParam as a dR cut
664  continue;
665 
666  dir = dir.unit();
667  fastjet::PseudoJet p(
668  dir.x(), dir.y(), dir.z(), dir.mag()); // using SV flight direction so treating SV as massless
669  if (useSVMomentum)
670  p = fastjet::PseudoJet(extSV.p4().px(), extSV.p4().py(), extSV.p4().pz(), extSV.p4().energy());
671 
672  std::vector<double> dR2toSubjets;
673 
674  for (size_t sj = 0; sj < subjetIndices.at(i).size(); ++sj)
675  dR2toSubjets.push_back(Geom::deltaR2(p.rapidity(),
676  p.phi_std(),
677  trackIPTagInfos->at(subjetIndices.at(i).at(sj)).jet()->rapidity(),
678  trackIPTagInfos->at(subjetIndices.at(i).at(sj)).jet()->phi()));
679 
680  // find the closest subjet
681  int closestSubjetIdx =
682  std::distance(dR2toSubjets.begin(), std::min_element(dR2toSubjets.begin(), dR2toSubjets.end()));
683 
684  clusteredSVs.at(subjetIndices.at(i).at(closestSubjetIdx)).push_back(sv);
685  }
686  }
687  }
688  // ------------------------------------ SV clustering END ----------------------------------------------
689 
690  std::unique_ptr<ConfigurableVertexReconstructor> vertexReco;
691  std::unique_ptr<GhostTrackVertexFinder> vertexRecoGT;
692  if (useGhostTrack)
693  vertexRecoGT = std::make_unique<GhostTrackVertexFinder>(
694  vtxRecoPSet.getParameter<double>("maxFitChi2"),
695  vtxRecoPSet.getParameter<double>("mergeThreshold"),
696  vtxRecoPSet.getParameter<double>("primcut"),
697  vtxRecoPSet.getParameter<double>("seccut"),
698  getGhostTrackFitType(vtxRecoPSet.getParameter<std::string>("fitType")));
699  else
700  vertexReco = std::make_unique<ConfigurableVertexReconstructor>(vtxRecoPSet);
701 
702  TransientTrackMap primariesMap;
703 
704  // result secondary vertices
705 
706  auto tagInfos = std::make_unique<Product>();
707 
708  for (typename std::vector<IPTI>::const_iterator iterJets = trackIPTagInfos->begin();
709  iterJets != trackIPTagInfos->end();
710  ++iterJets) {
711  TrackDataVector trackData;
712  // std::cout << "Jet " << iterJets-trackIPTagInfos->begin() << std::endl;
713 
714  const Vertex &pv = *iterJets->primaryVertex();
715 
716  std::set<TransientTrack> primaries;
717  if (constraint == CONSTRAINT_PV_PRIMARIES_IN_FIT) {
718  for (Vertex::trackRef_iterator iter = pv.tracks_begin(); iter != pv.tracks_end(); ++iter) {
719  TransientTrackMap::iterator pos = primariesMap.lower_bound(iter->get());
720 
721  if (pos != primariesMap.end() && pos->first == iter->get())
722  primaries.insert(pos->second);
723  else {
724  TransientTrack track = trackBuilder->build(iter->castTo<TrackRef>());
725  primariesMap.insert(pos, std::make_pair(iter->get(), track));
726  primaries.insert(track);
727  }
728  }
729  }
730 
731  edm::RefToBase<Jet> jetRef = iterJets->jet();
732 
733  GlobalVector jetDir(jetRef->momentum().x(), jetRef->momentum().y(), jetRef->momentum().z());
734 
735  std::vector<std::size_t> indices = iterJets->sortedIndexes(sortCriterium);
736 
737  input_container trackRefs = iterJets->sortedTracks(indices);
738 
739  const std::vector<reco::btag::TrackIPData> &ipData = iterJets->impactParameterData();
740 
741  // build transient tracks used for vertex reconstruction
742 
743  std::vector<TransientTrack> fitTracks;
744  std::vector<GhostTrackState> gtStates;
745  std::unique_ptr<GhostTrackPrediction> gtPred;
746  if (useGhostTrack)
747  gtPred = std::make_unique<GhostTrackPrediction>(*iterJets->ghostTrack());
748 
749  for (unsigned int i = 0; i < indices.size(); i++) {
751 
752  const input_item &trackRef = trackRefs[i];
753 
754  trackData.push_back(IndexedTrackData());
755  trackData.back().first = indices[i];
756 
757  // select tracks for SV finder
758 
759  if (!trackSelector(
760  *reco::btag::toTrack(trackRef), ipData[indices[i]], *jetRef, RecoVertex::convertPos(pv.position()))) {
762  continue;
763  }
764 
765  TransientTrackMap::const_iterator pos = primariesMap.find(reco::btag::toTrack((trackRef)));
766  TransientTrack fitTrack;
767  if (pos != primariesMap.end()) {
768  primaries.erase(pos->second);
769  fitTrack = pos->second;
770  } else
771  fitTrack = trackBuilder->build(trackRef);
772  fitTracks.push_back(fitTrack);
773 
775 
776  if (useGhostTrack) {
777  GhostTrackState gtState(fitTrack);
778  GlobalPoint pos = ipData[indices[i]].closestToGhostTrack;
779  gtState.linearize(*gtPred, true, gtPred->lambda(pos));
780  gtState.setWeight(ipData[indices[i]].ghostTrackWeight);
781  gtStates.push_back(gtState);
782  }
783  }
784 
785  std::unique_ptr<GhostTrack> ghostTrack;
786  if (useGhostTrack)
787  ghostTrack = std::make_unique<GhostTrack>(
789  RecoVertex::convertPos(pv.position()),
790  RecoVertex::convertError(pv.error()),
791  GlobalVector(iterJets->ghostTrack()->px(), iterJets->ghostTrack()->py(), iterJets->ghostTrack()->pz()),
792  0.05),
793  *gtPred,
794  gtStates,
795  iterJets->ghostTrack()->chi2(),
796  iterJets->ghostTrack()->ndof());
797 
798  // perform actual vertex finding
799 
800  std::vector<VTX> extAssoCollection;
801  std::vector<TransientVertex> fittedSVs;
802  std::vector<SecondaryVertex> SVs;
803  if (!useExternalSV) {
804  switch (constraint) {
805  case CONSTRAINT_NONE:
806  if (useGhostTrack)
807  fittedSVs = vertexRecoGT->vertices(pv, *ghostTrack);
808  else
809  fittedSVs = vertexReco->vertices(fitTracks);
810  break;
811 
812  case CONSTRAINT_BEAMSPOT:
813  if (useGhostTrack)
814  fittedSVs = vertexRecoGT->vertices(pv, *beamSpot, *ghostTrack);
815  else
816  fittedSVs = vertexReco->vertices(fitTracks, *beamSpot);
817  break;
818 
819  case CONSTRAINT_PV_BEAMSPOT_SIZE:
820  case CONSTRAINT_PV_BS_Z_ERRORS_SCALED:
821  case CONSTRAINT_PV_ERROR_SCALED: {
823  for (unsigned int i = 0; i < 7; i++) {
824  unsigned int covSrc = bsCovSrc[i];
825  for (unsigned int j = 0; j < 7; j++) {
826  double v = 0.0;
827  if (!covSrc || bsCovSrc[j] != covSrc)
828  v = 0.0;
829  else if (covSrc == 1)
830  v = beamSpot->covariance(i, j);
831  else if (j < 3 && i < 3)
832  v = pv.covariance(i, j) * constraintScaling;
833  cov(i, j) = v;
834  }
835  }
836 
837  BeamSpot bs(pv.position(),
838  sigmaZ,
839  beamSpot.isValid() ? beamSpot->dxdz() : 0.,
840  beamSpot.isValid() ? beamSpot->dydz() : 0.,
841  beamWidth,
842  cov,
844 
845  if (useGhostTrack)
846  fittedSVs = vertexRecoGT->vertices(pv, bs, *ghostTrack);
847  else
848  fittedSVs = vertexReco->vertices(fitTracks, bs);
849  } break;
850 
851  case CONSTRAINT_PV_PRIMARIES_IN_FIT: {
852  std::vector<TransientTrack> primaries_(primaries.begin(), primaries.end());
853  if (useGhostTrack)
854  fittedSVs = vertexRecoGT->vertices(pv, *beamSpot, primaries_, *ghostTrack);
855  else
856  fittedSVs = vertexReco->vertices(primaries_, fitTracks, *beamSpot);
857  } break;
858  }
859  // build combined SV information and filter
860  SVBuilder svBuilder(pv, jetDir, withPVError, minTrackWeight);
861  std::remove_copy_if(boost::make_transform_iterator(fittedSVs.begin(), svBuilder),
862  boost::make_transform_iterator(fittedSVs.end(), svBuilder),
863  std::back_inserter(SVs),
864  SVFilter(vertexFilter, pv, jetDir));
865 
866  } else {
867  if (useSVClustering || useFatJets) {
868  size_t jetIdx = (iterJets - trackIPTagInfos->begin());
869 
870  for (size_t iExtSv = 0; iExtSv < clusteredSVs.at(jetIdx).size(); iExtSv++) {
871  const VTX &extVertex = (*extSecVertex)[clusteredSVs.at(jetIdx).at(iExtSv)];
872  if (extVertex.p4().M() < 0.3)
873  continue;
874  extAssoCollection.push_back(extVertex);
875  }
876  } else {
877  for (size_t iExtSv = 0; iExtSv < extSecVertex->size(); iExtSv++) {
878  const VTX &extVertex = (*extSecVertex)[iExtSv];
879  if (Geom::deltaR2((position(extVertex) - pv.position()), (extSVDeltaRToJet > 0) ? jetDir : -jetDir) >
881  extVertex.p4().M() < 0.3)
882  continue;
883  extAssoCollection.push_back(extVertex);
884  }
885  }
886  // build combined SV information and filter
887  SVBuilder svBuilder(pv, jetDir, withPVError, minTrackWeight);
888  std::remove_copy_if(boost::make_transform_iterator(extAssoCollection.begin(), svBuilder),
889  boost::make_transform_iterator(extAssoCollection.end(), svBuilder),
890  std::back_inserter(SVs),
891  SVFilter(vertexFilter, pv, jetDir));
892  }
893  // clean up now unneeded collections
894  gtPred.reset();
895  ghostTrack.reset();
896  gtStates.clear();
897  fitTracks.clear();
898  fittedSVs.clear();
899  extAssoCollection.clear();
900 
901  // sort SVs by importance
902 
903  std::vector<unsigned int> vtxIndices = vertexSorting(SVs);
904 
905  std::vector<typename TemplatedSecondaryVertexTagInfo<IPTI, VTX>::VertexData> svData;
906 
907  svData.resize(vtxIndices.size());
908  for (unsigned int idx = 0; idx < vtxIndices.size(); idx++) {
909  const SecondaryVertex &sv = SVs[vtxIndices[idx]];
910 
911  svData[idx].vertex = sv;
912  svData[idx].dist1d = sv.dist1d();
913  svData[idx].dist2d = sv.dist2d();
914  svData[idx].dist3d = sv.dist3d();
915  svData[idx].direction = flightDirection(pv, sv);
916  // mark tracks successfully used in vertex fit
917  markUsedTracks(trackData, trackRefs, sv, idx);
918  }
919 
920  // fill result into tag infos
921 
923  trackData,
924  svData,
925  SVs.size(),
927  }
928 
929  event.put(std::move(tagInfos));
930 }
931 
932 //Need specialized template because reco::Vertex iterators are TrackBase and it is a mess to make general
933 template <>
935  const input_container &trackRefs,
936  const SecondaryVertex &sv,
937  size_t idx) {
938  for (Vertex::trackRef_iterator iter = sv.tracks_begin(); iter != sv.tracks_end(); ++iter) {
939  if (sv.trackWeight(*iter) < minTrackWeight)
940  continue;
941 
942  typename input_container::const_iterator pos =
943  std::find(trackRefs.begin(), trackRefs.end(), iter->castTo<input_item>());
944 
945  if (pos == trackRefs.end()) {
946  if (!useExternalSV)
947  throw cms::Exception("TrackNotFound") << "Could not find track from secondary "
948  "vertex in original tracks."
949  << std::endl;
950  } else {
951  unsigned int index = pos - trackRefs.begin();
952  trackData[index].second.svStatus = (btag::TrackData::trackAssociatedToVertex + idx);
953  }
954  }
955 }
956 template <>
958  TrackDataVector &trackData, const input_container &trackRefs, const SecondaryVertex &sv, size_t idx) {
959  for (typename input_container::const_iterator iter = sv.daughterPtrVector().begin();
960  iter != sv.daughterPtrVector().end();
961  ++iter) {
962  typename input_container::const_iterator pos = std::find(trackRefs.begin(), trackRefs.end(), *iter);
963 
964  if (pos != trackRefs.end()) {
965  unsigned int index = pos - trackRefs.begin();
966  trackData[index].second.svStatus = (btag::TrackData::trackAssociatedToVertex + idx);
967  }
968  }
969 }
970 
971 template <>
974  if (!sv.originalTracks().empty() && sv.originalTracks()[0].trackBaseRef().isNonnull())
976  else {
977  edm::LogError("UnexpectedInputs") << "Building from Candidates, should not happen!";
979  }
980 }
981 
982 template <>
985  const TransientVertex &sv) const {
986  if (!sv.originalTracks().empty() && sv.originalTracks()[0].trackBaseRef().isNonnull()) {
987  edm::LogError("UnexpectedInputs") << "Building from Tracks, should not happen!";
988  VertexCompositePtrCandidate vtxCompPtrCand;
989 
990  vtxCompPtrCand.setCovariance(sv.vertexState().error().matrix());
991  vtxCompPtrCand.setChi2AndNdof(sv.totalChiSquared(), sv.degreesOfFreedom());
992  vtxCompPtrCand.setVertex(Candidate::Point(sv.position().x(), sv.position().y(), sv.position().z()));
993 
994  return SecondaryVertex(pv, vtxCompPtrCand, direction, withPVError);
995  } else {
996  VertexCompositePtrCandidate vtxCompPtrCand;
997 
998  vtxCompPtrCand.setCovariance(sv.vertexState().error().matrix());
999  vtxCompPtrCand.setChi2AndNdof(sv.totalChiSquared(), sv.degreesOfFreedom());
1000  vtxCompPtrCand.setVertex(Candidate::Point(sv.position().x(), sv.position().y(), sv.position().z()));
1001 
1003  for (std::vector<reco::TransientTrack>::const_iterator tt = sv.originalTracks().begin();
1004  tt != sv.originalTracks().end();
1005  ++tt) {
1006  if (sv.trackWeight(*tt) < minTrackWeight)
1007  continue;
1008 
1009  const CandidatePtrTransientTrack *cptt =
1010  dynamic_cast<const CandidatePtrTransientTrack *>(tt->basicTransientTrack());
1011  if (cptt == nullptr)
1012  edm::LogError("DynamicCastingFailed") << "Casting of TransientTrack to CandidatePtrTransientTrack failed!";
1013  else {
1014  p4 += cptt->candidate()->p4();
1015  vtxCompPtrCand.addDaughter(cptt->candidate());
1016  }
1017  }
1018  vtxCompPtrCand.setP4(p4);
1019 
1020  return SecondaryVertex(pv, vtxCompPtrCand, direction, withPVError);
1021  }
1022 }
1023 
1024 // ------------ method that matches reclustered and original jets based on minimum dR ------------
1025 template <class IPTI, class VTX>
1026 template <class CONTAINER>
1029  const std::vector<fastjet::PseudoJet> &reclusteredJets,
1030  std::vector<int> &matchedIndices,
1031  const std::string &jetType) {
1032  std::string type = (!jetType.empty() ? jetType + " " : jetType);
1033 
1034  std::vector<bool> matchedLocks(reclusteredJets.size(), false);
1035 
1036  for (size_t j = 0; j < jets->size(); ++j) {
1037  double matchedDR2 = 1e9;
1038  int matchedIdx = -1;
1039 
1040  for (size_t rj = 0; rj < reclusteredJets.size(); ++rj) {
1041  if (matchedLocks.at(rj))
1042  continue; // skip jets that have already been matched
1043 
1044  double tempDR2 = Geom::deltaR2(toJet(jets->at(j))->rapidity(),
1045  toJet(jets->at(j))->phi(),
1046  reclusteredJets.at(rj).rapidity(),
1047  reclusteredJets.at(rj).phi_std());
1048  if (tempDR2 < matchedDR2) {
1049  matchedDR2 = tempDR2;
1050  matchedIdx = rj;
1051  }
1052  }
1053 
1054  if (matchedIdx >= 0) {
1055  if (matchedDR2 > rParam * rParam) {
1056  edm::LogError("JetMatchingFailed") << "Matched reclustered jet " << matchedIdx << " and original " << type
1057  << "jet " << j << " are separated by dR=" << sqrt(matchedDR2)
1058  << " which is greater than the jet size R=" << rParam << ".\n"
1059  << "This is not expected so please check that the jet algorithm and jet "
1060  "size match those used for the original "
1061  << type << "jet collection.";
1062  } else
1063  matchedLocks.at(matchedIdx) = true;
1064  } else
1065  edm::LogError("JetMatchingFailed")
1066  << "Matching reclustered to original " << type
1067  << "jets failed. Please check that the jet algorithm and jet size match those used for the original " << type
1068  << "jet collection.";
1069 
1070  matchedIndices.push_back(matchedIdx);
1071  }
1072 }
1073 
1074 // ------------ method that matches groomed and original jets based on minimum dR ------------
1075 template <class IPTI, class VTX>
1077  const edm::Handle<edm::View<reco::Jet> > &groomedJets,
1078  std::vector<int> &matchedIndices) {
1079  std::vector<bool> jetLocks(jets->size(), false);
1080  std::vector<int> jetIndices;
1081 
1082  for (size_t gj = 0; gj < groomedJets->size(); ++gj) {
1083  double matchedDR2 = 1e9;
1084  int matchedIdx = -1;
1085 
1086  if (groomedJets->at(gj).pt() > 0.) // skip pathological cases of groomed jets with Pt=0
1087  {
1088  for (size_t j = 0; j < jets->size(); ++j) {
1089  if (jetLocks.at(j))
1090  continue; // skip jets that have already been matched
1091 
1092  double tempDR2 = Geom::deltaR2(
1093  jets->at(j).rapidity(), jets->at(j).phi(), groomedJets->at(gj).rapidity(), groomedJets->at(gj).phi());
1094  if (tempDR2 < matchedDR2) {
1095  matchedDR2 = tempDR2;
1096  matchedIdx = j;
1097  }
1098  }
1099  }
1100 
1101  if (matchedIdx >= 0) {
1102  if (matchedDR2 > rParam * rParam) {
1103  edm::LogWarning("MatchedJetsFarApart")
1104  << "Matched groomed jet " << gj << " and original jet " << matchedIdx
1105  << " are separated by dR=" << sqrt(matchedDR2) << " which is greater than the jet size R=" << rParam
1106  << ".\n"
1107  << "This is not expected so the matching of these two jets has been discarded. Please check that the two "
1108  "jet collections belong to each other.";
1109  matchedIdx = -1;
1110  } else
1111  jetLocks.at(matchedIdx) = true;
1112  }
1113  jetIndices.push_back(matchedIdx);
1114  }
1115 
1116  for (size_t j = 0; j < jets->size(); ++j) {
1117  std::vector<int>::iterator matchedIndex = std::find(jetIndices.begin(), jetIndices.end(), j);
1118 
1119  matchedIndices.push_back(matchedIndex != jetIndices.end() ? std::distance(jetIndices.begin(), matchedIndex) : -1);
1120  }
1121 }
1122 
1123 // ------------ method that matches subjets and original fat jets ------------
1124 template <class IPTI, class VTX>
1125 void TemplatedSecondaryVertexProducer<IPTI, VTX>::matchSubjets(const std::vector<int> &groomedIndices,
1126  const edm::Handle<edm::View<reco::Jet> > &groomedJets,
1127  const edm::Handle<std::vector<IPTI> > &subjets,
1128  std::vector<std::vector<int> > &matchedIndices) {
1129  for (size_t g = 0; g < groomedIndices.size(); ++g) {
1130  std::vector<int> subjetIndices;
1131 
1132  if (groomedIndices.at(g) >= 0) {
1133  for (size_t s = 0; s < groomedJets->at(groomedIndices.at(g)).numberOfDaughters(); ++s) {
1134  const edm::Ptr<reco::Candidate> &subjet = groomedJets->at(groomedIndices.at(g)).daughterPtr(s);
1135 
1136  for (size_t sj = 0; sj < subjets->size(); ++sj) {
1137  const edm::RefToBase<reco::Jet> &subjetRef = subjets->at(sj).jet();
1138  if (subjet == edm::Ptr<reco::Candidate>(subjetRef.id(), subjetRef.get(), subjetRef.key())) {
1139  subjetIndices.push_back(sj);
1140  break;
1141  }
1142  }
1143  }
1144 
1145  if (subjetIndices.empty())
1146  edm::LogError("SubjetMatchingFailed") << "Matching subjets to original fat jets failed. Please check that the "
1147  "groomed fat jet and subjet collections belong to each other.";
1148 
1149  matchedIndices.push_back(subjetIndices);
1150  } else
1151  matchedIndices.push_back(subjetIndices);
1152  }
1153 }
1154 
1155 // ------------ method that matches subjets and original fat jets ------------
1156 template <class IPTI, class VTX>
1158  const edm::Handle<std::vector<IPTI> > &subjets,
1159  std::vector<std::vector<int> > &matchedIndices) {
1160  for (size_t fj = 0; fj < fatJets->size(); ++fj) {
1161  std::vector<int> subjetIndices;
1162  size_t nSubjetCollections = 0;
1163  size_t nSubjets = 0;
1164 
1165  const pat::Jet *fatJet = dynamic_cast<const pat::Jet *>(fatJets->ptrAt(fj).get());
1166 
1167  if (!fatJet) {
1168  if (fj == 0)
1169  edm::LogError("WrongJetType")
1170  << "Wrong jet type for input fat jets. Please check that the input fat jets are of the pat::Jet type.";
1171 
1172  matchedIndices.push_back(subjetIndices);
1173  continue;
1174  } else {
1175  nSubjetCollections = fatJet->subjetCollectionNames().size();
1176 
1177  if (nSubjetCollections > 0) {
1178  for (size_t coll = 0; coll < nSubjetCollections; ++coll) {
1179  const pat::JetPtrCollection &fatJetSubjets = fatJet->subjets(coll);
1180 
1181  for (size_t fjsj = 0; fjsj < fatJetSubjets.size(); ++fjsj) {
1182  ++nSubjets;
1183 
1184  for (size_t sj = 0; sj < subjets->size(); ++sj) {
1185  const pat::Jet *subJet = dynamic_cast<const pat::Jet *>(subjets->at(sj).jet().get());
1186 
1187  if (!subJet) {
1188  if (fj == 0 && coll == 0 && fjsj == 0 && sj == 0)
1189  edm::LogError("WrongJetType") << "Wrong jet type for input subjets. Please check that the input "
1190  "subjets are of the pat::Jet type.";
1191 
1192  break;
1193  } else {
1194  if (subJet->originalObjectRef() == fatJetSubjets.at(fjsj)->originalObjectRef()) {
1195  subjetIndices.push_back(sj);
1196  break;
1197  }
1198  }
1199  }
1200  }
1201  }
1202 
1203  if (subjetIndices.empty() && nSubjets > 0)
1204  edm::LogError("SubjetMatchingFailed") << "Matching subjets to fat jets failed. Please check that the fat jet "
1205  "and subjet collections belong to each other.";
1206 
1207  matchedIndices.push_back(subjetIndices);
1208  } else
1209  matchedIndices.push_back(subjetIndices);
1210  }
1211  }
1212 }
1213 
1214 // ------------ method fills 'descriptions' with the allowed parameters for the module ------------
1215 template <class IPTI, class VTX>
1218  desc.add<double>("extSVDeltaRToJet", 0.3);
1219  desc.add<edm::InputTag>("beamSpotTag", edm::InputTag("offlineBeamSpot"));
1220  {
1222  vertexReco.add<double>("primcut", 1.8);
1223  vertexReco.add<double>("seccut", 6.0);
1224  vertexReco.add<std::string>("finder", "avr");
1225  vertexReco.addOptionalNode(edm::ParameterDescription<double>("minweight", 0.5, true) and
1226  edm::ParameterDescription<double>("weightthreshold", 0.001, true) and
1227  edm::ParameterDescription<bool>("smoothing", false, true),
1228  true);
1229  vertexReco.addOptionalNode(
1230  edm::ParameterDescription<double>("maxFitChi2", 10.0, true) and
1231  edm::ParameterDescription<double>("mergeThreshold", 3.0, true) and
1232  edm::ParameterDescription<std::string>("fitType", "RefitGhostTrackWithVertices", true),
1233  true);
1234  desc.add<edm::ParameterSetDescription>("vertexReco", vertexReco);
1235  }
1236  {
1238  vertexSelection.add<std::string>("sortCriterium", "dist3dError");
1239  desc.add<edm::ParameterSetDescription>("vertexSelection", vertexSelection);
1240  }
1241  desc.add<std::string>("constraint", "BeamSpot");
1242  desc.add<edm::InputTag>("trackIPTagInfos", edm::InputTag("impactParameterTagInfos"));
1243  {
1245  vertexCuts.add<double>("distSig3dMax", 99999.9);
1246  vertexCuts.add<double>("fracPV", 0.65);
1247  vertexCuts.add<double>("distVal2dMax", 2.5);
1248  vertexCuts.add<bool>("useTrackWeights", true);
1249  vertexCuts.add<double>("maxDeltaRToJetAxis", 0.4);
1250  {
1252  v0Filter.add<double>("k0sMassWindow", 0.05);
1254  }
1255  vertexCuts.add<double>("distSig2dMin", 3.0);
1256  vertexCuts.add<unsigned int>("multiplicityMin", 2);
1257  vertexCuts.add<double>("distVal2dMin", 0.01);
1258  vertexCuts.add<double>("distSig2dMax", 99999.9);
1259  vertexCuts.add<double>("distVal3dMax", 99999.9);
1260  vertexCuts.add<double>("minimumTrackWeight", 0.5);
1261  vertexCuts.add<double>("distVal3dMin", -99999.9);
1262  vertexCuts.add<double>("massMax", 6.5);
1263  vertexCuts.add<double>("distSig3dMin", -99999.9);
1264  desc.add<edm::ParameterSetDescription>("vertexCuts", vertexCuts);
1265  }
1266  desc.add<bool>("useExternalSV", false);
1267  desc.add<double>("minimumTrackWeight", 0.5);
1268  desc.add<bool>("usePVError", true);
1269  {
1271  trackSelection.add<double>("b_pT", 0.3684);
1272  trackSelection.add<double>("max_pT", 500);
1273  trackSelection.add<bool>("useVariableJTA", false);
1274  trackSelection.add<double>("maxDecayLen", 99999.9);
1275  trackSelection.add<double>("sip3dValMin", -99999.9);
1276  trackSelection.add<double>("max_pT_dRcut", 0.1);
1277  trackSelection.add<double>("a_pT", 0.005263);
1278  trackSelection.add<unsigned int>("totalHitsMin", 8);
1279  trackSelection.add<double>("jetDeltaRMax", 0.3);
1280  trackSelection.add<double>("a_dR", -0.001053);
1281  trackSelection.add<double>("maxDistToAxis", 0.2);
1282  trackSelection.add<double>("ptMin", 1.0);
1283  trackSelection.add<std::string>("qualityClass", "any");
1284  trackSelection.add<unsigned int>("pixelHitsMin", 2);
1285  trackSelection.add<double>("sip2dValMax", 99999.9);
1286  trackSelection.add<double>("max_pT_trackPTcut", 3);
1287  trackSelection.add<double>("sip2dValMin", -99999.9);
1288  trackSelection.add<double>("normChi2Max", 99999.9);
1289  trackSelection.add<double>("sip3dValMax", 99999.9);
1290  trackSelection.add<double>("sip3dSigMin", -99999.9);
1291  trackSelection.add<double>("min_pT", 120);
1292  trackSelection.add<double>("min_pT_dRcut", 0.5);
1293  trackSelection.add<double>("sip2dSigMax", 99999.9);
1294  trackSelection.add<double>("sip3dSigMax", 99999.9);
1295  trackSelection.add<double>("sip2dSigMin", -99999.9);
1296  trackSelection.add<double>("b_dR", 0.6263);
1297  desc.add<edm::ParameterSetDescription>("trackSelection", trackSelection);
1298  }
1299  desc.add<std::string>("trackSort", "sip3dSig");
1300  desc.add<edm::InputTag>("extSVCollection", edm::InputTag("secondaryVertices"));
1301  desc.addOptionalNode(edm::ParameterDescription<bool>("useSVClustering", false, true) and
1302  edm::ParameterDescription<std::string>("jetAlgorithm", true) and
1303  edm::ParameterDescription<double>("rParam", true),
1304  true);
1305  desc.addOptional<bool>("useSVMomentum", false);
1306  desc.addOptional<double>("ghostRescaling", 1e-18);
1307  desc.addOptional<double>("relPtTolerance", 1e-03);
1308  desc.addOptional<edm::InputTag>("fatJets");
1309  desc.addOptional<edm::InputTag>("groomedFatJets");
1310  desc.add<edm::InputTag>("weights", edm::InputTag(""));
1311  descriptions.addDefault(desc);
1312 }
1313 
1314 //define this as a plug-in
1317 
std::shared_ptr< fastjet::JetDefinition > JetDefPtr
math::Error< dimension >::type CovarianceMatrix
Definition: BeamSpot.h:29
reco::Vertex::Point convertPos(const GlobalPoint &p)
edm::EDGetTokenT< edm::View< reco::Jet > > token_fatJets
edm::ESGetToken< TransientTrackBuilder, TransientTrackRecord > token_trackBuilder
const math::XYZPoint & position(const reco::Vertex &sv)
reco::btag::SortCriteria getCriterium(const std::string &name)
Definition: TrackSorting.cc:11
virtual double energy() const =0
energy
TemplatedSecondaryVertex< reco::Vertex > SecondaryVertex
trackSelector
Tracks selection.
TemplatedSecondaryVertexProducer(const edm::ParameterSet &params)
void produce(edm::Event &event, const edm::EventSetup &es) override
T w() const
virtual double pt() const =0
transverse momentum
CandidatePtr candidate() const override
edm::EDGetTokenT< reco::BeamSpot > token_BeamSpot
Base class for all types of Jets.
Definition: Jet.h:20
virtual double pz() const =0
z coordinate of momentum vector
reco::Vertex::Error convertError(const GlobalError &ge)
Definition: ConvertError.h:8
pat::JetPtrCollection const & subjets(unsigned int index=0) const
Access to subjet list.
void setWeight(double weight)
SVFilter(const VertexFilter &filter, const Vertex &pv, const GlobalVector &direction)
Log< level::Error, false > LogError
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
const reco::Track * toTrack(const reco::TrackBaseRef &t)
Definition: IPTagInfo.h:24
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 g
Definition: Activities.doc:4
TemplatedSecondaryVertexProducer< CandIPTagInfo, reco::VertexCompositePtrCandidate > CandSecondaryVertexProducer
void setVertex(const Point &vertex) override
set vertex
static GhostTrackVertexFinder::FitType getGhostTrackFitType(const std::string &name)
void matchReclusteredJets(const edm::Handle< CONTAINER > &jets, const std::vector< fastjet::PseudoJet > &matchedJets, std::vector< int > &matchedIndices, const std::string &jetType="")
ProductID id() const
Definition: RefToBase.h:214
reco::TransientTrack build(const reco::Track *p) const
edm::EDGetTokenT< std::vector< IPTI > > token_trackIPTagInfo
std::vector< std::string > const & subjetCollectionNames() const
Subjet collection names.
Definition: Jet.h:564
IPTI::input_container::value_type input_item
Definition: TTTypes.h:54
bool isNull() const
Checks for null.
Definition: Ptr.h:142
void addDefault(ParameterSetDescription const &psetDescription)
std::vector< TemplatedSecondaryVertexTagInfo< IPTI, VTX > > Product
GlobalVector flightDirection(const reco::Vertex &pv, const reco::Vertex &sv)
T sqrt(T t)
Definition: SSEVec.h:19
std::vector< edm::Ptr< pat::Jet > > JetPtrCollection
Definition: Jet.h:75
edm::EDGetTokenT< edm::ValueMap< float > > token_weights
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
std::shared_ptr< fastjet::ClusterSequence > ClusterSequencePtr
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
VertexSorting< SecondaryVertex > vertexSorting
static ConstraintType getConstraintType(const std::string &name)
virtual double py() const =0
y coordinate of momentum vector
ESHandle< T > getHandle(const ESGetToken< T, R > &iToken) const
Definition: EventSetup.h:151
void matchGroomedJets(const edm::Handle< edm::View< reco::Jet > > &jets, const edm::Handle< edm::View< reco::Jet > > &matchedJets, std::vector< int > &matchedIndices)
void matchSubjets(const std::vector< int > &groomedIndices, const edm::Handle< edm::View< reco::Jet > > &groomedJets, const edm::Handle< std::vector< IPTI > > &subjets, std::vector< std::vector< int > > &matchedIndices)
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
void markUsedTracks(TrackDataVector &trackData, const input_container &trackRefs, const SecondaryVertex &sv, size_t idx)
edm::EDGetTokenT< edm::View< VTX > > token_extSVCollection
virtual double px() const =0
x coordinate of momentum vector
SVBuilder(const reco::Vertex &pv, const GlobalVector &direction, bool withPVError, double minTrackWeight)
std::shared_ptr< fastjet::ClusterSequence > ClusterSequencePtr
size_t key() const
Definition: RefToBase.h:219
static void fillDescriptions(edm::ConfigurationDescriptions &descriptions)
TemplatedSecondaryVertex< VTX > SecondaryVertex
edm::EDGetTokenT< edm::View< reco::Jet > > token_groomedFatJets
bool linearize(const GhostTrackPrediction &pred, bool initial=false, double lambda=0.)
XYZPointD XYZPoint
point in space with cartesian internal representation
Definition: Point3D.h:12
std::shared_ptr< fastjet::JetDefinition > JetDefPtr
Analysis-level calorimeter jet class.
Definition: Jet.h:77
TemplatedSecondaryVertexProducer< TrackIPTagInfo, reco::Vertex > SecondaryVertexProducer
math::XYZTLorentzVector LorentzVector
Lorentz vector.
Definition: Candidate.h:36
deadvectors [0] push_back({0.0175431, 0.538005, 6.80997, 13.29})
SecondaryVertex operator()(const TransientVertex &sv) const
std::vector< reco::btag::IndexedTrackData > TrackDataVector
fixed size matrix
HLT enums.
boost::indirect_iterator< typename seq_t::const_iterator > const_iterator
Definition: View.h:86
void setCovariance(const CovarianceMatrix &m)
set covariance matrix
void addDaughter(const CandidatePtr &)
add a daughter via a reference
math::XYZPoint Point
point in the space
Definition: Candidate.h:40
const edm::Ptr< reco::Candidate > & originalObjectRef() const
reference to original object. Returns a null reference if not available
Definition: PATObject.h:537
void setChi2AndNdof(double chi2, double ndof)
set chi2 and ndof
Log< level::Warning, false > LogWarning
value_type const * get() const
Definition: RefToBase.h:209
void setP4(const LorentzVector &p4) final
set 4-momentum
const reco::Jet * toJet(const reco::Jet &j)
def move(src, dest)
Definition: eostools.py:511
std::vector< TrackBaseRef >::const_iterator trackRef_iterator
The iteratator for the vector<TrackRef>
Definition: Vertex.h:38
std::pair< unsigned int, TrackData > IndexedTrackData
Definition: event.py:1
Global3DVector GlobalVector
Definition: GlobalVector.h:10
virtual const LorentzVector & p4() const =0
four-momentum Lorentz vector