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 
9 
13 
15 
20 
25 
26 
31 
33 
36 
37 #include<algorithm>
38 #include<functional>
39 
41 
42 using namespace edm;
43 using namespace std;
44 
45 namespace cms{
46  CkfTrackCandidateMakerBase::CkfTrackCandidateMakerBase(edm::ParameterSet const& conf, edm::ConsumesCollector && iC) :
47 
48  conf_(conf),
49  theTrackCandidateOutput(true),
50  theTrajectoryOutput(false),
51  useSplitting(conf.getParameter<bool>("useHitsSplitting")),
52  doSeedingRegionRebuilding(conf.getParameter<bool>("doSeedingRegionRebuilding")),
53  cleanTrajectoryAfterInOut(conf.getParameter<bool>("cleanTrajectoryAfterInOut")),
54  reverseTrajectories(conf.existsAs<bool>("reverseTrajectories") && conf.getParameter<bool>("reverseTrajectories")),
55  theMaxNSeeds(conf.getParameter<unsigned int>("maxNSeeds")),
56  theTrajectoryBuilderName(conf.getParameter<std::string>("TrajectoryBuilder")),
57  theTrajectoryBuilder(0),
58  theTrajectoryCleanerName(conf.getParameter<std::string>("TrajectoryCleaner")),
59  theTrajectoryCleaner(0),
60  theInitialState(0),
61  theNavigationSchoolName(conf.getParameter<std::string>("NavigationSchool")),
62  theNavigationSchool(0),
63  theSeedCleaner(0),
64  maxSeedsBeforeCleaning_(0),
65  theMTELabel(iC.consumes<MeasurementTrackerEvent>(conf.getParameter<edm::InputTag>("MeasurementTrackerEvent"))),
66  skipClusters_(false)
67  {
68  //produces<TrackCandidateCollection>();
69  // old configuration totally descoped.
70  // if (!conf.exists("src"))
71  // theSeedLabel = InputTag(conf_.getParameter<std::string>("SeedProducer"),conf_.getParameter<std::string>("SeedLabel"));
72  // else
74  if ( conf.exists("maxSeedsBeforeCleaning") )
75  maxSeedsBeforeCleaning_=conf.getParameter<unsigned int>("maxSeedsBeforeCleaning");
76 
77  if (conf.existsAs<edm::InputTag>("clustersToSkip")) {
78  skipClusters_ = true;
79  maskPixels_ = iC.consumes<PixelClusterMask>(conf.getParameter<edm::InputTag>("clustersToSkip"));
80  maskStrips_ = iC.consumes<StripClusterMask>(conf.getParameter<edm::InputTag>("clustersToSkip"));
81  maskStripsLazy_ = iC.consumes<StripClusterLazyMask>(conf.getParameter<edm::InputTag>("clustersToSkip"));
82  }
83 
84  std::string cleaner = conf_.getParameter<std::string>("RedundantSeedCleaner");
85  if (cleaner == "SeedCleanerByHitPosition") {
87  } else if (cleaner == "SeedCleanerBySharedInput") {
89  } else if (cleaner == "CachingSeedCleanerByHitPosition") {
91  } else if (cleaner == "CachingSeedCleanerBySharedInput") {
92  int numHitsForSeedCleaner = conf_.existsAs<int>("numHitsForSeedCleaner") ?
93  conf_.getParameter<int>("numHitsForSeedCleaner") : 4;
94  int onlyPixelHits = conf_.existsAs<bool>("onlyPixelHitsForSeedCleaner") ?
95  conf_.getParameter<bool>("onlyPixelHitsForSeedCleaner") : false;
96  theSeedCleaner = new CachingSeedCleanerBySharedInput(numHitsForSeedCleaner,onlyPixelHits);
97  } else if (cleaner == "none") {
98  theSeedCleaner = 0;
99  } else {
100  throw cms::Exception("RedundantSeedCleaner not found", cleaner);
101  }
102 
103 
104  }
105 
106 
107  // Virtual destructor needed.
109  delete theInitialState;
110  if (theSeedCleaner) delete theSeedCleaner;
111  }
112 
114  {
115  /* no op*/
116  }
117 
119 
120  //services
123 
124  if (!theInitialState){
125  // constructor uses the EventSetup, it must be in the setEventSetup were it has a proper value.
126  // get nested parameter set for the TransientInitialStateEstimator
127  ParameterSet tise_params = conf_.getParameter<ParameterSet>("TransientInitialStateEstimatorParameters") ;
128  theInitialState = new TransientInitialStateEstimator( es,tise_params);
129  }
130 
132 
133  edm::ESHandle<TrajectoryCleaner> trajectoryCleanerH;
134  es.get<TrajectoryCleaner::Record>().get(theTrajectoryCleanerName, trajectoryCleanerH);
135  theTrajectoryCleaner= trajectoryCleanerH.product();
136 
137  edm::ESHandle<NavigationSchool> navigationSchoolH;
138  es.get<NavigationSchoolRecord>().get(theNavigationSchoolName, navigationSchoolH);
139  theNavigationSchool = navigationSchoolH.product();
140 
141  // set the TrajectoryBuilder
142  edm::ESHandle<TrajectoryBuilder> theTrajectoryBuilderHandle;
143  es.get<CkfComponentsRecord>().get(theTrajectoryBuilderName,theTrajectoryBuilderHandle);
144  theTrajectoryBuilder = dynamic_cast<const BaseCkfTrajectoryBuilder*>(theTrajectoryBuilderHandle.product());
145  assert(theTrajectoryBuilder);
146  }
147 
148  // Functions that gets called by framework every event
150  {
151  // getting objects from the EventSetup
152  setEventSetup( es );
153 
154  // set the correct navigation
156 
157  // propagator
158  edm::ESHandle<Propagator> thePropagator;
159  es.get<TrackingComponentsRecord>().get("AnyDirectionAnalyticalPropagator",
160  thePropagator);
161 
162  // method for Debugging
164 
165  // Step A: set Event for the TrajectoryBuilder
167  e.getByToken(theMTELabel, data);
168 
169  std::auto_ptr<BaseCkfTrajectoryBuilder> trajectoryBuilder;
170  std::auto_ptr<MeasurementTrackerEvent> dataWithMasks;
171  if (skipClusters_) {
173  e.getByToken(maskPixels_, pixelMask);
174  if (data->isStripRegional()) {
176  e.getByToken(maskStripsLazy_, stripMask);
177  dataWithMasks.reset(new MeasurementTrackerEvent(*data, *stripMask, *pixelMask));
178  } else {
180  e.getByToken(maskStrips_, stripMask);
181  dataWithMasks.reset(new MeasurementTrackerEvent(*data, *stripMask, *pixelMask));
182  }
183  //std::cout << "Trajectory builder " << conf_.getParameter<std::string>("@module_label") << " created with masks, " << (!data->isStripRegional() ? "offline": "onDemand") << std::endl;
184  trajectoryBuilder.reset(theTrajectoryBuilder->clone(&*dataWithMasks));
185  } else {
186  //std::cout << "Trajectory builder " << conf_.getParameter<std::string>("@module_label") << " created without masks, " << (!data->isStripRegional() ? "offline": "onDemand") << std::endl;
187  trajectoryBuilder.reset(theTrajectoryBuilder->clone(&*data));
188  }
189 
190  // Step B: Retrieve seeds
191 
193  e.getByToken(theSeedLabel, collseed);
194 
195  // Step C: Create empty output collection
196  std::auto_ptr<TrackCandidateCollection> output(new TrackCandidateCollection);
197  std::auto_ptr<std::vector<Trajectory> > outputT (new std::vector<Trajectory>());
198 
199  if ( (*collseed).size()>theMaxNSeeds ) {
200  LogError("TooManySeeds")<<"Exceeded maximum numeber of seeds! theMaxNSeeds="<<theMaxNSeeds<<" nSeed="<<(*collseed).size();
201  if (theTrackCandidateOutput){ e.put(output);}
202  if (theTrajectoryOutput){e.put(outputT);}
203  return;
204  }
205 
206  // Step D: Invoke the building algorithm
207  if ((*collseed).size()>0){
208 
209  unsigned int lastCleanResult=0;
210  vector<Trajectory> rawResult;
211  rawResult.reserve(collseed->size() * 4);
212 
213  if (theSeedCleaner) theSeedCleaner->init( &rawResult );
214 
215  // method for debugging
217 
218  vector<Trajectory> theTmpTrajectories;
219 
220  // Loop over seeds
221  size_t collseed_size = collseed->size();
222  for (size_t j = 0; j < collseed_size; j++){
223 
224  LogDebug("CkfPattern") << "======== Begin to look for trajectories from seed " << j << " ========"<<endl;
225 
226  // Check if seed hits already used by another track
227  if (theSeedCleaner && !theSeedCleaner->good( &((*collseed)[j])) ) {
228  LogDebug("CkfTrackCandidateMakerBase")<<" Seed cleaning kills seed "<<j;
229  continue;
230  }
231 
232  // Build trajectory from seed outwards
233  theTmpTrajectories.clear();
234  auto const & startTraj = trajectoryBuilder->buildTrajectories( (*collseed)[j], theTmpTrajectories, nullptr );
235 
236 
237  LogDebug("CkfPattern") << "======== In-out trajectory building found " << theTmpTrajectories.size()
238  << " trajectories from seed " << j << " ========"<<endl
239  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
240 
242 
243  // Select the best trajectory from this seed (declare others invalid)
244  theTrajectoryCleaner->clean(theTmpTrajectories);
245 
246  LogDebug("CkfPattern") << "======== In-out trajectory cleaning gave the following valid trajectories from seed "
247  << j << " ========"<<endl
248  << PrintoutHelper::dumpCandidates(theTmpTrajectories);
249  }
250 
251  // Optionally continue building trajectory back through
252  // seed and if possible further inwards.
253 
255  trajectoryBuilder->rebuildTrajectories(startTraj,(*collseed)[j],theTmpTrajectories);
256 
257  LogDebug("CkfPattern") << "======== Out-in trajectory building found " << theTmpTrajectories.size()
258  << " valid/invalid trajectories from seed " << j << " ========"<<endl
259  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
260  }
261 
262 
263  // Select the best trajectory from this seed (after seed region rebuilding, can be more than one)
264  theTrajectoryCleaner->clean(theTmpTrajectories);
265 
266  LogDebug("CkfPattern") << "======== Trajectory cleaning gave the following valid trajectories from seed "
267  << j << " ========"<<endl
268  <<PrintoutHelper::dumpCandidates(theTmpTrajectories);
269 
270  for(vector<Trajectory>::iterator it=theTmpTrajectories.begin();
271  it!=theTmpTrajectories.end(); it++){
272  if( it->isValid() ) {
273  it->setSeedRef(collseed->refAt(j));
274  // Store trajectory
275  rawResult.push_back(*it);
276  // Tell seed cleaner which hits this trajectory used.
277  //TO BE FIXED: this cut should be configurable via cfi file
278  if (theSeedCleaner && it->foundHits()>3) theSeedCleaner->add( & (*it) );
279  //if (theSeedCleaner ) theSeedCleaner->add( & (*it) );
280  }
281  }
282 
283  theTmpTrajectories.clear();
284 
285  LogDebug("CkfPattern") << "rawResult trajectories found so far = " << rawResult.size();
286 
287  if ( maxSeedsBeforeCleaning_ >0 && rawResult.size() > maxSeedsBeforeCleaning_+lastCleanResult) {
288  theTrajectoryCleaner->clean(rawResult);
289  rawResult.erase(std::remove_if(rawResult.begin(),rawResult.end(),
290  std::not1(std::mem_fun_ref(&Trajectory::isValid))),
291  rawResult.end());
292  lastCleanResult=rawResult.size();
293  }
294 
295  }
296  // end of loop over seeds
297 
299 
300  // Step E: Clean the results to avoid duplicate tracks
301  // Rejected ones just flagged as invalid.
302  theTrajectoryCleaner->clean(rawResult);
303 
304  LogDebug("CkfPattern") << "======== Final cleaning of entire event found " << rawResult.size()
305  << " valid/invalid trajectories ======="<<endl
306  <<PrintoutHelper::dumpCandidates(rawResult);
307 
308  LogDebug("CkfPattern") << "removing invalid trajectories.";
309 
310  vector<Trajectory> & unsmoothedResult(rawResult);
311  unsmoothedResult.erase(std::remove_if(unsmoothedResult.begin(),unsmoothedResult.end(),
312  std::not1(std::mem_fun_ref(&Trajectory::isValid))),
313  unsmoothedResult.end());
314 
315  // If requested, reverse the trajectories creating a new 1-hit seed on the last measurement of the track
316  if (reverseTrajectories) {
317  vector<Trajectory> reversed;
318  reversed.reserve(unsmoothedResult.size());
319  for (vector<Trajectory>::const_iterator it = unsmoothedResult.begin(), ed = unsmoothedResult.end(); it != ed; ++it) {
320  // reverse the trajectory only if it has valid hit on the last measurement (should happen)
321  if (it->lastMeasurement().updatedState().isValid() &&
322  it->lastMeasurement().recHit().get() != 0 &&
323  it->lastMeasurement().recHit()->isValid()) {
324  // I can't use reverse in place, because I want to change the seed
325  // 1) reverse propagation direction
326  PropagationDirection direction = it->direction();
327  if (direction == alongMomentum) direction = oppositeToMomentum;
328  else if (direction == oppositeToMomentum) direction = alongMomentum;
329  // 2) make a seed
330  TrajectoryStateOnSurface initState = it->lastMeasurement().updatedState();
331  DetId initDetId = it->lastMeasurement().recHit()->geographicalId();
334  hits.push_back(*it->lastMeasurement().recHit()->hit());
335  boost::shared_ptr<const TrajectorySeed> seed(new TrajectorySeed(state, hits, direction));
336  // 3) make a trajectory
337  Trajectory trajectory(seed, direction);
338  trajectory.setNLoops(it->nLoops());
339  trajectory.setSeedRef(it->seedRef());
340  // 4) push states in reversed order
341  const Trajectory::DataContainer &meas = it->measurements();
342  for (Trajectory::DataContainer::const_reverse_iterator itmeas = meas.rbegin(), endmeas = meas.rend(); itmeas != endmeas; ++itmeas) {
343  trajectory.push(*itmeas);
344  }
345  reversed.push_back(trajectory);
346  } else {
347  edm::LogWarning("CkfPattern_InvalidLastMeasurement") << "Last measurement of the trajectory is invalid, cannot reverse it";
348  reversed.push_back(*it);
349  }
350  }
351  unsmoothedResult.swap(reversed);
352  }
353 
354  // for (vector<Trajectory>::const_iterator itraw = rawResult.begin();
355  // itraw != rawResult.end(); itraw++) {
356  //if((*itraw).isValid()) unsmoothedResult.push_back( *itraw);
357  //}
358 
359  //analyseCleanedTrajectories(unsmoothedResult);
360 
362  // Step F: Convert to TrackCandidates
363  output->reserve(unsmoothedResult.size());
364  for (vector<Trajectory>::const_iterator it = unsmoothedResult.begin();
365  it != unsmoothedResult.end(); ++it) {
366 
368  //it->recHitsV(thits);
369  LogDebug("CkfPattern") << "retrieving "<<(useSplitting?"splitted":"un-splitted")<<" hits from trajectory";
370  it->recHitsV(thits,useSplitting);
372  recHits.reserve(thits.size());
373  LogDebug("CkfPattern") << "cloning hits into new collection.";
374  for (Trajectory::RecHitContainer::const_iterator hitIt = thits.begin();
375  hitIt != thits.end(); ++hitIt) {
376  recHits.push_back( (**hitIt).hit()->clone());
377  }
378 
379  LogDebug("CkfPattern") << "getting initial state.";
380  const bool doBackFit = !doSeedingRegionRebuilding && !reverseTrajectories;
381  std::pair<TrajectoryStateOnSurface, const GeomDet*> initState =
382  theInitialState->innerState( *it , doBackFit);
383 
384  // temporary protection againt invalid initial states
385  if (! initState.first.isValid() || initState.second == 0 || edm::isNotFinite(initState.first.globalPosition().x())) {
386  //cout << "invalid innerState, will not make TrackCandidate" << endl;
387  continue;
388  }
389 
390  PTrajectoryStateOnDet state;
391  if(useSplitting && (initState.second != thits.front()->det()) && thits.front()->det() ){
392  LogDebug("CkfPattern") << "propagating to hit front in case of splitting.";
393  TrajectoryStateOnSurface propagated = thePropagator->propagate(initState.first,thits.front()->det()->surface());
394  if (!propagated.isValid()) continue;
396  thits.front()->det()->geographicalId().rawId());
397  }
398  else state = trajectoryStateTransform::persistentState( initState.first,
399  initState.second->geographicalId().rawId());
400  LogDebug("CkfPattern") << "pushing a TrackCandidate.";
401  output->push_back(TrackCandidate(recHits,it->seed(),state,it->seedRef(),it->nLoops() ) );
402  }
403  }//output trackcandidates
404 
406  es.get<TrackerDigiGeometryRecord>().get(tracker);
407  LogTrace("CkfPattern|TrackingRegressionTest") << "========== CkfTrackCandidateMaker Info =========="
408  << "number of Seed: " << collseed->size()<<endl
409  <<PrintoutHelper::regressionTest(*tracker,unsmoothedResult);
410 
411 
412 
413  if (theTrajectoryOutput){ outputT->swap(unsmoothedResult);}
414 
415  }// end of ((*collseed).size()>0)
416 
417  // method for debugging
419 
420  // Step G: write output to file
421  if (theTrackCandidateOutput){ e.put(output);}
422  if (theTrajectoryOutput){e.put(outputT);}
423  }
424 
425 }
426 
#define LogDebug(id)
T getParameter(std::string const &) const
static std::string dumpCandidates(collection &candidates)
void setEventSetup(const edm::EventSetup &es)
Call this at each event until this object will come from the EventSetup as it should.
bool existsAs(std::string const &parameterName, bool trackiness=true) const
checks if a parameter exists as a given type
Definition: ParameterSet.h:184
const BaseCkfTrajectoryBuilder * theTrajectoryBuilder
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:434
edm::EDGetTokenT< StripClusterMask > maskStrips_
std::vector< TrackCandidate > TrackCandidateCollection
void setNLoops(signed char value)
Definition: Trajectory.h:334
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.
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.
uint32_t rawId() const
get the raw id
Definition: DetId.h:43
static std::string regressionTest(const TrackerGeometry &tracker, std::vector< Trajectory > &unsmoothedResult)
void push_back(D *&d)
Definition: OwnVector.h:273
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:116
virtual void produceBase(edm::Event &e, const edm::EventSetup &es)
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
Definition: DetId.h:18
bool isValid() const
Definition: Trajectory.h:271
ConstRecHitContainer RecHitContainer
Definition: Trajectory.h:44
const T & get() const
Definition: EventSetup.h:55
T const * product() const
Definition: ESHandle.h:62
TransientInitialStateEstimator * theInitialState
void setSeedRef(const edm::RefToBase< TrajectorySeed > &seedRef)
Definition: Trajectory.h:310
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
edm::EDGetTokenT< StripClusterLazyMask > maskStripsLazy_
virtual BaseCkfTrajectoryBuilder * clone(const MeasurementTrackerEvent *data) const =0
volatile std::atomic< bool > shutdown_flag false
void push(const TrajectoryMeasurement &tm)
Definition: Trajectory.cc:35
std::pair< TrajectoryStateOnSurface, const GeomDet * > innerState(const Trajectory &traj, bool doBackFit=true) const
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 ...
void reserve(size_t)
Definition: OwnVector.h:267
Definition: Run.h:41
edm::ESHandle< MagneticField > theMagField