CMS 3D CMS Logo

MkBuilder.cc
Go to the documentation of this file.
1 #include <memory>
2 #include <limits>
3 #include <algorithm>
4 
6 
10 
11 #include "Pool.h"
12 #include "CandCloner.h"
13 #include "FindingFoos.h"
14 #include "MkFitter.h"
15 #include "MkFinder.h"
16 
17 #ifdef MKFIT_STANDALONE
19 #endif
20 
21 //#define DEBUG
22 #include "Debug.h"
23 //#define DEBUG_FINAL_FIT
24 
25 #include "oneapi/tbb/parallel_for.h"
26 #include "oneapi/tbb/parallel_for_each.h"
27 
28 namespace mkfit {
29 
30  //==============================================================================
31  // Execution context -- Pools of helper objects
32  //==============================================================================
33 
35  ExecutionContext() = default;
36  ~ExecutionContext() = default;
37 
41 
42  void populate(int n_thr) {
43  m_cloners.populate(n_thr - m_cloners.size());
44  m_fitters.populate(n_thr - m_fitters.size());
45  m_finders.populate(n_thr - m_finders.size());
46  }
47  };
48 
50 
51 } // end namespace mkfit
52 
53 //------------------------------------------------------------------------------
54 
55 namespace {
56  using namespace mkfit;
57 
58  // Range of indices processed within one iteration of a TBB parallel_for.
59  struct RangeOfSeedIndices {
60  int m_rng_beg, m_rng_end;
61  int m_beg, m_end;
62 
63  RangeOfSeedIndices(int rb, int re) : m_rng_beg(rb), m_rng_end(re) { reset(); }
64 
65  void reset() {
66  m_end = m_rng_beg;
67  next_chunk();
68  }
69 
70  bool valid() const { return m_beg < m_rng_end; }
71 
72  int n_proc() const { return m_end - m_beg; }
73 
74  void next_chunk() {
75  m_beg = m_end;
76  m_end = std::min(m_end + NN, m_rng_end);
77  }
78 
79  RangeOfSeedIndices &operator++() {
80  next_chunk();
81  return *this;
82  }
83  };
84 
85  // Region of seed indices processed in a single TBB parallel for.
86  struct RegionOfSeedIndices {
87  int m_reg_beg, m_reg_end, m_vec_cnt;
88 
89  RegionOfSeedIndices(const std::vector<int> &seedEtaSeparators, int region) {
90  m_reg_beg = (region == 0) ? 0 : seedEtaSeparators[region - 1];
91  m_reg_end = seedEtaSeparators[region];
92  m_vec_cnt = (m_reg_end - m_reg_beg + NN - 1) / NN;
93  }
94 
95  int count() const { return m_reg_end - m_reg_beg; }
96 
97  tbb::blocked_range<int> tbb_blk_rng_std(int thr_hint = -1) const {
98  if (thr_hint < 0)
99  thr_hint = Config::numSeedsPerTask;
100  return tbb::blocked_range<int>(m_reg_beg, m_reg_end, thr_hint);
101  }
102 
103  tbb::blocked_range<int> tbb_blk_rng_vec() const {
104  return tbb::blocked_range<int>(0, m_vec_cnt, std::max(1, Config::numSeedsPerTask / NN));
105  }
106 
107  RangeOfSeedIndices seed_rng(const tbb::blocked_range<int> &i) const {
108  return RangeOfSeedIndices(m_reg_beg + NN * i.begin(), std::min(m_reg_beg + NN * i.end(), m_reg_end));
109  }
110  };
111 
112 #ifdef DEBUG
113  void pre_prop_print(int ilay, MkBase *fir) {
114  const float pt = 1.f / fir->getPar(0, 0, 3);
115  std::cout << "propagate to lay=" << ilay << " start from x=" << fir->getPar(0, 0, 0)
116  << " y=" << fir->getPar(0, 0, 1) << " z=" << fir->getPar(0, 0, 2)
117  << " r=" << getHypot(fir->getPar(0, 0, 0), fir->getPar(0, 0, 1))
118  << " px=" << pt * std::cos(fir->getPar(0, 0, 4)) << " py=" << pt * std::sin(fir->getPar(0, 0, 4))
119  << " pz=" << pt / std::tan(fir->getPar(0, 0, 5)) << " pT=" << pt << std::endl;
120  }
121 
122  void post_prop_print(int ilay, MkBase *fir) {
123  std::cout << "propagate to lay=" << ilay << " arrive at x=" << fir->getPar(0, 1, 0) << " y=" << fir->getPar(0, 1, 1)
124  << " z=" << fir->getPar(0, 1, 2) << " r=" << getHypot(fir->getPar(0, 1, 0), fir->getPar(0, 1, 1))
125  << std::endl;
126  }
127 
128  void print_seed(const Track &seed) {
129  std::cout << "MX - found seed with label=" << seed.label() << " nHits=" << seed.nFoundHits()
130  << " chi2=" << seed.chi2() << " posEta=" << seed.posEta() << " posPhi=" << seed.posPhi()
131  << " posR=" << seed.posR() << " posZ=" << seed.z() << " pT=" << seed.pT() << std::endl;
132  }
133 
134  void print_seed2(const TrackCand &seed) {
135  std::cout << "MX - found seed with nFoundHits=" << seed.nFoundHits() << " chi2=" << seed.chi2() << " x=" << seed.x()
136  << " y=" << seed.y() << " z=" << seed.z() << " px=" << seed.px() << " py=" << seed.py()
137  << " pz=" << seed.pz() << " pT=" << seed.pT() << std::endl;
138  }
139 
140  void print_seeds(const TrackVec &seeds) {
141  std::cout << "found total seeds=" << seeds.size() << std::endl;
142  for (auto &&seed : seeds) {
143  print_seed(seed);
144  }
145  }
146 
147  [[maybe_unused]] void print_seeds(const EventOfCombCandidates &event_of_comb_cands) {
148  for (int iseed = 0; iseed < event_of_comb_cands.size(); iseed++) {
149  print_seed2(event_of_comb_cands[iseed].front());
150  }
151  }
152 #endif
153 
154  bool sortCandByScore(const TrackCand &cand1, const TrackCand &cand2) {
155  return mkfit::sortByScoreTrackCand(cand1, cand2);
156  }
157 
158 } // end unnamed namespace
159 
160 //------------------------------------------------------------------------------
161 // Constructor and destructor
162 //------------------------------------------------------------------------------
163 
164 namespace mkfit {
165 
166  std::unique_ptr<MkBuilder> MkBuilder::make_builder(bool silent) { return std::make_unique<MkBuilder>(silent); }
167 
169 
170  std::pair<int, int> MkBuilder::max_hits_layer(const EventOfHits &eoh) const {
171  int maxN = 0;
172  int maxL = 0;
173  for (int l = 0; l < eoh.nLayers(); ++l) {
174  int lsize = eoh[l].nHits();
175  if (lsize > maxN) {
176  maxN = lsize;
177  maxL = eoh[l].layer_id();
178  }
179  }
180  return {maxN, maxL};
181  }
182 
184  int res = 0;
185  for (int i = 0; i < m_event_of_comb_cands.size(); ++i)
186  res += m_event_of_comb_cands[i].size();
187  return res;
188  }
189 
190  //------------------------------------------------------------------------------
191  // Common functions
192  //------------------------------------------------------------------------------
193 
194  void MkBuilder::begin_event(MkJob *job, Event *ev, const char *build_type) {
196 
197  m_job = job;
198  m_event = ev;
199 
203 
204  for (int i = 0; i < m_job->num_regions(); ++i) {
205  m_seedEtaSeparators[i] = 0;
206  m_seedMinLastLayer[i] = 9999;
207  m_seedMaxLastLayer[i] = 0;
208  }
209 
210  if (!m_silent) {
211  std::cout << "MkBuilder building tracks with '" << build_type << "'"
212  << ", iteration_index=" << job->m_iter_config.m_iteration_index
213  << ", track_algorithm=" << job->m_iter_config.m_track_algorithm << std::endl;
214  }
215  }
216 
218  m_job = nullptr;
219  m_event = nullptr;
220  }
221 
223  TrackVec tmp;
224  m_tracks.swap(tmp);
226  }
227 
228  void MkBuilder::import_seeds(const TrackVec &in_seeds,
229  const bool seeds_sorted,
230  std::function<insert_seed_foo> insert_seed) {
231  // bool debug = true;
232 
233  const int size = in_seeds.size();
234 
236  std::vector<unsigned> ranks;
237  if (!seeds_sorted) {
238  // We don't care about bins in phi, use low N to reduce overall number of bins.
240  axis<float, unsigned short, 8, 8> ax_eta(-3.0, 3.0, 64u);
242  part.m_phi_eta_foo = [&](float phi, float eta) { phi_eta_binnor.register_entry_safe(phi, eta); };
243 
244  phi_eta_binnor.begin_registration(size);
246  phi_eta_binnor.finalize_registration();
247  ranks.swap(phi_eta_binnor.m_ranks);
248  } else {
250  }
251 
252  for (int i = 0; i < size; ++i) {
253  int j = seeds_sorted ? i : ranks[i];
254  int reg = part.m_region[j];
255  ++m_seedEtaSeparators[reg];
256  }
257 
258  // Sum up region counts to contain actual ending indices and prepare insertion cursors.
259  // Fix min/max layers.
260  std::vector<int> seed_cursors(m_job->num_regions());
261  for (int reg = 1; reg < m_job->num_regions(); ++reg) {
262  seed_cursors[reg] = m_seedEtaSeparators[reg - 1];
263  m_seedEtaSeparators[reg] += m_seedEtaSeparators[reg - 1];
264  }
265 
266  // Actually imports seeds, detect last-hit layer range per region.
267  for (int i = 0; i < size; ++i) {
268  int j = seeds_sorted ? i : ranks[i];
269  int reg = part.m_region[j];
270  const Track &seed = in_seeds[j];
271  insert_seed(seed, j, reg, seed_cursors[reg]++);
272 
273  HitOnTrack hot = seed.getLastHitOnTrack();
276  }
277 
278  // Fix min/max layers
279  for (int reg = 0; reg < m_job->num_regions(); ++reg) {
280  if (m_seedMinLastLayer[reg] == 9999)
281  m_seedMinLastLayer[reg] = -1;
282  if (m_seedMaxLastLayer[reg] == 0)
283  m_seedMaxLastLayer[reg] = -1;
284  }
285 
286  // clang-format off
287  dprintf("MkBuilder::import_seeds finished import of %d seeds (last seeding layer min, max):\n"
288  " ec- = %d(%d,%d), t- = %d(%d,%d), brl = %d(%d,%d), t+ = %d(%d,%d), ec+ = %d(%d,%d).\n",
289  size,
295  // dcall(print_seeds(m_event_of_comb_cands));
296  // clang-format on
297  }
298 
299  //------------------------------------------------------------------------------
300 
303  int i = 0, place_pos = 0;
304 
305  dprintf("MkBuilder::filter_comb_cands Entering filter size eoccs.size=%d\n", eoccs.size());
306 
307  std::vector<int> removed_cnts(m_job->num_regions());
308  while (i < eoccs.size()) {
309  if (eoccs.cands_in_backward_rep())
310  eoccs[i].repackCandPostBkwSearch(0);
311  bool passed = filter(eoccs[i].front(), *m_job);
312 
313  if (!passed && attempt_all_cands) {
314  for (int j = 1; j < (int)eoccs[i].size(); ++j) {
315  if (eoccs.cands_in_backward_rep())
316  eoccs[i].repackCandPostBkwSearch(j);
317  if (filter(eoccs[i][j], *m_job)) {
318  eoccs[i][0] = eoccs[i][j]; // overwrite front, no need to std::swap() them
319  passed = true;
320  break;
321  }
322  }
323  }
324  if (passed) {
325  if (place_pos != i)
326  std::swap(eoccs[place_pos], eoccs[i]);
327  ++place_pos;
328  } else {
329  assert(eoccs[i].front().getEtaRegion() < m_job->num_regions());
330  ++removed_cnts[eoccs[i].front().getEtaRegion()];
331  }
332  ++i;
333  }
334 
335  int n_removed = 0;
336  for (int reg = 0; reg < m_job->num_regions(); ++reg) {
337  dprintf("MkBuilder::filter_comb_cands reg=%d: n_rem_was=%d removed_in_r=%d n_rem=%d, es_was=%d es_new=%d\n",
338  reg,
339  n_removed,
340  removed_cnts[reg],
341  n_removed + removed_cnts[reg],
342  m_seedEtaSeparators[reg],
343  m_seedEtaSeparators[reg] - n_removed - removed_cnts[reg]);
344 
345  n_removed += removed_cnts[reg];
346  m_seedEtaSeparators[reg] -= n_removed;
347  }
348 
349  eoccs.resizeAfterFiltering(n_removed);
350 
351  dprintf("MkBuilder::filter_comb_cands n_removed = %d, eoccs.size=%d\n", n_removed, eoccs.size());
352 
353  return n_removed;
354  }
355 
358  int min[5], max[5], gmin = 0, gmax = 0;
359  int i = 0;
360  for (int reg = 0; reg < 5; ++reg) {
361  min[reg] = 9999;
362  max[reg] = 0;
363  for (; i < m_seedEtaSeparators[reg]; i++) {
364  min[reg] = std::min(min[reg], eoccs[i].hotsSize());
365  max[reg] = std::max(max[reg], eoccs[i].hotsSize());
366  }
367  gmin = std::max(gmin, min[reg]);
368  gmax = std::max(gmax, max[reg]);
369  }
370  // clang-format off
371  printf("MkBuilder::find_min_max_hots_size MIN %3d -- [ %3d | %3d | %3d | %3d | %3d ] "
372  "MAX %3d -- [ %3d | %3d | %3d | %3d | %3d ]\n",
373  gmin, min[0], min[1], min[2], min[3], min[4],
374  gmax, max[0], max[1], max[2], max[3], max[4]);
375  // clang-format on
376  }
377 
378  void MkBuilder::select_best_comb_cands(bool clear_m_tracks, bool remove_missing_hits) {
379  if (clear_m_tracks)
380  m_tracks.clear();
381  export_best_comb_cands(m_tracks, remove_missing_hits);
382  }
383 
384  void MkBuilder::export_best_comb_cands(TrackVec &out_vec, bool remove_missing_hits) {
386  out_vec.reserve(out_vec.size() + eoccs.size());
387  for (int i = 0; i < eoccs.size(); i++) {
388  // Take the first candidate, if it exists.
389  if (!eoccs[i].empty()) {
390  const TrackCand &bcand = eoccs[i].front();
391  out_vec.emplace_back(bcand.exportTrack(remove_missing_hits));
392  }
393  }
394  }
395 
397  out_vec.reserve(out_vec.size() + m_tracks.size());
398  for (auto &t : m_tracks) {
399  out_vec.emplace_back(t);
400  }
401  }
402 
403  //------------------------------------------------------------------------------
404  // PrepareSeeds
405  //------------------------------------------------------------------------------
406 
409  int count = 0;
410 
411  for (int i = 0; i < (int)tv.size(); ++i) {
412  bool silly = tv[i].hasSillyValues(Const::nan_n_silly_print_bad_seeds,
414  "Post-cleaning seed silly value check and fix");
415  if (silly) {
416  ++count;
418  // XXXX MT
419  // Could do somethin smarter here: set as Stopped ? check in seed cleaning ?
420  tv.erase(tv.begin() + i);
421  --i;
422  }
423  }
424  }
425 
426  if (count > 0 && !m_silent) {
427  printf("Nan'n'Silly detected %d silly seeds (fix=%d, remove=%d).\n",
428  count,
431  }
432  }
433  }
434 
435  //------------------------------------------------------------------------------
436  // FindTracksBestHit
437  //------------------------------------------------------------------------------
438 
439  void MkBuilder::find_tracks_load_seeds_BH(const TrackVec &in_seeds, const bool seeds_sorted) {
440  // bool debug = true;
441  assert(!in_seeds.empty());
442  m_tracks.resize(in_seeds.size());
443 
444  import_seeds(in_seeds, seeds_sorted, [&](const Track &seed, int seed_idx, int region, int pos) {
445  m_tracks[pos] = seed;
446  m_tracks[pos].setNSeedHits(seed.nTotalHits());
447  m_tracks[pos].setEtaRegion(region);
448  });
449 
450  //dump seeds
451  dcall(print_seeds(m_tracks));
452  }
453 
455  // bool debug = true;
456 
458 
459  tbb::parallel_for_each(m_job->regions_begin(), m_job->regions_end(), [&](int region) {
460  if (iteration_dir == SteeringParams::IT_BkwSearch && !m_job->steering_params(region).has_bksearch_plan()) {
461  printf("No backward search plan for region %d\n", region);
462  return;
463  }
464 
465  // XXXXXX Select endcap / barrel only ...
466  // if (region != TrackerInfo::Reg_Endcap_Neg && region != TrackerInfo::Reg_Endcap_Pos)
467  // if (region != TrackerInfo::Reg_Barrel)
468  // return;
469 
470  const SteeringParams &st_par = m_job->steering_params(region);
471  const TrackerInfo &trk_info = m_job->m_trk_info;
472  const PropagationConfig &prop_config = trk_info.prop_config();
473 
474  const RegionOfSeedIndices rosi(m_seedEtaSeparators, region);
475 
476  tbb::parallel_for(rosi.tbb_blk_rng_vec(), [&](const tbb::blocked_range<int> &blk_rng) {
477  auto mkfndr = g_exe_ctx.m_finders.makeOrGet();
478 
479  RangeOfSeedIndices rng = rosi.seed_rng(blk_rng);
480 
481  std::vector<int> trk_idcs(NN); // track indices in Matriplex
482  std::vector<int> trk_llay(NN); // last layer on input track
483 
484  while (rng.valid()) {
485  dprint(std::endl << "processing track=" << rng.m_beg << ", label=" << cands[rng.m_beg].label());
486 
487  int prev_layer = 9999;
488 
489  for (int i = rng.m_beg, ii = 0; i < rng.m_end; ++i, ++ii) {
490  int llay = cands[i].getLastHitLyr();
491  trk_llay[ii] = llay;
492  prev_layer = std::min(prev_layer, llay);
493 
494  dprintf(" %2d %2d %2d lay=%3d prev_layer=%d\n", ii, i, cands[i].label(), llay, prev_layer);
495  }
496  int curr_tridx = 0;
497 
498  auto layer_plan_it = st_par.make_iterator(iteration_dir);
499 
500  dprintf("Made iterator for %d, first layer=%d ... end layer=%d\n",
501  iteration_dir,
502  layer_plan_it.layer(),
503  layer_plan_it.last_layer());
504 
505  assert(layer_plan_it.is_pickup_only());
506 
507  int curr_layer = layer_plan_it.layer();
508 
509  mkfndr->m_Stopped.setVal(0);
510 
511  // Loop over layers, starting from after the seed.
512  // Consider inverting loop order and make layer outer, need to
513  // trade off hit prefetching with copy-out of candidates.
514  while (++layer_plan_it) {
515  prev_layer = curr_layer;
516  curr_layer = layer_plan_it.layer();
517  mkfndr->setup(prop_config,
520  m_job->m_iter_config.m_layer_configs[curr_layer],
521  st_par,
522  m_job->get_mask_for_layer(curr_layer),
523  m_event,
524  region,
525  m_job->m_in_fwd);
526 
527  const LayerOfHits &layer_of_hits = m_job->m_event_of_hits[curr_layer];
528  const LayerInfo &layer_info = trk_info.layer(curr_layer);
529  const FindingFoos &fnd_foos = FindingFoos::get_finding_foos(layer_info.is_barrel());
530  dprint("at layer " << curr_layer << ", nHits in layer " << layer_of_hits.nHits());
531 
532  // Pick up seeds that become active on current layer -- unless already fully loaded.
533  if (curr_tridx < rng.n_proc()) {
534  int prev_tridx = curr_tridx;
535 
536  for (int i = rng.m_beg, ii = 0; i < rng.m_end; ++i, ++ii) {
537  if (trk_llay[ii] == prev_layer)
538  trk_idcs[curr_tridx++] = i;
539  }
540  if (curr_tridx > prev_tridx) {
541  dprintf("added %d seeds, started with %d\n", curr_tridx - prev_tridx, prev_tridx);
542 
543  mkfndr->inputTracksAndHitIdx(cands, trk_idcs, prev_tridx, curr_tridx, false, prev_tridx);
544  }
545  }
546 
547  if (layer_plan_it.is_pickup_only())
548  continue;
549 
550  dcall(pre_prop_print(curr_layer, mkfndr.get()));
551 
552  mkfndr->clearFailFlag();
553  (mkfndr.get()->*fnd_foos.m_propagate_foo)(
554  layer_info.propagate_to(), curr_tridx, prop_config.finding_inter_layer_pflags);
555 
556  dcall(post_prop_print(curr_layer, mkfndr.get()));
557 
558  mkfndr->selectHitIndices(layer_of_hits, curr_tridx);
559 
560  // Stop low-pT tracks that can not reach the current barrel layer.
561  if (layer_info.is_barrel()) {
562  const float r_min_sqr = layer_info.rin() * layer_info.rin();
563  for (int i = 0; i < curr_tridx; ++i) {
564  if (!mkfndr->m_Stopped[i]) {
565  if (mkfndr->radiusSqr(i, MkBase::iP) < r_min_sqr) {
567  mkfndr->m_Stopped[i] = 1;
568  mkfndr->outputTrackAndHitIdx(cands[rng.m_beg + i], i, false);
569  }
570  mkfndr->m_XWsrResult[i].m_wsr = WSR_Outside;
571  mkfndr->m_XHitSize[i] = 0;
572  }
573  } else { // make sure we don't add extra work for AddBestHit
574  mkfndr->m_XWsrResult[i].m_wsr = WSR_Outside;
575  mkfndr->m_XHitSize[i] = 0;
576  }
577  }
578  }
579 
580  // make candidates with best hit
581  dprint("make new candidates");
582 
583  mkfndr->addBestHit(layer_of_hits, curr_tridx, fnd_foos);
584 
585  // Stop tracks that have reached N_max_holes.
586  for (int i = 0; i < curr_tridx; ++i) {
587  if (!mkfndr->m_Stopped[i] && mkfndr->bestHitLastHoT(i).index == -2) {
588  mkfndr->m_Stopped[i] = 1;
589  mkfndr->outputTrackAndHitIdx(cands[rng.m_beg + i], i, false);
590  }
591  }
592 
593  } // end of layer loop
594 
595  mkfndr->outputNonStoppedTracksAndHitIdx(cands, trk_idcs, 0, curr_tridx, false);
596 
597  ++rng;
598  } // end of loop over candidates in a tbb chunk
599 
600  mkfndr->release();
601  }); // end parallel_for over candidates in a region
602  }); // end of parallel_for_each over regions
603  }
604 
605  //------------------------------------------------------------------------------
606  // FindTracksCombinatorial: Standard TBB and CloneEngine TBB
607  //------------------------------------------------------------------------------
608 
609  void MkBuilder::find_tracks_load_seeds(const TrackVec &in_seeds, const bool seeds_sorted) {
610  // This will sort seeds according to iteration configuration.
611  assert(!in_seeds.empty());
612  m_tracks.clear(); // m_tracks can be used for BkFit.
613 
614  m_event_of_comb_cands.reset((int)in_seeds.size(), m_job->max_max_cands());
615 
616  import_seeds(in_seeds, seeds_sorted, [&](const Track &seed, int seed_idx, int region, int pos) {
618  });
619  }
620 
621  int MkBuilder::find_tracks_unroll_candidates(std::vector<std::pair<int, int>> &seed_cand_vec,
622  int start_seed,
623  int end_seed,
624  int layer,
625  int prev_layer,
626  bool pickup_only,
627  SteeringParams::IterationType_e iteration_dir) {
628  int silly_count = 0;
629 
630  seed_cand_vec.clear();
631 
632  auto &iter_params = (iteration_dir == SteeringParams::IT_BkwSearch) ? m_job->m_iter_config.m_backward_params
634 
635  for (int iseed = start_seed; iseed < end_seed; ++iseed) {
637 
638  if (ccand.state() == CombCandidate::Dormant && ccand.pickupLayer() == prev_layer) {
640  }
641  if (!pickup_only && ccand.state() == CombCandidate::Finding) {
642  bool active = false;
643  for (int ic = 0; ic < (int)ccand.size(); ++ic) {
644  if (ccand[ic].getLastHitIdx() != -2) {
645  // Stop candidates with pT<X GeV
646  if (ccand[ic].pT() < iter_params.minPtCut) {
647  ccand[ic].addHitIdx(-2, layer, 0.0f);
648  continue;
649  }
650  // Check if the candidate is close to it's max_r, pi/2 - 0.2 rad (11.5 deg)
651  if (iteration_dir == SteeringParams::IT_FwdSearch && ccand[ic].pT() < 1.2) {
652  const float dphi = std::abs(ccand[ic].posPhi() - ccand[ic].momPhi());
653  if (ccand[ic].posRsq() > 625.f && dphi > 1.371f && dphi < 4.512f) {
654  // printf("Stopping cand at r=%f, posPhi=%.1f momPhi=%.2f pt=%.2f emomEta=%.2f\n",
655  // ccand[ic].posR(), ccand[ic].posPhi(), ccand[ic].momPhi(), ccand[ic].pT(), ccand[ic].momEta());
656  ccand[ic].addHitIdx(-2, layer, 0.0f);
657  continue;
658  }
659  }
660 
661  active = true;
662  seed_cand_vec.push_back(std::pair<int, int>(iseed, ic));
663  ccand[ic].resetOverlaps();
664 
666  if (ccand[ic].hasSillyValues(Const::nan_n_silly_print_bad_cands_every_layer,
668  "Per layer silly check"))
669  ++silly_count;
670  }
671  }
672  }
673  if (!active) {
675  }
676  }
677  }
678 
679  if (Const::nan_n_silly_check_cands_every_layer && silly_count > 0) {
680  m_nan_n_silly_per_layer_count += silly_count;
681  }
682 
683  return seed_cand_vec.size();
684  }
685 
687  const LayerInfo &layer_info,
688  std::vector<std::vector<TrackCand>> &tmp_cands,
689  const std::vector<std::pair<int, int>> &seed_cand_idx,
690  const int region,
691  const int start_seed,
692  const int itrack,
693  const int end) {
694  // XXXX-1 If I miss a layer, insert the original track into tmp_cands
695  // AND do not do it in FindCandidates as the position can be badly
696  // screwed by then. See comment there, too.
697  // One could also do a pre-check ... so as not to use up a slot.
698 
699  // bool debug = true;
700 
701  for (int ti = itrack; ti < end; ++ti) {
702  TrackCand &cand = m_event_of_comb_cands[seed_cand_idx[ti].first][seed_cand_idx[ti].second];
703  WSR_Result &w = mkfndr->m_XWsrResult[ti - itrack];
704 
705  // Low pT tracks can miss a barrel layer ... and should be stopped
706  dprintf("WSR Check label %d, seed %d, cand %d score %f -> wsr %d, in_gap %d\n",
707  cand.label(),
708  seed_cand_idx[ti].first,
709  seed_cand_idx[ti].second,
710  cand.score(),
711  w.m_wsr,
712  w.m_in_gap);
713 
714  if (w.m_wsr == WSR_Failed) {
715  // Fake outside so it does not get processed in FindTracks BH/Std/CE.
716  // [ Should add handling of WSR_Failed there, perhaps. ]
717  w.m_wsr = WSR_Outside;
718 
719  if (layer_info.is_barrel()) {
720  dprintf("Barrel cand propagation failed, got to r=%f ... layer is %f - %f\n",
721  mkfndr->radius(ti - itrack, MkBase::iP),
722  layer_info.rin(),
723  layer_info.rout());
724  // In barrel region, create a stopped replica. In transition region keep the original copy
725  // as there is still a chance to hit endcaps.
726  tmp_cands[seed_cand_idx[ti].first - start_seed].push_back(cand);
728  dprintf(" creating extra stopped held back candidate\n");
729  tmp_cands[seed_cand_idx[ti].first - start_seed].back().addHitIdx(-2, layer_info.layer_id(), 0);
730  }
731  }
732  // Never happens for endcap / propToZ
733  } else if (w.m_wsr == WSR_Outside) {
734  dprintf(" creating extra held back candidate\n");
735  tmp_cands[seed_cand_idx[ti].first - start_seed].push_back(cand);
736  } else if (w.m_wsr == WSR_Edge) {
737  // Do nothing special here, this case is handled also in MkFinder:findTracks()
738  }
739  }
740  }
741 
742  //------------------------------------------------------------------------------
743  // FindTracksCombinatorial: Standard TBB
744  //------------------------------------------------------------------------------
745 
747  // debug = true;
748 
750 
751  tbb::parallel_for_each(m_job->regions_begin(), m_job->regions_end(), [&](int region) {
752  if (iteration_dir == SteeringParams::IT_BkwSearch && !m_job->steering_params(region).has_bksearch_plan()) {
753  printf("No backward search plan for region %d\n", region);
754  return;
755  }
756 
757  const TrackerInfo &trk_info = m_job->m_trk_info;
758  const SteeringParams &st_par = m_job->steering_params(region);
759  const IterationParams &params = m_job->params();
760  const PropagationConfig &prop_config = trk_info.prop_config();
761 
762  const RegionOfSeedIndices rosi(m_seedEtaSeparators, region);
763 
764  // adaptive seeds per task based on the total estimated amount of work to divide among all threads
765  const int adaptiveSPT = std::clamp(
767  dprint("adaptiveSPT " << adaptiveSPT << " fill " << rosi.count() << "/" << eoccs.size() << " region " << region);
768 
769  // loop over seeds
770  tbb::parallel_for(rosi.tbb_blk_rng_std(adaptiveSPT), [&](const tbb::blocked_range<int> &seeds) {
771  auto mkfndr = g_exe_ctx.m_finders.makeOrGet();
772 
773  const int start_seed = seeds.begin();
774  const int end_seed = seeds.end();
775  const int n_seeds = end_seed - start_seed;
776 
777  std::vector<std::vector<TrackCand>> tmp_cands(n_seeds);
778  for (size_t iseed = 0; iseed < tmp_cands.size(); ++iseed) {
779  tmp_cands[iseed].reserve(2 * params.maxCandsPerSeed); //factor 2 seems reasonable to start with
780  }
781 
782  std::vector<std::pair<int, int>> seed_cand_idx;
783  seed_cand_idx.reserve(n_seeds * params.maxCandsPerSeed);
784 
785  auto layer_plan_it = st_par.make_iterator(iteration_dir);
786 
787  dprintf("Made iterator for %d, first layer=%d ... end layer=%d\n",
788  iteration_dir,
789  layer_plan_it.layer(),
790  layer_plan_it.last_layer());
791 
792  assert(layer_plan_it.is_pickup_only());
793 
794  int curr_layer = layer_plan_it.layer(), prev_layer;
795 
796  dprintf("\nMkBuilder::FindTracksStandard region=%d, seed_pickup_layer=%d, first_layer=%d\n",
797  region,
798  curr_layer,
799  layer_plan_it.next_layer());
800 
801  auto &iter_params = (iteration_dir == SteeringParams::IT_BkwSearch) ? m_job->m_iter_config.m_backward_params
803 
804  // Loop over layers, starting from after the seed.
805  while (++layer_plan_it) {
806  prev_layer = curr_layer;
807  curr_layer = layer_plan_it.layer();
808  mkfndr->setup(prop_config,
810  iter_params,
811  m_job->m_iter_config.m_layer_configs[curr_layer],
812  st_par,
813  m_job->get_mask_for_layer(curr_layer),
814  m_event,
815  region,
816  m_job->m_in_fwd);
817 
818  const LayerOfHits &layer_of_hits = m_job->m_event_of_hits[curr_layer];
819  const LayerInfo &layer_info = trk_info.layer(curr_layer);
820  const FindingFoos &fnd_foos = FindingFoos::get_finding_foos(layer_info.is_barrel());
821 
822  dprintf("\n* Processing layer %d\n", curr_layer);
823  mkfndr->begin_layer(layer_of_hits);
824 
825  int theEndCand = find_tracks_unroll_candidates(seed_cand_idx,
826  start_seed,
827  end_seed,
828  curr_layer,
829  prev_layer,
830  layer_plan_it.is_pickup_only(),
831  iteration_dir);
832 
833  dprintf(" Number of candidates to process: %d, nHits in layer: %d\n", theEndCand, layer_of_hits.nHits());
834 
835  if (layer_plan_it.is_pickup_only() || theEndCand == 0)
836  continue;
837 
838  // vectorized loop
839  for (int itrack = 0; itrack < theEndCand; itrack += NN) {
840  int end = std::min(itrack + NN, theEndCand);
841 
842  dprint("processing track=" << itrack << ", label="
843  << eoccs[seed_cand_idx[itrack].first][seed_cand_idx[itrack].second].label());
844 
845  //fixme find a way to deal only with the candidates needed in this thread
846  mkfndr->inputTracksAndHitIdx(eoccs.refCandidates(), seed_cand_idx, itrack, end, false);
847 
848  //propagate to layer
849  dcall(pre_prop_print(curr_layer, mkfndr.get()));
850 
851  mkfndr->clearFailFlag();
852  (mkfndr.get()->*fnd_foos.m_propagate_foo)(
853  layer_info.propagate_to(), end - itrack, prop_config.finding_inter_layer_pflags);
854 
855  dcall(post_prop_print(curr_layer, mkfndr.get()));
856 
857  dprint("now get hit range");
858  mkfndr->selectHitIndices(layer_of_hits, end - itrack);
859 
861  mkfndr.get(), layer_info, tmp_cands, seed_cand_idx, region, start_seed, itrack, end);
862 
863  dprint("make new candidates");
864  mkfndr->findCandidates(layer_of_hits, tmp_cands, start_seed, end - itrack, fnd_foos);
865 
866  } //end of vectorized loop
867 
868  // sort the input candidates
869  for (int is = 0; is < n_seeds; ++is) {
870  dprint("dump seed n " << is << " with N_input_candidates=" << tmp_cands[is].size());
871 
872  std::sort(tmp_cands[is].begin(), tmp_cands[is].end(), sortCandByScore);
873  }
874 
875  // now fill out the output candidates
876  for (int is = 0; is < n_seeds; ++is) {
877  if (!tmp_cands[is].empty()) {
878  eoccs[start_seed + is].clear();
879 
880  // Put good candidates into eoccs, process -2 candidates.
881  int n_placed = 0;
882  bool first_short = true;
883  for (int ii = 0; ii < (int)tmp_cands[is].size() && n_placed < params.maxCandsPerSeed; ++ii) {
884  TrackCand &tc = tmp_cands[is][ii];
885 
886  // See if we have an overlap hit available, but only if we have a true hit in this layer
887  // and pT is above the pTCutOverlap
888  if (tc.pT() > params.pTCutOverlap && tc.getLastHitLyr() == curr_layer && tc.getLastHitIdx() >= 0) {
889  CombCandidate &ccand = eoccs[start_seed + is];
890 
891  HitMatch *hm = ccand[tc.originIndex()].findOverlap(
892  tc.getLastHitIdx(), layer_of_hits.refHit(tc.getLastHitIdx()).detIDinLayer());
893 
894  if (hm) {
895  tc.addHitIdx(hm->m_hit_idx, curr_layer, hm->m_chi2);
896  tc.incOverlapCount();
897  }
898  }
899 
900  if (tc.getLastHitIdx() != -2) {
901  eoccs[start_seed + is].emplace_back(tc);
902  ++n_placed;
903  } else if (first_short) {
904  first_short = false;
905  if (tc.score() > eoccs[start_seed + is].refBestShortCand().score()) {
906  eoccs[start_seed + is].setBestShortCand(tc);
907  }
908  }
909  }
910 
911  tmp_cands[is].clear();
912  }
913  }
914  mkfndr->end_layer();
915  } // end of layer loop
916  mkfndr->release();
917 
918  // final sorting
919  for (int iseed = start_seed; iseed < end_seed; ++iseed) {
920  eoccs[iseed].mergeCandsAndBestShortOne(m_job->params(), st_par.m_track_scorer, true, true);
921  }
922  }); // end parallel-for over chunk of seeds within region
923  }); // end of parallel-for-each over eta regions
924 
925  // debug = false;
926  }
927 
928  //------------------------------------------------------------------------------
929  // FindTracksCombinatorial: CloneEngine TBB
930  //------------------------------------------------------------------------------
931 
933  // debug = true;
934 
936 
937  tbb::parallel_for_each(m_job->regions_begin(), m_job->regions_end(), [&](int region) {
938  if (iteration_dir == SteeringParams::IT_BkwSearch && !m_job->steering_params(region).has_bksearch_plan()) {
939  printf("No backward search plan for region %d\n", region);
940  return;
941  }
942 
943  const RegionOfSeedIndices rosi(m_seedEtaSeparators, region);
944 
945  // adaptive seeds per task based on the total estimated amount of work to divide among all threads
946  const int adaptiveSPT = std::clamp(
948  dprint("adaptiveSPT " << adaptiveSPT << " fill " << rosi.count() << "/" << eoccs.size() << " region " << region);
949 
950  tbb::parallel_for(rosi.tbb_blk_rng_std(adaptiveSPT), [&](const tbb::blocked_range<int> &seeds) {
951  auto cloner = g_exe_ctx.m_cloners.makeOrGet();
952  auto mkfndr = g_exe_ctx.m_finders.makeOrGet();
953 
954  cloner->setup(m_job->params());
955 
956  // loop over layers
957  find_tracks_in_layers(*cloner, mkfndr.get(), iteration_dir, seeds.begin(), seeds.end(), region);
958 
959  mkfndr->release();
960  cloner->release();
961  });
962  });
963 
964  // debug = false;
965  }
966 
968  MkFinder *mkfndr,
969  SteeringParams::IterationType_e iteration_dir,
970  const int start_seed,
971  const int end_seed,
972  const int region) {
974  const TrackerInfo &trk_info = m_job->m_trk_info;
975  const SteeringParams &st_par = m_job->steering_params(region);
976  const IterationParams &params = m_job->params();
977  const PropagationConfig &prop_config = trk_info.prop_config();
978 
979  const int n_seeds = end_seed - start_seed;
980 
981  std::vector<std::pair<int, int>> seed_cand_idx;
982  std::vector<UpdateIndices> seed_cand_update_idx, seed_cand_overlap_idx;
983  seed_cand_idx.reserve(n_seeds * params.maxCandsPerSeed);
984  seed_cand_update_idx.reserve(n_seeds * params.maxCandsPerSeed);
985  seed_cand_overlap_idx.reserve(n_seeds * params.maxCandsPerSeed);
986 
987  std::vector<std::vector<TrackCand>> extra_cands(n_seeds);
988  for (int ii = 0; ii < n_seeds; ++ii)
989  extra_cands[ii].reserve(params.maxCandsPerSeed);
990 
991  cloner.begin_eta_bin(&eoccs, &seed_cand_update_idx, &seed_cand_overlap_idx, &extra_cands, start_seed, n_seeds);
992 
993  // Loop over layers, starting from after the seed.
994 
995  auto layer_plan_it = st_par.make_iterator(iteration_dir);
996 
997  dprintf("Made iterator for %d, first layer=%d ... end layer=%d\n",
998  iteration_dir,
999  layer_plan_it.layer(),
1000  layer_plan_it.last_layer());
1001 
1002  assert(layer_plan_it.is_pickup_only());
1003 
1004  int curr_layer = layer_plan_it.layer(), prev_layer;
1005 
1006  dprintf(
1007  "\nMkBuilder::find_tracks_in_layers region=%d, seed_pickup_layer=%d, first_layer=%d; start_seed=%d, "
1008  "end_seed=%d\n",
1009  region,
1010  curr_layer,
1011  layer_plan_it.next_layer(),
1012  start_seed,
1013  end_seed);
1014 
1015  auto &iter_params = (iteration_dir == SteeringParams::IT_BkwSearch) ? m_job->m_iter_config.m_backward_params
1017 
1018  // Loop over layers according to plan.
1019  while (++layer_plan_it) {
1020  prev_layer = curr_layer;
1021  curr_layer = layer_plan_it.layer();
1022  mkfndr->setup(prop_config,
1024  iter_params,
1025  m_job->m_iter_config.m_layer_configs[curr_layer],
1026  st_par,
1027  m_job->get_mask_for_layer(curr_layer),
1028  m_event,
1029  region,
1030  m_job->m_in_fwd);
1031 
1032  const bool pickup_only = layer_plan_it.is_pickup_only();
1033 
1034  const LayerInfo &layer_info = trk_info.layer(curr_layer);
1035  const LayerOfHits &layer_of_hits = m_job->m_event_of_hits[curr_layer];
1036  const FindingFoos &fnd_foos = FindingFoos::get_finding_foos(layer_info.is_barrel());
1037 
1038  dprintf("\n\n* Processing layer %d, %s\n\n", curr_layer, pickup_only ? "pickup only" : "full finding");
1039  mkfndr->begin_layer(layer_of_hits);
1040 
1041  const int theEndCand = find_tracks_unroll_candidates(
1042  seed_cand_idx, start_seed, end_seed, curr_layer, prev_layer, pickup_only, iteration_dir);
1043 
1044  dprintf(" Number of candidates to process: %d, nHits in layer: %d\n", theEndCand, layer_of_hits.nHits());
1045 
1046  // Don't bother messing with the clone engine if there are no candidates
1047  // (actually it crashes, so this protection is needed).
1048  // If there are no cands on this iteration, there won't be any later on either,
1049  // by the construction of the seed_cand_idx vector.
1050  // XXXXMT There might be cases in endcap where all tracks will miss the
1051  // next layer, but only relevant if we do geometric selection before.
1052 
1053  if (pickup_only || theEndCand == 0)
1054  continue;
1055 
1056  cloner.begin_layer(curr_layer);
1057 
1058  //vectorized loop
1059  for (int itrack = 0; itrack < theEndCand; itrack += NN) {
1060  const int end = std::min(itrack + NN, theEndCand);
1061 
1062 #ifdef DEBUG
1063  dprintf("\nProcessing track=%d, start_seed=%d, n_seeds=%d, theEndCand=%d, end=%d, nn=%d, end_eq_tec=%d\n",
1064  itrack,
1065  start_seed,
1066  n_seeds,
1067  theEndCand,
1068  end,
1069  end - itrack,
1070  end == theEndCand);
1071  dprintf(" (seed,cand): ");
1072  for (int i = itrack; i < end; ++i)
1073  dprintf("(%d,%d) ", seed_cand_idx[i].first, seed_cand_idx[i].second);
1074  dprintf("\n");
1075 #endif
1076 
1077  mkfndr->inputTracksAndHitIdx(eoccs.refCandidates(), seed_cand_idx, itrack, end, false);
1078 
1079 #ifdef DEBUG
1080  for (int i = itrack; i < end; ++i)
1081  dprintf(" track %d, idx %d is from seed %d\n", i, i - itrack, mkfndr->m_Label(i - itrack, 0, 0));
1082 #endif
1083 
1084  // propagate to current layer
1085  mkfndr->clearFailFlag();
1086  (mkfndr->*fnd_foos.m_propagate_foo)(
1087  layer_info.propagate_to(), end - itrack, prop_config.finding_inter_layer_pflags);
1088 
1089  dprint("now get hit range");
1090 
1091  if (iter_params.useHitSelectionV2)
1092  mkfndr->selectHitIndicesV2(layer_of_hits, end - itrack);
1093  else
1094  mkfndr->selectHitIndices(layer_of_hits, end - itrack);
1095 
1097  mkfndr, layer_info, extra_cands, seed_cand_idx, region, start_seed, itrack, end);
1098 
1099  // copy_out the propagated track params, errors only.
1100  // Do not, keep cands at last valid hit until actual update,
1101  // this requires change to propagation flags used in MkFinder::updateWithLastHit()
1102  // from intra-layer to inter-layer.
1103  // mkfndr->copyOutParErr(eoccs.refCandidates_nc(), end - itrack, true);
1104 
1105  // For prop-to-plane propagate from the last hit, not layer center.
1106  if (Config::usePropToPlane) {
1107  mkfndr->inputTracksAndHitIdx(eoccs.refCandidates(), seed_cand_idx, itrack, end, false);
1108  }
1109 
1110  dprint("make new candidates");
1111  cloner.begin_iteration();
1112 
1113  mkfndr->findCandidatesCloneEngine(layer_of_hits, cloner, start_seed, end - itrack, fnd_foos);
1114 
1115  cloner.end_iteration();
1116  } //end of vectorized loop
1117 
1118  cloner.end_layer();
1119 
1120  // Update loop of best candidates. CandCloner prepares the list of those
1121  // that need update (excluding all those with negative last hit index).
1122  // This is split into two sections - candidates without overlaps and with overlaps.
1123  // On CMS PU-50 the ratio of those is ~ 65 : 35 over all iterations.
1124  // Note, overlap recheck is only enabled for some iterations, e.g. pixelLess.
1125 
1126  const int theEndUpdater = seed_cand_update_idx.size();
1127 
1128  for (int itrack = 0; itrack < theEndUpdater; itrack += NN) {
1129  const int end = std::min(itrack + NN, theEndUpdater);
1130 
1131  mkfndr->inputTracksAndHits(eoccs.refCandidates(), layer_of_hits, seed_cand_update_idx, itrack, end, true);
1132 
1133  mkfndr->updateWithLoadedHit(end - itrack, layer_of_hits, fnd_foos);
1134 
1135  // copy_out the updated track params, errors only (hit-idcs and chi2 already set)
1136  mkfndr->copyOutParErr(eoccs.refCandidates_nc(), end - itrack, false);
1137  }
1138 
1139  const int theEndOverlapper = seed_cand_overlap_idx.size();
1140 
1141  for (int itrack = 0; itrack < theEndOverlapper; itrack += NN) {
1142  const int end = std::min(itrack + NN, theEndOverlapper);
1143 
1144  mkfndr->inputTracksAndHits(eoccs.refCandidates(), layer_of_hits, seed_cand_overlap_idx, itrack, end, true);
1145 
1146  mkfndr->updateWithLoadedHit(end - itrack, layer_of_hits, fnd_foos);
1147 
1148  mkfndr->copyOutParErr(eoccs.refCandidates_nc(), end - itrack, false);
1149 
1150  mkfndr->inputOverlapHits(layer_of_hits, seed_cand_overlap_idx, itrack, end);
1151 
1152  // XXXX Could also be calcChi2AndUpdate(), then copy-out would have to be done
1153  // below, choosing appropriate slot (with or without the overlap hit).
1154  // Probably in a dedicated MkFinder copyOutXyzz function.
1155  mkfndr->chi2OfLoadedHit(end - itrack, fnd_foos);
1156 
1157  for (int ii = itrack; ii < end; ++ii) {
1158  const int fi = ii - itrack;
1159  TrackCand &tc = eoccs[seed_cand_overlap_idx[ii].seed_idx][seed_cand_overlap_idx[ii].cand_idx];
1160 
1161  // XXXX For now we DO NOT use chi2 as this was how things were done before the post-update
1162  // chi2 check. To use it we should retune scoring function (might be even simpler).
1163  auto chi2Ovlp = mkfndr->m_Chi2[fi];
1164  if (mkfndr->m_FailFlag[fi] == 0 && chi2Ovlp >= 0.0f && chi2Ovlp <= 60.0f) {
1165  auto scoreCand =
1166  getScoreCand(st_par.m_track_scorer, tc, true /*penalizeTailMissHits*/, true /*inFindCandidates*/);
1167  tc.addHitIdx(seed_cand_overlap_idx[ii].ovlp_idx, curr_layer, chi2Ovlp);
1168  tc.incOverlapCount();
1169  auto scoreCandOvlp = getScoreCand(st_par.m_track_scorer, tc, true, true);
1170  if (scoreCand > scoreCandOvlp)
1171  tc.popOverlap();
1172  }
1173  }
1174  }
1175 
1176  // Check if cands are sorted, as expected.
1177 #ifdef DEBUG
1178  for (int iseed = start_seed; iseed < end_seed; ++iseed) {
1179  auto &cc = eoccs[iseed];
1180 
1181  for (int i = 0; i < ((int)cc.size()) - 1; ++i) {
1182  if (cc[i].score() < cc[i + 1].score()) {
1183  printf("CloneEngine - NOT SORTED: layer=%d, iseed=%d (size=%lu)-- %d : %f smaller than %d : %f\n",
1184  curr_layer,
1185  iseed,
1186  cc.size(),
1187  i,
1188  cc[i].score(),
1189  i + 1,
1190  cc[i + 1].score());
1191  }
1192  }
1193  }
1194 #endif
1195  mkfndr->end_layer();
1196  } // end of layer loop
1197 
1198  cloner.end_eta_bin();
1199 
1200  // final sorting
1201  for (int iseed = start_seed; iseed < end_seed; ++iseed) {
1202  eoccs[iseed].mergeCandsAndBestShortOne(m_job->params(), st_par.m_track_scorer, true, true);
1203  }
1204  }
1205 
1206  //==============================================================================
1207  // BackwardFit
1208  //==============================================================================
1209 
1210 #ifdef DEBUG_FINAL_FIT
1211  namespace {
1212  // clang-format off
1213  void dprint_tcand(const TrackCand &t, int i) {
1214  dprintf(" %4d with q=%+d chi2=%7.3f pT=%7.3f eta=% 7.3f x=%.3f y=%.3f z=%.3f"
1215  " nHits=%2d label=%4d findable=%d\n",
1216  i, t.charge(), t.chi2(), t.pT(), t.momEta(), t.x(), t.y(), t.z(),
1217  t.nFoundHits(), t.label(), t.isFindable());
1218  }
1219  // clang-format on
1220  } // namespace
1221 #endif
1222 
1224  tbb::parallel_for_each(m_job->regions_begin(), m_job->regions_end(), [&](int region) {
1225  const RegionOfSeedIndices rosi(m_seedEtaSeparators, region);
1226 
1227  tbb::parallel_for(rosi.tbb_blk_rng_vec(), [&](const tbb::blocked_range<int> &blk_rng) {
1228  auto mkfndr = g_exe_ctx.m_finders.makeOrGet();
1229 
1230  RangeOfSeedIndices rng = rosi.seed_rng(blk_rng);
1231 
1232  while (rng.valid()) {
1233  // final backward fit
1234  fit_cands_BH(mkfndr.get(), rng.m_beg, rng.m_end, region);
1235 
1236  ++rng;
1237  }
1238  });
1239  });
1240  }
1241 
1242  void MkBuilder::fit_cands_BH(MkFinder *mkfndr, int start_cand, int end_cand, int region) {
1243  const SteeringParams &st_par = m_job->steering_params(region);
1244  const PropagationConfig &prop_config = m_job->m_trk_info.prop_config();
1245  mkfndr->setup_bkfit(prop_config, st_par, m_event);
1246 #ifdef DEBUG_FINAL_FIT
1248  bool debug = true;
1249 #endif
1250 
1251  for (int icand = start_cand; icand < end_cand; icand += NN) {
1252  const int end = std::min(icand + NN, end_cand);
1253 
1254 #ifdef DEBUG_FINAL_FIT
1255  dprintf("Pre Final fit for %d - %d\n", icand, end);
1256  for (int i = icand; i < end; ++i) {
1257  dprint_tcand(eoccs[i][0], i);
1258  }
1259 #endif
1260 
1261  bool chi_debug = false;
1262 #ifdef DEBUG_BACKWARD_FIT_BH
1263  redo_fit:
1264 #endif
1265 
1266  // input candidate tracks
1267  mkfndr->bkFitInputTracks(m_tracks, icand, end);
1268 
1269  // perform fit back to first layer on track
1270  mkfndr->bkFitFitTracksBH(m_job->m_event_of_hits, st_par, end - icand, chi_debug);
1271 
1272  // now move one last time to PCA
1273  if (prop_config.backward_fit_to_pca) {
1274  mkfndr->bkFitPropTracksToPCA(end - icand);
1275  }
1276 
1277 #ifdef DEBUG_BACKWARD_FIT_BH
1278  // Dump tracks with pT > 2 and chi2/dof > 20. Assumes MPT_SIZE=1.
1279  if (!chi_debug && 1.0f / mkfndr->m_Par[MkBase::iP].At(0, 3, 0) > 2.0f &&
1280  mkfndr->m_Chi2(0, 0, 0) / (eoccs[icand][0].nFoundHits() * 3 - 6) > 20.0f) {
1281  chi_debug = true;
1282 #ifdef MKFIT_STANDALONE
1283  printf("CHIHDR Event %d, Cand %3d, pT %f, chipdof %f ### NOTE x,y,z in cm, sigmas, deltas in mum ### !!!\n",
1284  m_event->evtID(),
1285 #else
1286  printf("CHIHDR Cand %3d, pT %f, chipdof %f ### NOTE x,y,z in cm, sigmas, deltas in mum ### !!!\n",
1287 #endif
1288  icand,
1289  1.0f / mkfndr->m_Par[MkBase::iP].At(0, 3, 0),
1290  mkfndr->m_Chi2(0, 0, 0) / (eoccs[icand][0].nFoundHits() * 3 - 6));
1291  // clang-format off
1292  printf("CHIHDR %3s %10s"
1293  " %10s %10s %10s %10s %11s %11s %11s"
1294  " %10s %10s %10s %10s %11s %11s %11s"
1295  " %10s %10s %10s %10s %10s %11s %11s\n",
1296  "lyr", "chi2",
1297  "x_h", "y_h", "z_h", "r_h", "sx_h", "sy_h", "sz_h",
1298  "x_t", "y_t", "z_t", "r_t", "sx_t", "sy_t", "sz_t",
1299  "pt", "phi", "theta", "phi_h", "phi_t", "d_xy", "d_z");
1300  // clang-format on
1301  goto redo_fit;
1302  }
1303 #endif
1304 
1305  // copy out full set of info at last propagated position
1306  mkfndr->bkFitOutputTracks(m_tracks, icand, end, prop_config.backward_fit_to_pca);
1307 
1308 #ifdef DEBUG_FINAL_FIT
1309  dprintf("Post Final fit for %d - %d\n", icand, end);
1310  for (int i = icand; i < end; ++i) {
1311  dprint_tcand(eoccs[i][0], i);
1312  }
1313 #endif
1314  }
1315  }
1316 
1317  //------------------------------------------------------------------------------
1318 
1321 
1322  tbb::parallel_for_each(m_job->regions_begin(), m_job->regions_end(), [&](int region) {
1323  const RegionOfSeedIndices rosi(m_seedEtaSeparators, region);
1324 
1325  // adaptive seeds per task based on the total estimated amount of work to divide among all threads
1326  const int adaptiveSPT = std::clamp(
1328  dprint("adaptiveSPT " << adaptiveSPT << " fill " << rosi.count() << "/" << eoccs.size() << " region " << region);
1329 
1330  tbb::parallel_for(rosi.tbb_blk_rng_std(adaptiveSPT), [&](const tbb::blocked_range<int> &cands) {
1331  auto mkfndr = g_exe_ctx.m_finders.makeOrGet();
1332 
1333  fit_cands(mkfndr.get(), cands.begin(), cands.end(), region);
1334  });
1335  });
1336  }
1337 
1338  void MkBuilder::fit_cands(MkFinder *mkfndr, int start_cand, int end_cand, int region) {
1340  const SteeringParams &st_par = m_job->steering_params(region);
1341  const PropagationConfig &prop_config = m_job->m_trk_info.prop_config();
1342  mkfndr->setup_bkfit(prop_config, st_par, m_event);
1343 
1344  int step = NN;
1345  for (int icand = start_cand; icand < end_cand; icand += step) {
1346  int end = std::min(icand + NN, end_cand);
1347 
1348  bool chi_debug = false;
1349 
1350 #ifdef DEBUG_FINAL_FIT
1351  bool debug = true;
1352  dprintf("Pre Final fit for %d - %d\n", icand, end);
1353  for (int i = icand; i < end; ++i) {
1354  dprint_tcand(eoccs[i][0], i);
1355  }
1356  chi_debug = true;
1357  static bool first = true;
1358  if (first) {
1359  // ./mkFit ... | perl -ne 'if (/^BKF_OVERLAP/) { s/^BKF_OVERLAP //og; print; }' > bkf_ovlp.rtt
1360  dprintf(
1361  "BKF_OVERLAP event/I:label/I:prod_type/I:is_findable/I:layer/I:is_stereo/I:is_barrel/I:"
1362  "pt/F:pt_cur/F:eta/F:phi/F:phi_cur/F:r_cur/F:z_cur/F:chi2/F:isnan/I:isfin/I:gtzero/I:hit_label/I:"
1363  "sx_t/F:sy_t/F:sz_t/F:d_xy/F:d_z/F\n");
1364  first = false;
1365  }
1366 #endif
1367 
1368  // input tracks
1369  mkfndr->bkFitInputTracks(eoccs, icand, end);
1370 
1371  // fit tracks back to first layer
1372  mkfndr->bkFitFitTracks(m_job->m_event_of_hits, st_par, end - icand, chi_debug);
1373 
1374  // now move one last time to PCA
1375  if (prop_config.backward_fit_to_pca) {
1376  mkfndr->bkFitPropTracksToPCA(end - icand);
1377  }
1378 
1379  mkfndr->bkFitOutputTracks(eoccs, icand, end, prop_config.backward_fit_to_pca);
1380 
1381 #ifdef DEBUG_FINAL_FIT
1382  dprintf("Post Final fit for %d - %d\n", icand, end);
1383  for (int i = icand; i < end; ++i) {
1384  dprint_tcand(eoccs[i][0], i);
1385  }
1386 #endif
1387  }
1388  mkfndr->release();
1389  }
1390 
1391 } // end namespace mkfit
void(MkBase::* m_propagate_foo)(float, const int, const PropagationFlags &)
Definition: FindingFoos.h:27
const IterationConfig & m_iter_config
Definition: MkJob.h:12
float getScoreCand(const track_score_func &score_func, const Track &cand1, bool penalizeTailMissHits=false, bool inFindCandidates=false)
Definition: Track.h:615
void import_seeds(const TrackVec &in_seeds, const bool seeds_sorted, std::function< insert_seed_foo > insert_seed)
Definition: MkBuilder.cc:228
void addHitIdx(int hitIdx, int hitLyr, float chi2)
int find_tracks_unroll_candidates(std::vector< std::pair< int, int >> &seed_cand_vec, int start_seed, int end_seed, int layer, int prev_layer, bool pickup_only, SteeringParams::IterationType_e iteration_dir)
Definition: MkBuilder.cc:621
IterationParams m_params
static void populate()
Definition: MkBuilder.cc:168
std::pair< int, int > max_hits_layer(const EventOfHits &eoh) const
Definition: MkBuilder.cc:170
#define CMS_SA_ALLOW
void export_tracks(TrackVec &out_vec)
Definition: MkBuilder.cc:396
IterationParams m_backward_params
void findTracksBestHit(SteeringParams::IterationType_e iteration_dir=SteeringParams::IT_FwdSearch)
Definition: MkBuilder.cc:454
void chi2OfLoadedHit(int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1784
Track exportTrack(bool remove_missing_hits=false) const
float radius(int itrack, int i) const
Definition: MkBase.h:24
static constexpr int iP
Definition: MkBase.h:19
void inputOverlapHits(const LayerOfHits &layer_of_hits, const std::vector< UpdateIndices > &idxs, int beg, int end)
Definition: MkFinder.cc:181
void resizeAfterFiltering(int n_removed)
float rin() const
Definition: TrackerInfo.h:67
void insertSeed(const Track &seed, int seed_idx, const track_score_func &score_func, int region, int pos)
void begin_eta_bin(EventOfCombCandidates *e_o_ccs, std::vector< UpdateIndices > *update_list, std::vector< UpdateIndices > *overlap_list, std::vector< std::vector< TrackCand >> *extra_cands, int start_seed, int n_seeds)
Definition: CandCloner.cc:25
float pT() const
Definition: Track.h:171
T w() const
void inputTracksAndHitIdx(const std::vector< Track > &tracks, int beg, int end, bool inputProp)
Definition: MkFinder.cc:99
void bkFitInputTracks(TrackVec &cands, int beg, int end)
Definition: MkFinder.cc:1829
for(int i=first, nt=offsets[nh];i< nt;i+=gridDim.x *blockDim.x)
uint32_t cc[maxCellsPerHit]
Definition: gpuFishbone.h:49
constexpr bool nan_n_silly_print_bad_seeds
Definition: Config.h:19
std::atomic< int > m_nan_n_silly_per_layer_count
Definition: MkBuilder.h:137
void find_min_max_hots_size()
Definition: MkBuilder.cc:356
Sin< T >::type sin(const T &t)
Definition: Sin.h:22
const auto regions_begin() const
Definition: MkJob.h:22
MPlexLV m_Par[2]
Definition: MkBase.h:102
MPlexQI m_FailFlag
Definition: MkBase.h:104
constexpr Process operator++(Process p)
Definition: DataFormats.h:68
void setState(SeedState_e ss)
void selectHitIndices(const LayerOfHits &layer_of_hits, const int N_proc, bool fill_binsearch_only=false)
Definition: MkFinder.cc:316
void setup(const PropagationConfig &pc, const IterationConfig &ic, const IterationParams &ip, const IterationLayerConfig &ilc, const SteeringParams &sp, const std::vector< bool > *ihm, const Event *ev, int region, bool infwd)
Definition: MkFinder.cc:30
void findTracksCloneEngine(SteeringParams::IterationType_e iteration_dir=SteeringParams::IT_FwdSearch)
Definition: MkBuilder.cc:932
int nLayers() const
void bkFitPropTracksToPCA(const int N_proc)
Definition: MkFinder.cc:2315
int evtID() const
Definition: Event.h:23
constexpr bool nan_n_silly_check_seeds
Definition: Config.h:18
void inputTracksAndHits(const std::vector< CombCandidate > &tracks, const LayerOfHits &layer_of_hits, const std::vector< UpdateIndices > &idxs, int beg, int end, bool inputProp)
Definition: MkFinder.cc:149
float propagate_to() const
Definition: TrackerInfo.h:73
void begin_event(MkJob *job, Event *ev, const char *build_type)
Definition: MkBuilder.cc:194
void release()
Definition: MkFinder.cc:56
assert(be >=bs)
const auto & params() const
Definition: MkJob.h:27
const EventOfHits & m_event_of_hits
Definition: MkJob.h:13
constexpr bool nan_n_silly_fixup_bad_cands_every_layer
Definition: Config.h:25
void swap(Association< C > &lhs, Association< C > &rhs)
Definition: Association.h:112
Definition: Electron.h:6
void finalize_registration()
Definition: binnor.h:289
track_score_func m_track_scorer
void backwardFitBH()
Definition: MkBuilder.cc:1223
unsigned int nHits() const
Definition: HitStructures.h:68
U second(std::pair< T, U > const &p)
#define dcall(x)
Definition: Debug.h:97
void end_iteration()
Definition: CandCloner.cc:66
char const * label
PropagationFlags finding_inter_layer_pflags
std::vector< C > m_ranks
Definition: binnor.h:211
void find_tracks_load_seeds_BH(const TrackVec &in_seeds, const bool seeds_sorted)
Definition: MkBuilder.cc:439
float score() const
Definition: Track.h:187
void findTracksStandard(SteeringParams::IterationType_e iteration_dir=SteeringParams::IT_FwdSearch)
Definition: MkBuilder.cc:746
std::function< filter_candidates_cf > filter_candidates_func
Definition: FunctionTypes.h:28
iterator make_iterator(IterationType_e type) const
std::vector< IterationLayerConfig > m_layer_configs
void reset(int new_capacity, int max_cands_per_seed, int expected_num_hots=128)
void find_tracks_load_seeds(const TrackVec &in_seeds, const bool seeds_sorted)
Definition: MkBuilder.cc:609
constexpr float PI
Definition: Config.h:7
void release_memory()
Definition: MkBuilder.cc:222
constexpr bool nan_n_silly_remove_bad_seeds
Definition: Config.h:21
TrackVec m_tracks
Definition: MkBuilder.h:127
void register_entry_safe(typename A1::real_t r1, typename A2::real_t r2)
Definition: binnor.h:282
constexpr Matriplex::idx_t NN
Definition: Matrix.h:43
Cos< T >::type cos(const T &t)
Definition: Cos.h:22
void setup_bkfit(const PropagationConfig &pc, const SteeringParams &sp, const Event *ev)
Definition: MkFinder.cc:50
partition_seeds_func m_seed_partitioner
int layer_id() const
Definition: TrackerInfo.h:65
std::vector< int > m_seedEtaSeparators
Definition: MkBuilder.h:133
Tan< T >::type tan(const T &t)
Definition: Tan.h:22
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
void seed_post_cleaning(TrackVec &tv)
Definition: MkBuilder.cc:407
ExecutionContext g_exe_ctx
Definition: MkBuilder.cc:49
Pool< MkFinder > m_finders
Definition: MkBuilder.cc:40
double f[11][100]
Event * m_event
Definition: MkBuilder.h:124
float getHypot(float x, float y)
Definition: Hit.h:47
void clearFailFlag()
Definition: MkBase.h:96
void select_best_comb_cands(bool clear_m_tracks=false, bool remove_missing_hits=false)
Definition: MkBuilder.cc:378
constexpr int numThreadsFinder
Definition: Config.h:87
int filter_comb_cands(filter_candidates_func filter, bool attempt_all_cands)
Definition: MkBuilder.cc:301
Pool< CandCloner > m_cloners
Definition: MkBuilder.cc:38
int total_cands() const
Definition: MkBuilder.cc:183
void begin_registration(C n_items)
Definition: binnor.h:264
void begin_layer(const LayerOfHits &layer_of_hits)
Definition: MkFinder.cc:68
ii
Definition: cuy.py:589
trk_cand_vec_type::size_type size() const
const LayerInfo & layer(int l) const
Definition: TrackerInfo.h:203
const auto & steering_params(int i)
Definition: MkJob.h:25
const TrackerInfo & m_trk_info
Definition: MkJob.h:10
bool m_in_fwd
Definition: MkJob.h:18
void updateWithLoadedHit(int N_proc, const LayerOfHits &layer_of_hits, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1739
void selectHitIndicesV2(const LayerOfHits &layer_of_hits, const int N_proc)
Definition: MkFinder.cc:751
std::vector< Track > TrackVec
constexpr bool nan_n_silly_fixup_bad_seeds
Definition: Config.h:20
void begin_layer(int lay)
Definition: CandCloner.cc:48
Pool< MkFitter > m_fitters
Definition: MkBuilder.cc:39
#define debug
Definition: HDRShower.cc:19
const std::vector< CombCandidate > & refCandidates() const
int iseed
Definition: AMPTWrapper.h:134
bool sortByScoreTrackCand(const TrackCand &cand1, const TrackCand &cand2)
void bkFitFitTracks(const EventOfHits &eventofhits, const SteeringParams &st_par, const int N_proc, bool chiDebug=false)
Definition: MkFinder.cc:2087
EventOfCombCandidates m_event_of_comb_cands
Definition: MkBuilder.h:130
std::vector< CombCandidate > & refCandidates_nc()
void find_tracks_handle_missed_layers(MkFinder *mkfndr, const LayerInfo &layer_info, std::vector< std::vector< TrackCand >> &tmp_cands, const std::vector< std::pair< int, int >> &seed_cand_idx, const int region, const int start_seed, const int itrack, const int end)
Definition: MkBuilder.cc:686
static const FindingFoos & get_finding_foos(bool is_barrel)
Definition: FindingFoos.cc:18
part
Definition: HCALResponse.h:20
std::vector< int > m_seedMaxLastLayer
Definition: MkBuilder.h:135
void populate(int n_thr)
Definition: MkBuilder.cc:42
float rout() const
Definition: TrackerInfo.h:68
constexpr bool nan_n_silly_check_cands_every_layer
Definition: Config.h:23
int getLastHitIdx() const
void begin_iteration()
Definition: CandCloner.cc:62
#define dprint(x)
Definition: Debug.h:95
MPlexQF m_Chi2
Definition: MkFinder.h:291
void export_best_comb_cands(TrackVec &out_vec, bool remove_missing_hits=false)
Definition: MkBuilder.cc:384
void bkFitOutputTracks(TrackVec &cands, int beg, int end, bool outputProp)
Definition: MkFinder.cc:1886
void bkFitFitTracksBH(const EventOfHits &eventofhits, const SteeringParams &st_par, const int N_proc, bool chiDebug=false)
Definition: MkFinder.cc:1934
static std::unique_ptr< MkBuilder > make_builder(bool silent=true)
Definition: MkBuilder.cc:166
constexpr int numSeedsPerTask
Definition: Config.h:89
constexpr int numThreadsEvents
Definition: Config.h:88
const auto regions_end() const
Definition: MkJob.h:23
int getLastHitLyr() const
void copyOutParErr(std::vector< CombCandidate > &seed_cand_vec, int N_proc, bool outputProp) const
Definition: MkFinder.cc:1808
void findCandidatesCloneEngine(const LayerOfHits &layer_of_hits, CandCloner &cloner, const int offset, const int N_proc, const FindingFoos &fnd_foos)
Definition: MkFinder.cc:1519
void fit_cands(MkFinder *mkfndr, int start_cand, int end_cand, int region)
Definition: MkBuilder.cc:1338
const std::vector< bool > * get_mask_for_layer(int layer)
Definition: MkJob.h:33
while(__syncthreads_or(more))
int max_max_cands() const
Definition: MkJob.h:31
constexpr bool usePropToPlane
Definition: Config.h:51
step
Definition: StallMonitor.cc:83
std::vector< int > m_seedMinLastLayer
Definition: MkBuilder.h:134
int originIndex() const
tmp
align.sh
Definition: createJobs.py:716
WSR_Result m_XWsrResult[NN]
Definition: MkFinder.h:321
constexpr bool nan_n_silly_print_bad_cands_every_layer
Definition: Config.h:24
void reset(double vett[256])
Definition: TPedValues.cc:11
int num_regions() const
Definition: MkJob.h:21
SeedState_e state() const
#define dprintf(...)
Definition: Debug.h:98
MPlexQI m_Label
Definition: MkFinder.h:292
void fit_cands_BH(MkFinder *mkfndr, int start_cand, int end_cand, int region)
Definition: MkBuilder.cc:1242
bool is_barrel() const
Definition: TrackerInfo.h:77
void find_tracks_in_layers(CandCloner &cloner, MkFinder *mkfndr, SteeringParams::IterationType_e iteration_dir, const int start_seed, const int end_seed, const int region)
Definition: MkBuilder.cc:967
void end_layer()
Definition: MkFinder.cc:88
const PropagationConfig & prop_config() const
Definition: TrackerInfo.h:216
const Hit & refHit(int i) const
float getPar(int itrack, int i, int par) const
Definition: MkBase.h:21