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