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