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