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  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  auto theLoop = [&](size_t j) {
220 
221  // to be moved inside a par section
222  vector<Trajectory> theTmpTrajectories;
223 
224 
225  LogDebug("CkfPattern") << "======== Begin to look for trajectories from seed " << j << " ========"<<endl;
226 
227  { Lock lock(theMutex);
228  // Check if seed hits already used by another track
229  if (theSeedCleaner && !theSeedCleaner->good( &((*collseed)[j])) ) {
230  LogDebug("CkfTrackCandidateMakerBase")<<" Seed cleaning kills seed "<<j;
231  return; // from the lambda!
232  }}
233 
234  // Build trajectory from seed outwards
235  theTmpTrajectories.clear();
236  auto const & startTraj = theTrajectoryBuilder->buildTrajectories( (*collseed)[j], theTmpTrajectories, nullptr );
237 
238 
239  LogDebug("CkfPattern") << "======== In-out trajectory building found " << theTmpTrajectories.size()
240  << " trajectories from seed " << j << " ========"<<endl
241  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
242 
244 
245  // Select the best trajectory from this seed (declare others invalid)
246  theTrajectoryCleaner->clean(theTmpTrajectories);
247 
248  LogDebug("CkfPattern") << "======== In-out trajectory cleaning gave the following valid trajectories from seed "
249  << j << " ========"<<endl
250  << PrintoutHelper::dumpCandidates(theTmpTrajectories);
251  }
252 
253  // Optionally continue building trajectory back through
254  // seed and if possible further inwards.
255 
257  theTrajectoryBuilder->rebuildTrajectories(startTraj,(*collseed)[j],theTmpTrajectories);
258 
259  LogDebug("CkfPattern") << "======== Out-in trajectory building found " << theTmpTrajectories.size()
260  << " valid/invalid trajectories from seed " << j << " ========"<<endl
261  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
262  }
263 
264 
265  // Select the best trajectory from this seed (after seed region rebuilding, can be more than one)
266  theTrajectoryCleaner->clean(theTmpTrajectories);
267 
268  LogDebug("CkfPattern") << "======== Trajectory cleaning gave the following valid trajectories from seed "
269  << j << " ========"<<endl
270  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
271 
272  { Lock lock(theMutex);
273  for(vector<Trajectory>::iterator it=theTmpTrajectories.begin();
274  it!=theTmpTrajectories.end(); it++){
275  if( it->isValid() ) {
276  it->setSeedRef(collseed->refAt(j));
277  // Store trajectory
278  rawResult.push_back(std::move(*it));
279  // Tell seed cleaner which hits this trajectory used.
280  //TO BE FIXED: this cut should be configurable via cfi file
281  if (theSeedCleaner && rawResult.back().foundHits()>3) theSeedCleaner->add( &rawResult.back() );
282  //if (theSeedCleaner ) theSeedCleaner->add( & (*it) );
283  }
284  }}
285 
286  theTmpTrajectories.clear();
287 
288  LogDebug("CkfPattern") << "rawResult trajectories found so far = " << rawResult.size();
289 
290  { Lock lock(theMutex);
291  if ( maxSeedsBeforeCleaning_ >0 && rawResult.size() > maxSeedsBeforeCleaning_+lastCleanResult) {
292  theTrajectoryCleaner->clean(rawResult);
293  rawResult.erase(std::remove_if(rawResult.begin()+lastCleanResult,rawResult.end(),
294  std::not1(std::mem_fun_ref(&Trajectory::isValid))),
295  rawResult.end());
296  lastCleanResult=rawResult.size();
297  }
298  }
299 
300  };
301  // end of loop over seeds
302 
303 
304 #ifdef VI_TBB
305  tbb::parallel_for(0UL,collseed_size,1UL,theLoop);
306 #else
307 #ifdef VI_OMP
308 #pragma omp parallel for schedule(dynamic,4)
309 #endif
310  for (size_t j = 0; j < collseed_size; j++){
311  theLoop(j);
312  }
313 #endif
314 
316 
317  // std::cout << "VICkfPattern " << "rawResult trajectories found = " << rawResult.size() << std::endl;
318 
319 
320  // Step E: Clean the results to avoid duplicate tracks
321  // Rejected ones just flagged as invalid.
322  theTrajectoryCleaner->clean(rawResult);
323 
324  LogDebug("CkfPattern") << "======== Final cleaning of entire event found " << rawResult.size()
325  << " valid/invalid trajectories ======="<<endl
326  <<PrintoutHelper::dumpCandidates(rawResult);
327 
328  LogDebug("CkfPattern") << "removing invalid trajectories.";
329 
330  vector<Trajectory> & unsmoothedResult(rawResult);
331  unsmoothedResult.erase(std::remove_if(unsmoothedResult.begin(),unsmoothedResult.end(),
332  std::not1(std::mem_fun_ref(&Trajectory::isValid))),
333  unsmoothedResult.end());
334  unsmoothedResult.shrink_to_fit();
335  // If requested, reverse the trajectories creating a new 1-hit seed on the last measurement of the track
336  if (reverseTrajectories) {
337  for (auto it = unsmoothedResult.begin(), ed = unsmoothedResult.end(); it != ed; ++it) {
338  // reverse the trajectory only if it has valid hit on the last measurement (should happen)
339  if (it->lastMeasurement().updatedState().isValid() &&
340  it->lastMeasurement().recHit().get() != 0 &&
341  it->lastMeasurement().recHit()->isValid()) {
342  // I can't use reverse in place, because I want to change the seed
343  // 1) reverse propagation direction
344  PropagationDirection direction = it->direction();
345  if (direction == alongMomentum) direction = oppositeToMomentum;
346  else if (direction == oppositeToMomentum) direction = alongMomentum;
347  // 2) make a seed
348  TrajectoryStateOnSurface const & initState = it->lastMeasurement().updatedState();
349  auto initId = it->lastMeasurement().recHitR().rawId();
352  hits.push_back(it->lastMeasurement().recHit()->hit()->clone());
353  boost::shared_ptr<const TrajectorySeed> seed(new TrajectorySeed(state, std::move(hits), direction));
354  // 3) make a trajectory
355  Trajectory trajectory(seed, direction);
356  trajectory.setNLoops(it->nLoops());
357  trajectory.setSeedRef(it->seedRef());
358  // 4) push states in reversed order
359  Trajectory::DataContainer &meas = it->measurements();
360  trajectory.reserve(meas.size());
361  for (auto itmeas = meas.rbegin(), endmeas = meas.rend(); itmeas != endmeas; ++itmeas) {
362  trajectory.push(std::move(*itmeas));
363  }
364  // replace
365  (*it)= std::move(trajectory);
366  } else {
367  edm::LogWarning("CkfPattern_InvalidLastMeasurement") << "Last measurement of the trajectory is invalid, cannot reverse it";
368  }
369  }
370  }
371 
372 
373  int viTotHits=0;
374 
376  // Step F: Convert to TrackCandidates
377  output->reserve(unsmoothedResult.size());
378  Traj2TrackHits t2t(theTrajectoryBuilder->hitBuilder(),true);
379 
380  for (vector<Trajectory>::const_iterator it = unsmoothedResult.begin();
381  it != unsmoothedResult.end(); ++it) {
382 
383  LogDebug("CkfPattern") << "copying "<<(useSplitting?"splitted":"un-splitted")<<" hits from trajectory";
385  if(it->direction() != alongMomentum) LogDebug("CkfPattern") << "not along momentum... " << std::endl;
386  t2t(*it,recHits,useSplitting);
387 
388  viTotHits+=recHits.size();
389 
390  LogDebug("CkfPattern") << "getting initial state.";
391  const bool doBackFit = (!doSeedingRegionRebuilding) & (!reverseTrajectories);
392  std::pair<TrajectoryStateOnSurface, const GeomDet*> && initState = theInitialState->innerState( *it , doBackFit);
393 
394  // temporary protection againt invalid initial states
395  if ( !initState.first.isValid() || initState.second == nullptr || edm::isNotFinite(initState.first.globalPosition().x())) {
396  //cout << "invalid innerState, will not make TrackCandidate" << endl;
397  continue;
398  }
399 
400  PTrajectoryStateOnDet state;
401  if(useSplitting && (initState.second != recHits.front().det()) && recHits.front().det() ){
402  LogDebug("CkfPattern") << "propagating to hit front in case of splitting.";
403  TrajectoryStateOnSurface && propagated = thePropagator->propagate(initState.first,recHits.front().det()->surface());
404  if (!propagated.isValid()) continue;
406  recHits.front().rawId());
407  }
408  else state = trajectoryStateTransform::persistentState( initState.first,
409  initState.second->geographicalId().rawId());
410  LogDebug("CkfPattern") << "pushing a TrackCandidate.";
411  output->emplace_back(recHits,it->seed(),state,it->seedRef(),it->nLoops());
412  }
413  }//output trackcandidates
414 
416  es.get<TrackerDigiGeometryRecord>().get(tracker);
417  LogTrace("CkfPattern|TrackingRegressionTest") << "========== CkfTrackCandidateMaker Info =========="
418  << "number of Seed: " << collseed->size()<<endl
419  <<PrintoutHelper::regressionTest(*tracker,unsmoothedResult);
420 
421  assert(viTotHits>=0); // just to use it...
422  // std::cout << "VICkfPattern result " << output->size() << " " << viTotHits << std::endl;
423 
424  if (theTrajectoryOutput){ outputT->swap(unsmoothedResult);}
425 
426  }// end of ((*collseed).size()>0)
427 
428  // method for debugging
430 
431  // Step G: write output to file
432  if (theTrackCandidateOutput){ e.put(output);}
433  if (theTrajectoryOutput){e.put(outputT);}
434  }
435 
436 }
437 
#define LogDebug(id)
T getParameter(std::string const &) const
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:184
static boost::mutex mutex
Definition: LHEProxy.cc:11
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:446
edm::EDGetTokenT< StripClusterMask > maskStrips_
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
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:113
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
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