CMS 3D CMS Logo

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