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