CMS 3D CMS Logo

TrajectorySegmentBuilder.cc
Go to the documentation of this file.
1 #include <algorithm>
2 
4 
6 
20 
23 
24 // #define DBG_TSB
25 // #define STAT_TSB
26 
27 namespace {
28 #ifdef STAT_TSB
29  struct StatCount {
30  long long totGroup;
31  long long totSeg;
32  long long totLockHits;
33  long long totInvCand;
34  long long trunc;
35  void zero() { totGroup = totSeg = totLockHits = totInvCand = trunc = 0; }
36  void incr(long long g, long long s, long long l) {
37  totGroup += g;
38  totSeg += s;
39  totLockHits += l;
40  }
41  void truncated() { ++trunc; }
42  void invalid() { ++totInvCand; }
43  void print() const {
44  std::cout << "TrajectorySegmentBuilder stat\nGroup/Seg/Lock/Inv/Trunc " << totGroup << '/' << totSeg << '/'
45  << totLockHits << '/' << totInvCand << '/' << trunc << std::endl;
46  }
47  StatCount() { zero(); }
48  ~StatCount() { print(); }
49  };
50  StatCount statCount;
51 
52 #else
53  struct StatCount {
54  void incr(long long, long long, long long) {}
55  void truncated() {}
56  void invalid() {}
57  };
58  CMS_THREAD_SAFE StatCount statCount;
59 #endif
60 
61 } // namespace
62 
63 using namespace std;
64 
66  //
67  // create empty trajectory
68  //
69  theLockedHits.clear();
70  TempTrajectory startingTrajectory(theFullPropagator.propagationDirection(), 0);
71  //
72  // get measurement groups
73  //
74  auto&& measGroups =
75  theLayerMeasurements->groupedMeasurements(theLayer, startingState, theFullPropagator, theEstimator);
76 
77 #ifdef DBG_TSB
78  cout << "TSB: number of measurement groups = " << measGroups.size() << endl;
79  // theDbgFlg = measGroups.size()>1;
80  theDbgFlg = true;
81 #else
82  theDbgFlg = false;
83 #endif
84 
85 #ifdef TSB_TRUNCATE
86  // V.I. to me makes things slower...
87 
88  //
89  // check number of combinations
90  //
91  constexpr long long MAXCOMB = 100000000;
92  long long ncomb(1);
93  int ngrp(0);
94  bool truncate(false);
95  for (auto const& gr : measGroups) {
96  ++ngrp;
97  int nhit(0);
98  for (auto const& m : gr.measurements())
99  if LIKELY (m.recHitR().isValid())
100  nhit++;
101 
102  if (nhit > 1)
103  ncomb *= nhit;
104  if UNLIKELY (ncomb > MAXCOMB) {
105  edm::LogInfo("TrajectorySegmentBuilder")
106  << " found " << measGroups.size() << " groups and more than " << static_cast<unsigned int>(MAXCOMB)
107  << " combinations - limiting to " << (ngrp - 1) << " groups";
108  truncate = true;
109 
110  statCount.truncated();
111 
112  break;
113  }
114  }
115  // cout << "Groups / combinations = " << measGroups.size() << " " << ncomb << endl;
116  if UNLIKELY (truncate && ngrp > 0)
117  measGroups.resize(ngrp - 1);
118 
119 #endif
120 
121 #ifdef DBG_TSB
122  if (theDbgFlg) {
123  int ntot(1);
124  for (vector<TMG>::const_iterator ig = measGroups.begin(); ig != measGroups.end(); ++ig) {
125  int ngrp(0);
126  const vector<TM>& measurements = ig->measurements();
127  for (vector<TM>::const_iterator im = measurements.begin(); im != measurements.end(); ++im) {
128  if (im->recHit()->isValid())
129  ngrp++;
130  }
131  cout << " " << ngrp;
132  if (ngrp > 0)
133  ntot *= ngrp;
134  }
135  cout << endl;
136  cout << "TrajectorySegmentBuilder::partialTrajectories:: det ids & hit types / group" << endl;
137  for (vector<TMG>::const_iterator ig = measGroups.begin(); ig != measGroups.end(); ++ig) {
138  const vector<TM>& measurements = ig->measurements();
139  for (vector<TM>::const_iterator im = measurements.begin(); im != measurements.end(); ++im) {
140  if (im != measurements.begin())
141  cout << " / ";
142  if (im->recHit()->det())
143  cout << im->recHit()->det()->geographicalId().rawId() << " " << im->recHit()->getType();
144  else
145  cout << "no det";
146  }
147  cout << endl;
148  }
149 
150  // if ( measGroups.size()>4 ) {
151  cout << typeid(theLayer).name() << endl;
152  cout << startingState.localError().matrix() << endl;
153  // for (vector<TMG>::const_iterator ig=measGroups.begin();
154  // ig!=measGroups.end(); ig++) {
155  // cout << "Nr. of measurements = " << ig->measurements().size() << endl;
156  // const DetGroup& dg = ig->detGroup();
157  // for ( DetGroup::const_iterator id=dg.begin();
158  // id!=dg.end(); id++ ) {
159  // GlobalPoint p(id->det()->position());
160  // GlobalVector v(id->det()->toGlobal(LocalVector(0.,0.,1.)));
161  // cout << p.perp() << " " << p.phi() << " " << p.z() << " ; "
162  // << v.phi() << " " << v.z() << endl;
163  // }
164  // }
165  // }
166  }
167 #endif
168 
169  TempTrajectoryContainer candidates = addGroup(startingTrajectory, measGroups.begin(), measGroups.end());
170 
171  if UNLIKELY (theDbgFlg)
172  cout << "TSB: back with " << candidates.size() << " candidates" << endl;
173 
174  //
175  // add invalid hit - try to get first detector hit by the extrapolation
176  //
177 
178  updateWithInvalidHit(startingTrajectory, measGroups, candidates);
179 
180  if UNLIKELY (theDbgFlg)
181  cout << "TSB: " << candidates.size() << " candidates after invalid hit" << endl;
182 
183  statCount.incr(measGroups.size(), candidates.size(), theLockedHits.size());
184 
185  theLockedHits.clear();
186 
187  return candidates;
188 }
189 
191  auto&& predictedState = tm.predictedState();
192  auto&& hit = tm.recHit();
193 
194  if (hit->isValid()) {
195  auto&& upState = theUpdator.update(predictedState, *hit);
196  traj.emplace(predictedState, std::move(upState), hit, tm.estimate(), tm.layer());
197 
198  // TrajectoryMeasurement tm(traj.lastMeasurement());
199  // if ( tm.updatedState().isValid() ) {
200  // if ( !hit.det().surface()->bounds().inside(tm.updatedState().localPosition(),
201  // tm.updatedState().localError().positionError(),3.f) ) {
202  // cout << "Incompatibility after update for det at " << hit.det().position() << ":" << endl;
203  // cout << tm.predictedState().localPosition() << " "
204  // << tm.predictedState().localError().positionError() << endl;
205  // cout << hit.localPosition() << " " << hit.localPositionError() << endl;
206  // cout << tm.updatedState().localPosition() << " "
207  // << tm.updatedState().localError().positionError() << endl;
208  // }
209  // }
210  } else {
211  traj.emplace(predictedState, hit, 0, tm.layer());
212  }
213 }
214 
216  vector<TMG>::const_iterator begin,
217  vector<TMG>::const_iterator end) {
218  vector<TempTrajectory> ret;
219  if (begin == end) {
220  //std::cout << "TrajectorySegmentBuilder::addGroup" << " traj.empty()=" << traj.empty() << "EMPTY" << std::endl;
221  if UNLIKELY (theDbgFlg)
222  cout << "TSB::addGroup : no groups left" << endl;
223  if (!traj.empty())
224  ret.push_back(traj);
225  return ret;
226  }
227 
228  if UNLIKELY (theDbgFlg)
229  cout << "TSB::addGroup : traj.size() = " << traj.measurements().size() << " first group at "
230  << &(*begin)
231  // << " nr. of candidates = " << candidates.size()
232  << endl;
233 
234  TempTrajectoryContainer updatedTrajectories;
235  updatedTrajectories.reserve(2);
236  if (traj.measurements().empty()) {
237  if (theMaxCand == 1) {
238  auto&& firstMeasurements = unlockedMeasurements(begin->measurements());
239  if (!firstMeasurements.empty())
240  updateCandidatesWithBestHit(traj, std::move(firstMeasurements.front()), updatedTrajectories);
241  } else {
242  updateCandidates(traj, begin->measurements(), updatedTrajectories);
243  }
244  if UNLIKELY (theDbgFlg)
245  cout << "TSB::addGroup : updating with first group - " << updatedTrajectories.size() << " trajectories" << endl;
246  } else {
247  auto&& meas = redoMeasurements(traj, begin->detGroup());
248  if (!meas.empty()) {
249  if (theBestHitOnly) {
250  updateCandidatesWithBestHit(traj, std::move(meas.front()), updatedTrajectories);
251  } else {
252  updateCandidates(traj, meas, updatedTrajectories);
253  }
254  if UNLIKELY (theDbgFlg)
255  cout << "TSB::addGroup : updating" << updatedTrajectories.size() << " trajectories-1" << endl;
256  }
257  }
258  // keep old trajectory
259  //
260  updatedTrajectories.push_back(traj);
261 
262  if (begin + 1 != end) {
263  ret.reserve(4); // a good upper bound
264  for (auto const& ut : updatedTrajectories) {
265  if UNLIKELY (theDbgFlg)
266  cout << "TSB::addGroup : trying to extend candidate at " << &ut << " size " << ut.measurements().size() << endl;
267  vector<TempTrajectory>&& finalTrajectories = addGroup(ut, begin + 1, end);
268  if UNLIKELY (theDbgFlg)
269  cout << "TSB::addGroup : " << finalTrajectories.size() << " finalised candidates before cleaning" << endl;
270  //B.M. to be ported later
271  // V.I. only mark invalidate
272  cleanCandidates(finalTrajectories);
273 
274  if UNLIKELY (theDbgFlg) {
275  int ntf = 0;
276  for (auto const& t : finalTrajectories)
277  if (t.isValid())
278  ++ntf;
279  cout << "TSB::addGroup : got " << ntf << " finalised candidates" << endl;
280  }
281 
282  for (auto& t : finalTrajectories)
283  if (t.isValid())
284  ret.push_back(std::move(t));
285 
286  // ret.insert(ret.end(),make_move_iterator(finalTrajectories.begin()),
287  // make_move_iterator(finalTrajectories.end()));
288  }
289  } else {
290  ret.reserve(updatedTrajectories.size());
291  for (auto& t : updatedTrajectories)
292  if (!t.empty())
293  ret.push_back(std::move(t));
294  }
295 
296  //std::cout << "TrajectorySegmentBuilder::addGroup" <<
297  // " traj.empty()=" << traj.empty() <<
298  // " end-begin=" << (end-begin) <<
299  // " #updated=" << updatedTrajectories.size() <<
300  // " #result=" << ret.size() << std::endl;
301  return ret;
302 }
303 
305  const vector<TM>& measurements,
307  //
308  // generate updated candidates with all valid hits
309  //
310  for (auto im = measurements.begin(); im != measurements.end(); ++im) {
311  if (im->recHit()->isValid()) {
312  candidates.push_back(traj);
313  updateTrajectory(candidates.back(), *im);
314  if (theLockHits)
315  lockMeasurement(*im);
316  }
317  }
318 }
319 
321  TM measurement,
323  // here we arrive with only valid hits and sorted.
324  //so the best is the first!
325 
326  if (theLockHits)
327  lockMeasurement(measurement);
328  candidates.push_back(traj);
329  updateTrajectory(candidates.back(), std::move(measurement));
330 }
331 
332 vector<TrajectoryMeasurement> TrajectorySegmentBuilder::redoMeasurements(const TempTrajectory& traj,
333  const DetGroup& detGroup) const {
334  vector<TM> result;
335  //
336  // loop over all dets
337  //
338  if UNLIKELY (theDbgFlg)
339  cout << "TSB::redoMeasurements : nr. of measurements / group =";
340 
342 
343  for (auto const& det : detGroup) {
344  pair<bool, TrajectoryStateOnSurface> compat = GeomDetCompatibilityChecker().isCompatible(
345  det.det(), traj.lastMeasurement().updatedState(), theGeomPropagator, theEstimator);
346 
347  if UNLIKELY (theDbgFlg && !compat.first)
348  std::cout << " 0";
349 
350  if (!compat.first)
351  continue;
352 
353  MeasurementDetWithData mdet = theLayerMeasurements->idToDet(det.det()->geographicalId());
354  // verify also that first (and only!) not be inactive..
355  if (mdet.measurements(compat.second, theEstimator, tmps) && tmps.hits[0]->isValid())
356  for (std::size_t i = 0; i != tmps.size(); ++i)
357  result.emplace_back(compat.second, std::move(tmps.hits[i]), tmps.distances[i], &theLayer);
358 
359  if UNLIKELY (theDbgFlg)
360  std::cout << " " << tmps.size();
361  tmps.clear();
362  }
363 
364  if UNLIKELY (theDbgFlg)
365  cout << endl;
366 
367  std::sort(result.begin(), result.end(), TrajMeasLessEstim());
368 
369  return result;
370 }
371 
373  const vector<TMG>& groups,
375  //
376  // first try to find an inactive hit with dets crossed by the prediction,
377  // then take any inactive hit
378  //
379  // loop over groups
380  for (int iteration = 0; iteration < 2; iteration++) {
381  for (auto const& gr : groups) {
382  auto const& measurements = gr.measurements();
383  for (auto im = measurements.rbegin(); im != measurements.rend(); ++im) {
384  auto const& hit = im->recHitR();
385  if ((hit.getType() == TrackingRecHit::valid) || (hit.getType() == TrackingRecHit::missing))
386  continue;
387  //
388  // check, if the extrapolation traverses the Det or
389  // if 2nd iteration
390  //
391  if (hit.det()) {
392  auto const& predState = im->predictedState();
393  if (iteration > 0 ||
394  (predState.isValid() && hit.det()->surface().bounds().inside(predState.localPosition()))) {
395  // add the hit
396  candidates.push_back(traj);
397  updateTrajectory(candidates.back(), *im);
398  if UNLIKELY (theDbgFlg)
399  cout << "TrajectorySegmentBuilder::updateWithInvalidHit "
400  << "added inactive hit" << endl;
401  return;
402  }
403  }
404  }
405  }
406  }
407  //
408  // No suitable inactive hit: add a missing one
409  //
410  for (int iteration = 0; iteration < 2; iteration++) {
411  //
412  // loop over groups
413  //
414  for (auto const& gr : groups) {
415  auto const& measurements = gr.measurements();
416  for (auto im = measurements.rbegin(); im != measurements.rend(); ++im) {
417  // only use invalid hits
418  auto const& hit = im->recHitR();
419  if LIKELY (hit.isValid())
420  continue;
421 
422  // check, if the extrapolation traverses the Det
423  auto const& predState = im->predictedState();
424  if (iteration > 0 || (predState.isValid() && hit.surface()->bounds().inside(predState.localPosition()))) {
425  // add invalid hit
426  candidates.push_back(traj);
427  updateTrajectory(candidates.back(), *im);
428  return;
429  }
430  }
431  }
432  if UNLIKELY (theDbgFlg && iteration == 0)
433  cout << "TrajectorySegmentBuilder::updateWithInvalidHit: "
434  << " did not find invalid hit on 1st iteration" << endl;
435  }
436 
437  if UNLIKELY (theDbgFlg)
438  cout << "TrajectorySegmentBuilder::updateWithInvalidHit: "
439  << " did not find invalid hit" << endl;
440 }
441 
442 vector<TrajectoryMeasurement> TrajectorySegmentBuilder::unlockedMeasurements(const vector<TM>& measurements) const {
443  // if ( !theLockHits ) return measurements;
444 
445  vector<TM> result;
446  result.reserve(measurements.size());
447 
448  //RecHitEqualByChannels recHitEqual(false,true);
449 
450  for (auto const& m : measurements) {
451  auto const& testHit = m.recHitR();
452  if UNLIKELY (!testHit.isValid())
453  continue;
454  bool found(false);
455  if LIKELY (theLockHits) {
456  for (auto const& h : theLockedHits) {
457  if (h->hit()->sharesInput(testHit.hit(), TrackingRecHit::all)) {
458  found = true;
459  break;
460  }
461  }
462  }
463  if LIKELY (!found)
464  result.push_back(m);
465  }
466  return result;
467 }
468 
469 void TrajectorySegmentBuilder::lockMeasurement(const TM& measurement) { theLockedHits.push_back(measurement.recHit()); }
470 
471 // ================= B.M. to be ported later ===============================
472 void TrajectorySegmentBuilder::cleanCandidates(vector<TempTrajectory>& candidates) const {
473  //
474  // remove candidates which are subsets of others
475  // assumptions: no invalid hits and no duplicates
476  //
477  if (candidates.size() <= 1)
478  return;
479  //RecHitEqualByChannels recHitEqual(false,true);
480  //
481  const int NC = candidates.size();
482  int index[NC];
483  for (int i = 0; i != NC; ++i)
484  index[i] = i;
485  std::sort(index, index + NC, [&candidates](int i, int j) { return lessByFoundHits(candidates[i], candidates[j]); });
486  // cout << "SortedCandidates.foundHits";
487  // for (auto i1 : index)
488  // cout << " " << candidates[i1].foundHits();
489  // cout << endl;
490  //
491  for (auto i1 = index; i1 != index + NC - 1; ++i1) {
492  // get measurements of candidate to be checked
493  const TempTrajectory::DataContainer& measurements1 = candidates[*i1].measurements();
494  for (auto i2 = i1 + 1; i2 != index + NC; ++i2) {
495  // no duplicates: two candidates of same size are different
496  if (candidates[*i2].foundHits() == candidates[*i1].foundHits())
497  continue;
498  // get measurements of "reference"
499  const TempTrajectory::DataContainer& measurements2 = candidates[*i2].measurements();
500  //
501  // use the fact that TMs are ordered:
502  // start search in trajectory#1 from last hit match found
503  //
504  bool allFound(true);
505  TempTrajectory::DataContainer::const_iterator from2 = measurements2.rbegin(), im2end = measurements2.rend();
506  for (TempTrajectory::DataContainer::const_iterator im1 = measurements1.rbegin(), im1end = measurements1.rend();
507  im1 != im1end;
508  --im1) {
509  // redundant protection - segments should not contain invalid RecHits
510  // assert( im1->recHit()->isValid());
511  bool found(false);
512  for (TempTrajectory::DataContainer::const_iterator im2 = from2; im2 != im2end; --im2) {
513  // redundant protection - segments should not contain invalid RecHits
514  // assert (im2->recHit()->isValid());
515  if (im1->recHitR().hit()->sharesInput(im2->recHitR().hit(), TrackingRecHit::all)) {
516  found = true;
517  from2 = im2;
518  --from2;
519  break;
520  }
521  }
522  if (!found) {
523  allFound = false;
524  break;
525  }
526  }
527  if (allFound) {
528  candidates[*i1].invalidate();
529  statCount.invalid();
530  }
531  }
532  }
533 }
534 
535 //==================================================
void emplace(Args &&... args)
const_iterator rbegin() const
Definition: bqueue.h:197
TrajectoryStateOnSurface const & predictedState() const
const LocalTrajectoryError & localError() const
std::vector< TempTrajectory > TempTrajectoryContainer
bool measurements(const TrajectoryStateOnSurface &stateOnThisDet, const MeasurementEstimator &est, TempMeasurements &result) const
ret
prodAgent to be discontinued
#define LIKELY(x)
Definition: Likely.h:20
TempTrajectoryContainer segments(const TSOS startingState)
new segments within layer
const DataContainer & measurements() const
std::vector< TempTrajectory > addGroup(TempTrajectory const &traj, std::vector< TrajectoryMeasurementGroup >::const_iterator begin, std::vector< TrajectoryMeasurementGroup >::const_iterator end)
The Signals That Services Can Subscribe To This is based on ActivityRegistry and is current per Services can connect to the signals distributed by the ActivityRegistry in order to monitor the activity of the application Each possible callback has some defined which we here list in angle e g
Definition: Activities.doc:4
static std::pair< bool, TrajectoryStateOnSurface > isCompatible(const GeomDet *theDet, const TrajectoryStateOnSurface &ts, const Propagator &prop, const MeasurementEstimator &est)
void updateCandidatesWithBestHit(TempTrajectory const &traj, TM measurements, TempTrajectoryContainer &candidates)
creation of a new candidate from a segment and the best hit out of a collection
void lockMeasurement(const TM &measurement)
mark a hit as used
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
const TrajectoryMeasurement & lastMeasurement() const
#define CMS_THREAD_SAFE
void updateWithInvalidHit(TempTrajectory &traj, const std::vector< TMG > &groups, TempTrajectoryContainer &candidates) const
void updateTrajectory(TempTrajectory &traj, TM tm) const
update of a trajectory with a hit
void cleanCandidates(std::vector< TempTrajectory > &candidates) const
clean a set of candidates
std::vector< TrajectoryMeasurement > redoMeasurements(const TempTrajectory &traj, const DetGroup &detGroup) const
retrieve compatible hits from a DetGroup
Log< level::Info, false > LogInfo
bool lessByFoundHits(const Trajectory &a, const Trajectory &b)
size_type size() const
Definition: bqueue.h:201
bool empty() const
Definition: bqueue.h:202
TrajectoryStateOnSurface const & updatedState() const
const AlgebraicSymMatrix55 & matrix() const
void updateCandidates(TempTrajectory const &traj, const std::vector< TM > &measurements, TempTrajectoryContainer &candidates)
creation of new candidates from a segment and a collection of hits
const_iterator rend() const
Definition: bqueue.h:198
std::vector< TrajectoryMeasurement > unlockedMeasurements(const std::vector< TM > &measurements) const
get list of unused hits
#define UNLIKELY(x)
Definition: Likely.h:21
The Signals That Services Can Subscribe To This is based on ActivityRegistry h
Helper function to determine trigger accepts.
Definition: Activities.doc:4
std::size_t size() const
const DetLayer * layer() const
__shared__ uint32_t ntot
def move(src, dest)
Definition: eostools.py:511
ConstRecHitPointer const & recHit() const
bool empty() const
True if trajectory has no measurements.