CMS 3D CMS Logo

CkfTrajectoryBuilder.cc
Go to the documentation of this file.
2 
4 
6 
10 
17 
18 
21 
23 
27 
28 using namespace std;
29 
32  BaseCkfTrajectoryBuilder::createTrajectoryFilter(conf.getParameter<edm::ParameterSet>("trajectoryFilter"), iC))
33 {}
34 
36  BaseCkfTrajectoryBuilder(conf, filter)
37 {
38  theMaxCand = conf.getParameter<int>("maxCand");
39  theLostHitPenalty = conf.getParameter<double>("lostHitPenalty");
40  theIntermediateCleaning = conf.getParameter<bool>("intermediateCleaning");
41  theAlwaysUseInvalidHits = conf.getParameter<bool>("alwaysUseInvalidHits");
42  /*
43  theSharedSeedCheck = conf.getParameter<bool>("SharedSeedCheck");
44  std::stringstream ss;
45  ss<<"CkfTrajectoryBuilder_"<<conf.getParameter<std::string>("ComponentName")<<"_"<<this;
46  theUniqueName = ss.str();
47  LogDebug("CkfPattern")<<"my unique name is: "<<theUniqueName;
48  */
49 }
50 
51 /*
52  void CkfTrajectoryBuilder::setEvent(const edm::Event& event) const
53  {
54  theMeasurementTracker->update(event);
55  }
56 */
57 
59 }
60 
63 {
65  result.reserve(5);
66  trajectories(seed, result);
67  return result;
68 }
69 
70 /*
71  void CkfTrajectoryBuilder::rememberSeedAndTrajectories(const TrajectorySeed& seed,
72  CkfTrajectoryBuilder::TrajectoryContainer &result) const
73  {
74 
75  //result ----> theCachedTrajectories
76  //every first iteration on event. forget about everything that happened before
77  if (edm::Service<UpdaterService>()->checkOnce(theUniqueName))
78  theCachedTrajectories.clear();
79 
80  if (seed.nHits()==0) return;
81 
82  //then remember those trajectories
83  for (TrajectoryContainer::iterator traj=result.begin();
84  traj!=result.end(); ++traj) {
85  theCachedTrajectories.insert(std::make_pair(seed.recHits().first->geographicalId(),*traj));
86  }
87  }
88 
89  bool CkfTrajectoryBuilder::sharedSeed(const TrajectorySeed& s1,const TrajectorySeed& s2) const{
90  //quit right away on nH=0
91  if (s1.nHits()==0 || s2.nHits()==0) return false;
92  //quit right away if not the same number of hits
93  if (s1.nHits()!=s2.nHits()) return false;
94  TrajectorySeed::range r1=s1.recHits();
95  TrajectorySeed::range r2=s2.recHits();
96  TrajectorySeed::const_iterator i1,i2;
97  TrajectorySeed::const_iterator & i1_e=r1.second,&i2_e=r2.second;
98  TrajectorySeed::const_iterator & i1_b=r1.first,&i2_b=r2.first;
99  //quit right away if first detId does not match. front exist because of ==0 ->quit test
100  if(i1_b->geographicalId() != i2_b->geographicalId()) return false;
101  //then check hit by hit if they are the same
102  for (i1=i1_b,i2=i2_b;i1!=i1_e,i2!=i2_e;++i1,++i2){
103  if (!i1->sharesInput(&(*i2),TrackingRecHit::all)) return false;
104  }
105  return true;
106  }
107  bool CkfTrajectoryBuilder::seedAlreadyUsed(const TrajectorySeed& seed,
108  CkfTrajectoryBuilder::TempTrajectoryContainer &candidates) const
109  {
110  //theCachedTrajectories ---> candidates
111  if (seed.nHits()==0) return false;
112  bool answer=false;
113  pair<SharedTrajectory::const_iterator, SharedTrajectory::const_iterator> range =
114  theCachedTrajectories.equal_range(seed.recHits().first->geographicalId());
115  SharedTrajectory::const_iterator trajP;
116  for (trajP = range.first; trajP!=range.second;++trajP){
117  //check whether seeds are identical
118  if (sharedSeed(trajP->second.seed(),seed)){
119  candidates.push_back(trajP->second);
120  answer=true;
121  }//already existing trajectory shares the seed.
122  }//loop already made trajectories
123 
124  return answer;
125  }
126 */
127 
128 void
130 {
131  // analyseSeed( seed);
132  /*
133  if (theSharedSeedCheck){
134  TempTrajectoryContainer candidates;
135  if (seedAlreadyUsed(seed,candidates))
136  {
137  //start with those candidates already made before
138  limitedCandidates(candidates,result);
139  //and quit
140  return;
141  }
142  }
143  */
144 
145  unsigned int tmp;
146  buildTrajectories(seed, result, tmp, nullptr);
147 }
148 
151  unsigned int& nCandPerSeed,
152  const TrajectoryFilter*) const {
153  if (theMeasurementTracker == nullptr) {
154  throw cms::Exception("LogicError") << "Asking to create trajectories to an un-initialized CkfTrajectoryBuilder.\nYou have to call clone(const MeasurementTrackerEvent *data) and then call trajectories on it instead.\n";
155  }
156 
157  TempTrajectory && startingTraj = createStartingTrajectory( seed );
158 
161  nCandPerSeed = limitedCandidates(seed, startingTraj, result);
162 
163  return startingTraj;
164 
165  /*
166  //and remember what you just did
167  if (theSharedSeedCheck) rememberSeedAndTrajectories(seed,result);
168  */
169 
170  // analyseResult(result);
171 }
172 
173 unsigned int CkfTrajectoryBuilder::
176 {
178  candidates.push_back( startingTraj);
179  boost::shared_ptr<const TrajectorySeed> sharedSeed(new TrajectorySeed(seed));
180  return limitedCandidates(sharedSeed, candidates,result);
181 }
182 
183 unsigned int CkfTrajectoryBuilder::
184 limitedCandidates(const boost::shared_ptr<const TrajectorySeed> & sharedSeed, TempTrajectoryContainer &candidates,
186 {
187  unsigned int nIter=1;
188  unsigned int nCands=0; // ignore startingTraj
189  unsigned int prevNewCandSize=0;
190  TempTrajectoryContainer newCand; // = TrajectoryContainer();
191  newCand.reserve(2*theMaxCand);
192 
193 
194  auto trajCandLess = [&](TempTrajectory const & a, TempTrajectory const & b) {
195  return (a.chiSquared() + a.lostHits()*theLostHitPenalty) <
196  (b.chiSquared() + b.lostHits()*theLostHitPenalty);
197  };
198 
199 
200  while ( !candidates.empty()) {
201 
202  newCand.clear();
203  for (auto traj=candidates.begin(); traj!=candidates.end(); traj++) {
204  std::vector<TM> meas;
205  findCompatibleMeasurements(*sharedSeed, *traj, meas);
206 
207  // --- method for debugging
208  if(!analyzeMeasurementsDebugger(*traj,meas,
210  forwardPropagator(*sharedSeed),theEstimator,
211  theTTRHBuilder)) return nCands;
212  // ---
213 
214  if ( meas.empty()) {
215  addToResult(sharedSeed, *traj, result);
216  }
217  else {
218  std::vector<TM>::const_iterator last;
219  if ( theAlwaysUseInvalidHits) last = meas.end();
220  else {
221  if (meas.front().recHit()->isValid()) {
222  last = find_if( meas.begin(), meas.end(), RecHitIsInvalid());
223  }
224  else last = meas.end();
225  }
226 
227  for(auto itm = meas.begin(); itm != last; itm++) {
228  TempTrajectory newTraj = *traj;
229  updateTrajectory( newTraj, std::move(*itm));
230 
231  if ( toBeContinued(newTraj)) {
232  newCand.push_back(std::move(newTraj)); std::push_heap(newCand.begin(),newCand.end(),trajCandLess);
233  }
234  else {
235  addToResult(sharedSeed, newTraj, result);
237  }
238  }
239  }
240 
241  // account only new candidates, i.e.
242  // - 1 candidate -> 1 candidate, don't increase count
243  // - 1 candidate -> 2 candidates, increase count by 1
244  nCands += newCand.size() - prevNewCandSize;
245  prevNewCandSize = newCand.size();
246 
247  /*
248  auto trajVal = [&](TempTrajectory const & a) {
249  return a.chiSquared() + a.lostHits()*theLostHitPenalty;
250  };
251 
252  // safe (stable?) logig: always sort, kill exceeding only if worse than last to keep
253  // if ((int)newCand.size() > theMaxCand) std::cout << "TrajVal " << theMaxCand << ' ' << newCand.size() << ' ' << trajVal(newCand.front());
254  int toCut = int(newCand.size()) - int(theMaxCand);
255  if (toCut>0) {
256  // move largest "toCut" to the end
257  for (int i=0; i<toCut; ++i)
258  std::pop_heap(newCand.begin(),newCand.end()-i,trajCandLess);
259  auto fval = trajVal(newCand.front());
260  // remove till equal to highest to keep
261  for (int i=0; i<toCut; ++i) {
262  if (fval==trajVal(newCand.back())) break;
263  newCand.pop_back();
264  }
265  //assert((int)newCand.size() >= theMaxCand);
266  //std::cout << "; " << newCand.size() << ' ' << trajVal(newCand.front()) << " " << trajVal(newCand.back());
267 
268  // std::make_heap(newCand.begin(),newCand.end(),trajCandLess);
269  // push_heap again the one left
270  for (auto iter = newCand.begin()+theMaxCand+1; iter<=newCand.end(); ++iter )
271  std::push_heap(newCand.begin(),iter,trajCandLess);
272 
273  // std::cout << "; " << newCand.size() << ' ' << trajVal(newCand.front()) << " " << trajVal(newCand.back()) << std::endl;
274  }
275 
276  */
277 
278 
279  // intermedeate login: always sort, kill all exceeding
280  while ((int)newCand.size() > theMaxCand) {
281  std::pop_heap(newCand.begin(),newCand.end(),trajCandLess);
282  // if ((int)newCand.size() == theMaxCand+1) std::cout << " " << trajVal(newCand.front()) << " " << trajVal(newCand.back()) << std::endl;
283  newCand.pop_back();
284  }
285 
286  /*
287  // original logic: sort only if > theMaxCand, kill all exceeding
288  if ((int)newCand.size() > theMaxCand) {
289  std::sort( newCand.begin(), newCand.end(), TrajCandLess<TempTrajectory>(theLostHitPenalty));
290  // std::partial_sort( newCand.begin(), newCand.begin()+theMaxCand, newCand.end(), TrajCandLess<TempTrajectory>(theLostHitPenalty));
291  std::cout << "TrajVal " << theMaxCand << ' ' << newCand.size() << ' '
292  << trajVal(newCand.back()) << ' ' << trajVal(newCand[theMaxCand-1]) << ' ' << trajVal(newCand[theMaxCand]) << std::endl;
293  newCand.resize(theMaxCand);
294  }
295  */
296 
297  } // end loop on candidates
298 
299  std::sort_heap(newCand.begin(),newCand.end(),trajCandLess);
301 
302  candidates.swap(newCand);
303 
304  LogDebug("CkfPattern") <<result.size()<<" candidates after "<<nIter++<<" CKF iteration: \n"
306  <<"\n "<<candidates.size()<<" running candidates are: \n"
307  <<PrintoutHelper::dumpCandidates(candidates);
308 
309  }
310  return nCands;
311 }
312 
313 
314 
316  TM && tm) const
317 {
318  auto && predictedState = tm.predictedState();
319  auto && hit = tm.recHit();
320  if ( hit->isValid()) {
321  auto && upState = theUpdator->update( predictedState, *hit);
322  traj.emplace( std::move(predictedState), std::move(upState),
323  std::move(hit), tm.estimate(), tm.layer());
324  }
325  else {
326  traj.emplace( std::move(predictedState), std::move(hit), 0, tm.layer());
327  }
328 }
329 
330 
331 void
333  const TempTrajectory& traj,
334  std::vector<TrajectoryMeasurement> & result) const
335 {
336  int invalidHits = 0;
337  //Use findStateAndLayers which handles the hitless seed use case
338  std::pair<TSOS,std::vector<const DetLayer*> > && stateAndLayers = findStateAndLayers(seed,traj);
339  if (stateAndLayers.second.empty()) return;
340 
341  auto layerBegin = stateAndLayers.second.begin();
342  auto layerEnd = stateAndLayers.second.end();
343  LogDebug("CkfPattern")<<"looping on "<< stateAndLayers.second.size()<<" layers.";
344  const Propagator *fwdPropagator = forwardPropagator(seed);
345  for (auto il = layerBegin; il != layerEnd; il++) {
346 
347  LogDebug("CkfPattern")<<"looping on a layer in findCompatibleMeasurements.\n last layer: "<<traj.lastLayer()<<" current layer: "<<(*il);
348 
349  TSOS stateToUse = stateAndLayers.first;
350  //Added protection before asking for the lastLayer on the trajectory
351  if UNLIKELY (!traj.empty() && (*il)==traj.lastLayer()) {
352  LogDebug("CkfPattern")<<" self propagating in findCompatibleMeasurements.\n from: \n"<<stateToUse;
353  //self navigation case
354  // go to a middle point first
356  GlobalPoint center(0,0,0);
357  stateToUse = middle.extrapolate(stateToUse, center, *fwdPropagator);
358 
359  if (!stateToUse.isValid()) continue;
360  LogDebug("CkfPattern")<<"to: "<<stateToUse;
361  }
362 
363  LayerMeasurements layerMeasurements(theMeasurementTracker->measurementTracker(), *theMeasurementTracker);
364  std::vector<TrajectoryMeasurement> && tmp = layerMeasurements.measurements((**il),stateToUse, *fwdPropagator, *theEstimator);
365 
366  if ( !tmp.empty()) {
367  if ( result.empty()) result.swap(tmp);
368  else {
369  // keep one dummy TM at the end, skip the others
370  result.insert( result.end()-invalidHits,
371  std::make_move_iterator(tmp.begin()), std::make_move_iterator(tmp.end()));
372  }
373  invalidHits++;
374  }
375  }
376 
377  // sort the final result, keep dummy measurements at the end
378  if ( result.size() > 1) {
379  std::sort( result.begin(), result.end()-invalidHits, TrajMeasLessEstim());
380  }
381 
382  LogDebug("CkfPattern")<<"starting from:\n"
383  <<"x: "<<stateAndLayers.first.globalPosition()<<"\n"
384  <<"p: "<<stateAndLayers.first.globalMomentum()<<"\n"
386 
387 #ifdef DEBUG_INVALID
388  bool afterInvalid = false;
389  for (vector<TM>::const_iterator i=result.begin();
390  i!=result.end(); i++) {
391  if ( ! i->recHit().isValid()) afterInvalid = true;
392  if (afterInvalid && i->recHit().isValid()) {
393  edm::LogError("CkfPattern") << "CkfTrajectoryBuilder error: valid hit after invalid!" ;
394  }
395  }
396 #endif
397 
398  //analyseMeasurements( result, traj);
399 
400 }
401 
#define LogDebug(id)
T getParameter(std::string const &) const
static std::string dumpCandidates(collection &candidates)
std::vector< Trajectory > TrajectoryContainer
bool empty() const
True if trajectory has no measurements.
static void clean(TempTrajectoryContainer &tracks)
const Propagator * forwardPropagator(const TrajectorySeed &seed) const
TrajectoryContainer trajectories(const TrajectorySeed &seed) const override
trajectories building starting from a seed
CkfTrajectoryBuilder(const edm::ParameterSet &conf, edm::ConsumesCollector &iC)
virtual bool analyzeMeasurementsDebugger(Trajectory &traj, const std::vector< TrajectoryMeasurement > &meas, const MeasurementTrackerEvent *theMeasurementTracker, const Propagator *theForwardPropagator, const Chi2MeasurementEstimatorBase *theEstimator, const TransientTrackingRecHitBuilder *theTTRHBuilder) const
const TrajectoryStateUpdator * theUpdator
static std::string dumpMeasurements(const std::vector< TrajectoryMeasurement > &v)
virtual TrajectoryStateOnSurface update(const TrajectoryStateOnSurface &, const TrackingRecHit &) const =0
const TransientTrackingRecHitBuilder * theTTRHBuilder
void addToResult(boost::shared_ptr< const TrajectorySeed > const &seed, TempTrajectory &traj, TrajectoryContainer &result, bool inOut=false) const
StateAndLayers findStateAndLayers(const TrajectorySeed &seed, const TempTrajectory &traj) const
const MeasurementTrackerEvent * theMeasurementTracker
unsigned int limitedCandidates(const TrajectorySeed &seed, TempTrajectory &startingTraj, TrajectoryContainer &result) const
std::vector< TempTrajectory > TempTrajectoryContainer
float chiSquared() const
Value of the raw Chi2 of the trajectory, not normalised to the N.D.F.
double b
Definition: hdecay.h:120
TrajectoryStateOnSurface extrapolate(const FreeTrajectoryState &fts, const GlobalPoint &vtx) const
extrapolation with default (=geometrical) propagator
std::vector< std::vector< double > > tmp
Definition: MVATrainer.cc:100
void emplace(Args &&...args)
HLT enums.
bool toBeContinued(TempTrajectory &traj, bool inOut=false) const
double a
Definition: hdecay.h:121
TempTrajectory buildTrajectories(const TrajectorySeed &, TrajectoryContainer &ret, unsigned int &nCandPerSeed, const TrajectoryFilter *) const override
virtual void findCompatibleMeasurements(const TrajectorySeed &seed, const TempTrajectory &traj, std::vector< TrajectoryMeasurement > &result) const
void updateTrajectory(TempTrajectory &traj, TM &&tm) const
void setEvent_(const edm::Event &iEvent, const edm::EventSetup &iSetup) override
const DetLayer * lastLayer() const
Redundant method, returns the layer of lastMeasurement() .
int theMaxCand
set Event for the internal MeasurementTracker data member
std::vector< Trajectory > TrajectoryContainer
def move(src, dest)
Definition: eostools.py:510
const Chi2MeasurementEstimatorBase * theEstimator
Definition: event.py:1
TempTrajectory createStartingTrajectory(const TrajectorySeed &seed) const
int lostHits() const
#define UNLIKELY(x)