CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
CkfTrackCandidateMakerBase.cc
Go to the documentation of this file.
1 #include <memory>
2 #include <string>
3 
10 
14 
16 
21 
27 
28 
33 
35 
38 
40 
41 #include<algorithm>
42 #include<functional>
43 
44 #include <thread>
45 #ifdef VI_TBB
46 #include "tbb/parallel_for.h"
47 #endif
48 
50 
51 using namespace edm;
52 using namespace std;
53 
54 namespace {
55  BaseCkfTrajectoryBuilder *createBaseCkfTrajectoryBuilder(const edm::ParameterSet& pset, edm::ConsumesCollector& iC) {
56  return BaseCkfTrajectoryBuilderFactory::get()->create(pset.getParameter<std::string>("ComponentType"), pset, iC);
57  }
58 }
59 
60 namespace cms{
61  CkfTrackCandidateMakerBase::CkfTrackCandidateMakerBase(edm::ParameterSet const& conf, edm::ConsumesCollector && iC) :
62  theTrackCandidateOutput(true),
63  theTrajectoryOutput(false),
64  useSplitting(conf.getParameter<bool>("useHitsSplitting")),
65  doSeedingRegionRebuilding(conf.getParameter<bool>("doSeedingRegionRebuilding")),
66  cleanTrajectoryAfterInOut(conf.getParameter<bool>("cleanTrajectoryAfterInOut")),
67  reverseTrajectories(conf.existsAs<bool>("reverseTrajectories") && conf.getParameter<bool>("reverseTrajectories")),
68  theMaxNSeeds(conf.getParameter<unsigned int>("maxNSeeds")),
69  theTrajectoryBuilder(createBaseCkfTrajectoryBuilder(conf.getParameter<edm::ParameterSet>("TrajectoryBuilderPSet"), iC)),
70  theTrajectoryCleanerName(conf.getParameter<std::string>("TrajectoryCleaner")),
71  theTrajectoryCleaner(0),
72  theInitialState(new TransientInitialStateEstimator(conf.getParameter<ParameterSet>("TransientInitialStateEstimatorParameters"))),
73  theMagFieldName(conf.exists("SimpleMagneticField") ? conf.getParameter<std::string>("SimpleMagneticField") : ""),
74  theNavigationSchoolName(conf.getParameter<std::string>("NavigationSchool")),
75  theNavigationSchool(0),
76  theSeedCleaner(0),
77  maxSeedsBeforeCleaning_(0),
78  theMTELabel(iC.consumes<MeasurementTrackerEvent>(conf.getParameter<edm::InputTag>("MeasurementTrackerEvent"))),
79  skipClusters_(false)
80  {
81  //produces<TrackCandidateCollection>();
82  // old configuration totally descoped.
83  // if (!conf.exists("src"))
84  // theSeedLabel = InputTag(conf_.getParameter<std::string>("SeedProducer"),conf_.getParameter<std::string>("SeedLabel"));
85  // else
87  if ( conf.exists("maxSeedsBeforeCleaning") )
88  maxSeedsBeforeCleaning_=conf.getParameter<unsigned int>("maxSeedsBeforeCleaning");
89 
90  if (conf.existsAs<edm::InputTag>("clustersToSkip")) {
91  skipClusters_ = true;
92  maskPixels_ = iC.consumes<PixelClusterMask>(conf.getParameter<edm::InputTag>("clustersToSkip"));
93  maskStrips_ = iC.consumes<StripClusterMask>(conf.getParameter<edm::InputTag>("clustersToSkip"));
94  }
95 
96  std::string cleaner = conf.getParameter<std::string>("RedundantSeedCleaner");
97  if (cleaner == "SeedCleanerByHitPosition") {
99  } else if (cleaner == "SeedCleanerBySharedInput") {
101  } else if (cleaner == "CachingSeedCleanerByHitPosition") {
103  } else if (cleaner == "CachingSeedCleanerBySharedInput") {
104  int numHitsForSeedCleaner = conf.existsAs<int>("numHitsForSeedCleaner") ?
105  conf.getParameter<int>("numHitsForSeedCleaner") : 4;
106  int onlyPixelHits = conf.existsAs<bool>("onlyPixelHitsForSeedCleaner") ?
107  conf.getParameter<bool>("onlyPixelHitsForSeedCleaner") : false;
108  theSeedCleaner = new CachingSeedCleanerBySharedInput(numHitsForSeedCleaner,onlyPixelHits);
109  } else if (cleaner == "none") {
110  theSeedCleaner = 0;
111  } else {
112  throw cms::Exception("RedundantSeedCleaner not found", cleaner);
113  }
114 
115 
116  }
117 
118 
119  // Virtual destructor needed.
121  if (theSeedCleaner) delete theSeedCleaner;
122  }
123 
125  {
126  /* no op*/
127  }
128 
130 
131  //services
134  // edm::ESInputTag mfESInputTag(mfName);
135  // es.get<IdealMagneticFieldRecord>().get(mfESInputTag,theMagField );
136 
137  edm::ESHandle<TrajectoryCleaner> trajectoryCleanerH;
138  es.get<TrajectoryCleaner::Record>().get(theTrajectoryCleanerName, trajectoryCleanerH);
139  theTrajectoryCleaner= trajectoryCleanerH.product();
140 
141  edm::ESHandle<NavigationSchool> navigationSchoolH;
142  es.get<NavigationSchoolRecord>().get(theNavigationSchoolName, navigationSchoolH);
143  theNavigationSchool = navigationSchoolH.product();
144  theTrajectoryBuilder->setNavigationSchool(theNavigationSchool);
145  }
146 
147  // Functions that gets called by framework every event
149  {
150  // getting objects from the EventSetup
151  setEventSetup( es );
152 
153  // set the correct navigation
154  // NavigationSetter setter( *theNavigationSchool);
155 
156  // propagator
157  edm::ESHandle<Propagator> thePropagator;
158  es.get<TrackingComponentsRecord>().get("AnyDirectionAnalyticalPropagator",
159  thePropagator);
160 
161  // method for Debugging
163 
164  // Step A: set Event for the TrajectoryBuilder
166  e.getByToken(theMTELabel, data);
167 
168  std::auto_ptr<MeasurementTrackerEvent> dataWithMasks;
169  if (skipClusters_) {
171  e.getByToken(maskPixels_, pixelMask);
173  e.getByToken(maskStrips_, stripMask);
174  dataWithMasks.reset(new MeasurementTrackerEvent(*data, *stripMask, *pixelMask));
175  //std::cout << "Trajectory builder " << conf_.getParameter<std::string>("@module_label") << " created with masks, " << std::endl;
176  theTrajectoryBuilder->setEvent(e, es, &*dataWithMasks);
177  } else {
178  //std::cout << "Trajectory builder " << conf_.getParameter<std::string>("@module_label") << " created without masks, " << std::endl;
179  theTrajectoryBuilder->setEvent(e, es, &*data);
180  }
181  // TISE ES must be set here due to dependence on theTrajectoryBuilder
182  theInitialState->setEventSetup( es, static_cast<TkTransientTrackingRecHitBuilder const *>(theTrajectoryBuilder->hitBuilder())->cloner() );
183 
184  // Step B: Retrieve seeds
185 
187  e.getByToken(theSeedLabel, collseed);
188 
189  // Step C: Create empty output collection
190  std::auto_ptr<TrackCandidateCollection> output(new TrackCandidateCollection);
191  std::auto_ptr<std::vector<Trajectory> > outputT (new std::vector<Trajectory>());
192 
193  if ( (*collseed).size()>theMaxNSeeds ) {
194  LogError("TooManySeeds")<<"Exceeded maximum numeber of seeds! theMaxNSeeds="<<theMaxNSeeds<<" nSeed="<<(*collseed).size();
195  if (theTrackCandidateOutput){ e.put(output);}
196  if (theTrajectoryOutput){e.put(outputT);}
197  return;
198  }
199 
200  // Step D: Invoke the building algorithm
201  if ((*collseed).size()>0){
202 
203  unsigned int lastCleanResult=0;
204  std::vector<Trajectory> rawResult;
205  rawResult.reserve(collseed->size() * 4);
206 
207  if (theSeedCleaner) theSeedCleaner->init( &rawResult );
208 
209  // method for debugging
211 
212  // the mutex
213  std::mutex theMutex;
214  using Lock = std::unique_lock<std::mutex>;
215 
216  // Loop over seeds
217  size_t collseed_size = collseed->size();
218 
219  unsigned int indeces[collseed_size]; for (auto i=0U; i< collseed_size; ++i) indeces[i]=i;
220  // std::random_shuffle(indeces,indeces+collseed_size);
221 
222 
223  /*
224  * here only for reference: does not seems to help
225 
226  auto const & seeds = *collseed;
227 
228 
229  float val[collseed_size];
230  for (auto i=0U; i< collseed_size; ++i)
231  { val[i] = seeds[i].startingState().pt();};
232  // { val[i] = std::abs((*seeds[i].recHits().first).surface()->eta());}
233 
234 
235  unsigned long long val[collseed_size];
236  for (auto i=0U; i< collseed_size; ++i) {
237  if (seeds[i].nHits()<2) { val[i]=0; continue;}
238  auto h = seeds[i].recHits().first;
239  auto const & hit = static_cast<BaseTrackerRecHit const&>(*h);
240  val[i] = hit.firstClusterRef().key();
241  if (++h != seeds[i].recHits().second) {
242  auto const & hit = static_cast<BaseTrackerRecHit const&>(*h);
243  val[i] |= (unsigned long long)(hit.firstClusterRef().key())<<32;
244  }
245  }
246 
247  std::sort(indeces,indeces+collseed_size, [&](unsigned int i, unsigned int j){return val[i]<val[j];});
248 
249 
250  // std::cout << spt(indeces[0]) << ' ' << spt(indeces[collseed_size-1]) << std::endl;
251 
252  */
253 
254  auto theLoop = [&](size_t ii) {
255  auto j = indeces[ii];
256 
257  // to be moved inside a par section (how with tbb??)
258  std::vector<Trajectory> theTmpTrajectories;
259 
260 
261  LogDebug("CkfPattern") << "======== Begin to look for trajectories from seed " << j << " ========"<<endl;
262 
263  { Lock lock(theMutex);
264  // Check if seed hits already used by another track
265  if (theSeedCleaner && !theSeedCleaner->good( &((*collseed)[j])) ) {
266  LogDebug("CkfTrackCandidateMakerBase")<<" Seed cleaning kills seed "<<j;
267  return; // from the lambda!
268  }}
269 
270  // Build trajectory from seed outwards
271  theTmpTrajectories.clear();
272  auto const & startTraj = theTrajectoryBuilder->buildTrajectories( (*collseed)[j], theTmpTrajectories, nullptr );
273 
274 
275  LogDebug("CkfPattern") << "======== In-out trajectory building found " << theTmpTrajectories.size()
276  << " trajectories from seed " << j << " ========"<<endl
277  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
278 
280 
281  // Select the best trajectory from this seed (declare others invalid)
282  theTrajectoryCleaner->clean(theTmpTrajectories);
283 
284  LogDebug("CkfPattern") << "======== In-out trajectory cleaning gave the following valid trajectories from seed "
285  << j << " ========"<<endl
286  << PrintoutHelper::dumpCandidates(theTmpTrajectories);
287  }
288 
289  // Optionally continue building trajectory back through
290  // seed and if possible further inwards.
291 
293  theTrajectoryBuilder->rebuildTrajectories(startTraj,(*collseed)[j],theTmpTrajectories);
294 
295  LogDebug("CkfPattern") << "======== Out-in trajectory building found " << theTmpTrajectories.size()
296  << " valid/invalid trajectories from seed " << j << " ========"<<endl
297  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
298  }
299 
300 
301  // Select the best trajectory from this seed (after seed region rebuilding, can be more than one)
302  theTrajectoryCleaner->clean(theTmpTrajectories);
303 
304  LogDebug("CkfPattern") << "======== Trajectory cleaning gave the following valid trajectories from seed "
305  << j << " ========"<<endl
306  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
307 
308  { Lock lock(theMutex);
309  for(vector<Trajectory>::iterator it=theTmpTrajectories.begin();
310  it!=theTmpTrajectories.end(); it++){
311  if( it->isValid() ) {
312  it->setSeedRef(collseed->refAt(j));
313  // Store trajectory
314  rawResult.push_back(std::move(*it));
315  // Tell seed cleaner which hits this trajectory used.
316  //TO BE FIXED: this cut should be configurable via cfi file
317  if (theSeedCleaner && rawResult.back().foundHits()>3) theSeedCleaner->add( &rawResult.back() );
318  //if (theSeedCleaner ) theSeedCleaner->add( & (*it) );
319  }
320  }}
321 
322  theTmpTrajectories.clear();
323 
324  LogDebug("CkfPattern") << "rawResult trajectories found so far = " << rawResult.size();
325 
326  { Lock lock(theMutex);
327  if ( maxSeedsBeforeCleaning_ >0 && rawResult.size() > maxSeedsBeforeCleaning_+lastCleanResult) {
328  theTrajectoryCleaner->clean(rawResult);
329  rawResult.erase(std::remove_if(rawResult.begin()+lastCleanResult,rawResult.end(),
330  std::not1(std::mem_fun_ref(&Trajectory::isValid))),
331  rawResult.end());
332  lastCleanResult=rawResult.size();
333  }
334  }
335 
336  };
337  // end of loop over seeds
338 
339 
340 #ifdef VI_TBB
341  tbb::parallel_for(0UL,collseed_size,1UL,theLoop);
342 #else
343 #ifdef VI_OMP
344 #pragma omp parallel for schedule(dynamic,4)
345 #endif
346  for (size_t j = 0; j < collseed_size; j++){
347  theLoop(j);
348  }
349 #endif
350 
352 
353  // std::cout << "VICkfPattern " << "rawResult trajectories found = " << rawResult.size() << std::endl;
354 
355 
356  // Step E: Clean the results to avoid duplicate tracks
357  // Rejected ones just flagged as invalid.
358  theTrajectoryCleaner->clean(rawResult);
359 
360  LogDebug("CkfPattern") << "======== Final cleaning of entire event found " << rawResult.size()
361  << " valid/invalid trajectories ======="<<endl
362  <<PrintoutHelper::dumpCandidates(rawResult);
363 
364  LogDebug("CkfPattern") << "removing invalid trajectories.";
365 
366  vector<Trajectory> & unsmoothedResult(rawResult);
367  unsmoothedResult.erase(std::remove_if(unsmoothedResult.begin(),unsmoothedResult.end(),
368  std::not1(std::mem_fun_ref(&Trajectory::isValid))),
369  unsmoothedResult.end());
370  unsmoothedResult.shrink_to_fit();
371  // If requested, reverse the trajectories creating a new 1-hit seed on the last measurement of the track
372  if (reverseTrajectories) {
373  for (auto it = unsmoothedResult.begin(), ed = unsmoothedResult.end(); it != ed; ++it) {
374  // reverse the trajectory only if it has valid hit on the last measurement (should happen)
375  if (it->lastMeasurement().updatedState().isValid() &&
376  it->lastMeasurement().recHit().get() != 0 &&
377  it->lastMeasurement().recHit()->isValid()) {
378  // I can't use reverse in place, because I want to change the seed
379  // 1) reverse propagation direction
380  PropagationDirection direction = it->direction();
381  if (direction == alongMomentum) direction = oppositeToMomentum;
382  else if (direction == oppositeToMomentum) direction = alongMomentum;
383  // 2) make a seed
384  TrajectoryStateOnSurface const & initState = it->lastMeasurement().updatedState();
385  auto initId = it->lastMeasurement().recHitR().rawId();
388  hits.push_back(it->lastMeasurement().recHit()->hit()->clone());
389  boost::shared_ptr<const TrajectorySeed> seed(new TrajectorySeed(state, std::move(hits), direction));
390  // 3) make a trajectory
391  Trajectory trajectory(seed, direction);
392  trajectory.setNLoops(it->nLoops());
393  trajectory.setSeedRef(it->seedRef());
394  // 4) push states in reversed order
395  Trajectory::DataContainer &meas = it->measurements();
396  trajectory.reserve(meas.size());
397  for (auto itmeas = meas.rbegin(), endmeas = meas.rend(); itmeas != endmeas; ++itmeas) {
398  trajectory.push(std::move(*itmeas));
399  }
400  // replace
401  (*it)= std::move(trajectory);
402  } else {
403  edm::LogWarning("CkfPattern_InvalidLastMeasurement") << "Last measurement of the trajectory is invalid, cannot reverse it";
404  }
405  }
406  }
407 
408 
409  int viTotHits=0;
410 
412  // Step F: Convert to TrackCandidates
413  output->reserve(unsmoothedResult.size());
414  Traj2TrackHits t2t(theTrajectoryBuilder->hitBuilder(),true);
415 
416  for (vector<Trajectory>::const_iterator it = unsmoothedResult.begin();
417  it != unsmoothedResult.end(); ++it) {
418 
419  LogDebug("CkfPattern") << "copying "<<(useSplitting?"splitted":"un-splitted")<<" hits from trajectory";
421  if(it->direction() != alongMomentum) LogDebug("CkfPattern") << "not along momentum... " << std::endl;
422  t2t(*it,recHits,useSplitting);
423 
424  viTotHits+=recHits.size();
425 
426 
427  LogDebug("CkfPattern") << "getting initial state.";
428  Trajectory trialTrajectory = (*it);
429  std::pair<TrajectoryStateOnSurface, const GeomDet*> initState;
430  bool failed = false;
431 
432  do {
433  // Drop last hit if previous backFitter was not successful
434  if(failed) {
435  LogDebug("CkfPattern") << "removing last hit";
436  trialTrajectory.pop();
437  LogDebug("CkfPattern") << "hits remaining " << trialTrajectory.foundHits();
438  }
439 
440  // Get inner state
441  const bool doBackFit = (!doSeedingRegionRebuilding) & (!reverseTrajectories);
442  initState = theInitialState->innerState(trialTrajectory, doBackFit);
443 
444  // Check if that was successful
445  failed = (!initState.first.isValid()) || initState.second == nullptr || edm::isNotFinite(initState.first.globalPosition().x());
446  } while(failed && trialTrajectory.foundHits() > 3);
447 
448  if(failed) continue;
449 
450 
451 
452  PTrajectoryStateOnDet state;
453  if(useSplitting && (initState.second != recHits.front().det()) && recHits.front().det() ){
454  LogDebug("CkfPattern") << "propagating to hit front in case of splitting.";
455  TrajectoryStateOnSurface && propagated = thePropagator->propagate(initState.first,recHits.front().det()->surface());
456  if (!propagated.isValid()) continue;
458  recHits.front().rawId());
459  }
460  else state = trajectoryStateTransform::persistentState( initState.first,
461  initState.second->geographicalId().rawId());
462  LogDebug("CkfPattern") << "pushing a TrackCandidate.";
463  output->emplace_back(recHits,it->seed(),state,it->seedRef(),it->nLoops());
464  }
465  }//output trackcandidates
466 
468  es.get<TrackerDigiGeometryRecord>().get(tracker);
469  LogTrace("CkfPattern|TrackingRegressionTest") << "========== CkfTrackCandidateMaker Info =========="
470  << "number of Seed: " << collseed->size()<<endl
471  <<PrintoutHelper::regressionTest(*tracker,unsmoothedResult);
472 
473  assert(viTotHits>=0); // just to use it...
474  // std::cout << "VICkfPattern result " << output->size() << " " << viTotHits << std::endl;
475 
476  if (theTrajectoryOutput){ outputT->swap(unsmoothedResult);}
477 
478  }// end of ((*collseed).size()>0)
479 
480  // method for debugging
482 
483  // Step G: write output to file
484  if (theTrackCandidateOutput){ e.put(output);}
485  if (theTrajectoryOutput){e.put(outputT);}
486  }
487 
488 }
489 
#define LogDebug(id)
T getParameter(std::string const &) const
int foundHits() const
Definition: Trajectory.h:234
int i
Definition: DBlmapReader.cc:9
static std::string dumpCandidates(collection &candidates)
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:186
static boost::mutex mutex
Definition: LHEProxy.cc:11
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:457
edm::EDGetTokenT< StripClusterMask > maskStrips_
assert(m_qm.get())
std::vector< TrackCandidate > TrackCandidateCollection
std::unique_ptr< TransientInitialStateEstimator > theInitialState
size_type size() const
Definition: OwnVector.h:254
void setNLoops(signed char value)
Definition: Trajectory.h:332
PTrajectoryStateOnDet persistentState(const TrajectoryStateOnSurface &ts, unsigned int detid)
bool exists(std::string const &parameterName) const
checks if a parameter exists
virtual void printHitsDebugger(edm::Event &e)
edm::ESHandle< GeometricSearchTracker > theGeomSearchTracker
PropagationDirection
virtual void done()=0
Tells the cleaner that the seeds are finished, and so it can clear any cache it has.
void reserve(unsigned int n)
Definition: Trajectory.h:155
int ii
Definition: cuy.py:588
const Plane & surface() const
The nominal surface of the GeomDet.
Definition: GeomDet.h:40
virtual void add(const Trajectory *traj)=0
Informs the cleaner that a new trajectory has been made, in case the cleaner keeps a local collection...
virtual bool good(const TrajectorySeed *seed)=0
Returns true if the seed is not overlapping with another trajectory.
static std::string regressionTest(const TrackerGeometry &tracker, std::vector< Trajectory > &unsmoothedResult)
void push_back(D *&d)
Definition: OwnVector.h:280
edm::EDGetTokenT< PixelClusterMask > maskPixels_
std::vector< TrajectoryMeasurement > DataContainer
Definition: Trajectory.h:42
bool isNotFinite(T x)
Definition: isFinite.h:10
const TrajectoryCleaner * theTrajectoryCleaner
const NavigationSchool * theNavigationSchool
OrphanHandle< PROD > put(std::auto_ptr< PROD > product)
Put a new product.
Definition: Event.h:115
const GeomDet * det() const
virtual void produceBase(edm::Event &e, const edm::EventSetup &es)
std::unique_ptr< BaseCkfTrajectoryBuilder > theTrajectoryBuilder
virtual void clean(TrajectoryContainer &) const
edm::EDGetTokenT< MeasurementTrackerEvent > theMTELabel
int j
Definition: DBlmapReader.cc:9
#define LogTrace(id)
edm::EDGetTokenT< edm::View< TrajectorySeed > > theSeedLabel
tuple conf
Definition: dbtoconf.py:185
bool isValid() const
Definition: Trajectory.h:269
void pop()
Definition: Trajectory.cc:12
const T & get() const
Definition: EventSetup.h:55
T const * product() const
Definition: ESHandle.h:86
void setSeedRef(const edm::RefToBase< TrajectorySeed > &seedRef)
Definition: Trajectory.h:308
void setEventSetup(const edm::EventSetup &es)
Initialize EventSetup objects at each event.
virtual void beginRunBase(edm::Run const &, edm::EventSetup const &es)
char data[epos_bytes_allocation]
Definition: EPOS_Wrapper.h:82
volatile std::atomic< bool > shutdown_flag false
void push(const TrajectoryMeasurement &tm)
Definition: Trajectory.cc:30
virtual void init(const std::vector< Trajectory > *vect)=0
Provides the cleaner a pointer to the vector where trajectories are stored, in case it does not want ...
reference front()
Definition: OwnVector.h:355
id_type rawId() const
T get(const Candidate &c)
Definition: component.h:55
Definition: Run.h:41
edm::ESHandle< MagneticField > theMagField