CMS 3D CMS Logo

TrackListMerger.cc
Go to the documentation of this file.
1 //
2 // Package: RecoTracker/FinalTrackSelectors
3 // Class: TrackListMerger
4 //
5 // Description: Hit Dumper
6 //
7 // Original Author: Steve Wagner, stevew@pizero.colorado.edu
8 // Created: Sat Jan 14 22:00:00 UTC 2006
9 //
10 //
11 
31 
33 public:
34  explicit TrackListMerger(const edm::ParameterSet& conf);
35 
36  ~TrackListMerger() override = default;
37 
38  void produce(edm::Event& e, const edm::EventSetup& c) override;
39 
40 private:
41  void returnEmptyCollections(edm::Event& e);
42 
43  using MVACollection = std::vector<float>;
44  using QualityMaskCollection = std::vector<unsigned char>;
45 
46  std::unique_ptr<reco::TrackCollection> outputTrks;
47  std::unique_ptr<reco::TrackExtraCollection> outputTrkExtras;
48  std::unique_ptr<TrackingRecHitCollection> outputTrkHits;
49  std::unique_ptr<std::vector<Trajectory>> outputTrajs;
50  std::unique_ptr<TrajTrackAssociationCollection> outputTTAss;
51  std::unique_ptr<TrajectorySeedCollection> outputSeeds;
52 
58 
61 
63 
64  struct TkEDGetTokenss {
74  edm::EDGetTokenT<std::vector<Trajectory>>&& traj_,
78  : tag(tag_), tk(tk_), traj(traj_), tass(tass_), tsel(tsel_), tmva(tmva_) {}
79  };
80  TkEDGetTokenss edTokens(const edm::InputTag& tag, const edm::InputTag& seltag, const edm::InputTag& mvatag) {
81  return TkEDGetTokenss(tag,
82  consumes<reco::TrackCollection>(tag),
83  consumes<std::vector<Trajectory>>(tag),
84  consumes<TrajTrackAssociationCollection>(tag),
85  consumes<edm::ValueMap<int>>(seltag),
86  consumes<edm::ValueMap<float>>(mvatag));
87  }
89  return TkEDGetTokenss(tag,
90  consumes<reco::TrackCollection>(tag),
91  consumes<std::vector<Trajectory>>(tag),
92  consumes<TrajTrackAssociationCollection>(tag),
94  consumes<edm::ValueMap<float>>(mvatag));
95  }
96  std::vector<TkEDGetTokenss> trackProducers_;
97 
99 
101  double minPT_;
102  unsigned int minFound_;
103  float epsilon_;
104  float shareFrac_;
107  std::vector<double> indivShareFrac_;
108 
109  std::vector<std::vector<int>> listsToMerge_;
110  std::vector<bool> promoteQuality_;
111  std::vector<int> hasSelector_;
112  bool copyMVA_;
113 
118 };
119 
120 #include <memory>
121 #include <string>
122 #include <iostream>
123 #include <cmath>
124 #include <vector>
125 
133 
135 
139 
140 //#include "DataFormats/TrackReco/src/classes.h"
141 
143 
144 #ifdef STAT_TSB
145 #include <x86intrin.h>
146 #endif
147 
148 namespace {
149 #ifdef STAT_TSB
150  inline volatile unsigned long long rdtsc() { return __rdtsc(); }
151 
152  struct StatCount {
153  float maxDP = 0.;
154  float maxDE = 0.;
155  unsigned long long st;
156  long long totBegin = 0;
157  long long totPre = 0;
158  long long totEnd = 0;
159  unsigned long long timeNo; // no-overlap
160  unsigned long long timeOv; // overlap
161  void begin(int tt) { totBegin += tt; }
162  void start() { st = rdtsc(); }
163  void noOverlap() { timeNo += (rdtsc() - st); }
164  void overlap() { timeOv += (rdtsc() - st); }
165  void pre(int tt) { totPre += tt; }
166  void end(int tt) { totEnd += tt; }
167  void de(float d) {
168  if (d > maxDE)
169  maxDE = d;
170  }
171  void dp(float d) {
172  if (d > maxDP)
173  maxDP = d;
174  }
175 
176  void print() const {
177  std::cout << "TrackListMerger stat\nBegin/Pre/End/maxDPhi/maxDEta/Overlap/NoOverlap " << totBegin << '/' << totPre
178  << '/' << totEnd << '/' << maxDP << '/' << maxDE << '/' << timeOv / 1000 << '/' << timeNo / 1000
179  << std::endl;
180  }
181  StatCount() {}
182  ~StatCount() { print(); }
183  };
184  StatCount statCount;
185 
186 #else
187  struct StatCount {
188  void begin(int) {}
189  void pre(int) {}
190  void end(int) {}
191  void start() {}
192  void noOverlap() {}
193  void overlap() {}
194  void de(float) {}
195  void dp(float) {}
196  };
197  CMS_THREAD_SAFE StatCount statCount;
198 #endif
199 
200 } // namespace
201 
202 namespace {
203  edm::ProductID clusterProductB(const TrackingRecHit* hit) {
204  return reinterpret_cast<const BaseTrackerRecHit*>(hit)->firstClusterRef().id();
205  }
206 } // namespace
207 
209  copyExtras_ = conf.getUntrackedParameter<bool>("copyExtras", true);
210  priorityName_ = conf.getParameter<std::string>("trackAlgoPriorityOrder");
211 
212  std::vector<edm::InputTag> trackProducerTags(conf.getParameter<std::vector<edm::InputTag>>("TrackProducers"));
213  //which of these do I need to turn into vectors?
214  maxNormalizedChisq_ = conf.getParameter<double>("MaxNormalizedChisq");
215  minPT_ = conf.getParameter<double>("MinPT");
216  minFound_ = (unsigned int)conf.getParameter<int>("MinFound");
217  epsilon_ = conf.getParameter<double>("Epsilon");
218  shareFrac_ = conf.getParameter<double>("ShareFrac");
219  allowFirstHitShare_ = conf.getParameter<bool>("allowFirstHitShare");
220  foundHitBonus_ = conf.getParameter<double>("FoundHitBonus");
221  lostHitPenalty_ = conf.getParameter<double>("LostHitPenalty");
222  indivShareFrac_ = conf.getParameter<std::vector<double>>("indivShareFrac");
223  std::string qualityStr = conf.getParameter<std::string>("newQuality");
224  priorityToken = esConsumes<TrackAlgoPriorityOrder, CkfComponentsRecord>(edm::ESInputTag("", priorityName_));
225 
226  if (!qualityStr.empty()) {
228  } else
230 
231  use_sharesInput_ = true;
232  if (epsilon_ > 0.0)
233  use_sharesInput_ = false;
234 
236 
237  for (unsigned int i = 0; i < setsToMerge.size(); i++) {
238  listsToMerge_.push_back(setsToMerge[i].getParameter<std::vector<int>>("tLists"));
239  promoteQuality_.push_back(setsToMerge[i].getParameter<bool>("pQual"));
240  }
241  hasSelector_ = conf.getParameter<std::vector<int>>("hasSelector");
242  copyMVA_ = conf.getParameter<bool>("copyMVA");
243 
244  std::vector<edm::InputTag> selectors(conf.getParameter<std::vector<edm::InputTag>>("selectedTrackQuals"));
245  std::vector<edm::InputTag> mvaStores;
246  if (conf.exists("mvaValueTags")) {
247  mvaStores = conf.getParameter<std::vector<edm::InputTag>>("mvaValueTags");
248  } else {
249  for (int i = 0; i < (int)selectors.size(); i++) {
250  edm::InputTag ntag(selectors[i].label(), "MVAVals");
251  mvaStores.push_back(ntag);
252  }
253  }
254  unsigned int numTrkColl = trackProducerTags.size();
255  if (numTrkColl != hasSelector_.size() || numTrkColl != selectors.size()) {
256  throw cms::Exception("Inconsistent size") << "need same number of track collections and selectors";
257  }
258  if (numTrkColl != hasSelector_.size() || numTrkColl != mvaStores.size()) {
259  throw cms::Exception("Inconsistent size") << "need same number of track collections and MVA stores";
260  }
261  for (unsigned int i = indivShareFrac_.size(); i < numTrkColl; i++) {
262  // edm::LogWarning("TrackListMerger") << "No indivShareFrac for " << trackProducersTags <<". Using default value of 1";
263  indivShareFrac_.push_back(1.0);
264  }
265 
266  trkQualMod_ = conf.getParameter<bool>("writeOnlyTrkQuals");
267  if (trkQualMod_) {
268  bool ok = true;
269  for (unsigned int i = 1; i < numTrkColl; i++) {
270  if (!(trackProducerTags[i] == trackProducerTags[0]))
271  ok = false;
272  }
273  if (!ok) {
274  throw cms::Exception("Bad input") << "to use writeOnlyTrkQuals=True all input InputTags must be the same";
275  }
276  produces<edm::ValueMap<int>>();
277  produces<QualityMaskCollection>("QualityMasks");
278  } else {
279  produces<reco::TrackCollection>();
280 
281  makeReKeyedSeeds_ = conf.getUntrackedParameter<bool>("makeReKeyedSeeds", false);
282  if (makeReKeyedSeeds_) {
283  copyExtras_ = true;
284  produces<TrajectorySeedCollection>();
285  }
286 
287  if (copyExtras_) {
288  produces<reco::TrackExtraCollection>();
289  produces<TrackingRecHitCollection>();
290  }
291  produces<std::vector<Trajectory>>();
292  produces<TrajTrackAssociationCollection>();
293  }
294  produces<edm::ValueMap<float>>("MVAVals");
295  produces<MVACollection>("MVAValues");
296 
297  // Do all the consumes
298  trackProducers_.resize(numTrkColl);
299  for (unsigned int i = 0; i < numTrkColl; ++i) {
300  trackProducers_[i] = hasSelector_[i] > 0 ? edTokens(trackProducerTags[i], selectors[i], mvaStores[i])
301  : edTokens(trackProducerTags[i], mvaStores[i]);
302  }
303 }
304 
305 // Functions that gets called by framework every event
307  // extract tracker geometry
308  //
309  //edm::ESHandle<TrackerGeometry> theG;
310  //es.get<TrackerDigiGeometryRecord>().get(theG);
311 
312  // using namespace reco;
313 
315  auto const& trackAlgoPriorityOrder = *priorityH;
316 
317  // get Inputs
318  // if 1 input list doesn't exist, make an empty list, issue a warning, and continue
319  // this allows TrackListMerger to be used as a cleaner only if handed just one list
320  // if both input lists don't exist, will issue 2 warnings and generate an empty output collection
321  //
322  static const reco::TrackCollection s_empty;
323 
324  std::vector<const reco::TrackCollection*> trackColls;
325  std::vector<edm::Handle<reco::TrackCollection>> trackHandles(trackProducers_.size());
326  for (unsigned int i = 0; i < trackProducers_.size(); i++) {
327  trackColls.push_back(nullptr);
328  //edm::Handle<reco::TrackCollection> trackColl;
329  e.getByToken(trackProducers_[i].tk, trackHandles[i]);
330  if (trackHandles[i].isValid()) {
331  trackColls[i] = trackHandles[i].product();
332  } else {
333  edm::LogWarning("TrackListMerger") << "TrackCollection " << trackProducers_[i].tag << " not found";
334  trackColls[i] = &s_empty;
335  }
336  }
337 
338  if (trackColls.empty()) {
339  // output empty collections and early return
340  this->returnEmptyCollections(e);
341  return;
342  }
343 
344  unsigned int collsSize = trackColls.size();
345  unsigned int rSize = 0;
346  unsigned int trackCollSizes[collsSize];
347  unsigned int trackCollFirsts[collsSize];
348  for (unsigned int i = 0; i != collsSize; i++) {
349  trackCollSizes[i] = trackColls[i]->size();
350  trackCollFirsts[i] = rSize;
351  rSize += trackCollSizes[i];
352  }
353 
354  if (rSize == 0) {
355  // output empty collections and early return
356  this->returnEmptyCollections(e);
357  return;
358  }
359 
360  statCount.begin(rSize);
361 
362  //
363  // quality cuts first
364  //
365  int i = -1;
366 
367  int selected[rSize];
368  int indexG[rSize];
369  bool trkUpdated[rSize];
370  int trackCollNum[rSize];
371  int trackQuals[rSize];
372  float trackMVAs[rSize];
373  reco::TrackBase::TrackAlgorithm oriAlgo[rSize];
374  std::vector<reco::TrackBase::AlgoMask> algoMask(rSize);
375  for (unsigned int j = 0; j < rSize; j++) {
376  indexG[j] = -1;
377  selected[j] = 1;
378  trkUpdated[j] = false;
379  trackCollNum[j] = 0;
380  trackQuals[j] = 0;
381  trackMVAs[j] = -998.0;
383  }
384 
385  int ngood = 0;
386  for (unsigned int j = 0; j != collsSize; j++) {
387  const reco::TrackCollection* tC1 = trackColls[j];
388 
389  edm::Handle<edm::ValueMap<int>> trackSelColl;
390  edm::Handle<edm::ValueMap<float>> trackMVAStore;
391  if (copyMVA_)
392  e.getByToken(trackProducers_[j].tmva, trackMVAStore);
393  if (hasSelector_[j] > 0) {
394  e.getByToken(trackProducers_[j].tsel, trackSelColl);
395  }
396 
397  if (!tC1->empty()) {
398  unsigned int iC = 0;
399  for (reco::TrackCollection::const_iterator track = tC1->begin(); track != tC1->end(); track++) {
400  i++;
401  trackCollNum[i] = j;
402  trackQuals[i] = track->qualityMask();
403  oriAlgo[i] = track->originalAlgo();
404  algoMask[i] = track->algoMask();
405 
406  reco::TrackRef trkRef = reco::TrackRef(trackHandles[j], iC);
407  if (copyMVA_)
408  if ((*trackMVAStore).contains(trkRef.id()))
409  trackMVAs[i] = (*trackMVAStore)[trkRef];
410  if (hasSelector_[j] > 0) {
411  int qual = (*trackSelColl)[trkRef];
412  if (qual < 0) {
413  selected[i] = 0;
414  iC++;
415  continue;
416  } else {
417  trackQuals[i] = qual;
418  }
419  }
420  iC++;
421  selected[i] = trackQuals[i] + 10; //10 is magic number used throughout...
422  if ((short unsigned)track->ndof() < 1) {
423  selected[i] = 0;
424  continue;
425  }
426  if (track->normalizedChi2() > maxNormalizedChisq_) {
427  selected[i] = 0;
428  continue;
429  }
430  if (track->found() < minFound_) {
431  selected[i] = 0;
432  continue;
433  }
434  if (track->pt() < minPT_) {
435  selected[i] = 0;
436  continue;
437  }
438  // good!
439  indexG[i] = ngood++;
440  //if ( beVerb) std::cout << "inverb " << track->pt() << " " << selected[i] << std::endl;
441  } //end loop over tracks
442  } //end more than 0 track
443  } // loop over trackcolls
444 
445  statCount.pre(ngood);
446 
447  //cache the id and rechits of valid hits
448  typedef std::pair<unsigned int, const TrackingRecHit*> IHit;
449  std::vector<std::vector<IHit>> rh1(ngood); // "not an array" of vectors!
450  //const TrackingRecHit* fh1[ngood]; // first hit...
452  float score[ngood];
453 
454  for (unsigned int j = 0; j < rSize; j++) {
455  if (selected[j] == 0)
456  continue;
457  int i = indexG[j];
458  assert(i >= 0);
459  unsigned int collNum = trackCollNum[j];
460  unsigned int trackNum = j - trackCollFirsts[collNum];
461  const reco::Track* track = &((trackColls[collNum])->at(trackNum));
462 
463  algo[i] = track->algo();
464  int validHits = track->numberOfValidHits();
465  int validPixelHits = track->hitPattern().numberOfValidPixelHits();
466  int lostHits = track->numberOfLostHits();
467  score[i] =
468  foundHitBonus_ * validPixelHits + foundHitBonus_ * validHits - lostHitPenalty_ * lostHits - track->chi2();
469 
470  rh1[i].reserve(validHits);
471  auto compById = [](IHit const& h1, IHit const& h2) { return h1.first < h2.first; };
472  for (trackingRecHit_iterator it = track->recHitsBegin(); it != track->recHitsEnd(); ++it) {
473  const TrackingRecHit* hit = (*it);
474  unsigned int id = hit->rawId();
475  if (hit->geographicalId().subdetId() > 2)
476  id &= (~3); // mask mono/stereo in strips...
477  if LIKELY (hit->isValid()) {
478  rh1[i].emplace_back(id, hit);
479  std::push_heap(rh1[i].begin(), rh1[i].end(), compById);
480  }
481  }
482  std::sort_heap(rh1[i].begin(), rh1[i].end(), compById);
483  }
484 
485  //DL here
486  if LIKELY (ngood > 1 && collsSize > 1)
487  for (unsigned int ltm = 0; ltm < listsToMerge_.size(); ltm++) {
488  int saveSelected[rSize];
489  bool notActive[collsSize];
490  for (unsigned int cn = 0; cn != collsSize; ++cn)
491  notActive[cn] = find(listsToMerge_[ltm].begin(), listsToMerge_[ltm].end(), cn) == listsToMerge_[ltm].end();
492 
493  for (unsigned int i = 0; i < rSize; i++)
494  saveSelected[i] = selected[i];
495 
496  //DL protect against 0 tracks?
497  for (unsigned int i = 0; i < rSize - 1; i++) {
498  if (selected[i] == 0)
499  continue;
500  unsigned int collNum = trackCollNum[i];
501 
502  //check that this track is in one of the lists for this iteration
503  if (notActive[collNum])
504  continue;
505 
506  int k1 = indexG[i];
507  unsigned int nh1 = rh1[k1].size();
508  int qualityMaskT1 = trackQuals[i];
509 
510  int nhit1 = nh1; // validHits[k1];
511  float score1 = score[k1];
512 
513  // start at next collection
514  for (unsigned int j = i + 1; j < rSize; j++) {
515  if (selected[j] == 0)
516  continue;
517  unsigned int collNum2 = trackCollNum[j];
518  if ((collNum == collNum2) && indivShareFrac_[collNum] > 0.99)
519  continue;
520  //check that this track is in one of the lists for this iteration
521  if (notActive[collNum2])
522  continue;
523 
524  int k2 = indexG[j];
525 
526  int newQualityMask = -9; //avoid resetting quality mask if not desired 10+ -9 =1
527  if (promoteQuality_[ltm]) {
528  int maskT1 = saveSelected[i] > 1 ? saveSelected[i] - 10 : qualityMaskT1;
529  int maskT2 = saveSelected[j] > 1 ? saveSelected[j] - 10 : trackQuals[j];
530  newQualityMask = (maskT1 | maskT2); // take OR of trackQuality
531  }
532  unsigned int nh2 = rh1[k2].size();
533  int nhit2 = nh2;
534 
535  auto share = use_sharesInput_ ? [](const TrackingRecHit* it, const TrackingRecHit* jt, float) -> bool {
536  return it->sharesInput(jt, TrackingRecHit::some);
537  }
538  : [](const TrackingRecHit* it, const TrackingRecHit* jt, float eps) -> bool {
539  float delta = std::abs(it->localPosition().x() - jt->localPosition().x());
540  return (it->geographicalId() == jt->geographicalId()) && (delta < eps);
541  };
542 
543  statCount.start();
544 
545  //loop over rechits
546  int noverlap = 0;
547  int firstoverlap = 0;
548  // check first hit (should use REAL first hit?)
549  if UNLIKELY (allowFirstHitShare_ && rh1[k1][0].first == rh1[k2][0].first) {
550  const TrackingRecHit* it = rh1[k1][0].second;
551  const TrackingRecHit* jt = rh1[k2][0].second;
552  if (share(it, jt, epsilon_))
553  firstoverlap = 1;
554  }
555 
556  // exploit sorting
557  unsigned int jh = 0;
558  unsigned int ih = 0;
559  while (ih != nh1 && jh != nh2) {
560  // break if not enough to go...
561  // if ( nprecut-noverlap+firstoverlap > int(nh1-ih)) break;
562  // if ( nprecut-noverlap+firstoverlap > int(nh2-jh)) break;
563  auto const id1 = rh1[k1][ih].first;
564  auto const id2 = rh1[k2][jh].first;
565  if (id1 < id2)
566  ++ih;
567  else if (id2 < id1)
568  ++jh;
569  else {
570  // in case of split-hit do full conbinatorics
571  auto li = ih;
572  while ((++li) != nh1 && id1 == rh1[k1][li].first) {
573  }
574  auto lj = jh;
575  while ((++lj) != nh2 && id2 == rh1[k2][lj].first) {
576  }
577  for (auto ii = ih; ii != li; ++ii)
578  for (auto jj = jh; jj != lj; ++jj) {
579  const TrackingRecHit* it = rh1[k1][ii].second;
580  const TrackingRecHit* jt = rh1[k2][jj].second;
581  if (share(it, jt, epsilon_))
582  noverlap++;
583  }
584  jh = lj;
585  ih = li;
586  } // equal ids
587 
588  } //loop over ih & jh
589 
590  bool dupfound =
591  (collNum != collNum2)
592  ? (noverlap - firstoverlap) > (std::min(nhit1, nhit2) - firstoverlap) * shareFrac_
593  : (noverlap - firstoverlap) > (std::min(nhit1, nhit2) - firstoverlap) * indivShareFrac_[collNum];
594 
595  auto seti = [&](unsigned int ii, unsigned int jj) {
596  selected[jj] = 0;
597  selected[ii] = 10 + newQualityMask; // add 10 to avoid the case where mask = 1
598  trkUpdated[ii] = true;
599  if (trackAlgoPriorityOrder.priority(oriAlgo[jj]) < trackAlgoPriorityOrder.priority(oriAlgo[ii]))
600  oriAlgo[ii] = oriAlgo[jj];
601  algoMask[ii] |= algoMask[jj];
602  algoMask[jj] = algoMask[ii]; // in case we keep discarded
603  };
604 
605  if (dupfound) {
606  float score2 = score[k2];
607  constexpr float almostSame =
608  0.01f; // difference rather than ratio due to possible negative values for score
609  if (score1 - score2 > almostSame) {
610  seti(i, j);
611  } else if (score2 - score1 > almostSame) {
612  seti(j, i);
613  } else {
614  // If tracks from both iterations are virtually identical, choose the one with the best quality or with lower algo
615  if ((trackQuals[j] &
617  (trackQuals[i] &
619  //same quality, pick earlier algo
620  if (trackAlgoPriorityOrder.priority(algo[k1]) <= trackAlgoPriorityOrder.priority(algo[k2])) {
621  seti(i, j);
622  } else {
623  seti(j, i);
624  }
625  } else if ((trackQuals[j] & (1 << reco::TrackBase::loose | 1 << reco::TrackBase::tight |
627  (trackQuals[i] & (1 << reco::TrackBase::loose | 1 << reco::TrackBase::tight |
629  seti(i, j);
630  } else {
631  seti(j, i);
632  }
633  } //end fi < fj
634  statCount.overlap();
635  /*
636  if (at0[k1]&&at0[k2]) {
637  statCount.dp(dphi);
638  if (dz<1.f) statCount.de(deta);
639  }
640  */
641  } //end got a duplicate
642  else {
643  statCount.noOverlap();
644  }
645  //stop if the ith track is now unselected
646  if (selected[i] == 0)
647  break;
648  } //end track2 loop
649  } //end track loop
650  } //end loop over track list sets
651 
652  auto vmMVA = std::make_unique<edm::ValueMap<float>>();
653  edm::ValueMap<float>::Filler fillerMVA(*vmMVA);
654 
655  // special case - if just doing the trkquals
656  if (trkQualMod_) {
657  unsigned int tSize = trackColls[0]->size();
658  auto vm = std::make_unique<edm::ValueMap<int>>();
660 
661  std::vector<int> finalQuals(tSize, -1); //default is unselected
662  for (unsigned int i = 0; i < rSize; i++) {
663  unsigned int tNum = i % tSize;
664 
665  if (selected[i] > 1) {
666  finalQuals[tNum] = selected[i] - 10;
667  if (trkUpdated[i])
668  finalQuals[tNum] = (finalQuals[tNum] | (1 << qualityToSet_));
669  }
670  if (selected[i] == 1)
671  finalQuals[tNum] = trackQuals[i];
672  }
673 
674  filler.insert(trackHandles[0], finalQuals.begin(), finalQuals.end());
675  filler.fill();
676 
677  e.put(std::move(vm));
678  for (auto& q : finalQuals)
679  q = std::max(q, 0);
680  auto quals = std::make_unique<QualityMaskCollection>(finalQuals.begin(), finalQuals.end());
681  e.put(std::move(quals), "QualityMasks");
682 
683  std::vector<float> mvaVec(tSize, -99);
684 
685  for (unsigned int i = 0; i < rSize; i++) {
686  unsigned int tNum = i % tSize;
687  mvaVec[tNum] = trackMVAs[tNum];
688  }
689 
690  fillerMVA.insert(trackHandles[0], mvaVec.begin(), mvaVec.end());
691  fillerMVA.fill();
692  if (copyMVA_) {
693  e.put(std::move(vmMVA), "MVAVals");
694  auto mvas = std::make_unique<MVACollection>(mvaVec.begin(), mvaVec.end());
695  e.put(std::move(mvas), "MVAValues");
696  }
697  return;
698  }
699 
700  //
701  // output selected tracks - if any
702  //
703 
704  std::vector<reco::TrackRef> trackRefs(rSize);
705  std::vector<edm::RefToBase<TrajectorySeed>> seedsRefs(rSize);
706 
707  unsigned int nToWrite = 0;
708  for (unsigned int i = 0; i < rSize; i++)
709  if (selected[i] != 0)
710  nToWrite++;
711 
712  std::vector<float> mvaVec;
713 
714  outputTrks = std::make_unique<reco::TrackCollection>();
715  outputTrks->reserve(nToWrite);
716  refTrks = e.getRefBeforePut<reco::TrackCollection>();
717 
718  if (copyExtras_) {
719  outputTrkExtras = std::make_unique<reco::TrackExtraCollection>();
720  outputTrkExtras->reserve(nToWrite);
721  refTrkExtras = e.getRefBeforePut<reco::TrackExtraCollection>();
722  outputTrkHits = std::make_unique<TrackingRecHitCollection>();
723  outputTrkHits->reserve(nToWrite * 25);
724  refTrkHits = e.getRefBeforePut<TrackingRecHitCollection>();
725  if (makeReKeyedSeeds_) {
726  outputSeeds = std::make_unique<TrajectorySeedCollection>();
727  outputSeeds->reserve(nToWrite);
728  refTrajSeeds = e.getRefBeforePut<TrajectorySeedCollection>();
729  }
730  }
731 
732  outputTrajs = std::make_unique<std::vector<Trajectory>>();
733  outputTrajs->reserve(rSize);
734 
735  for (unsigned int i = 0; i < rSize; i++) {
736  if (selected[i] == 0) {
737  trackRefs[i] = reco::TrackRef();
738  continue;
739  }
740 
741  unsigned int collNum = trackCollNum[i];
742  unsigned int trackNum = i - trackCollFirsts[collNum];
743  const reco::Track* track = &((trackColls[collNum])->at(trackNum));
744  outputTrks->push_back(reco::Track(*track));
745  mvaVec.push_back(trackMVAs[i]);
746  if (selected[i] > 1) {
747  outputTrks->back().setQualityMask(selected[i] - 10);
748  if (trkUpdated[i])
749  outputTrks->back().setQuality(qualityToSet_);
750  }
751  //might duplicate things, but doesnt hurt
752  if (selected[i] == 1)
753  outputTrks->back().setQualityMask(trackQuals[i]);
754  outputTrks->back().setOriginalAlgorithm(oriAlgo[i]);
755  outputTrks->back().setAlgoMask(algoMask[i]);
756 
757  // if ( beVerb ) std::cout << "selected " << outputTrks->back().pt() << " " << outputTrks->back().qualityMask() << " " << selected[i] << std::endl;
758 
759  //fill the TrackCollection
760  if (copyExtras_) {
761  edm::RefToBase<TrajectorySeed> origSeedRef = track->seedRef();
762  //creating a seed with rekeyed clusters if required
763  if (makeReKeyedSeeds_) {
764  bool doRekeyOnThisSeed = false;
765 
766  edm::InputTag clusterRemovalInfos("");
767  //grab on of the hits of the seed
768  if (origSeedRef->nHits() != 0) {
769  TrackingRecHit const& hit = *origSeedRef->recHits().begin();
770  if (hit.isValid()) {
771  edm::ProductID pID = clusterProductB(&hit);
772  // the cluster collection either produced a removalInfo or mot
773  //get the clusterremoval info from the provenance: will rekey if this is found
775  edm::StableProvenance const& prov = e.getStableProvenance(pID);
776  clusterRemovalInfos = edm::InputTag(prov.moduleLabel(), prov.productInstanceName(), prov.processName());
777  doRekeyOnThisSeed = e.getByLabel(clusterRemovalInfos, CRIh);
778  } //valid hit
779  } //nhit!=0
780 
781  if (doRekeyOnThisSeed && !(clusterRemovalInfos == edm::InputTag(""))) {
782  ClusterRemovalRefSetter refSetter(e, clusterRemovalInfos);
783  TrajectorySeed::RecHitContainer newRecHitContainer;
784  newRecHitContainer.reserve(origSeedRef->nHits());
785  for (auto const& recHit : origSeedRef->recHits()) {
786  newRecHitContainer.push_back(recHit);
787  refSetter.reKey(&newRecHitContainer.back());
788  }
789  outputSeeds->push_back(
790  TrajectorySeed(origSeedRef->startingState(), newRecHitContainer, origSeedRef->direction()));
791  }
792  //doRekeyOnThisSeed=true
793  else {
794  //just copy the one we had before
795  outputSeeds->push_back(TrajectorySeed(*origSeedRef));
796  }
798  origSeedRef = edm::RefToBase<TrajectorySeed>(pureRef);
799  } //creating a new seed and rekeying it rechit clusters.
800 
801  // Fill TrackExtra collection
802  outputTrkExtras->push_back(reco::TrackExtra(track->outerPosition(),
803  track->outerMomentum(),
804  track->outerOk(),
805  track->innerPosition(),
806  track->innerMomentum(),
807  track->innerOk(),
808  track->outerStateCovariance(),
809  track->outerDetId(),
810  track->innerStateCovariance(),
811  track->innerDetId(),
812  track->seedDirection(),
813  origSeedRef));
814  seedsRefs[i] = origSeedRef;
815  outputTrks->back().setExtra(reco::TrackExtraRef(refTrkExtras, outputTrkExtras->size() - 1));
816  reco::TrackExtra& tx = outputTrkExtras->back();
817  tx.setResiduals(track->residuals());
818 
819  // fill TrackingRecHits
820  unsigned nh1 = track->recHitsSize();
821  tx.setHits(refTrkHits, outputTrkHits->size(), nh1);
822  tx.setTrajParams(track->extra()->trajParams(), track->extra()->chi2sX5());
823  assert(tx.trajParams().size() == tx.recHitsSize());
824  for (auto hh = track->recHitsBegin(), eh = track->recHitsEnd(); hh != eh; ++hh) {
825  outputTrkHits->push_back((*hh)->clone());
826  }
827  }
828  trackRefs[i] = reco::TrackRef(refTrks, outputTrks->size() - 1);
829 
830  } //end faux loop over tracks
831 
832  //Fill the trajectories, etc. for 1st collection
833  refTrajs = e.getRefBeforePut<std::vector<Trajectory>>();
834 
835  outputTTAss = std::make_unique<TrajTrackAssociationCollection>(refTrajs, refTrks);
836 
837  for (unsigned int ti = 0; ti < trackColls.size(); ti++) {
840  e.getByToken(trackProducers_[ti].traj, hTraj1);
841  e.getByToken(trackProducers_[ti].tass, hTTAss1);
842 
843  if (hTraj1.failedToGet() || hTTAss1.failedToGet())
844  continue;
845 
846  for (size_t i = 0, n = hTraj1->size(); i < n; ++i) {
847  edm::Ref<std::vector<Trajectory>> trajRef(hTraj1, i);
849  if (match != hTTAss1->end()) {
850  const edm::Ref<reco::TrackCollection>& trkRef = match->val;
851  uint32_t oldKey = trackCollFirsts[ti] + static_cast<uint32_t>(trkRef.key());
852  if (trackRefs[oldKey].isNonnull()) {
853  outputTrajs->push_back(*trajRef);
854  //if making extras and the seeds at the same time, change the seed ref on the trajectory
856  outputTrajs->back().setSeedRef(seedsRefs[oldKey]);
857  outputTTAss->insert(edm::Ref<std::vector<Trajectory>>(refTrajs, outputTrajs->size() - 1), trackRefs[oldKey]);
858  }
859  }
860  }
861  }
862 
863  statCount.end(outputTrks->size());
864 
865  edm::ProductID nPID = refTrks.id();
866  edm::TestHandle<reco::TrackCollection> outHandle(outputTrks.get(), nPID);
867  fillerMVA.insert(outHandle, mvaVec.begin(), mvaVec.end());
868  fillerMVA.fill();
869 
870  e.put(std::move(outputTrks));
871  if (copyMVA_) {
872  e.put(std::move(vmMVA), "MVAVals");
873  auto mvas = std::make_unique<MVACollection>(mvaVec.begin(), mvaVec.end());
874  e.put(std::move(mvas), "MVAValues");
875  }
876  if (copyExtras_) {
878  e.put(std::move(outputTrkHits));
879  if (makeReKeyedSeeds_)
880  e.put(std::move(outputSeeds));
881  }
882  e.put(std::move(outputTrajs));
883  e.put(std::move(outputTTAss));
884  return;
885 
886 } //end produce
887 
889  if (trkQualMod_) {
890  auto vm = std::make_unique<edm::ValueMap<int>>();
891  e.put(std::move(vm));
892  auto quals = std::make_unique<QualityMaskCollection>();
893  e.put(std::move(quals), "QualityMasks");
894  } else {
895  auto outputTrks = std::make_unique<reco::TrackCollection>();
896  e.put(std::move(outputTrks));
897 
898  if (makeReKeyedSeeds_) {
899  auto outputSeeds = std::make_unique<TrajectorySeedCollection>();
900  e.put(std::move(outputSeeds));
901  }
902 
903  if (copyExtras_) {
904  auto outputTrkExtras = std::make_unique<reco::TrackExtraCollection>();
905  auto outputTrkHits = std::make_unique<TrackingRecHitCollection>();
907  e.put(std::move(outputTrkHits));
908  }
909 
910  auto outputTrajs = std::make_unique<std::vector<Trajectory>>();
911  outputTTAss = std::make_unique<TrajTrackAssociationCollection>();
912  e.put(std::move(outputTrajs));
913  e.put(std::move(outputTTAss));
914  }
915  auto vmMVA = std::make_unique<edm::ValueMap<float>>();
916  e.put(std::move(vmMVA), "MVAVals");
917  auto mvas = std::make_unique<MVACollection>();
918  e.put(std::move(mvas), "MVAValues");
919  return;
920 }
921 
924 
TrackListMerger(const edm::ParameterSet &conf)
std::vector< unsigned char > QualityMaskCollection
T getParameter(std::string const &) const
Definition: ParameterSet.h:303
reference back()
Definition: OwnVector.h:431
TrajParams const & trajParams() const
std::vector< bool > promoteQuality_
std::unique_ptr< TrajTrackAssociationCollection > outputTTAss
ProductID id() const
Accessor for product ID.
Definition: Ref.h:244
const bool isValid(const Frame &aFrame, const FrameQuality &aQuality, const uint16_t aExpectedPos)
T begin() const
Definition: Range.h:15
reco::TrackRefProd refTrks
RecHitRange recHits() const
void returnEmptyCollections(edm::Event &e)
TkEDGetTokenss edTokens(const edm::InputTag &tag, const edm::InputTag &mvatag)
TrackQuality
track quality
Definition: TrackBase.h:150
#define DEFINE_FWK_MODULE(type)
Definition: MakerMacros.h:16
void setHits(TrackingRecHitRefProd const &prod, unsigned firstH, unsigned int nH)
std::string const & productInstanceName() const
std::vector< ParameterSet > VParameterSet
Definition: ParameterSet.h:34
unsigned int recHitsSize() const
number of RecHits
auto const & hh
bool exists(std::string const &parameterName) const
checks if a parameter exists
reco::TrackBase::TrackQuality qualityToSet_
std::vector< Track > TrackCollection
collection of Tracks
Definition: TrackFwd.h:14
#define LIKELY(x)
Definition: Likely.h:20
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
assert(be >=bs)
std::vector< float > MVACollection
std::unique_ptr< std::vector< Trajectory > > outputTrajs
key_type key() const
Accessor for product key.
Definition: Ref.h:250
const_iterator find(const key_type &k) const
find element with specified reference key
TrackAlgorithm
track algorithm
Definition: TrackBase.h:89
TrackingRecHitRefProd refTrkHits
void produce(edm::Event &e, const edm::EventSetup &c) override
std::vector< double > indivShareFrac_
const_iterator end() const
last iterator over the map (read only)
T getUntrackedParameter(std::string const &, T const &) const
PropagationDirection direction() const
bool failedToGet() const
Definition: HandleBase.h:72
char const * label
T x() const
Definition: PV3DBase.h:59
void push_back(D *&d)
Definition: OwnVector.h:326
std::unique_ptr< TrackingRecHitCollection > outputTrkHits
edm::EDGetTokenT< edm::ValueMap< int > > tsel
std::vector< TrajectorySeed > TrajectorySeedCollection
std::string const & moduleLabel() const
unsigned int nHits() const
edm::RefProd< TrajectorySeedCollection > refTrajSeeds
edm::EDGetTokenT< reco::TrackCollection > tk
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
std::string const & processName() const
TkEDGetTokenss edTokens(const edm::InputTag &tag, const edm::InputTag &seltag, const edm::InputTag &mvatag)
#define CMS_THREAD_SAFE
edm::ESGetToken< TrackAlgoPriorityOrder, CkfComponentsRecord > priorityToken
edm::EDGetTokenT< TrajTrackAssociationCollection > tass
edm::RefProd< std::vector< Trajectory > > refTrajs
ESHandle< T > getHandle(const ESGetToken< T, R > &iToken) const
Definition: EventSetup.h:151
d
Definition: ztail.py:151
PTrajectoryStateOnDet const & startingState() const
std::unique_ptr< reco::TrackExtraCollection > outputTrkExtras
std::vector< int > hasSelector_
ii
Definition: cuy.py:589
ProductID id() const
Accessor for product ID.
Definition: RefProd.h:124
#define dso_hidden
Definition: Visibility.h:12
std::vector< TrackExtra > TrackExtraCollection
collection of TrackExtra objects
Definition: TrackExtraFwd.h:10
static TrackQuality qualityByName(const std::string &name)
Definition: TrackBase.cc:126
DetId geographicalId() const
std::unique_ptr< TrajectorySeedCollection > outputSeeds
edm::EDGetTokenT< edm::ValueMap< float > > tmva
edm::Ref< TrackCollection > TrackRef
persistent reference to a Track
Definition: TrackFwd.h:20
constexpr std::array< unsigned int, reco::TrackBase::algoSize > trackAlgoPriorityOrder
void reKey(TrackingRecHit *hit) const
unsigned int minFound_
std::vector< TkEDGetTokenss > trackProducers_
TkEDGetTokenss(const edm::InputTag &tag_, edm::EDGetTokenT< reco::TrackCollection > &&tk_, edm::EDGetTokenT< std::vector< Trajectory >> &&traj_, edm::EDGetTokenT< TrajTrackAssociationCollection > &&tass_, edm::EDGetTokenT< edm::ValueMap< int >> &&tsel_, edm::EDGetTokenT< edm::ValueMap< float >> &&tmva_)
std::vector< std::vector< int > > listsToMerge_
std::unique_ptr< reco::TrackCollection > outputTrks
edm::EDGetTokenT< std::vector< Trajectory > > traj
std::pair< typename Association::data_type::first_type, double > match(Reference key, Association association, bool bestMatchByMaxValue)
Generic matching function.
Definition: Utils.h:10
#define UNLIKELY(x)
Definition: Likely.h:21
Log< level::Warning, false > LogWarning
std::string priorityName_
virtual LocalPoint localPosition() const =0
def move(src, dest)
Definition: eostools.py:511
void reserve(size_t)
Definition: OwnVector.h:320
void setTrajParams(TrajParams tmps, Chi2sFive chi2s)
reco::TrackExtraRefProd refTrkExtras
void setResiduals(const TrackResiduals &r)
set the residuals
Definition: TrackExtra.h:132